Skip to content
STAGING — not production

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 v3 charges a protocol-set flash loan premium (historically 0.09% for Aave v2, configurable in v3 — check current docs for the live rate). Balancer offers fee-free flash loans on their own pool liquidity (you only pay 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 via flash loan.
  2. Manipulate: Sell USDC for ETH on Uniswap, pushing ETH’s spot price up dramatically on that pool.
  3. Exploit: A protocol that reads Uniswap spot price for collateral valuation now thinks ETH is worth much more than it is.
  4. Drain: Deposit ETH as collateral, borrow USDC at the inflated valuation.
  5. Clean up: Sell ETH back, restoring spot price. Repay flash loan. Keep the drained USDC.

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 many blocks (common windows: 10-30 minutes). A flash loan affects price for only 1 block (~12 seconds on mainnet), so it moves the TWAP by roughly 1/150th of the window — not enough to exploit.

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.

Want to go deeper?

Weekly infrastructure insights for engineers who build trading systems.

Free forever. Unsubscribe anytime.

You're in. Check your inbox.

Questions about this lesson? Working on related infrastructure?

Let's discuss