A flash loan is an uncollateralised loan that is borrowed and repaid inside a single transaction. The lending contract sends you the tokens, calls a function on your contract, then checks it has been repaid plus a fee; if not, it reverts and the whole transaction is undone as if the loan never happened. The lender takes no credit risk, so anyone can borrow millions for the cost of gas and a small fee. A flash loan attack isn't a bug in the loan itself: the attacker uses the borrowed capital to exploit a protocol that assumed moving a price, a vote or an exchange rate would be too expensive, then repays the loan in the same transaction and keeps the profit.
How does a flash loan work?
On Ethereum and other EVM chains, a transaction either completes entirely or reverts entirely. Flash loans rely on that atomicity:
- Your contract calls the lender's
flashLoanfunction with an asset and amount. - The lender transfers the tokens to your contract.
- The lender calls a callback on your contract, such as Aave's
executeOperationor ERC-3156'sonFlashLoan. - Your code uses the funds: an arbitrage, a liquidation, a collateral swap.
- The lender pulls back the principal plus fee and checks its balance. If it's short, it reverts.
Here's a minimal Aave v3 receiver:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
interface IPool {
function flashLoanSimple(
address receiverAddress,
address asset,
uint256 amount,
bytes calldata params,
uint16 referralCode
) external;
}
contract FlashBorrower {
using SafeERC20 for IERC20;
IPool public immutable pool;
address public immutable owner;
constructor(IPool _pool) {
pool = _pool;
owner = msg.sender;
}
function start(address asset, uint256 amount, bytes calldata params) external {
require(msg.sender == owner, "not owner");
pool.flashLoanSimple(address(this), asset, amount, params, 0);
}
function executeOperation(
address asset,
uint256 amount,
uint256 premium,
address initiator,
bytes calldata params
) external returns (bool) {
require(msg.sender == address(pool), "caller is not the pool");
require(initiator == address(this), "untrusted initiator");
// Use `amount` of `asset` here, decoded from `params`.
// The pool pulls amount + premium with transferFrom after we return.
IERC20(asset).forceApprove(address(pool), amount + premium);
return true;
}
}
The two require checks in the callback matter. Anyone can call flashLoanSimple naming your contract as the receiver, and anyone can call executeOperation directly. Receivers that skip these checks, and that hold tokens or standing token approvals, have been drained by strangers triggering their logic with crafted params.
Where do flash loans come from?
| Source | Interface | Fee |
|---|---|---|
| Aave v3 | flashLoan / flashLoanSimple, callback executeOperation | Premium set by governance; read FLASHLOAN_PREMIUM_TOTAL |
| Balancer Vault | flashLoan, callback receiveFlashLoan | Governance-set, often zero |
| Uniswap v2 | Flash swap: swap with non-empty data, callback uniswapV2Call | Normal 0.3% swap fee |
| Uniswap v3 | flash, callback uniswapV3FlashCallback | Pool's fee tier |
| Uniswap v4 | Flash accounting: borrow inside unlock, settle deltas before it returns | None beyond settling |
| ERC-3156 lenders | flashLoan, callback onFlashLoan returning keccak256("ERC3156FlashBorrower.onFlashLoan") | Lender-defined |
Flash mints (e.g. OpenZeppelin ERC20FlashMint) | Token mints the loan and burns it on repayment | Token-defined |
ERC-3156 standardises the interface so a borrower can switch lenders without new code.
Legitimate uses are common. Liquidation bots borrow the debt asset, repay an unhealthy position, receive discounted collateral and sell it, all without holding inventory. Users swap collateral or move a loan between protocols in one transaction. Arbitrageurs close price gaps between pools, which is a large part of the MEV that searchers compete for.
What is a flash loan attack?
Flash loans remove the capital barrier. Any state that a single transaction can create, an attacker can now create for the price of a fee. Protocols that were safe only because "nobody has that much money" stop being safe. The attacks fall into a few patterns.
Spot price manipulation
The most common pattern. A lending protocol values collateral using the current reserves of an AMM pool:
// Vulnerable: anyone can move this within one transaction.
function collateralPrice() public view returns (uint256) {
(uint112 r0, uint112 r1, ) = pair.getReserves();
return (uint256(r1) * 1e18) / r0;
}
The attack:
- Flash-borrow a large amount of WETH.
- Buy the collateral token from the thin pool the protocol reads. Its spot price jumps.
- Deposit some of the token as collateral, valued at the inflated price.
- Borrow far more than the collateral is really worth.
- Sell the token back, restoring the price, and repay the flash loan.
- Keep the excess borrowed funds. The protocol is left with bad debt.
Early DeFi incidents such as the bZx attacks in February 2020 followed this shape, and so have many since, including vaults that priced their shares from a Curve or Uniswap pool's current state.
Governance with current-balance voting
If voting power is the token balance at the moment of voting, and proposals can execute immediately, an attacker can borrow enough tokens to pass a proposal and execute it in one transaction. The Beanstalk exploit in April 2022 worked this way: the attacker borrowed enough to reach a supermajority, used an emergency execution path to pass a proposal that sent the protocol's funds to themselves, and repaid the loans.
Accounting bugs at scale
Some bugs only pay off with large amounts. Euler Finance was exploited in March 2023 through a donateToReserves function that reduced a position's collateral without checking its health afterwards. The attacker used a flash loan to build a large leveraged position, donated to make it insolvent, then liquidated it through a second contract at a discount. The flash loan was the funding; the missing health check was the bug. Exchange-rate rounding in vaults, where share prices are computed from balanceOf(address(this)) and can be inflated by donations, is another member of this family.
Amplifying other bugs
Reentrancy, missing access control and faulty callbacks become worse with unlimited capital. A bug that would leak a few dollars per call with a small balance can drain a pool when the attacker controls a nine-figure position for one block. If your contract makes external calls mid-update, start with how to prevent reentrancy in Solidity.
How do I protect a protocol against flash loan attacks?
Design as if every attacker has unlimited capital for one transaction. Flash loans aren't the only source of it: whales and other protocols' liquidity can do the same.
- Never price from spot reserves. Use an oracle that a single transaction can't move, such as a Chainlink feed with staleness checks (see reading a Chainlink price feed safely) or a time-weighted average price over a long enough window. A TWAP over a few blocks is still movable by someone who controls consecutive blocks, so match the window to the value at risk.
- Snapshot voting power in the past. OpenZeppelin's
ERC20VotesandGovernorcount votes at the proposal's snapshot block withgetPastVotes, so tokens borrowed after the proposal is created carry no weight. Add a voting delay and a timelock before execution. - Track balances internally. Don't derive exchange rates or share prices from
balanceOf(address(this)), which anyone can increase by sending tokens. - Check health on every path. Any function that changes a position's collateral or debt must re-check solvency, including rarely used ones like donations or migrations.
- Don't rely on "same block" detection. Blocking
tx.origin != msg.senderor same-block deposit and withdrawal is easy to bypass and breaks smart wallets. Fix the assumption instead. - Secure your own receivers. Check
msg.senderandinitiator, hold no idle balances or approvals in the receiver, and approve exactlyamount + premium.
How do I test for it?
You don't need a real flash loan in tests. In a Foundry fork test, deal gives an attacker any balance, which is equivalent for the duration of a transaction:
function test_CollateralPriceResistsLargeSwap() public {
uint256 priceBefore = lending.collateralPrice();
deal(address(weth), attacker, 50_000 ether); // stand-in for a flash loan
vm.startPrank(attacker);
weth.approve(address(router), type(uint256).max);
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(token);
router.swapExactTokensForTokens(50_000 ether, 0, path, attacker, block.timestamp);
vm.stopPrank();
// The protocol's price must not follow the pool within one transaction.
assertApproxEqRel(lending.collateralPrice(), priceBefore, 0.01e18);
}
Better still, give an invariant-test handler an "attacker" actor with a huge balance and let the fuzzer search for sequences that break solvency. Fuzz and invariant tests in Foundry shows how to set up handlers and ghost variables for exactly this.
Checklist
- Assume one transaction can borrow any amount the market holds.
- Price assets from manipulation-resistant oracles, never from current pool reserves.
- Count governance votes at a past snapshot, and delay execution with a timelock.
- Keep internal accounting; don't trust
balanceOf(address(this))for rates. - Re-check position health on every function that changes collateral or debt.
- In flash loan receivers, verify the caller and initiator, and approve only what's owed.
- Test with
deal-funded attackers and invariant handlers before an auditor does it for you.
Get the weekly commit
New blockchain deep dives every week.