AAVE Source Code Analysis: Flash Loans
Flash Loans
A flash loan is a loan that is borrowed and repaid within a single transaction, without collateral. The key is that everything happens inside one transaction. Because repayment happens in the same transaction, no collateral is required. The blockchain can verify whether the repayment amount is greater than or equal to the principal plus interest. If it is not, the whole transaction reverts and all state changes are rolled back. In other words, the borrowed funds are rolled back too, so the lender takes no risk.
Flash loans can also generate meaningful fee income. A single block only lasts a few seconds, yet the protocol can charge 9 basis points. In practice, flash loans are often used with very large position sizes, easily tens or even hundreds of millions of dollars.
Flash loans are one of the most important innovations in DeFi. I am not sure whether AAVE was the first protocol to introduce them, but today many protocols support them. For example:
- Lending protocols such as AAVE and Compound can support flash loans directly or through extensions. AAVE’s default flash-loan fee is 9 basis points.
- Uniswap also enables a flash-loan-like flow during swaps. The pair contract sends you the output tokens first, you use them for your strategy, and then you transfer the input tokens back to the pair. Uniswap does not charge an extra flash-loan fee, only the normal swap fee.
- Some tokens also implement flash-loan functionality using similar ideas. The fee depends on the implementation.
Flash Loan Flow
The flow is roughly:
- Validate the parameters with
ValidationLogic.validateFlashloan. - Calculate the premium and transfer the tokens to the user.
- Call the user contract so it can execute its logic.
- Add the premium and transfer principal plus fee back from the user contract. If the user has collateral, the protocol can also choose to open debt instead.
Who Receives Flash-Loan Revenue?
The answer is: all depositors. After the flash loan finishes, the protocol updates the deposit interest index, which means the premium is ultimately distributed to liquidity providers.
| |
One subtle difference from Uniswap is that in AAVE the final token transfer happens from inside the AAVE contract after the user contract finishes executing. The user contract does not proactively send the tokens back to AAVE.