Flash Loans: The Physics of Atomic Credit

Borrowing $1 Billion for 12 seconds. How atomic transactions enable uncollateralized lending and why if you fail, it never happened.

Intermediate 45 min read Expert Version →

🎯 What You'll Learn

  • Deconstruct the 'Atomic Transaction' lifecycle
  • Implement an Aave V3 FlashLoan Receiver
  • Calculate the profitability threshold of a flash arb
  • Analyze the 'Time Travel' property of EVM Reverts
  • Trace an Oracle Manipulation attack vector

Introduction

In the physical world, credit requires trust (Credit Score) or enforcement (Collateral). In the EVM, credit requires Atomicity.

A Flash Loan is not a loan. It is a conditional state transition.

  • Condition: “If the balance of the lending pool returns to X + Fee by the end of the transaction…”
  • Result: “…then the transaction makes it into the history books.”
  • Else: “…the universe resets (Revert).”

This allows anyone with 0 net worth to act as a whale for 1 block.


The Physics: Atomicity & Callbacks

The magic happens in the Callback. You don’t “request” money and get it later. You request money, and the lender calls a function on your contract giving you the money.

The Aave V3 Flow

  1. You: Call Pool.flashLoanSimple(receiver, asset, amount).
  2. Aave: Transfers amount to receiver.
  3. Aave: Calls receiver.executeOperation().
  4. You (inside executeOperation): Do arbitrage. Make profit. Approve repayment.
  5. Aave (regaining control): Checks balance >= amount + fee.
  6. EVM: If check fails -> REVERT.

Visualizing the Revert

If step 5 fails, the EVM unwinds the stack. It is as if Step 1 never happened. You never borrowed the money. The arbitrage never executed. The gas is spent, but the state is unchanged.


Code: Writing a Receiver

To receive a flash loan, you must implement a specific interface.

import {FlashLoanSimpleReceiverBase} from "@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import {IERC20} from "@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20.sol";

contract FlashArb is FlashLoanSimpleReceiverBase {
    constructor(IPoolAddressesProvider provider)
        FlashLoanSimpleReceiverBase(provider) {}

    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        
        // 1. We have the money now!
        // Logic: Buy on Uniswap, Sell on Sushiswap
        uint256 amountBought = swapUniswap(asset, amount);
        uint256 finalAsset = swapSushi(amountBought);

        // 2. Calculate debt
        uint256 amountOwed = amount + premium;
        require(finalAsset >= amountOwed, "Arb failed");

        // 3. Approve repayment (Pool will pull funds after this returns)
        IERC20(asset).approve(address(POOL), amountOwed);

        return true;
    }

    function requestFlashLoan(address asset, uint256 amount) external {
        POOL.flashLoanSimple(address(this), asset, amount, "", 0);
    }
}

The Safety Mechanism: Notice require(finalAsset >= amountOwed). We strictly check our own profitability. If we aren’t profitable, we choose to revert, cancelling the debt.


Economics: The Cost of Capital

Flash loans are not free. Aave charges 0.05% - 0.09%. Startups like Balancer offer 0% flash loans (paying only gas).

The Arb Equation

For a flash loan to be valid: ΔPrice>(Feeloan+Feeswap1+Feeswap2+Gas)\Delta Price > (Fee_{loan} + Fee_{swap1} + Fee_{swap2} + Gas) Since DEX fees are usually 0.3%, you need a price discrepancy of > 0.7% just to break even using Aave.


Deep Dive: Weaponized Capital (Attacks)

Flash loans allow hackers to scale attacks.

Oracle Manipulation:

  1. Borrow: $100M USDC.
  2. Dump: Buy ETH on Uniswap. ETH price skyrockets on Uniswap.
  3. Exploit: Another protocol (e.g., Harvest) looks at Uniswap price to determine collateral value. It thinks ETH is worth $1M.
  4. Drain: Deposit tiny ETH, borrow massive USDC from Harvest.
  5. Clean up: Sell ETH back on Uniswap, repay flash loan.

Defense: Never use a Spot Price Oracle (Uniswap spot). Use Time-Weighted Average Price (TWAP) or Chainlink.


Practice Exercises

Exercise 1: The Fee Limit (Beginner)

Scenario: You find an arbitrage opportunity of 0.04% spread. Task: Can you execute this using Aave (0.05% fee)? What about Balancer (0% fee)?

Exercise 2: Revert Logic (Intermediate)

Scenario: Your arbitrage logic successfully buys the token but fails to sell it (slippage too high). Task: What happens when the callback returns? Does the Aave contract get its money back? (Hint: The transferFrom in Aave will fail).

Exercise 3: Code Interaction (Advanced)

Task: Write a foundry test that forks Mainnet, borrows 1000 USDC from Aave, and prints the balance validation in the console.


Knowledge Check

  1. Why can Aave lend you money without checking your credit score?
  2. What is the “Callback” function?
  3. If your flash loan profit is negative, what happens?
  4. Why are flash loans called “One Block Liquidity”?
  5. How do Time-Weighted Oracles (TWAP) prevent flash loan attacks?
Answers
  1. Atomic enforcement. They know the transaction cannot end unless they are repaid. A debt default is physically impossible in the EVM.
  2. executeOperation. The function the lender calls after sending you the money, passing control to your logic.
  3. Revert. You can’t repay the debt, so the transaction fails. You lose only gas.
  4. Instant. The capital exists in your hands for the duration of a single transaction execution (sub-block).
  5. Time Buffering. TWAPs average price over 30 mins. A flash loan affects price for only 1 block (12 seconds), so it barely moves the TWAP.

Summary

  • Flash Loans: Are not loans. They are atomic state transitions requiring solvent end-states.
  • Utility: Democratizes capital. Anyone can act like a whale.
  • Risk: Weaponizes attacks. Anyone can crash a market.

Questions about this lesson? Working on related infrastructure?

Let's discuss