Flash loans
Suggest an editA flash loan lets a contract borrow any amount of any token without putting up collateral, on the condition that the loan is repaid before the same transaction ends. If the borrower doesn't repay, the entire transaction reverts and the loan effectively never happened.
Atomicity replaces collateral
In normal lending, a borrower posts collateral worth more than the loan. The lender accepts default risk in exchange for keeping that collateral if the borrower disappears. In a flash loan the borrower posts nothing.
The reason it's safe for the lender is that Ethereum transactions are atomic. Every state change inside one transaction either commits together or reverts together. So the lender sends the borrower the funds, gives them control to do whatever they want, then at the end of the call checks that the balance is back, plus a small fee. If it isn't, the lender reverts the transaction, and the principal is still in its pool. The worst case for the lender is that the transaction reverts and it earns no fee.
In code, the provider's side fits in one function:
function flashLoan(address token, uint256 amount, bytes calldata data) external {
uint256 fee = amount * 5 / 10_000;
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(msg.sender, amount);
IFlashLoanReceiver(msg.sender).executeOperation(token, amount, fee, data);
require(IERC20(token).balanceOf(address(this)) >= balanceBefore + fee, "loan not repaid");
}If the borrower sends back less than amount + fee, the require on the last line fails, and the revert also undoes the transfer that sent the loan out.
The borrower implements a callback
A contract that wants to take a flash loan implements a callback function (the exact name depends on the provider: Aave calls it executeOperation, Balancer calls it receiveFlashLoan, Uniswap V3 uses uniswapV3FlashCallback). The contract requests a loan, the provider sends the tokens and immediately calls back into the contract, and the contract has the duration of that callback to do whatever it wants. Before the callback returns, the contract must have approved (or pushed) enough tokens back to the provider to cover the loan plus the fee.
A minimal sketch in Solidity:
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IFlashLoanProvider {
function flashLoan(address token, uint256 amount, bytes calldata data) external;
}
interface IFlashLoanReceiver {
function executeOperation(address token, uint256 amount, uint256 fee, bytes calldata data) external;
}
contract MyArbitrageur is IFlashLoanReceiver {
IFlashLoanProvider public immutable provider;
constructor(IFlashLoanProvider _provider) {
provider = _provider;
}
function startArbitrage(address token, uint256 amount) external {
provider.flashLoan(token, amount, "");
// by the time this returns, the entire arb has executed
}
function executeOperation(address token, uint256 amount, uint256 fee, bytes calldata) external {
require(msg.sender == address(provider), "caller is not the provider");
// 1. we now hold `amount` of token
// 2. do whatever the strategy needs (swaps, calls to other protocols)
// 3. send amount + fee back to the provider
IERC20(token).transfer(msg.sender, amount + fee);
}
}The require at the top of executeOperation lets only the provider in. The function is external and sends amount + fee to whoever calls it, so without the check anyone could call it directly with any amount and take the tokens the contract holds. The provider in this sketch calls back the contract that asked for the loan, so with the check the callback runs only inside a loan that startArbitrage opened. Aave and Balancer take the receiver's address as a parameter, so anyone can open a loan to your contract and the provider still calls it. With them the callback also has to check who opened the loan, which Aave passes in as initiator.
Fees are small: Aave charges 0.05% of the borrowed amount at the time of writing. Balancer charges nothing on its core flash loans, which is one reason it's a popular source. Uniswap V3's flash mechanism charges the regular pool swap fee.
There's no practical cap on the borrowable amount beyond the provider's pool depth. If Aave has $400M of USDC in its lending pool, that's the limit.
Flash loans fund arbitrage, refinancing and liquidations
Flash loans look like a tool for attackers when you first encounter them, but the dominant volume across the major providers is legitimate. It falls into three main categories.
Arbitrage between exchanges. If Uniswap and SushiSwap show different prices for the same pair, someone can profit by buying on the cheaper one and selling on the more expensive one. Without a flash loan they'd need the upfront capital. With a flash loan they can do it from a contract that holds nothing.
Refinancing and collateral swaps. A user has a loan on Aave collateralized by ETH. They want to switch to using staked-ETH as collateral instead. Without a flash loan, they'd have to repay the loan first, which means they need the USDC they don't have. With a flash loan they can do all of it in a single transaction: flash-loan the USDC to repay, withdraw ETH, swap to staked-ETH, redeposit, reborrow, repay the flash loan from the new borrow.
Liquidations. When someone else's loan goes underwater, anyone can liquidate it and take a bounty. Liquidators normally need capital sitting around to repay the bad loan. With a flash loan, they can liquidate any size position without holding capital of their own, and keep the bounty.
Borrowed capital can move a pool's spot price for one transaction
A flash loan can also be used to manipulate something the rest of the system depends on. The most common target is a price oracle that reads from a single AMM pool.
A Uniswap V2 pool's spot price is the ratio of its reserves, as the AMM lesson showed. Any swap moves the ratio, and a big enough swap moves it a lot. Normally this isn't an issue because moving the price means paying a lot of slippage, and any attacker would lose more in slippage than they could gain by exploiting the moved price. But if some other protocol reads that pool's spot price and trusts it as the price of TOKEN, an attacker who can briefly distort the pool's reserves can extract value from the downstream protocol. The flash loan provides the capital needed for the distortion at the cost of its fee.
In the diagram the pool holds 100,000 TOKEN and 1,000,000 USDC, so the spot price is $10. A lending protocol reads that price and lends up to 80% of the collateral's value. The attacker swaps a flash-loaned 1,000,000 USDC into the pool, which leaves the pool with 50,000 TOKEN and 2,000,000 USDC, a spot price of $40. The lending protocol values the attacker's 50,000 TOKEN at $2,000,000 and lends 1,600,000 USDC against them. The attacker repays 1,000,500 USDC to Aave, keeps 599,500 USDC, and never comes back for the collateral. Once arbitrageurs bring the pool back to $10, that collateral is worth $500,000, and the lending protocol is left with about $1.1M of bad debt.
The manipulation was not free. The attacker paid 1,000,000 USDC for tokens worth $500,000 at the real price, so the swap cost them $500,000. Against those tokens they borrowed 1,600,000 USDC, which is $1,100,000 more than the tokens are worth. The difference between the two, about $600,000, is the profit. When the exploit does not need the tokens to stay behind as collateral, the attacker reverses the swap before repaying and recovers most of what they pushed through.
Every attack of this class has the same steps: borrow a large amount, distort a pool, exploit a downstream protocol that trusted the pool's spot price, repay, and keep the difference. bZx was hit this way in February 2020, twice in one week, for combined losses around $1M. Harvest Finance followed later that year at $24M. In total, oracle manipulation enabled by flash loans has cost protocols hundreds of millions of dollars, and the pattern still surfaces on smaller projects with weak oracle designs.
A spot price from one pool was never a safe oracle
The attacker doesn't strictly need a flash loan to manipulate a pool. Anyone with enough capital can do the same attack with their own tokens. The flash loan reduces the barrier from needing $10M of capital to needing only gas and a flash-loan fee.
So a spot price from a single AMM pool was never a safe oracle. Someone with enough capital could always move it, and flash loans made that capital available to anyone. Blocking flash loans is therefore not a defense. The defense is at the oracle layer. Protocols need price signals that can't be moved by a single transaction.
There are three main approaches in production today.
External oracles like Chainlink price feeds. The price is set by off-chain aggregation across many exchanges. A single on-chain swap can't move it. This is the dominant defense.
Time-weighted prices, where the oracle reports an average over a window rather than a spot read. A one-block manipulation contributes only one block's worth of price to the average, which dilutes its impact to near zero. The TWAP lesson covers this in detail.
Multi-source checks, where the protocol consumes two oracles and reverts if they diverge significantly. This catches the case where one of them is wrong or being attacked.
For every value your contract reads from another contract, ask whether someone who can borrow any amount for one transaction could move that value before your contract reads it. If they could, do not lend or pay out against it.