Bitget App
Trade smarter
Buy cryptoMarketsTradeFuturesCopyBotsEarn
Flash Loans: A Beginner's Guide

Flash Loans: A Beginner's Guide

Arkm-research2024/06/11 10:45
By:Research Team

INTRODUCTION

Flash loans are a type of loan in DeFi that are made and returned in a single block. This means that the recipient of the loan must be able to perform some kind of arbitrage or MEV action that can take place immediately. This allows arbitrageurs or MEV bots to perform profitable DeFi actions with far more capital than what they may have immediately available. They often attract attention due to the large sizes of the loans involved.

A Series of Flash Loans

SUMMARY

  • Flash loans are instant-return loans made by DeFi protocols like AAVE to any user
  • Flash loans provide users with a large amount of capital to execute profitable actions in a single block
  • Flash loans are most commonly used to maintain DeFi positions and perform arbitrage
  • Flash loans have historically been used to help attackers exploit protocols and drain funds

WHAT IS A FLASH LOAN IN CRYPTO?

A flash loan is a loan of capital that is borrowed and returned in a single block. This means that the borrower must be able to perform some kind of profitable action or MEV strategy in order to make the flash loan worthwhile.

With flash loans, borrowers never actually take custody of the capital, and the loaner (in theory) takes limited financial risk. This is because the code governing flash loans will only execute as long as it can verify that the borrower will return at least the amount of capital that they borrowed, plus any fees for using the flash loan service. The DeFi service providing the loan will check if the borrower has called a function to return the funds in the same block - if their transaction does not return the funds, the loan contract will never issue the funds in the first place.

Whatever the borrower wishes to do with the money must be executed immediately and must also be profitable, so that they can at least return the amount that they originally borrowed in the loan. This means that common flash loan borrowers include MEV Bots, Arbitrageurs, and Protocol Exploiters - these individuals can all perform actions to instantaneously derive profit from executing blockchain transactions, whether these be liquidations of DeFi users, arbitrage between different liquidity pools, or receiving funds from exploiting a protocol.

HOW TO DO A FLASH LOAN?

Flash loans are performed by MEV Bots and protocol users who can code complex transactions to both borrow and return funds in a single transaction.

Flash loans can be called from a number of different DeFi protocols, such as MakerDAO’s DssFlash contract (which will flash loan any amount of DAI ) or AAVE’s flash loan contract (which will flash loan any amount of tokens that are deposited in AAVE). These contracts will only accept flash loan function calls if the caller will also return funds in the same block, so users will often have to set up a custom Smart Contract in order to perform multiple actions at once.

An MEV Bot Performing a Series of Transactions Involving a Flash Loan

Most MEV Bots will submit all of their function calls bundled into a single transaction. This means that you will be able to see the borrow transaction and return transaction occurring on the same transaction page on analysis tools like Arkham. In between, they will also execute the transactions that are necessary to make profit - this will show an observer what exactly a MEV bot was up to when they took out a flash loan.

DO YOU HAVE TO PAY BACK A FLASH LOAN?

Flash loans are created and paid back instantly - therefore, the borrower never actually takes possession of the borrowed capital. Since the borrow and repay transactions must occur in the same block, there is never actually any period of time during which the borrower needs to “pay back” the loan. Unlike typical loans in DeFi, flash loans are uncollateralized - which means that if the lending protocol didn’t immediately check for a return of funds in the same block, there is a chance that the borrower could just walk away with the money! So yes, you have to pay back a flash loan, but in order to take it out you must have already paid it back.

If the borrower submits a request for a flash loan without the appropriate transactions to repay in the same block, the flash loan contract will simply refuse the request - meaning that the loan would never occur in the first place. This prevents individuals from borrowing money that they cannot repay. Unlike with other DeFi loans, you can never be liquidated as part of a flash loan - you don’t provide any collateral, so the protocol instead needs to check for an instantaneous return of funds.

This provides far more flexibility to MEV Searchers and coders looking for arbitrage opportunities, by allowing them to work with effectively unlimited capital when they are operating on-chain - the only costs being the extra gas used from invoking the flash loan.

WHY ARE FLASH LOANS EFFECTIVE?

Flash loans are very popular among MEV users because they allow the user to exploit opportunities to momentarily leverage large amounts of capital to gain instant profit in a single transaction. As you can imagine, there are a lot of users who would like to gain risk-free profit! This makes the flash loan landscape rather competitive. Flash loans are most often seen used by MEV bots liquidating protocol users - e.g. when loan positions enter liquidation mode on AAVE or MakerDAO. Frequently, the positions will have to be sold off across a number of different liquidity pools - so flash loans allow MEV Bots more capital to work with in order to take possession of and liquidate these DeFi positions.

Flash loans can also be used by MEV Bots with absolutely no capital to their name whatsoever. Occasionally, flash loans are used by MEV Bots to perform transactions, pay gas fees - and then reimburse the loan with the profit from an arbitrage transaction. Some MEV users have used flash loans to fund new wallets with gas money, simply by coding an effective arbitrage strategy and using profit from the flash loan to pay transaction fees.

DO FLASH LOAN ATTACKS STILL WORK?

Flash Loan Attacks refer to when flash loans are used as part of a protocol exploit or market manipulation in order to derive profit. Most commonly, flash loan attacks occur through a re-entrancy exploit or an oracle manipulation exploit.

Re-entrancy is when a certain DeFi function call (e.g. “Borrow” or “Repay” function) is manipulated and ‘re-entered’ in order to trick a protocol’s contracts into performing the wrong function. For example, one of the most infamous exploits in crypto, The DAO hack in 2016, was a re-entrancy exploit. The hacker exploited a bug in the withdrawal function to ‘withdraw’ all of the assets, before The DAO’s contracts had updated his internal balance. This meant that the hacker could repeatedly ‘loop’ this withdrawal function without the contract realizing that he had withdrawn more ETH than his entire deposit.

Oracle manipulation occurs when a hacker convinces a DeFi protocol to trade or loan its assets at the wrong price, and exploits this in order to drain the protocol of valuable assets at an unfavorable price. For instance, an attacker manipulated Alpha Homora’s contracts in early 2021 in order to drain millions of dollars from Cream’s Iron Bank , which performs protocol to protocol lending. The attacker managed to convince the Alpha Homora contracts to issue sUSD without incurring debt against the protocol. This resulted in the hacker borrowing millions of dollars from the protocol at the wrong price - and enabling them to drain $37M from the Iron Bank.

Iron Bank Exploit Transaction

Since flash loans are completely neutral in how they are performed, the borrower needs only to perform a transaction that makes any kind of profit. On-chain contracts do not distinguish between profit from an arbitrage across trading pools, and a protocol exploit that drains user funds - so attackers will be able to continue to utilize these strategies to hack protocols. The only prevention is for developers to make sure their code is resistant to bugs and exploits before they accept user funds.

HOW DO YOU MAKE MONEY WITH FLASH LOANS?

It is possible to make money with flash loans by finding an arbitrage or profitable action that can be executed in a single block.It is also necessary to include a function to return the flash loan funds in the original transaction. This can potentially be done by creating a custom smart contract that can perform at least three things - the borrow transaction, the arbitrage, and the return of funds.

Of course, the MEV landscape is currently very competitive. In order to seriously compete with the top searchers and arbitrageurs, you will need a direct connection to validators in order to submit your transactions. This is because transactions submitted directly through the mempool can be seen by every participant - and often other MEV participants will be able to see, and frontrun, and profitable strategies you have found. This is why you will frequently see MEV bots ‘bribing’ validators - or including a transaction to send a certain percentage of the profit to validators. This is to ensure that the MEV Bot’s transaction is placed with a higher priority than their competitors, and so they can actually execute and gain the profit from a certain arbitrage opportunity.

Post From MEV-Boost Bot - An X Account That Tracks Large Validator Bribes

Most commonly, flash loans are used to liquidate or manage positions on lending protocols - this is because often, a single lending protocol position may be larger than a MEV Bot’s individual available capital. This means that in order to perform the (profitable) liquidation, the MEV Bot must first borrow capital from a DeFi protocol using a flash loan. Some MEV Bot strategies automatically invoke a flash loan, even if they do not need all of the funds - for instance, one MEV Bot currently running on Ethereum Mainnet will frequently borrow $200M DAI from MakerDAO to perform arbitrage and operations on fund amounts under $100K. This is because there is no extra cost to protocols involved in executing a flash loan, which has driven down the interest on these loans to exactly 0%. MakerDAO currently provides 0% DAI flash loans as a form of public good on Ethereum, allowing traders and arbitrageurs with a large pool of capital to work with when managing DeFi pools and keeping lending positions healthy.

ON-CHAIN ANALYSIS OF FLASH LOANS: CASE STUDIES

CASE STUDY: BEANSTALK FINANCE FLASH LOAN ATTACK

Beanstalk Finance was an on-chain stablecoin protocol that was exploited through a flash loan attack on its governance mechanism. The attacker used flash loans to acquire a sufficient amount of Beanstalk’s governance token, STALK, in order to immediately approve and execute a malicious proposal that would drain the protocol’s assets. Since Beanstalk used an on-chain governance mechanism, it relied entirely upon other users noticing and then voting against a certain proposal. The attacker needed to first wait 7 days before executing their proposal - but in that time, no protocol user checked the code of their contract to examine what it actually did.

The attacker created 2 proposals: Proposal 18 would steal all of the funds in the protocol, and Proposal 19 would donate $250K to Ukraine’s crypto donation address . However - proposal 19 was named Bip18 - in order to trick any reviewers into believing that the 18th proposal would simply donate $250K from the protocol to Ukraine.

Beanstalk Finance Attack Transaction

Once the review period had passed, the attacker was free to execute the real 18th proposal, draining over $180M from Beanstalk’s contracts. In order to do this, they had to first flash loan $1 Billion in various stablecoins from AAVE - then, they used these to buy out the entire quantity of STALK (Beanstalk’s governance token) available on decentralized exchanges. With their accumulated STALK, they could then vote through the malicious proposal, sell off the remaining STALK, and profit over $70M after paying back AAVE’s flash loans. Game over for Beanstalk.

CASE STUDY: EULER FINANCE FLASH LOAN ATTACK

A flash loan strategy was also used by the Euler Finance Attacker in order to drain their protocol of over $200M in March 2023. To date, this is the largest flash loan attack ever. The Euler Exploiter managed to drain almost the entire contents of Euler -held funds by using two accounts to abuse Euler’s liquidation system. One account would incur a massive negative position on Euler by using the “donateToReserves” function - the other account would act as liquidator. ‘donateToReserves’ had a bug that would not check the account health of the address donating its tokens to Euler’s reserves - and thus, a massive negative position could be created using debt-tokens that effectively could not ever be properly liquidated. Because Euler’s contracts didn’t account for this, the attacker could use another account at the same time to ‘liquidate’ the bad debt - effectively liquidating debt against collateral that didn’t exist. Of course, this was quite bad for Euler.

Euler Finance Attack Transaction

The attacker flash loaned millions of dollars of DAI from AAVE to send their accounts across all Euler markets into massive bad debt. When they liquidated it with the second account, they could drain over $200M in total from the protocol, across all of Euler’s different markets - leaving the protocol with a TVL of under $10M.

CONCLUSION

While flash loans can be used for many different reasons, the most common is beneficial maintenance of the DeFi ecosystem - with arbitrage and liquidations going to the MEV bots that can execute the code to manage these positions and pools. High-profile, ‘flash loan attacks’ on protocols are far more rare. Currently, the flash loan ecosystem has matured to the extent that MEV Bots, the most common executors of flash loans, actually have to bid on the opportunities to use them and frequently pay hefty fees to block validators for the privilege of performing arbitrage or liquidations.

0

Disclaimer: The content of this article solely reflects the author's opinion and does not represent the platform in any capacity. This article is not intended to serve as a reference for making investment decisions.

PoolX: Locked for new tokens.
APR up to 10%. Always on, always get airdrop.
Lock now!