EVMTools

What is a Flash Loan?

Learn what flash loans are, how atomic transactions work, platforms like Aave, use cases including arbitrage, famous flash loan attacks, and Solidity code examples.

Flash loans are one of the most revolutionary innovations in decentralized finance (DeFi). They allow anyone to borrow millions of dollars with zero collateral, as long as the loan is repaid within the same blockchain transaction. If the borrower cannot repay, the entire transaction is reversed as if it never happened. This guide explains how flash loans work technically, the platforms that offer them, legitimate use cases, famous attacks, and includes a simplified Solidity code example.

What is a Flash Loan?

A flash loan is an uncollateralized loan that must be borrowed and repaid within a single atomic transaction on the blockchain. The word "flash" refers to the fact that the loan exists only for the duration of one transaction — typically a few seconds.

In traditional finance, loans require collateral, credit checks, and time. Flash loans eliminate all of these requirements through a clever use of blockchain transaction mechanics. The key property that makes flash loans possible is atomicity: either every step in the transaction succeeds, or the entire transaction reverts. The lending protocol never risks losing funds because non-repayment is literally impossible at the protocol level.

Key insight: Flash loans democratize access to capital. Previously, only well-capitalized traders could execute large arbitrage or liquidation strategies. Flash loans allow anyone with the technical skill to write a smart contract to access millions in liquidity with zero upfront capital.

How Flash Loans Work: Atomic Transactions

Understanding flash loans requires understanding how Ethereum transactions work. Every transaction on Ethereum is atomic: it either completes all its operations successfully, or it reverts entirely (all state changes are rolled back). Flash loans exploit this property:

Flash Loan Execution Flow (single transaction):

  Step 1: Your contract calls flashLoan() on the lending protocol
  Step 2: Protocol transfers the borrowed tokens to your contract
  Step 3: Protocol calls your executeOperation() callback function
  Step 4: Your contract performs actions (arbitrage, swaps, etc.)
  Step 5: Your contract repays the loan + fee to the protocol
  Step 6: Protocol verifies repayment

  If Step 6 fails (loan not fully repaid):
    → The ENTIRE transaction reverts
    → Steps 1-5 are undone as if they never happened
    → Only gas fee for the failed transaction is lost

  Timeline: All steps happen in ONE transaction (~12 seconds block time)
  Cost: Only gas fees + flash loan fee (0.05% on Aave V3)

This atomicity guarantee is what makes flash loans safe for the lender. There is no scenario where the borrower keeps the funds without repaying. The EVM (Ethereum Virtual Machine) enforces this at the protocol level — it is not a trust-based system.

Flash Loan Platforms

Several major DeFi protocols offer flash loan functionality. Each has different fee structures, available assets, and implementation details:

PlatformFeeAvailable LiquidityNotes
Aave V30.05%Billions USDMost popular, multi-chain, supports batch flash loans
Balancer0%Hundreds of millions USDFee-free flash loans from vault liquidity
dYdX~0%Hundreds of millions USDUses "flash actions" with deposit/withdraw pattern
Uniswap V3Pool fee tierBillions USDFlash swaps (borrow one token, repay with either token)
MakerDAO0%DAI supplyFlash mint: create DAI from nothing, must be burned in same tx

Legitimate Flash Loan Use Cases

Flash loans enable several powerful strategies that were previously only available to well-capitalized traders:

Arbitrage

The most common use case. When the price of a token differs between two DEXs, a flash loan can be used to borrow funds, buy on the cheaper exchange, sell on the more expensive one, repay the loan, and pocket the difference. This is a form of MEV extraction that helps equalize prices across markets.

Flash Loan Arbitrage Example:

  1. Flash borrow 1,000,000 USDC from Aave (fee: 0.05% = $500)
  2. Buy ETH on Uniswap at $2,000 per ETH → 500 ETH
  3. Sell 500 ETH on SushiSwap at $2,012 per ETH → 1,006,000 USDC
  4. Repay 1,000,500 USDC to Aave (principal + fee)
  5. Profit: 1,006,000 - 1,000,500 = $5,500 (minus gas ~$50)

  Total risk: only the gas cost if arbitrage is no longer profitable

Collateral Swaps

If you have an open loan on Aave collateralized with ETH but want to switch to WBTC collateral, you would normally need to repay the loan first. With a flash loan, you can do it in a single transaction: borrow enough to repay your loan, withdraw your ETH collateral, swap ETH for WBTC, deposit WBTC as new collateral, re-borrow, and repay the flash loan.

Self-Liquidation

If your lending position is close to liquidation and you do not have funds to repay, a flash loan lets you close or reduce your position before a liquidator takes a 5–10% penalty. Flash borrow enough to repay part of your debt, withdraw freed collateral, swap it to the debt token, repay the flash loan.

Liquidations

Flash loans allow anyone to participate in liquidating undercollateralized positions on lending protocols. The liquidator borrows the required funds via flash loan, repays the undercollateralized borrower's debt, receives the discounted collateral, sells the collateral, and repays the flash loan with profit.

Interest Rate Switching

Move a lending position between protocols to take advantage of better interest rates. Flash borrow to repay Protocol A, withdraw collateral, deposit into Protocol B with a lower rate, borrow from Protocol B, and repay the flash loan.

Simplified Solidity Code Example

Here is a simplified example of a flash loan contract using Aave V3. This demonstrates the basic structure — a real production contract would include additional safety checks and optimizations:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IFlashLoanSimpleReceiver} from "@aave/v3-core/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import {IPoolAddressesProvider} from "@aave/v3-core/contracts/interfaces/IPoolAddressesProvider.sol";
import {IPool} from "@aave/v3-core/contracts/interfaces/IPool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract SimpleFlashLoan is IFlashLoanSimpleReceiver {
    IPool public immutable POOL;

    constructor(address _poolProvider) {
        POOL = IPool(
            IPoolAddressesProvider(_poolProvider).getPool()
        );
    }

    // Step 1: Initiate the flash loan
    function executeFlashLoan(
        address token,
        uint256 amount
    ) external {
        POOL.flashLoanSimple(
            address(this), // receiverAddress
            token,         // asset to borrow
            amount,        // amount to borrow
            "",            // params (passed to callback)
            0              // referralCode
        );
    }

    // Step 2: Aave calls this function after sending you the tokens
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,   // the flash loan fee
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        // ============================================
        // YOUR CUSTOM LOGIC GOES HERE
        // You now have 'amount' of 'asset' tokens
        // Do arbitrage, collateral swaps, etc.
        // ============================================

        // Step 3: Approve repayment (principal + fee)
        uint256 amountOwed = amount + premium;
        IERC20(asset).approve(address(POOL), amountOwed);

        return true; // Signals successful execution
    }
}

Warning: This is a simplified example for educational purposes. Production flash loan contracts require thorough auditing, access controls, slippage protection, and careful handling of edge cases. Never deploy unaudited flash loan contracts with real funds.

Famous Flash Loan Attacks

While flash loans are a legitimate financial tool, they have been used to amplify attacks against vulnerable DeFi protocols. The flash loan itself is not the vulnerability — it merely provides the capital needed to exploit existing bugs or design flaws:

ProtocolDateLossAttack Vector
bZxFeb 2020$1MOracle manipulation via flash loan to manipulate Uniswap price
Harvest FinanceOct 2020$34MRepeated flash loan swaps to manipulate Curve pool prices
Pancake BunnyMay 2021$45MFlash loan used to inflate BNB price in PancakeSwap pool
Cream FinanceOct 2021$130MFlash loan to manipulate oracle pricing of yUSD collateral
Euler FinanceMar 2023$197MFlash loan exploited a donation-based accounting flaw

Anatomy of a Flash Loan Attack

Most flash loan attacks follow a common pattern:

Typical Flash Loan Attack Pattern:

  1. Flash borrow a large amount (e.g., $50M USDC)
  2. Use borrowed funds to manipulate an on-chain price oracle
     - Large swap on a DEX to move the spot price
     - Deposit into a pool to change reserve ratios
  3. Interact with a vulnerable protocol that reads the manipulated price
     - Borrow against inflated collateral value
     - Trigger a liquidation at a favorable price
     - Mint tokens at an incorrect exchange rate
  4. Reverse the price manipulation
  5. Repay the flash loan
  6. Keep the extracted profit

  The root cause is NEVER the flash loan itself.
  It is always a vulnerability in the target protocol:
  - Using on-chain spot prices as oracles (instead of Chainlink/TWAP)
  - Lack of reentrancy guards
  - Incorrect accounting logic

Risks and Defenses Against Flash Loan Attacks

For Protocol Developers

If you are building a smart contract that handles value, these defenses protect against flash loan-based exploits:

  • Use decentralized oracles: Never use on-chain spot prices (like Uniswap reserves) as price feeds. Use Chainlink price feeds or time-weighted average prices (TWAPs) that are resistant to single-transaction manipulation.
  • Add reentrancy guards: Use OpenZeppelin's ReentrancyGuard to prevent contracts from being called recursively within a single transaction.
  • Implement delay mechanisms: Require actions to span multiple blocks. If a price must be sampled across multiple blocks, flash loans (which operate within one block) cannot manipulate it.
  • Validate economic invariants: Check that key economic properties (like collateral ratios, total supply, reserve balances) remain valid before and after critical operations.
  • Audit thoroughly: Get multiple independent security audits and run formal verification where possible. Use established libraries and patterns.

For Users

  • Use protocols that have been audited and battle-tested with significant TVL over time.
  • Check if the protocol uses reliable oracle solutions like Chainlink rather than on-chain spot prices.
  • Monitor protocol governance for security-related proposals and risk parameter changes.
  • Diversify across multiple protocols to limit exposure to any single vulnerability.

Flash Loans vs Traditional Loans

FeatureTraditional LoanDeFi Collateralized LoanFlash Loan
CollateralRequired (property, assets)Required (150%+ crypto)None
Credit checkRequiredNoneNone
DurationMonths to yearsIndefinite (until liquidated)One transaction (~12 seconds)
Max amountBased on creditworthinessBased on collateral valueUp to total pool liquidity
Lender riskDefault riskSmart contract riskZero (atomic repayment)
Technical skillNone requiredBasic wallet usageSolidity/smart contract development

Frequently Asked Questions

Are flash loans free?

Flash loans are not entirely free. While they require no collateral, most platforms charge a small fee. Aave charges 0.05% on V3 flash loans. Balancer flash loans are currently fee-free. You also pay gas fees for the transaction, which can be significant on Ethereum mainnet due to the complexity of flash loan transactions.

Can anyone use flash loans?

Flash loans require writing or interacting with smart contracts, so they are primarily accessible to developers. You cannot use a flash loan through a normal wallet interface like MetaMask. However, platforms like Furucombo and DeFi Saver provide no-code interfaces that let non-developers execute flash loan strategies through a drag-and-drop interface.

What happens if a flash loan cannot be repaid?

If a flash loan cannot be repaid within the same transaction, the entire transaction reverts. Everything that happened in the transaction is undone as if it never occurred. No funds are lost except the gas fee for the failed transaction. This atomic property is what makes flash loans possible without collateral.

Are flash loan attacks illegal?

The legality of flash loan attacks is a gray area. The flash loan itself is a legitimate tool. However, using it to exploit vulnerabilities in protocols could potentially be considered unauthorized access or manipulation depending on the jurisdiction. Some attackers have been prosecuted, while others remain anonymous. Bug bounty programs offer legal alternatives for discovering vulnerabilities.

How much can you borrow with a flash loan?

You can borrow up to the total available liquidity in the lending pool. On Aave V3, this can be hundreds of millions or even billions of dollars worth of assets. The only limiting factor is the available liquidity at the moment of the transaction.

Build with Smart Contracts

Flash loans require smart contract development skills. Learn the fundamentals in our What is a Smart Contract? guide, and use our ABI Encoder / Decoder to encode calldata for your flash loan contract interactions.

Related Tools & Guides