Flash loans

The DeFi revolution is a shift of the philosophical view on how financial institutions should be built and run, however it is very much a technology revolution that allows for the philosophy behind DeFi to be expressed in code. One of the most innovative tools that came with DeFi is Flash loans. Flash Loans are often cited as the reason behind many DeFi hacks that resulted in hundreds of million dollars to be lost. In this piece we will be going over the anatomy of Flash Loans, their use cases, purpose and how they are used in certain DeFi exploits.

What are Flash loans?

Flash loans are uncollateralized loans on DeFi, borrowed and returned within one block transaction. 

  • Loans getting approved within seconds
  • Low-interest rates on the borrowing
  • Earning a better interest rate on your savings

Flash loans take it a step further, allowing users to take the maximum benefit of the DeFi ecosystem.

What are Flash loans?

Flash loans are uncollateralized loans on DeFi, borrowed and returned within one block transaction. 

  • Loans getting approved within seconds
  • Low-interest rates on the borrowing
  • Earning a better interest rate on your savings

Flash loans take it a step further, allowing users to take the maximum benefit of the DeFi ecosystem.

Flash loans allow a user to borrow any available amount of asset without any collateral, instantly. It is possible as long as the borrowed amount is returned within the same transaction – in a flash. This is possible because transactions on the ethereum blockchain are atomic.

The cost of a flash loan depends on the platform providing it. Aave charges 0.09% of the amount borrowed as a fee, whereas dydx charges zero fees.

Framework

Flash loan contracts have different functionalities and use-cases, but the inherent logic is the same. 

For the sake of explanation, flash loan smart contract => contract0

  1. The contract0 calls the LendingPool contract, requesting the desired asset.
  2. After a few checks, the LendingPool contract transfers the requested asset to the contract0.
  3. The contract0 then executes the arbitrary operations as specified in its code.
  4. After all the operations have been executed, the flash loan amount + fee is pulled back into the lending pool.
  5. In case the owed amount is not available, the transaction is reverted.

Use-cases of flash loans

Flash loans are popularly known for facilitating arbitrage opportunities. 

Here are the use-cases flash loans help achieve:

1. Arbitrage

Arbitrage opportunities arise when there is a price disparity of an asset in different markets. 

Eg: $ETH is priced at $3,300 on Compound and $3,400 on Uniswap. Flash loan allows you to borrow $100,000 from Aave’s liquidity pool.

  • Approximately 30 $ETH can be bought from Compound
  • That 30 $ETH can be sold at Uniswap for $102,000
  • The flash loan fees would be 0.09% of $100,000 = 90$
  • Total profit = $102,000 – $100,000 – $90 = $1910

2. Collateral swap

Collateral swaps allow users to replace the lent asset. This is done to maximize the interest earned on your asset. Eg:

  • Assume $DAI is being lent at 8% APY on Compound, similarly the current rate at which $USDC can be lent is 10% APY
  • It is a 2 step process to replace the asset 
  • This forces user to pay the gas fees for 2 transactions
  • Flash loan rolls it up in a single transaction 
Breakdown of transactions to collateral swap for a borrowing position using flashloans.

3. Self-hedging

A Flash loan helps a risky borrower trim down the risk by reducing the debt position. In most cases, there is a collateralization ratio to be maintained by a user. The ratio should be kept above the liquidity threshold to avoid liquidation of the assets. Eg:

  • $USDC can be borrowed from Aave and used to pay back part of the debt
  • The withdrawn $ETH is converted to $USDC and used to pay back the loan from Aave
  • This helps in maintaining the collateralization ratio

4. Self-liquidation

A sudden crash in the market might lead to the liquidation of your assets. But the liquidation cost is of concern, with penalties ranging from 3-15%. Flash loans allow you to build self-liquidation models. The cost of 0.09% for the flash loan is better than paying the penalty from 3-15%.

5. Interest rate swap 

Interest rate disparity is common amongst different exchanges. Flash loans help you transfer your debt from one platform to another.

6. Flash Swap

Introduced in the V2 rollout of Uniswap, flash swaps work similar to flash loans. 

Flash swaps allow you to swap assets on an exchange without verifying the required exchange value in the user’s wallet. The amount withdrawn is valid as long as the asset is returned to the exchange within one block transaction with a fee of 0.3% of the amount borrowed. In case the amount is not available the transaction is reverted.

7. Flash Minting

Whenever an amount is lent in a DEX an equivalent amount of token is minted. 

Eg: If an amount of 10 $ETH( lets say 1 $ETH = 1000 $DAI ) is deposited on MakerDAO, then 10,000 $DAI is minted.

In the case of a flash mint, no collateral is needed to mint. After minting a particular asset the necessary operations can be carried out and the minted amount can be returned to the exchange. It is to be made sure that this happens in a single block transaction for the flash mint to be valid. 

8. NFT flash loans

The main output expected from NFT flash loans is to earn profits  through the rewards distribution for the NFT holders.

NFTs may be borrowed through NFT pools, against liquidity from a flash loan. The accumulated rewards are collected while sitting in the pool. The particular rewards can be sold and then the NFTs can be returned back to the respective pools. 

History of Flash Loans

The term “Flash Loan” was first introduced by Max Wolff, creator of Marble protocol in the year 2018. With a view to tapping into the unexplored power, DeFi can offer. 

Since its inception flash loans have catered an amount of $7B+ across DeFi protocols. Aave has been the most prominent platform for flash loans, the first-ever flash loan to be minted was done by “The Flashboys” on Aave protocol. 

The First-Ever Flash Loan – ArbitrageDAO (Flashboys)

The first flash loan was used for arbitrage between $DAI and $SAI. This was done by the Flashboys. 

Total profit = 9 $DAI profit – 3.66 $DAI gas cost = 5.45 $DAI

The exact transaction details can be seen below. 

Flash loan attacks

Being cheap and low-risk, flash loans invite a range of exploitation opportunities for the black hats. Flash loans have been used from manipulating markets to exploiting bugs in protocols. They can be pooled into one single transaction and have a concentrated attack on a vulnerable smart contract. Phantom volumes are arranged with the help of flash loans to manipulate the demand of an asset.  In total over $400M+ have been lost to flash loan attacks. Some of the biggest most notable attacks were on Cream Finance, Yearn Finance and Alpha Homora attack. We discuss some of the recent flashloan attacks below:

1. Alpha Homora Protocol Attack – Feb 2021

$sUSD was borrowed repeatedly using Alpha Homora from Iron Bank. The borrowed amount was doubled each time. This process was done via two transactions. Each time the funds were lent back to Iron Bank, receiving $cySUSD. 

The attacker then borrowed $1.8M in $USDC from Aave using a flash loan. This $USDC was swapped with $sUSD via Curve. $sUSD received was lent back to the Iron Bank, receiving $cySUSD. This process was continued till a massive amount of $cySUSD was received. The $cySUSD was used to borrow different assets from the Iron Bank. 

A total of $37.5M worth of assets were drained using this exploit, in the following amounts: 

  • 13,200 $WETH
  • 3.6M $USDC
  • 5.6M $USDT
  • 4.2M $DAI

2. Pancake bunny attack – May 2021

$BNB was borrowed in large amounts via Pancake Swap. The price of $USDT/$BNB and $BUNNY/$BNB in Pancake Bunny’s pool was manipulated in this attack. This allowed the hacker to steal $BUNNY, which was later dumped in the market. These events caused the price to crash. The token price went from $140 to $240, then $0. In the aftermath of the attack, it was found that $45M were gone.

3. Ape-rocket Flash attack – July 2021

A Large amount of $AAVE and $CAKE were borrowed and kept in the protocol’s vault. The amount being sent to the vault generated the $SPACE (the native token of ape-rocket) token. The massive amount of $AAVE and $CAKE being sent led to the minting of more $SPACE. This led to a crash of 63% on the $SPACE token. A total loss of $1.26M was announced.

The attacks raise more concerns on whether flash loans should be allowed to continue or not. There are a few ways in which the risk of flash loans can be minimized.

Minimizing the risk of flash loan exploits

Looking at the major points of fault in the flash loan construct. There are 3 ways that will help reduce the risk of flash loan exploits in various DeFi protocols.

1. Use of decentralized oracles

Exchanges have been dependent on a single source for pricing information. This directly invites price manipulation and exploitation. Therefore, it’s better for exchanges to be dependent on pricing oracles like Chainlink and Band Protocol. This ensures that the data is pulled from multiple verified resources reducing the risk of manipulation.

2. Forcing critical transactions to go through 2 blocks

Flash loans are borrowed and returned within one single block transaction. Capital-intensive transactions can be made to span two blocks. This will prevent the user from repaying the loan and ensure the value is locked between two blocks. This will lead to transactions to be asynchronous. A proper care has to be taken while designing this solution. The attacker can take advantage of the weak design and carry out a flash attack on both the blocks. 

3. Using flash loan attack detection tools

We have often seen a delay in the detection of an exploit and the necessary remedy for the exploit by the developers of the victim platforms. This delay provides the exploiters enough time to get away with the exploit. To tackle this, it is beneficial to have automated tools that help in the detection of suspicious activities. This will enable the DeFi protocols to curb the exploitation before they cause critical damage. Open Zeppelin has taken the initiative in this direction with OpenZeppelin Defender. It helps project managers detect any unusual activities. 

To know more: OpenZeppelin Defender

These methods combined still won’t ensure complete safety against flash attacks. But it gives safety against the simplest kinds of exploitations that can be carried out using flash loans. 

The flash loan toolkit

The advantages of flash loans have been discussed above, but the important part is the actual hands-on execution. Given below is an overview of the tools which help in creating and executing flash loans for developers as well as non-developers. 

Platform Aave DyDx Uniswap Furucumbo DeFi Saver
Flashloan Fees 0.09% 0% 0.3% 0.09% 0.09%
Coding required
Tutorial Link Link Link Link Link

End note

With its arsenal of varied use-cases, flash loans have proven to be quite useful. Users with scarce resources have been able to explore the capital-intensive side of DeFi. 

Initially flash loans were meant for people with a moderate coding experience. This changed quickly with tools like Furucombo and Defi Saver enabled users with a basic understanding of DeFi to execute flash loans. Thus, increasing the user base of flash loans.

The marginal cost and low-risk have been an asset to the DeFi user base, but it also became a breeding ground for new exploits. Over $45M+ have been lost to these flash loan attacks. There have been attempts at minimizing the risk of flash loan attacks as discussed above. Though none of the methods make a DeFi protocol 100% resilient against a flash loan attack. 

Flash loan attacks have a fractional possibility in the case of layer 2 and the shard chains in the ETH 2.0 upgrade. Communication across a shard or layer 2 within a single block transaction is not possible. The evolving blockchain ecosystem will continue invite new use-cases and innovations for flash loans.

Disclaimer: This article is a summary of the writers opinions and research. Digital assets are a volatile asset class and readers should be aware of the potential risks of investing in blockchain projects. This is not investment advice & we will not accept liability for any loss or damage that may arise directly or indirectly from any such investments.

References

https://aavewatch.com/

https://docs.aave.com/faq/flash-loans

https://medium.com/dragonfly-research/flash-loans-why-flash-attacks-will-be-the-new-normal-5144e23ac75a

https://medium.com/nft20/introducing-nft-flash-loans-97ff8c9298d4