Flash Loan Attack

Flash loans are a legitimate DeFi primitive that let users borrow any amount of assets without collateral, provided the loan is repaid within the same transaction. Attackers abuse them to amplify the economic impact of other vulnerabilities — particularly price oracle manipulation.

How it works

In a single atomic transaction, an attacker:

  1. Borrows a massive sum via a flash loan (e.g., from Aave or dYdX).
  2. Uses the borrowed funds to manipulate a price oracle or exploit a protocol.
  3. Profits from the manipulated state.
  4. Repays the flash loan plus a small fee.

If any step fails, the entire transaction reverts — making flash loans risk-free for the attacker.

Vulnerable scenario

// Contract uses a single DEX spot price as an oracle — VULNERABLE
function getPrice() public view returns (uint) {
    return dex.getReserveA() / dex.getReserveB();  // easily manipulated
}

function borrow(uint amount) public {
    require(getPrice() >= MIN_COLLATERAL_RATIO);
    // Attacker manipulates dex price before calling this
    _mint(msg.sender, amount);
}

Safe pattern

// Use a time-weighted average price (TWAP) oracle
import "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";

function getPrice() public view returns (uint) {
    (int24 tick,) = OracleLibrary.consult(pool, 1800);  // 30-min TWAP
    return OracleLibrary.getQuoteAtTick(tick, 1e18, tokenA, tokenB);
}

Real-world exploits

  • bZx (2020) — two attacks netting ~$1 million using flash loans to manipulate margin positions.
  • Harvest Finance (2020) — $34 million drained by flash-loan-driven USDC/USDT price manipulation.
  • Cream Finance (2021) — $130 million taken using a complex flash loan and price oracle exploit.

How to prevent it

  • Never use spot prices from a single DEX as an oracle — use Chainlink or Uniswap V3 TWAPs.
  • Add slippage and sanity checks around price-sensitive operations.
  • Consider adding a block.number check to prevent same-block oracle reads after large swaps.
← Back to Glossary