TLDR:
- This paper analyzes two forms of flash loan attack that have significant (beyond 500K%) returns on investment (ROI), and describes how they can be “boosted” by optimizing parameters in these attacks, such as choosing the optimal amount of an asset to be borrowed or swapped.
Citation
- Qin, Kaihua, et al. “Attacking the DeFi Ecosystem with Flash Loans for Fun and Profit.” arXiv preprint arXiv:2003.03810 (2020).
Link
Core Research Question
- What are the implications of flash loans for decentralized finance (DeFi) ecosystems? How can an attacker’s profit be maximized?
Background
- Decentralized Finance (DeFi) are cryptocurrency-related financial protocols defined by smart contracts. The majority of the DeFi platforms operate on the Ethereum blockchain.
- Transactions on the blockchain will either be executed entirely or fail (meaning nothing changes).
- A Flash loan is a type of loan that is only valid within one transaction. It can be implemented through a smart contract. In traditional financial applications, flash loans aren’t possible, which opens up new attack vectors.
- Flash loan properties
- No debt default risk: that’s because if default occurs, the transaction will fail.
- No collateral, only a transaction fee: debt is guaranteed to be paid back unless there is a bug in the underlying smart contract
- Loan size: the loan comes from a smart contract-governed liquidity pool. Anyone can borrow from the entire pool.
- High gas fee per transaction (because of the complex operations)
- Steps (all in a single transaction):
- Take the loan
- Use the borrowed asset
- Pay back the loan with interest
- DEX stands for decentralized exchange, which uses smart contracts to implement exchange functionalities.
- Price slippage is the change in price during a trade. The greater the quantity to be traded, the greater the slippage.
- Margin trading is the use of borrowed funds to trade.
Summary
- Flash loans are implemented in smart contracts, so they can only interact with smart-contract powered platforms, such as the following:
- Limit order book (LOB) DEX: match limit orders to exchange assets
- Order book: a collection of bid and ask orders, orders are matched when bid / ask price is the same
- Limit order: an order with fixed price
- Market making: liquidity provider contributes multiple bid-and-asks, to better facilitate a match
- Existing DEX with limit order book
- Automated market maker (AMM) DEX: uses a liquidity pool to provide assets
- Margin trading: trade using an asset borrowed from the exchange
- Credit and lending: provide 125%-150% of asset x to lend asset y
- Existing platform:
- Limit order book (LOB) DEX: match limit orders to exchange assets
- The authors outline flash loan use cases.
- Arbitrage
- What: Exploiting price differences among exchanges for financial gain
- When: The same asset has different prices on each exchange
- Before the flash loan: Trader needs a reserve of an asset on different exchanges
- After the flash loan: Trader doesn’t have to hold the asset, they can perform the trade directly with the loan, which makes arbitrage risk-free.
- Example:
- Convert DAI to SAI with MakerDAO’s migration contract
- Convert SAI to ETH with Uniswap
- Convert ETH to DAI with Uniswap
- Wash Trading
- What: Artificially inflate the trading volume of an asset to attract others to trade
- When: anytime
- Before flash loan: Trader needs to hold and use real assets to make a trade on DEX
- After flash loan: Trader need only pay the gas fee to fake the volume
- Example:
- The cost to increase the 24 hour volume by 50% on the ETH/DAI market of Uniswap is ~1300 USD
- Collateral Swapping
- What: The user closes the original collateral by paying back asset x and immediately opens a new collateral position using asset y
- When: there is a cost difference between using assets as collateral
- Before flash loan: The user needs to hold asset x and y, the locked collateral may lose its value due to the asset’s price fluctuation
- After flash loan: The user can borrow asset x and y with the loan
- Example
- First uses 0.18 WETH as collateral for 20 DAI
- Uses flash loan to borrow 20 DAI and get back WETH
- Convert 0.18 WETH for 178.08 BAT
- Create 20.03 DAI using BAT as collateral
- Flash Minting
- What: mint and immediately burn an asset so it only exists within a single transaction
- When: anytime
- Sample code
- Arbitrage
-
Governance Attack
- What: to hold a large amount of voting tokens to change a voting result
-
The authors describe two flash loan attacks
- Pump and Arbitrage
- Main idea:
- A trader shorts a large amount of an asset on a DEX to distort the price on another DEX
- What do I need to perform this attack?
- ETH to pay gas price
- 2 different DEX to trade between (Uniswap, bZx in this case)
- 1 flash loan provider to supply the loan (dYdX)
- 1 collateral lending platform to borrow asset from (Compound)
- Transactions needed: 1 flash loan + many normal transactions
- Steps
- Within the flash loan transaction:
- Borrow ETH flash loan
- borrow WBTC using ETH as collateral
- Short ETH against WBTC
- purchase a lot of ETH at a “cheaper” price (convert WBTC to ETH
- Return ETH flash loan
- Ending up earning lots of ETH with lots of WBTC debt
- After the flash loan transaction:
- Gain ETH & has over-collateralized loan of ETH for WBTC
- Repeat (small volume each time to avoid price slippage)
- When the WBTC/ETH decreases back to normal, purchase WBTC with ETH
- Pay back WBTC to redeem the ETH collateral
- Within the flash loan transaction:
- Risk
- Price slippage for large trading volume (239.84% in the example) during the flash loan transaction
- Liquidation of the over-collateralized position
- Who’s the victim?
- Liquidity provider of WBTC-ETH
- Total loss is 2,330.86 ETH in this example
- Extra arbitrage opportunity for others
- When the price of WBTC/ETH increases after the flash loan, buy ETH on other market and exchange ETH for WBTC
- Main idea:
- Oracle Manipulation
- Main idea:
- Price manipulation by accessing prices from on-chain DEX
- What do I need to perform this attack?
- ETH to pay gas price
- Three different DEXes to trade between (Kyber-Uniswap reserve, Kyber, and Synthetix)
- 1 flash loan provider to supply the loan (bZx)
- 1 lending platform that reads price from other DEX (bZx)
- Transactions needed: only 1 flash loan
- Steps
- Borrow ETH flash loan
- Buy sUSD with ETH at DEX1
- sUSD/ETH price down at DEX1 so can’t buy too much
- Buy sUSD with ETH at DEX2
- sUSD/ETH price down at DEX2
- Buy sUSD with ETH on DEX3 (cause price at DEX2 drops a lot
- The lending platform reads the reduced price from DEX2
- Use sUSD as collateral to borrow a lot of ETH on lending platform
- Return ETH flash loan
- Ending up earning lots of ETH
- Who’s the victim?
- Lenders on the lending platform
- sUSD/ETH price oracle decreased significantly
- Total loss is 2,699.97 ETH
- Main idea:
- Pump and Arbitrage
Method
- The authors demonstrate how to generate optimized parameters to maximize profit of these attacks
- They formulate every action in DeFi into a state transition function and define constraints to form a “constrained optimization problem”
- State:
- the attacker’s initial balance
- DeFi platform’s internal state
- Constraint:
- execution requirements of the Ethereum Virtual Machine (Ether balance of an address >= 0)
- DeFi platform’s rules (flash loans must be paid full with interests, collateral size > k, max amount to borrow in the flash loan pool, etc)
- Goal: maximize the attacker’s balance given the initial state
- State:
- They define the actions and parameters to be optimized in the 2 attacks
- Pump and Arbitrage
- Action
- Loan (dYdX)
- CollateralizedBorrow (Compound)
- MarginShort(bZx) & SwapXforY (Uniswap)
- SwapYforX (Uniswap)
- Repay (dYdX)
- SellXforY & CollateralizedRepay(Compound)
- Parameters
- The amount of asset X collateralised to borrow Y
- The amount of asset X collateralised to short Y
- Action
- Oracle Manipulation
- Actions
- Loan(bZx)
- SwapXforY(Uniswap)
- ConvertXtoY(Kyber reserve)
- SellXforY(Synthetix)
- CollateralizedBorrow(bZx)
- Repay(bZx)
- Parameters
- The amount of asset X used to swap for Y in step 2
- The amount of asset X used to swap for Y in step 3
- The amount of asset X used to exchange for Y in step 4
- Actions
- Pump and Arbitrage
- They use the Sequential Least Squares Programming (SLSQP) algorithm from SciPy to solve the optimization problem. (Scipy function reference)
- Then, they execute the optimizer 1,000 times on the same Ubuntu 18.04.2 machine with 16 CPU cores and 32 GB RAM. The average convergence time is 12.9ms.
- They then fork the Ethereum blockchain at the block right before the original adversary transaction then perform the new transaction with the optimized parameters
Results
- Using the optimal parameters, they raised the profit of the two attacks to 829.5k USD and 1.1M USD, respectively, which is a boost of 2.37× and 1.73×, respectively.
- HOWEVER! Due to the inaccuracy of their model, they could not directly use the precise model output, but instead use the model output as a guide for a manual, trial and error search
Discussion & Key Takeaways
- The liquidity provider and lender are paying the price for the attacks.
- Others can also benefit from the malicious price manipulation caused by the flash loan, instead of issuing a flash loan themselves. This is because the attacker will not be able to directly arbitrage the distorted price during the flash loan transaction.
- For example, WBTC → ETH → WBTC within a short period of time will not end up having more WBTC. The arbitrage must happen in a certain time span that is long enough to let the price drop back to normal.
- To buy a large amount of an asset, we can use multiple exchanges to reduce price slippage. Prices on different exchanges are not synced in a short period of time.
- Some flash loan attacks are done in a single transaction, while others can cause after effects and will be done in many transactions within a time span.
- Currently there’s no “automatically tuned parameter” method for flash loan attacks. We still need to manually adjust the parameters given the model’s output. The model can only approximate.
- The authors did not put the maximum value of the parameter that makes the gas consumption under the block limit into the constraints
- The parameter optimization method in this paper requires the attack method to be known and coded to form the model. Not a generalized method.
Implications & Follow-ups
- Can we classify which flash loan attacks are malicious?
- Possible ways to prevent flash loan attack:
- Dex can limit transactions using flash loan
- Detect if the fund in this address only appear in this block but not the previous block
- Lower the capability of a normal transaction
- Dex should not allow a single transaction causing slippage over 100%
- Increase the delay for price oracles / average price over a time span
- Dex can limit transactions using flash loan
- Problems when preventing the attacks:
- The mechanisms exploited by the attacks are often not malicious
- Other ways to increase final revenue?
- Attackers having higher initial capital does not help increase the final revenue, since the maximum amount of assets to borrow has a limit.
Applicability
- DeFi protocols can model their risks and potential losses using the method in this paper (although the complete code is not provided here, only the functions & libraries used.)
- When designing new DeFi protocols, developers should pay careful attention to known attack vectors, which include (1) retrieving the price of an asset directly from a DEX may cause arbitrage opportunities, (2) voting power based on the amount of tokens held may be subjected to manipulation, (3) the price of the collateralized assets for lending may be distorted and paid back at a lower amount.
- To prevent flash loan attacks, future protocols can (1) set the price of an asset to the average value within a timespan and from multiple exchanges (such as using ChainLink), (2) limit the maximum votes from a single account or restrict the number / quantity of vote changes a single account can perform during a timespan, (3) the pay-back price of the collateralized asset cannot be too far off of the original borrowing price within a certain timespan.