critical

Flash Loan Attack: How It Works, Real Exploits & Automated Detection

April 1, 2026
Chainsethereumarbitrumbaseoptimismpolygonbnb-chainavalanche
Detected byslithermythrilechidnahound-ai

Flash loans allow uncollateralized borrowing of any amount, provided the funds are repaid within the same transaction. This mechanism enables attackers to manipulate prices, drain protocols, or execute governance attacks using borrowed capital. Flash loan exploits have cost over $250M, including PancakeBunny ($45M, 2021), bZx ($954K, 2020), and Euler Finance ($197M, 2023). Firepan's HOUND AI detects flash loan vulnerabilities automatically during development and post-deployment monitoring, covering continuous analysis across the full contract lifecycle.

What Is Flash Loan Attack?

Flash loans are atomic, uncollateralized loans that must be repaid in the same transaction. Protocols like Aave and dYdX offer them at near-zero cost. The atomic guarantee (all-or-nothing) was designed to prevent theft—if funds aren't repaid, the entire transaction reverts.

However, flash loans enable state-manipulation attacks:

  1. Attacker borrows massive funds without collateral
  2. Uses borrowed funds to manipulate prices or trigger state changes
  3. Exploits the temporary state inconsistency
  4. Repays the loan (plus fee) within the same transaction
  5. Profits remain with attacker; no theft is apparent

Unlike traditional reentrancy, flash loan attacks don't require multiple transactions or external contracts—a single transaction can drain an entire protocol's reserves if it depends on spot prices.

How Flash Loan Attack Works

Flash loan exploits typically follow the pattern:

  1. Call flash loan function: Attacker calls receiveFlashLoan() on target protocol
  2. Receive massive funds: Attacker receives borrowed amount
  3. Manipulate state: Use borrowed funds to:
    • Swap tokens on DEX to crash price of oracle-dependent token
    • Borrow against inflated collateral value
    • Trigger liquidations at favorable prices
    • Manipulate governance voting
  4. Extract value: Transfer profits to attacker (fees, liquidations, governance changes)
  5. Repay loan: Original borrowed amount + fee repaid, transaction commits
  6. Attacker profits: All value extracted remains, loan is repaid
// VULNERABLE — example only
// Demonstrates: Flash Loan Attack
// Do NOT use in production

pragma solidity ^0.8.0;

interface IFlashLoanReceiver {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external returns (bool);
}

contract VulnerableProtocol is IFlashLoanReceiver {
    mapping(address => uint256) public balances;
    address public priceOracle;  // Uses spot price for collateral

    // VULNERABLE: Uses spot price (manipulable via flash loan)
    function borrow(address token, uint256 amount) public {
        uint256 tokenPrice = PriceOracle(priceOracle).getPrice(token);
        uint256 collateralRequired = (amount * 120) / tokenPrice;  // 120% collateral

        require(balances[msg.sender] >= collateralRequired);
        // Borrow proceeds...
    }

    // Flash loan receiver callback
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        // VULNERABLE: State changes inside flash loan callback
        // Attacker can manipulate price, borrow at inflated collateral, swap, liquidate

        uint256 amountOwed = amount + premium;
        IERC20(asset).approve(msg.sender, amountOwed);
        return true;
    }
}

contract Attacker {
    VulnerableProtocol public target;
    address public flashLoanProvider;  // Aave, dYdX, etc.

    function exploitFlashLoan(address token, uint256 borrowAmount) public {
        // Step 1: Request flash loan
        IFlashLoanProvider(flashLoanProvider).flashLoan(
            address(this),
            token,
            borrowAmount,
            abi.encodeWithSignature(
                "executeOperation(address,uint256,uint256,address,bytes)",
                token,
                borrowAmount,
                0,
                address(this),
                ""
            )
        );
    }

    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external returns (bool) {
        // Step 2: Attacker has 'amount' borrowed funds
        // Swap on DEX to crash price
        uint256 swapAmount = amount / 2;
        IDex(DEX).swap(asset, USDC, swapAmount);  // Crashes price

        // Step 3: Borrow against new "cheap" asset, liquidate, or arbitrage
        target.borrow(asset, amount);  // Borrow at manipulated price

        // Step 4: Liquidate at favorable price
        target.liquidate(attacker_address);  // Collect liquidation bonus

        // Step 5: Repay flash loan
        uint256 amountOwed = amount + premium;
        IERC20(asset).approve(msg.sender, amountOwed);

        return true;  // Transaction succeeds, attacker keeps profit
    }
}

Real-World Flash Loan Attack Exploits

| Protocol | Date | Loss | Root Cause | |----------|------|------|-----------| | PancakeBunny | 2021-05 | $45M | Price oracle manipulation via flash loan swap | | Euler Finance | 2023-03 | $197M | Flash loan to manipulate collateral, liquidate at favorable prices | | bZx (Fulcrum) | 2020-02 | $954K | Oracle price manipulation to trigger liquidations | | Harvest Finance | 2020-10 | $34M | Flash loan to crash stablecoin price, drain yield farm | | Balancer | 2020-08 | $500K | Liquidity pool token price manipulation |

How to Detect Flash Loan Attack

Manual detection focuses on price dependencies and flash loan integration:

  • Price oracle calls: Flag functions that query prices inside flash loan callbacks
  • Flash loan integration: Identify contracts with flashLoan() or receiveFlashLoan() functions
  • State modifications: Confirm no state changes depend on spot price within same transaction
  • Callback logic: Review callback implementations for price-dependent logic
  • Multi-step transactions: Check if complex operations (liquidate, borrow, arbitrage) happen atomically

Red flags:

  • Use of spot DEX price without TWAP or Chainlink oracle
  • State changes that depend on token balance within flash loan callback
  • Liquidation triggers that read current spot price
  • Borrow decisions based on user-supplied price data
  • Single-transaction sequences: borrow → swap → liquidate → repay

How Firepan Detects Flash Loan Attack Automatically

Firepan's HOUND AI performs multi-level analysis:

  1. Flash loan flow mapping: Traces all flashLoan calls and their callbacks
  2. Price source analysis: Identifies price oracle calls and their atomicity
  3. State dependency mapping: Detects state changes that depend on transaction-local values
  4. Transaction simulation: Executes flash loan scenarios with extreme prices to find exploitable paths
  5. Liquidation cascade detection: Identifies sequences where borrowed funds trigger liquidations
  6. Arbitrage path finding: Searches for swap sequences that extract value during flash loan

Firepan's HOUND AI engine detects flash loan exploits across all monitored contracts.

Prevention Best Practices

1. Use Time-Weighted Average Price (TWAP)

Never use spot price for critical calculations. Use Uniswap V3 TWAP:

import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

function getTWAPPrice(address pool, uint32 timeWindow)
    internal view returns (uint256)
{
    (int56[] memory tickCumulatives, ) =
        IUniswapV3Pool(pool).observe(new uint32[](2));
    int56 tickCumulativeDelta = tickCumulatives[1] - tickCumulatives[0];
    int24 timeWeightedTick = int24(tickCumulativeDelta / int56(uint56(timeWindow)));
    return TickMath.getSqrtRatioAtTick(timeWeightedTick);
}

2. Use Chainlink Oracle with Circuit Breaker

Rely on external price feeds with deviation checks:

function getPrice(address token) public view returns (uint256) {
    (, int256 answer, , uint256 updatedAt, ) = priceFeed.latestRoundData();
    require(block.timestamp - updatedAt < 1 hours, "Stale price");
    require(answer > 0, "Invalid price");
    return uint256(answer);
}

3. Separate Flash Loan Callback Logic

Never modify critical state inside flash loan callbacks:

// SECURE: Callbacks don't modify core state
function executeOperation(
    address asset,
    uint256 amount,
    uint256 premium,
    address initiator,
    bytes calldata params
) external override returns (bool) {
    // Only repay; no lending or liquidation logic here
    IERC20(asset).approve(lender, amount + premium);
    return true;
}

4. Whitelist Flash Loan Providers

Only accept flash loans from trusted sources:

mapping(address => bool) public whitelistedFlashLoanProviders;

function executeOperation(...) external override returns (bool) {
    require(whitelistedFlashLoanProviders[msg.sender], "Untrusted provider");
    ...
}

5. Monitor for Flash Loan Attacks Post-Deployment

Track unusual liquidations, swaps, and arbitrage within single transactions. Use Firepan's post-deployment monitoring to detect flash loan attack patterns in mempool.

Frequently Asked Questions

Q: What is flash loan attack in smart contracts?

A: Flash loan attack involves borrowing massive sums without collateral, manipulating prices or state, extracting value, then repaying the loan in a single transaction. The attacker profits while all borrowed funds are repaid, making theft undetectable.


Q: Which protocols have been exploited via flash loan?

A: PancakeBunny ($45M, 2021), Euler Finance ($197M, 2023), and bZx ($954K, 2020) suffered major flash loan attacks. Attackers manipulated oracle prices, triggered liquidations, and arbitraged token prices atomically within single transactions.


Q: How does Firepan detect flash loan attack?

A: Firepan traces flash loan flows, identifies price oracle calls within callbacks, detects state changes dependent on spot prices, simulates extreme price scenarios, and finds liquidation cascades and arbitrage paths that expose flash loan exploitability.


Q: Can flash loan attack be exploited after deployment?

A: Yes. Flash loans are instant; attackers can strike the moment a vulnerable contract is live. They typically target oracle-dependent protocols, liquidation engines, or governance mechanisms. Mempool attacks detect flash loan requests and frontrun them.


Q: How do I prevent flash loan attack?

A: Use Time-Weighted Average Price (TWAP) instead of spot price. Integrate Chainlink Oracle with deviation checks. Avoid state changes within flash loan callbacks. Whitelist flash loan providers. Monitor for unusual liquidation/arbitrage patterns post-deployment.

Conclusion

Flash loans democratized DeFi composability but introduced a new exploit vector: atomic price manipulation. Protocols that depend on spot prices or single-transaction state consistency remain vulnerable. Using Chainlink oracles and Uniswap TWAP, and separating callback logic from critical state changes, greatly reduces flash loan risk. Firepan's HOUND AI detects exploitable flash loan paths across all monitored contracts.

Start securing your smart contracts at https://app.firepan.com/

Firepan

Scan Your Contracts Now

12,453 contracts secured. 2,851 vulnerabilities blocked. 236 exploits prevented. Run a free surface scan — results in minutes, no credit card required.

Run Free Scan →