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.
🎯 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
📚 Prerequisites
Before this lesson, you should understand:
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
- You: Call
Pool.flashLoanSimple(receiver, asset, amount). - Aave: Transfers
amounttoreceiver. - Aave: Calls
receiver.executeOperation(). - You (inside executeOperation): Do arbitrage. Make profit. Approve repayment.
- Aave (regaining control): Checks
balance >= amount + fee. - 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: 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:
- Borrow: $100M USDC.
- Dump: Buy ETH on Uniswap. ETH price skyrockets on Uniswap.
- Exploit: Another protocol (e.g., Harvest) looks at Uniswap price to determine collateral value. It thinks ETH is worth $1M.
- Drain: Deposit tiny ETH, borrow massive USDC from Harvest.
- 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
- Why can Aave lend you money without checking your credit score?
- What is the “Callback” function?
- If your flash loan profit is negative, what happens?
- Why are flash loans called “One Block Liquidity”?
- How do Time-Weighted Oracles (TWAP) prevent flash loan attacks?
Answers
- Atomic enforcement. They know the transaction cannot end unless they are repaid. A debt default is physically impossible in the EVM.
- executeOperation. The function the lender calls after sending you the money, passing control to your logic.
- Revert. You can’t repay the debt, so the transaction fails. You lose only gas.
- Instant. The capital exists in your hands for the duration of a single transaction execution (sub-block).
- 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