How do flash loans work?

Share on facebook
Share on twitter
Share on whatsapp
Share on linkedin

The past year has seen several high value exploits against DeFi platforms. The beginning of 2020 started with two back-to-back exploits against the bZx platform, losing a total of $1m. Though this is small compared to subsequent hacks, it was the first time flash loans were used in a malicious manner. The remainder of the year saw many more, such as Harvest Finance and Pickle Finance losing $34m and $20m respectively.

A significant portion of these involved the use of flash loans to manipulate multiple DeFi platforms for instant profit. But first, let’s define what a flash loan is and how they work.

What are flash loans?

To understand flash loans, let’s first look at how an Ethereum transaction works. To give an example, a trader making a trade on Uniswap (a decentralised exchange, DEX) from USDC to ETH tokens will be a single transaction. The reverse trade of ETH back to USDC will be another transaction. In both cases, the trader has constructed a simple Ethereum transaction which consists of only one action: swapTokens(). The two actions live inside their own transactions, and so occurred at different times. (Actions here refer to functions in Ethereum smart contracts, and function names have been renamed for simplicity.)

A more sophisticated trader might first swap USDC to ETH on Uniswap, followed by ETH back to USDC on SushiSwap (another DEX) immediately. This is a simple case of arbitrage (the act of buying and selling the same assets at different locations to take advantage of pricing discrepancies). Note the difference, where the two actions are bundled together: both actions live inside a single Ethereum transaction.

Now suppose the trader did not have any capital to make the trades. In come flash loans, or loans that are only valid for one Ethereum transaction.

Using the second example of switching USDC to ETH and back to USDC, the two actions can be wrapped with flash loan actions. The trader’s custom code can be sandwiched with a takeLoan() and a repayLoan() action, where their code would have the following order:

  • takeLoan()
  • swapTokens() on Uniswap
  • swapTokens() on SushiSwap
  • repayLoan()

If the borrower does not repay the debt taken before the end of the Ethereum transaction, the Ethereum transaction will revert (throw an error). All of the steps carried out will effectively be undone, as if it never happened (no loan taken, no swaps made).

Because of this atomic nature (an all-or-nothing situation) in code execution, it guarantees that either:

  • The repayment is made, and all associated actions between takeLoan() and repayLoan() occur
  • The repayment is not made, and all actions are cancelled.
  • This means lenders can offer these loans with no collateral requirement. The size of the loan depends on capital availability in the publicly funded platforms that offer flash loan services.

The closest comparison to the physical world would be payday loans. Both require no collateral and are only available for a short time. However, these are still very different. Payday loans typically require you to show paycheques and also consist of credit history checks, both of which assure the lender of repayment. The size of the loan is also limited, as the lender cannot overexpose to zero-collateral loans.

Flash loan use cases

To the uninitiated, flash loans could seem like they have very little use. However, the existence of several other money legos in DeFi make it a valuable tool in ensuring the ecosystem behaves in an efficient manner.

Arbitrage

The example given previously of our trader swapping USDC to ETH and back to USDC is an example of simple arbitrage. DeFi consists of several decentralised exchanges (DEX), with no built-in mechanism to ensure prices for assets are the same across different exchanges. It relies on rational external traders to take advantage of pricing discrepancies for personal profit, i.e. buy from a cheap place and sell at an expensive place. This will realign prices across exchanges.

Doing arbitrage would normally require some capital (USDC to purchase ETH in this case), but flash loans eliminate this requirement and democratises who can take part in arbitrage: anyone can borrow a large sum of money, take advantage of pricing discrepancies, repay the borrowed amount, and keep any profits – all in a single ethereum transaction.

Collateral swap

DeFi also consists of loans structured more similar to traditional loans. A user can provide collateral in the form of well-established crypto assets to take out loans in dollar-denominated stablecoins. As an example, a user providing a single Ethereum worth $2,000 is able to take out up to $1,600 in USDC on Aave.

A borrower would typically do this to increase their leverage. They could trade other coins while also being exposed to a price rise in ETH without having to sell it. Note how the loan is over-collateralised; on Aave, a borrower can only take out 80% of their collateral value. There is a $400 safety net to ensure that even in volatile markets, Aave would be able to recover their principal of $1,600.

Suppose the borrower is convinced that ETH will drop in the near future. If ETH dropped to $1,939 (the point where the loan is worth 82.5% of the collateral), the borrower’s position would be closed, resulting in a loss (how the position is closed is explained as part of the liquidation use case below). To prevent this, the borrower can make use of flash loans to collateral swap.

After the borrower has taken out their collateralised loan above, they could take out a flash loan to:

  • Borrow another $1,600 in USDC
  • Close their original loan to recover their ETH
  • Trade the ETH for another token
  • Reopen a loan with the new token as collateral
  • Use the newly issued USDC from step 4 to repay the flash loan
  • The net result is a simple swap of the underlying collateral from ETH to the new token.

The advantage of doing this is it automates several steps in a single transaction, making it quicker to execute and slightly cheaper in gas fees. The borrower will also have likely used the initially borrowed USDC for other activities, so would not have to unwind those positions either.

Debt refinancing

Debt refinancing is similar to the previous use case. A borrower of a collateralised loan may see that another platform is offering cheaper interest rates. A flash loan is used to pay off the more expensive loan, and take out a same-sized loan on the cheaper platform. The advantages are the same as those described for collateral swaps.

Debt liquidations

As mentioned previously, lending platforms such as Aave rely on third-party liquidators to close positions that fall below the minimum threshold for collateral value requirement. The process is as follows:

Using the same example as above, a borrower takes out $1,600 in USDC by providing $2,000 worth of ETH as collateral.
The market drops, and the ETH collateral is now worth $1,939, triggering the liquidation threshold.
The position is automatically locked by Aave (user cannot close position). As this all occurs on-chain, all information related to the position such as size and liquidation thresholds is visible to anyone. Liquidators will actively monitor the platform and see that this position is now under water.
The liquidator takes out a flash loan of $1,600 USDC (original loan amount), and pays it to receive $1,600 worth of ETH from the collateral Aave is holding.
At this point, the liquidator has made no profit and Aave still holds $339 in ETH from the borrower. To incentivise liquidations, an additional 5% in ETH ($80) is given to the liquidator.
The liquidator can then sell the ETH from step 4 to pay off the $1,600 USDC flash loan, and do whatever they wish with the 5% profit.

This is a simplified version where in practice only half the position is liquidated, but the logic is the same.

Conclusion

This first part in this series introduced flash loans and why they are useful. Part two will cover other pieces of DeFi and consist of greater technical depth. These elements are important in understanding how one of the high-profile flash loan attacks occurred. Understanding previous exploits will allow us to propose an adequate framework to safeguard against such attacks, which is a step closer to driving mainstream adoption of DeFi.