Back to blogs
Written by
Patrick Collins
Published on
October 3, 2024

Flash Loans: Everything You Need To Know

Flash loans are unique financial products, only available in DeFi. This blog post will teach you what a flash loan is, how it works, and what it can be used for.

Table of Contents

A flash loan is an uncollateralized loan of where the borrower has to pay back the assets within the same transaction on a blockchain.

Or, described in a more juvenile way: a flash loan allows you to borrow a million dollars so long as you give it back immediately.

Abstract iIllustration describing how a flash loan works on in a very general, humorous way.
Sample flash loan if done in real life.

In the context of the real world, this seems rather silly. However, smart contracts enable these types of loans to be used to accomplish a lot. In this article, we will describe:

  1. What is a flash loan?
  2. How flash loans work
  3. How flash loans are used / What are flash loans used for
  4. How you can use them, with code examples
  5. Security considerations of flash loans

What is a flash loan?

Flash loans are unsecured (uncollateralized) loans where a borrower must repay their entire loan back to a lender in the same transaction. They are unique financial products, only available in the DeFi world because smart contracts can force a user to pay the loan back immediately. In contrast, no such primitive exists in traditional finance. DeFi protocols like Aave and DyDx support flash loans. People believe protocols like MakerDAO and Uniswap support flash loans too, but technically, they are “flash mints,” which are very similar.

It’s easier to understand flash loans by understanding how they work. Let's dive in.

How does a flash loan work?

Diagram illustrating the mechanics of a flash loan including the deposit, the contract, asset movement, fee, and contract.
High level diagram of flash loan mechanics.

The mechanics are pretty straightforward. Here is an example of a flash loan of USDC (a dollar-pegged stablecoin), end to end:

  1. A lender (Whale, in the above image) decides they want to lend $1,000 USDC.
    1. They deposit their $1,000 in a smart contract that has the code for flash loans.
    2. They have heard that every time someone uses their money in a flash loan, they get paid, and they want to get paid.
  2. A user (MetaMask, in the above image) decides they want to take out a flash loan (see below for why).
  3. In a single transaction, the user (MetaMask) calls a flashloan function on the smart contract, which executes the following actions  either “all at once” or “none at all”:
    1. The user (Metamask) is given $1,000 USDC
    2. They do whatever they want with it (again, STILL IN THE SAME TRANSACTION)
    3. Then, they repay the $1,000 + a small fee

And that’s it.

Atomic transactions

All blockchain transactions are atomic and so-called because either all of it happens or none of it does. This property also applies to flashloans, where all flash loans are atomic. Atomic, in this context, means that if the user doesn’t repay the loan right away, they never got the loan in the first place.

Sounds like magic, right? Let’s take a look at some pseudo-Solidity code to explain it.

function flashLoan(uint256 amount) external {
        uint256 balanceBefore = token.balanceOf(address(this));

        token.transfer(msg.sender, amount);
        // Ignore IFlashLoanReceiver for this pseudo-code
        IFlashLoanReceiver(msg.sender).execute();

        if (token.balanceOf(address(this)) < balanceBefore) {
            revert RepayFailed();
        }
    }

A user calling a flashloan function will essentially call a function that looks like this in a smart contract. If the code hits the revert line, the whole transaction won’t succeed or finalize, meaning the user never borrowed the money in the first place!

Smart contracts work like this: anytime a revert statement is hit, the blockchain automatically reverts all state changes to the blockchain directly from the transaction back to its original state.

  • Did you print yourself $1,000,000,000 but hit a revert line? → You printed nothing
  • You made the trade of a lifetime but hit a revert? → You are not Keith Gill
  • You sent your long-lost relative an on-chain message, finally reconnecting after years of being estranged, and this was the only shot you had, but hit a revert? → Tragedy loves company

Flash loan EIP-3156 - getting technical

To get even more technical, most of the EVM community follows the EIP-3156 standard for supporting flash loan functionality. Where the most important function in a flash loan compatible contract looks like this:

  /**
     * @dev Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);

Typically, an externally owned wallet (aka, a non-smart contract wallet, aka Metamask in our images) won’t be the receiver in such a function call. Instead, the flash loan contract will send the borrowed tokens to another smart contract, which typically has the functionality to “do” stuff.

Diagram of a flash loan and how it interacts with the core contract, the receiver's contract, and replayment.
Diagram of flash loan interactions.

Below, we will expand on this for what the User's receiver contract might do.

How are flash loans used? What are they for?

In practice, flash loans are often used for reasons similar to what regular loans are used for. The most common is to “gain leverage” or capital for opportunities like:

  1. Arbitrage
  2. Liquidation
  3. Collateral swaps
  4. Other MEV

We won’t go over all these, though we do recommend you look deeper into each of them. We will explain flash loan arbitrage since it’s one of the most powerful visualizers of flash loan use.

What is arbitrage?

Arbitrage is a financial strategy that takes advantage of price differences of the same asset in different markets. Imagine eBay and Amazon (online resellers) sell apples for $5, while Alibaba (another online reseller) sells them for $1. If you have $100, what would be an easy way to make money?

  1. Buy 100 apples on Alibaba ($1 per apple * 100 apples = $100 cost)
  2. Sell those 100 apples on eBay and Amazon (100 apples * $5 per apple = $500 profit)
  3. You just made $400! ($500 profit - $100 cost)

This type of financial strategy exists in almost every market in the world, but profit margins are often very slim.

In DeFi, such opportunities exist on decentralized exchanges like Uniswap.

Diagram illustrating how arbitrage works.
Diagram illustrating how arbitrage works.

Now, let’s take this same scenario with the $1 and $5 apples. We only spent $100 buying apples since that’s all we had, but if we had more money, we could have made a bigger profit. And this is where flash loans come in.

Flash loan arbitrage

Let’s run through the above scenario again, but imagine we can do it after taking out a flash loan first.

  1. We borrow $1,000 from a flash loan contract and start the transaction.
    1. Remember, we have to pay it back in the same transaction!
    2. So, in the same transaction, we used $1,000 to buy 1,000 apples from Alibaba.
    3. We then immediately sell those 1,000 apples for $5,000 on Amazon and eBay, making $5,000!
    4. Then, we repay the original $1,000 we took out in a flash loan. Since the loan is  paid back, the transaction won’t revert! (Typically, you also have to pay a small fee, maybe $1.)
  2. Finally, the transaction is over, and we netted $4,000 (minus the small fee) instead of $400!
    1. $5,000 in sales - $1,000 loan paid back to the flash loan contract
  3. And we did this all without having money ourselves!

This is the power of a flash loan. Anyone, with no collateral, can exploit arbitrage opportunities.

Diagram illustrating how arbitrage works with flash loans.
Example arbitrage via flash loans from the Cyfrin Updraft flash loan security curriculum

Note from Patrick

One of the things I love about flash loans is that they equalize the financial playing field. If a small investor, or you at home reading this, find an amazing arbitrage opportunity in traditional finance, they will never do as well as a well-capitalized institution since the institution has more funds! But in DeFi, since flash loans exist, everyone has access to the same resources as a massive hedge fund! For a single transaction, anyway.

How you can use a flash loan

To use a flash loan, you must:

  1. Find a smart contract that is flash loan compatible and has liquidity (aka tokens) in it. These can typically be found on platforms like Aave, dydx, and others,
  2. Build a receiver contact to execute whatever you want during the flash loan
  3. Make sure your receiver pays back the full loan amount at the end.

In the Cyfrin Updraft Security and Auditing curriculum, we go over flash loans and how to use them since they are crucial to understanding price oracle manipulation attacks (more on that later).

To run a flash loan test script using Foundry and see how it works end to end, you can take this test here, and then run:

forge test --mt testFlashLoanBreaksIt

This specific example will also show you a flash loan being used to exploit a security vulnerability!

Security considerations

Flash loans are one of the most important considerations DeFi developers need to address when designing projects.

A flash loan is simply a tool/mechanism to exploit a gap in a codebase, where that gap historically was only exploitable by rich users/whales. Since flash loans really “temporarily make you rich,” they make it easier for less well-capitalized users to exploit a hole where traditionally only a rich person could.

One of the common attack vectors involving flash loans is a “price oracle manipulation” attack. This is when a protocol uses an exchange’s liquidity to determine the price of an asset, and a flash loan crashes the price. You can read more about these attacks in our article here.

Often, people mistakenly classify exploits as “Flash Loan Attacks,” when often they would be more accurately classified as “Price Oracle Manipulation.”

Typically, as a protocol or smart contract, defending against such attacks is as simple as not using a decentralized exchange to get your pricing information!

Summary

Flash loans are one of the most powerful and fantastic tools for investors, and they are only possible in the smart contract world. They involve temporarily taking out a loan without collateral, credit, or KYC as long as it's atomically paid back thein the exact same transaction. Flash loans are a tool that can be  used for arbitrage, liquidations, collateral swaps, and other MEV opportunities. When designing a protocol, be sure to keep flash loans in mind, or risk being exploited!

Secure your protocol today

Join some of the biggest protocols and companies in creating a better internet. Our security researchers will help you throughout the whole process.
Stay on the bleeding edge of security
Carefully crafted, short smart contract security tips and news freshly delivered every week.