First, you’ll learn the philosophy behind the flash loan. Why do people create flash loans in the first place? What are the use cases of the flash loan? You might have had heard of the flash loan attack if you follow DeFi news closely. What are they? How do hackers use flash loans to hack smart contracts?
Before you’ll learn about the flash loan, you need to refresh your knowledge first about DeFi.
Table of Contents
What is DeFi?
DeFi or Decentralized Finance is a trustless finance system built on top of Ethereum or a similar system to Ethereum like Binance Smart Chain.
Finance here means finance as you understand traditionally. For example, saving accounts, bonds, stocks, loans, interest swap, trading, fundraising.
The difference is the finance in DeFi is decentralized, meaning it can omit the centralized parties completely. The rules of finance in DeFi are enforced by algorithms unlike in traditional finance.
For example: in traditional finance, you can create 100 shares of the company and transfer 20 shares to your friend. The remaining 80 shares belong to you. You enforce this rule with law and company charter.
In DeFi, you create a smart contract that gives 80 shares of the token to you and 20 shares of the token to your friend. The algorithms enforce the condition. You can create a smart contract such that when you transfer the token to someone, you cannot take it back. This is different compared to the traditional application using databases. In that situation, you can reverse the transferring token transaction by manipulating the database. Of course, this hypothetical situation assumes you have access to the web application and its database.
Now, imagine if all of the finance applications run on Ethereum. They are decentralized. So you don’t have to worry about centralized parties. The smart contract is transparent, meaning you can read the code of the smart contracts to make sure the rules are fair.
The transactions on Ethereum are recorded on the blocks linked together like a linked list. One block can have many transactions. One block is built on top of another block.
To know more read our guide to Decentralised Finance.
What is Crypto Lending?
Lending is one of the finance applications. Basically, you provide some assets for people to borrow with an interest. Let’s say the price of 1 ETH (the native currency on the Ethereum) is 100 DAI. You provide 100 token DAI for people to borrow. I have some ETHs and I want to borrow DAI for whatever reasons. So I give 1.5 ETH to borrow 100 token DAI. The 1.5 ETH becomes collateral for the loan. In case, I don’t pay back 100 token DAI with an interest, the smart contract will liquidate the 1.5 ETH.
You can find similar situations in traditional finance. You want to borrow some money from a bank, then you need to provide your house as collateral. In case you don’t pay back your loan, the bank will take your house.
In traditional finance sometimes you can borrow money without collateral but only if you have connections to some influential people or you have good credit.
There is no such thing in the DeFi landscape. But some people are working on the credit rating on Ethereum. So in the future, with your account’s history on Ethereum, perhaps you can borrow some assets.
For example: when you get an airdrop token, you always keep the token at least for a year. So people can see that you have some loyalty. You don’t trade you’re token right away. With this history, maybe some people could lend you some assets without asking for collateral.
There is a risk when you give a loan to someone. A default could occur. People could fail to repay the loan. That’s why most people only give loans with collateral. Undercollateralized loans are not popular because of the default risk.
But what if you could give undercollateralized loans without the risk of default? If the loans happened, they would be guaranteed to succeed. You’d get the interest if people repaid the loan. So it’s a never losing money business.
The way to achieve that is by using flash loans. It’s a loan that you give to people but repaid in the same block. Transactions on Ethereum are written on the block. A block is an atomic unit of the transaction on Ethereum.
How do Collateralized Normal Loans work?
With collateralized normal loans, usually what happens is like this. On block 1009, you borrow some assets, for example, 100 DAI. Of course, you have to provide collateral, for example, 1.5 ETH. Life happens. Block 1010, block 1011, block 1012 happen. You use the loan to do whatever you want. Build a venture, get some profits. Then on block 1013, you repay the loan with an interest. As you can see, the loan extends until 5 blocks.
For example, a complete loan process on protocol XYZ could be described in the image below.
How do Flash Loans work?
With flash loans, all happen in one block. You borrow some assets without collateral. You do things with the borrowed assets. Build a venture. Do stuff. Finally, you repay the loan with an interest. All these things must happen in one block. If you borrow some assets in block 1009, then you need to repay the loan with an interest in the same block. You cannot repay it in the next block, which is block 1010.
If the smart contract providing the flash loans didn’t get the repayment in the same block, then it would abort the transaction. In other words, you fail to get the loan. So you need to do the things you want to do with extra money in the same block you get the loan. That’s a flash loan, which means a quick loan that is short-lived.
But can anything interesting happen in one block? When people think about a loan, they think about this situation. They borrow money. They build a business. They earn profits (hopefully!!!). Life goes by. Then they repay the loan. That takes some time. But there is another kind of loan, which is a short-term loan. You borrowed some money today. You repay the loan the next day. You may be short in cash on the day you borrow some money if you need to pay people to fix the electricity in your house. Then the next day, you get the income from your freelance job so you have money to repay the loan.
But a block on Ethereum lasts only for a short time. Just a couple of minutes. So what can you do with a loan in a short time? Apparently, a lot.
Use Cases of Flash Loans
Sometimes an asset has a different price on different exchanges. For example, 1 YFI is 10 ETH in exchange A, but 1 YFI is 12 ETH in exchange B. There are 10 YFI coins in exchange A. So, technically speaking, you could buy 10 YFI with 10 ETH price in exchange A and sell them with 12 ETH price in exchange B. Then you can pocket the difference which is 20 ETH (2 ETH x 10 coins) as profit (minus transaction fees).
However, to profit from this opportunity, you need to have 100 ETH in the first place. What if you don’t have that amount of money? You might only have 0.5 ETH in your wallet. You could still profit from the arbitrage opportunity. But the profit will be much less. You could only buy 0.05 YFI in exchange A.
But with a flash loan, you could borrow 100 ETH, then buy 10 YFI in exchange A, then sell them on exchange B, repay the loan with an interest, and pocket the difference as profit. All happen in one block. If one of the transactions fails, then every transaction will fail. So you risk nothing except paying gas fees and loan fees. The loan provider risks nothing.
When you want to borrow an asset from a lending protocol, such as Aave or Compound, you have to provide collateral. Let’s take an example. You borrow 100 BAT and provide 2 DAI as collateral. Then one week later, you want to change the collateral. You still want to borrow 100 BAT but you want to use another asset as collateral. For example, you want to use ETH as collateral. Let’s say 100 BAT needs 0.5 ETH as collateral.
You could repay the loan and borrow the same asset with different collateral. But you must do it in many steps. On top of that, you may not have 100 BAT in your hand. Maybe you have spent 100 BAT and you need to wait another week before you get 100 BAT from your activities.
With a flash loan, you could borrow 100 BAT to repay your loan. Then you would get your collateral back, which is 2 DAI. After that, you could store 2 MKR back into your wallet or you could sell them in exchange. Whatever it is, you would provide another collateral, which is ETH to the lending protocol. The result is your borrow position is 100 BAT with 0.5 ETH as collateral.
Imagine you get a loan of 100 BAT with 2 DAI as collateral. The price of 100 BAT is 1 DAI. It means you take a loan with a liquidation ratio of 2. In another word, your collateral is worth two times your loan. Usually, the lending protocol requires over-collateralized loans. The reason is the price of the collateral sometimes changes, caused by changes in the market. Today, the price of 100 BAT is equal to 1 DAI. But tomorrow, the price of 100 BAT could be equal to 1.2 DAI. It means the price of DAI drops relative to the price of BAT. Over-collateralized loans take this issue into account. So that’s why you see some lending protocols require you at least provide collateral which is 1.5 times worth of the loan.
Dropping price of Collateral
But what would happen if the price of the collateral kept dropping until the price of the collateral is worth less than the loan. The lending protocol would liquidate your collateral. Depending on the algorithms of the lending protocol, the lending protocol could auction your collateral with a discount. You also have to pay the liquidation fee.
So you may want to self-liquidate your collateral. You could repay your loan if you still have your 100 BAT. Alas, you may not have the asset in your hand right now but you don’t want to lose all your collateral.
With a flash loan, you could borrow BAT to repay the loan. You get back your collateral, which is DAI. You sell DAI in an exchange and get 100 BAT and repay the flash loan plus some fees. So you still have some DAI left. It’s less than 2 DAI. In this example, we omit the fees to make the calculation simple.
The Obstacles to a Successful Flash Loan
However, there are many obstacles to creating a successful flash loan. It’s not a straight road to profit.
You need to make transaction fees into account when executing arbitrage opportunities with flash loans. An arbitrage opportunity involves buying an asset in one exchange and selling the asset in another exchange. Don’t forget you have to take the flash loan and repay it back. At a minimum, you could have four transactions. It could be more because when selling an asset, you may need to sell them at different prices because of price slippage.
What is Price Slippage?
So you spot an arbitrage opportunity. Asset A is priced at $100 in the exchange X, but it is priced at $120 in the exchange B. So you want to execute this opportunity. You buy 1000 coins of asset A in the exchange X then you want to sell all of them in the exchange B with the price of $120. So you can have a profit of $20,000 ($20 x 1000 coins), right (excluding fees)? Not quite. The bid-ask spread may not support your order. Once you sell 100 coins with the price of $120, the price of asset A could drop to $110. The more you sell the asset, the higher chances the price can drop. By the time you want to sell 900 coins, the price may not be $120 anymore. The price could be $99.
So you have sent your arbitrage transaction with a flash loan and you sit down quietly waiting for your profit. But alas, the same arbitrage transaction has been mined but not your transaction. Someone else front-run you. It means your arbitrage transaction is sent from your computer and sits a while in mempool before getting picked up by a miner. Then a bot notices your transaction and replicates it then sends it to the mempool but with a higher gas fee so the miner will choose their transaction instead of yours.
Flash Loan Attack
However, there are bad actors out there. They will hack the smart contracts and steal the fund. So what does flash loans have to do with this? It gives the hackers steroids. It magnifies their attacks. It multiplies their damage.
On top of that, there are some kinds of attacks that are only possible using flash loans.
Pump and Arbitrage
The idea is you pump the bag using a flash loan, then execute the arbitrage opportunity. Let’s see an example.
You borrow a large amount of ETH from a lending protocol using a flash loan feature. Let’s pluck a number here. You take a 10,000 ETH flash loan.
Then you deposit 5,000 ETH to a lending protocol as collateral to get a loan. This is a normal loan, not a flash loan. With that amount of money, you get 100 token ABC. The price of 1 token ABC is 50 ETH.
Then you use margin trade to short ETH in favour of token ABC. You deposit 1000 ETH and execute margin trading. You get 5000 ETH which is 5 times leverage. Then 5000 ETH is swap with token ABC in a decentralized exchange. Because of low liquidity, the price of the token ABC in that decentralized exchange skyrockets. The price of 1 token ABC becomes 100 ETH now (2x from the previous price, 50 ETH).
Remember that you still have 100 token ABC from your previous loan. You dump them in that decentralized exchange. You get 10,000 ETH. You repay the flash loan. You still have 4000 ETH as profit. You can let the position in the margin trading protocol go default.
You have 200 ABC. You want to borrow 5,000 ETH with 200 ABC as collateral in a lending protocol. In the lending protocol, the price 1 ABC is 50 ETH. So your collateral is 2x of the loan. The price of 100 ABC is 5000 ETH. The rest of ABC (another 100 ABC) becomes pure collateral.
But how does the lending protocol decide the price of 1 ABC is 50 ETH? It checks the price of this pair, ABC/ETH, in a decentralized exchange. But how does a decentralized exchange decide the price of the pair, ABC/ETH? It has a certain formula to calculate the price. It derives the price of the pair from the liquidity of the pair. For example, there is 100 ABC and 5,000 ETH. So the price is 50 ETH for 1 ABC.
Imagine, you take a flash loan of 3,000 ETH from a lending protocol. With this amount of ETH, you buy 60 ABC from the decentralized exchange. So the liquidity in the decentralized exchange for the pair, ABC/ETH, becomes 40 ABC for 5,000 ETH. The price of 1 ABC becomes 125 ETH.
Now, you borrow ETH again from a lending protocol. This time with 200 ABC and 2x leverage, you can get 12,500 ETH. Notice the difference. By using flash loans, you manipulate the oracle price so you can get the cheaper price for ETH.
A reentrancy attack is a callback method of the attacker’s contract being called and called again before the accounting has been settled.
In a smart contract you created, sometimes you want to call an external contract’s method, such as safe transfer from for approval.
But sometimes the attacker could put a hidden call in this external method to do damage to your smart contract.
For example, your smart contract accepts stable coins. If people send some stable coins to your smart contract, your smart contract will mint your own token for the user. But in this method, your smart contract calls an external method called safe transfer from, a standard method for approval in ERC-20 token smart contract. But you forgot to check the address of the smart contract belonging to the approved stable coin smart contracts. So you call safe transfer from on the attacker’s smart contract innocently. Inside this evil method, the smart contract of the attacker mints your own token without your knowing and inflates the value of your own token.
The role of the flash loan is to amplify the damage.
Protocols Supporting Flash Loans
There are some DeFi protocols supporting flash loans. To get a flash loan from any protocol, you need to create a smart contract. You cannot get the flash loan with your own account. The protocol will send the loan to this smart contract. You do the things you want to do with the borrowed money in this smart contract. Once done, you return the loan back with a small fee.
Aave is a lending protocol where you can borrow and lend assets. This is the first DeFi protocol offering flash loans.
To get a flash loan from Aave, you need to execute the flash loan method of the lending pool smart contract. In this method, you give your smart contract’s address, the address of the principal reserve, the amount you want to borrow, and some parameter string that will be passed to your smart contract. Your smart contract must follow some rules to receive the flash loan.
This method sends the fund to your smart contract after making sure it has enough funds in the pool. The method executes the action on your smart contract. Then it checks whether the returned fund with a small fee has been returned or not. If the answer is yes, the method updates the state of the reserves. If things go awry, the method reverts the transaction.
You withdraw any token on Uniswap to your smart contract. You do whatever you want with them. Then you have two options. The first option is you return them with a fee. The second option is you pay Uniswap with the corresponding pair tokens. When you trade tokens in Uniswap, you basically call the same method.
For example, you want to buy DAI with your ETH. The process runs like this. Uniswap gives you DAI first. Then you do nothing with the DAI you got. Finally, you give your ETH to Uniswap as payment for the DAI you got. So normal trading is just a flash loan but you do nothing with the borrowed asset. You just pay them with another token.
DyDx is a decentralized exchange that supports other features, like margin trading among other things. They don’t support flash loans natively, but they have a SoloMargin smart contract. In this smart contract, you can execute many operations. So to execute a flash loan, you just need to execute a withdrawal action, a call function, and a deposit action in one transaction.
The withdrawal action is to borrow a loan. The call function is what you want to do with this borrowed fund. The deposit action is to return the loan.
Flash loan is an innovative feature that can only happen in the DeFi landscape. While it can be used for hacking smart contracts, it can help people do things in finance more efficiently, such as collateral swap, arbitrage trading.
The flash loan mainly is still only available to people with programming skills. But you can borrow money with flash loans using a web application like Furucombo.