Research Summary: Towards Understanding Flash Loan and Its Applications in DeFi Ecosystem

TLDR:

  • The first systematic study of flash loans. A system called “ThunderStorm” that can identify flash loans using transaction patterns is proposed and created. Using ThunderStorm, the authors find 22,244 flash loan transactions on Ethereum, and analyze their usage distribution.

Citation

  • Wang, Dabao, et al. “Towards understanding flash loan and its applications in DeFi ecosystem.” arXiv preprint arXiv:2010.12252 (2020).

Link

Core Research Question

  • Can we identify and decode existing flash loan transactions by defining their behaviors, and understand how they are being used?

Background

  • Functions in smart contracts are identified by the function signature, the first 4 bytes of hash (function name, parameters type).
  • Events in smart contracts are also identified by the first 4 bytes of hash (event name, parameter type). Events may be triggered in functions to record critical information.
  • Flash loan is a type of loan that is only valid within one transaction. It can be implemented via smart contracts.
  • Flash loan platforms (data from DefiPulse until Oct 2020)
    • Aave
      • Flash loan service: The first platform to officially provide the ‘flashLoan’ function.
      • Flash loan fee: 0.09% of the flash loan
      • Total value locked: $1.12B
    • dYdX
      • Flash loan service: no official function, can be performed by calling the function ’withdraw’ before ’deposit.’
      • Flash loan fee: 0
      • Total value locked: $24M
    • bZx
      • Flash loan service: no official function.
      • Flash loan fee: 0
      • Total value locked: $250K
    • UniswapV2
      • Flash loan service: they provide a feature called ‘flash swap.’
      • Flash loan fee: 0.3% of the borrowed asset
      • Total value locked: $2.7B
  • Collateral is an asset kept aside during margin trading to cover potential losses. If the price of a borrowed asset drops beyond a specific ratio, the collateral will be sold to cover the loss and pay back the lender.
  • Liquidation occurs when the deposited collateral is sold for cash. It usually happens when a trader is unable to fulfill the margin requirements for a leveraged position.

Summary

  • The authors provide background information on Ethereum and decentralized finance (DeFi)
  • They propose the “ThunderStorm” system, which has three components
    • The FlashLoan Identifier
      • Which identifies flash loan transactions
    • The primitive classifier
      • Classifies the semantics of a transaction into four patterns
        1. Exchange
        2. lending and borrowing
        3. margin trading
        4. liquidation
    • Advanced Classifier
      • Understands the intention of a transaction by its semantics
        1. Arbitrage
        2. Anti-Liquidation
        3. Swapping
  • They use ThunderStorm to understand how flash loans are used in the real world
  • They show the limitations of the ThunderStorm system:
    • Function patterns coverage can be limited
      • New patterns may emerge quickly and need to be added to the system
    • Identification of the type of asset
      • To identify a trading asset, an asset’s contract address needs to be in the database, so it is difficult to scale to identify all assets
    • Variety of Arbitrage
      • Currently the system only recognizes arbitrage performed by the same trader, it cannot recognize“group” arbitrage involving multiple traders.
    • Profit calculation
      • The system cannot calculate the profits based on the real time price during the attack (other research work is able to do this)

Method

  • Implementing ThunderStorm
    • FlashLoan Identifier
      • Decodes function and event names using the function signature and hash
        • ThunderStorm maps events and functions to their hashes, and matches hashes to decode their original value.
      • Defines a flash loan’s set of functions on popular DeFi platforms (from DefiPrime). Unlike ERC20, DeFi platforms use different function names, so the authors had to manually define each of them.
        • Aave
          • Function: flashloan
          • Smart contract: AAVELendingPool
          • Event: FlashLoan
          • Rule to identify: Check that the function name and transactions from the address are from the smart contract in question.
        • bZx
          • Function: flashBorrowToken
          • Rule to identify: Check if iToken is borrowed and the function name.
        • UniswapV2
          • Function
            • swap, uniswapV2Call: borrow asset
            • transfer / transferFrom: payback borrowed asset
          • Smart contract: UniswapV2Pair, created by UniswapV2Factory
          • Event: PairCreated
          • Rule to identify: Check the function name and whether the payback asset transaction is sent to the contract that triggered the asset borrow function.
        • dYdX
          • Function: a meta transaction with four functions
            • operate, Withdraw, callFunction, Deposit
          • Event (two possible chains of events):
            • LogOperate → LogCall → LogWithdraw → LogDeposit
            • LogOperate → LogWithdraw → LogDeposit
          • Rule to identify: Check if the ordered events exist
    • Primitive Classifier
      • Patterns found for each primitive
        • Flash loan
        • Exchange
        • Lending and Borrowing
        • Margin Trade
        • Liquidation
    • Advanced Classifier
      • Arbitrage
        • Price
          • trade the same asset across different platforms at different prices.
        • Interest rate
          • deposit capital in platforms providing a higher interest rate
        • Rule to identify: at least two trades swapping assets launched from the same trader on different DeFi platforms
      • Anti-Liquidation
        • Three ways to prevent liquidation when price drops
          • Pay back debt to receive deposited collateral
            • loss: fixed when paying back debt
          • Deposit more assets to raise the collateralization ratio
            • loss: may not be a loss if the price goes up afterwards and doesn’t touch the liquidation price. If the price drops below the new collateralization ratio, however, the loss would be more severe.
          • Pay back a portion of the debt with the collateral
            • loss: no immediate loss
        • Existing platform: DefiSaver
          • Integrated Aave’s flash loan service
          • Charge a small fee compared to the loss of liquidation
      • Swapping
        • Collateral Swapping
          • Collateral asset: changed from A to B
          • Borrowed asset: same
          • Platforms checked: MakerDAO
          • Action: redeem original collateral and deposit new collateral in a different form.
        • Loan Swapping
          • Collateral asset: same
          • Borrowed asset: changed from A to B
          • Platforms checked: Compound and Aave
          • Action: repay the loan and borrow a new loan
        • Platform Swapping
          • Collateral asset: same
          • Borrowed asset: same
          • Platforms checked: all
          • Action: pay back the loan and retrieve the asset from platform A and borrow the same amount from platform B

Results

  • ThunderStorm can analyze internal transactions and functions of existing flash loan attacks
    • Analysis result

  • 22,244 out of 863,504,142 transactions are identified from the start of the Ethereum network to October 2020 were identified as flash loans
  • Usage distribution
    • Note: since one transaction may use multiple flash loan providers, the sum of all transactions on each platform is larger than the total number of transactions.

  • Insights

    • Flash Loan providers usage: dYdX > Aave > UniswapV2 > bZx
    • In Aave, top 10 borrowers run 70% of the Flash Loan transactions
    • Over 60% of Flash Loan transactions were from 3.5% of borrowers
    • Main user ranking of the Aave Flash Loan: DeFi Saver > Furucombo
  • Behavior distribution

    • Insights
      • Usage: exchange > lending & borrowing > anti-liquidation (may because liquidation often happens as price fluctuates)

Discussion & Key Takeaways

  • Flash loan transactions can be identified and decoded by matching known function and event patterns.
  • Flash loan transactions may contain the following behaviors (ranked by usage frequency)
    • exchange > lending & borrowing > anti-liquidation > arbitrage > liquidation > swapping > margin trade
  • Usage of flash loan platforms: dYdX > Aave > UniswapV2 > bZx
  • Main players of flash loans: DeFi Saver > Furucombo > individual users
  • From the start of the Ethereum network to 2020 October, 22,244 out of 863,504,142 Ethereum transactions used flash loans.

Implications & Follow-ups

  • The “margin trade” category defined by the ThunderStorm system is weird. There was only one such transaction found.
  • Can we use this system to automatically generate new flash loan attacks by combining all the known patterns? (theoretically yes)

Applicability

  • This system can be used for security analysis to decode the underlying action of existing flash loan attacks.
  • This system can be combined with another work that optimizes parameters of known flash loan attacks to maximize the attack’s profit.
  • If the system can permutate all known patterns of flash loans, it will be able to find new flash loan attack opportunities.
5 Likes

What do you think is going on with the “margin trade” category? Do you think it’s a rare event or they just weren’t capturing it correctly?

2 Likes

I think it’s possible that using flash loan for margin trading rarely happens, because the attacker can borrow the money directly instead of opening leveraged positions which bears the risk to be liquidated.

4 Likes

Flash Loan Providers

In this context, I’d give a basic introduction of each Flash Loan provider and reveal their fee-charging mechanisms. Besides, I’d explain how users’ smart contracts interact with different FlashLoan providers.

Aave is currently the second largest lending platform that locks over $3.72B up to Jan 2021. As the first platform
officially providing the Flash Loan service, Aave provides a native function called flashLoan 2 designed in Aave’s official contract, i.e the LendingPool contract, to trigger Flash Loan. Moreover, requesting Flash Loan in Aave charges 0.25% of the borrowed assets as the fee.

UniswapV2 flash loan transactions identification Three steps are necessary to recognise Flash Loan transactions from UniswapV2. In order to gather a group of pair contracts (addresses) that provide the swap function, we first validate the PairCreated event released by the UniswapV2Factory contract. By causing the function swap in all transactions, we secondly confirm the event swap that was released.
The transaction is identified as a Flash Loan transaction from UniswapV2 by testing three conditions after we have determined that it invokes the swap function of pair contracts:

(1) The parameter data is longer than zero in length.

(2) The call to the transfer or transferFrom function must be part of the internal transaction that uniswapV2Call initiates.

(3) When using the transfer or transferFrom functions, the pair contract must be the receiver address.

Recognize Aave fast loan transactions.

As noted before, users can use Aave’s Flash Loan using an exposed native function named flashLoan. When the function flashLoan is successfully run, a special event called FlashLoan 5 is released. As a result, we can recognise Flash Loan transactions from Ave using this functionality. As a result, we learn that approximately 15,000 transactions, including Aave’s Flash Loan, have occurred as of January 31, 2021.
A non-custodial platform called dYdX offers services like lending and borrowing primarily using the cryptoassets it supports, such as ETH, USDC, and DAI. Over 157M USD have been frozen at the time this article was being written by dYdX.

1 Like

Nice summary @tina1998612.
All Ethereum-based decentralized financial protocols, including more recently Binance Chain, utilise flash loans.
Although dYdX and DEX Uniswap have added flash loans, Aave protocol is still the market leader. Furthermore, users can use flash swaps on Uniswap to take Ethereum-based tokens paired with other tokens, perform anything they want with them, and then promptly return the identical amount.
Since August 2020, it is believed that platforms like DeFi Saver and Furucombo have made it possible for less technologically savvy users to benefit from DeFi and flash loans by removing the requirement for specialized coding knowledge.
A fundamental aspect of the protocol known as “constitutionality” allows for the swapping out or connecting of pieces of the open-source smart contract code for Ethereum.
In conclusion,
Flash loans are still very new, and they are being used for ever-more-innovative things like borrowing money to buy tokens to force through governance elections.
Such actions could have long-lasting effects on protocols, therefore some have taken steps to limit them.
Some people still speculate that as DeFi develops, these financing practices will be considered as passing trends.
Others, however, support their development because they can increase market efficiency by giving everyone access to free money and the chance to become a crypto whale—even for a brief period of time—by creating protocols that are ever more safe.

4 Likes