Flash Loan Attacks: A Complete Breakdown
Flash loans are both a DeFi innovation and the single largest attack vector. They allow borrowing millions of dollars without collateral, manipulating prices within a single transaction, extracting profit, and repaying the loan — all atomically. The attacker's upfront cost is just the gas fee.
What Is a Flash Loan?
An uncollateralized loan that is borrowed and repaid within the same transaction. If not repaid, the entire transaction reverts. Available on Aave, dYdX, and Uniswap V2/V3.
// Aave V3 Flash Loan interface
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata interestRateModes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
Attack Pattern: Price Oracle Manipulation
1. Borrow a large amount of Token A via flash loan
2. Dump Token A on a DEX → Token A price crashes
3. Target protocol uses the DEX spot price as its oracle
4. Set up collateral or trigger liquidation at the depressed price
5. Profit after price recovery
6. Repay the flash loan
Case 1: bZx (2020, ~$1M)
The first major DeFi flash loan attack. sUSD price was manipulated on Uniswap to take out an overvalued collateral loan.
Attack flow:
- Flash loan 10,000 ETH from dYdX
- Deposit 5,500 ETH as collateral on Compound → borrow 112 WBTC
- Use remaining ETH to open a short position on Fulcrum
- Manipulate price on Uniswap/Kyber
- Realize profit from the short position
- Repay flash loan, keep the profit
Case 2: PancakeBunny (2021, ~$45M)
A BSC-based protocol. PancakeSwap's spot price was used as the oracle, allowing BUNNY token price manipulation.
Root cause: The priceCalculator relied on a single block's AMM spot price. A flash loan momentarily distorted the price, enabling excessive BUNNY minting.
Case 3: Euler Finance (2023, ~$197M)
Combined a flash loan with donateToReserves(). Missing health factor validation allowed creation of an artificial liquidation state.
Attack flow:
- Flash loan DAI from Aave
- Deposit DAI into Euler → mint eDAI
- Borrow additional DAI against eDAI (leverage)
- Call
donateToReserves()to donate eDAI to reserve → create undercollateralized state - Liquidate own position from a separate account → acquire collateral at a discount
- Repay flash loan, keep the profit
Defense 1: TWAP Oracle
Use a Time-Weighted Average Price instead of a single block's spot price.
// Uniswap V3 TWAP Oracle
function consult(address pool, uint32 secondsAgo) external view returns (int24 arithmeticMeanTick) {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondsAgos);
arithmeticMeanTick = int24(
(tickCumulatives[1] - tickCumulatives[0]) / int56(int32(secondsAgo))
);
}
Defense 2: Chainlink Oracle
Use off-chain data feeds instead of on-chain DEX prices. Cannot be manipulated via flash loans.
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
function getPrice() external view returns (uint256) {
(, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
require(block.timestamp - updatedAt < 3600, "Stale price");
return uint256(price);
}
Defense 3: Single-Transaction Restriction
mapping(address => uint256) private _lastActionBlock;
modifier noSameBlockAction() {
require(_lastActionBlock[msg.sender] != block.number, "Same block");
_lastActionBlock[msg.sender] = block.number;
_;
}
Defense 4: Health Factor Validation
Always re-validate the health factor after state-changing functions.
function donateToReserves(uint256 amount) external {
// ... donate logic ...
require(getHealthFactor(msg.sender) >= MIN_HEALTH_FACTOR, "Unhealthy");
}
Checklist
- [ ] Does the price oracle avoid relying on single-block spot prices?
- [ ] Is a manipulation-resistant oracle (TWAP or Chainlink) in use?
- [ ] Are price-dependent operations restricted within the same block?
- [ ] Is the health factor re-validated after state changes?
- [ ] Are there unintended state changes in flash loan callbacks?
Detecting These Issues with ContractScan
Semgrep's single-transaction-price-manipulation and unchecked-oracle-price rules, combined with AI analysis, detect flash loan vulnerability patterns.
→ ContractScan Free Scan
Try ContractScan free at contract-scanner.raccoonworld.xyz
Top comments (0)