Flash Loans Attacks

Smart Contract Vulnerability Deep Dive

JohnnyTime
JohnnyTime · Updated June 22, 2026
23 min read
Total Stolen $1,844,849,894
Last Attack Jun 15, 2026
Latest Victim Thetanuts Finance

Summarize with AI

Flash Loan Attacks Explained: The $500M DeFi Exploit (And How to Prevent It)

Imagine being able to borrow $100 million from a bank, manipulate a stock price, pocket the profits, and return the original money - all before the banker even blinks.

Sounds like a Hollywood heist movie, right? In decentralized finance (DeFi), it’s just another Tuesday.

Flash loans have become the ultimate weapon of choice for sophisticated Web3 hackers. In fact, over $500 million has been stolen through flash loan exploits, including the devastating $197 million Euler Finance attack. If you're building smart contracts, understanding this vulnerability isn't optional - it's a survival requirement.

In this definitive guide to smart contract security, we’ll break down exactly how DeFi flash loan attacks work, examine real-world exploits layer by layer, and show you the exact code you need to prevent them and keep your users' funds safe.


What Exactly Is a Flash Loan Attack?

A flash loan attack (often called a flash loan exploit) is a sophisticated DeFi hack where an attacker borrows massive amounts of cryptocurrency with absolutely zero collateral. They use this temporary and massive influx of capital to manipulate on-chain market conditions (usually price oracles), exploit a vulnerable smart contract, and repay the loan - all within a single atomic transaction.

The craziest part? The entire attack executes in a matter of seconds. If any step along the way fails, the blockchain automatically reverts the entire sequence. The hacker loses nothing but a few dollars in gas fees.

Auditor quick answer: flash loans are usually not the vulnerability. They are the capital amplifier. The real bug is normally a protocol that trusts same-block spot prices, thin liquidity, manipulable collateral values, governance snapshots, or accounting that assumes attackers cannot temporarily control huge balances.

The "Unlimited Capital" Problem

Think of it like this: imagine being able to borrow $100 million from a bank, manipulate a stock price, profit from the manipulation, and return the money - all before the bank even blinks.

That's exactly what flash loans enable. No collateral. No credit check. No approval process. Just code and opportunity.

Flash loans turned a legitimate DeFi innovation into a hacker's dream weapon. What started as an elegant solution for capital-efficient arbitrage has become responsible for over $500 million in protocol losses.


Watch: Flash Loan Attacks Explained


How Flash Loans Work

Flash loans are uncollateralized loans that must be borrowed and repaid within the same blockchain transaction.

The mechanics are simple:

  1. Borrow any amount available in the lending pool

  2. Use the funds however you want

  3. Repay the full amount plus a small fee

  4. If you can't repay, the entire transaction reverts

Platforms like Aave, dYdX, and Uniswap V2 offer flash loans. They were designed for legitimate use cases: arbitrage, collateral swaps, and debt refinancing.

But attackers realized something powerful: with unlimited capital and atomic execution, they could manipulate prices and exploit protocols with zero risk.


What Auditors Should Review for Flash Loan Risk

When auditing a DeFi protocol, ask where temporary capital could change what the protocol believes:

  • Map every price dependency. Flag reads from DEX spot reserves, pool balances, LP token prices, vault pricePerShare(), AMM slot0(), or any same-block market signal.

  • Check collateral valuation. If a borrowed asset can inflate collateral value, share value, or liquidity accounting within one transaction, assume it will be tried.

  • Review liquidation math. Liquidation thresholds, health factors, and bonus calculations should be resilient to single-block price movement.

  • Inspect governance snapshots. Vote power based on current balances can be borrowed, used, and returned in one transaction unless snapshots or delays exist.

  • Test donation and share-inflation paths. Direct transfers, reserve donations, rounding, and exchange-rate updates can become flash-loan-powered accounting attacks.

  • Validate oracle defenses. Prefer robust external feeds, TWAP windows, staleness checks, deviation limits, and circuit breakers over raw pool reads.

  • Model multi-protocol composition. The exploit may depend on borrowing from one protocol, manipulating a second, and draining a third.

If the attack path depends on price movement, review the oracle manipulation guide. If it depends on callbacks or external calls during accounting updates, review reentrancy attacks as well. To turn this into a working review process, use the smart contract audit checklist while mapping each assumption.


Why Flash Loan Attacks Are Dangerous

Flash loan attacks have caused catastrophic losses across DeFi:

$0M+
Total Value Stolen
$0M
Largest Single Attack
2020–2025
Active Threat Period
Attack Year Impact
Euler Finance 2023 $197M stolen
Cream Finance 2021 $130M drained
Harvest Finance 2020 $34M stolen
bZx Protocol 2020 Multiple attacks, millions lost

The fundamental vulnerability isn't the flash loan mechanism itself - it's protocols that rely on easily manipulable data sources.

Flash loan attack diagram - Flash loans don't create the bug - thin liquidity does
Flash loans don't create the bug - thin liquidity does

Why Attackers Love Flash Loans

  1. Zero capital required - Borrow millions with no collateral

  2. Risk-free execution - If the attack fails, you only lose gas fees

  3. Single transaction - No trace until the exploit is complete

  4. Massive leverage - Manipulate prices with borrowed billions

  5. Repeatable - Execute the same attack dozens of times

Price Manipulation
"Use borrowed capital to skew DEX reserves, exploiting protocols that trust spot prices"
Frequency: Most Common
💰
Arbitrage Exploitation
"Exploit price differences across protocols by temporarily creating artificial imbalances"
Frequency: Common
🔒
Governance Attacks
"Borrow governance tokens to pass malicious proposals or manipulate voting outcomes"
Frequency: Emerging

Real-World Flash Loan Attack Examples

Flash loan attacks aren't theoretical - they've drained hundreds of millions from DeFi protocols.

Euler Finance Attack (March 2023) - $197 Million

The Euler Finance exploit ranks as the 6th largest DeFi hack in history. On March 13, 2023, an attacker exploited a subtle vulnerability in Euler's donation mechanism.

Attack Mechanics:

  • Euler managed lending via eTokens (collateral) and dTokens (debt)

  • The attacker exploited the donateToReserves function from EIP-14

  • This function allowed donating eTokens without checking position health

  • Using two contracts, the attacker created bad debt and acted as liquidator

  • Flash-loaned funds created a large, underwater position

Final haul: 86k ETH ($134.6M), 849 WBTC ($18.6M), $34M USDC, $8.9M DAI

The Aftermath: Euler's TVL collapsed from $264 million to $10 million overnight. The EUL token fell 50%. Cascading effects hit Angle Protocol ($17M), Balancer ($11.9M), and Temple DAO ($5M).

Harvest Finance Attack (October 2020) - $34 Million

The Harvest Finance attack set the template for future flash loan exploits. An anonymous attacker drained $34 million in just seven minutes.

Attack Mechanics:

  • Borrowed $50 million USDT via flash loan from Uniswap

  • Swapped $11.4 million USDC to USDT on Curve, pumping USDT price

  • Deposited $60.6 million USDT into Harvest's vault at inflated price

  • Swapped back, crashing USDT price

  • Withdrew $61.1 million USDT at deflated price

  • Repeated this 32 times without prior testing

The attacker could have drained the entire $400 million TVL but chose to stop after $25 million.

bZx Protocol (February 2020) - Multiple Incidents

bZx suffered multiple flash loan attacks in early 2020 - the first major protocol to be exploited this way.

Attack Pattern:

  • Manipulated bZx's reliance on Uniswap price feeds

  • Flash-loaned large amounts to skew ETH/token ratios

  • Exploited temporary price distortion to over-borrow

These attacks occurred despite security audits from PeckShield and CertiK - highlighting that traditional audits weren't designed for flash loan attack vectors.


How Flash Loan Attacks Work: The Anatomy of an Exploit

Understanding the attack mechanism is crucial for prevention. Here's the step-by-step breakdown.

The Attack Flow

Step What Happens State
1 Attacker borrows massive capital Flash loan initiated
2 Manipulates market prices DEX reserves skewed
3 Exploits victim protocol Overborrowing at false price
4 Repays and profits Loan repaid, profit kept
5 Atomicity protects attacker If any step fails, all reverts
🔥
Flash loans are the ultimate equalizer.
Any attacker - regardless of capital - can borrow hundreds of millions to exploit your protocol. If your price oracle can be manipulated in a single transaction, you are vulnerable.
{
  "title": "🎬 Zero capital in, $40M out - and why it all happens in one transaction",
  "stage": { "width": 920, "height": 460 },
  "nodes": [
    { "id": "lender", "label": "Lender", "role": "Aave / dYdX pool", "emoji": "🏦", "color": "blue", "x": 70, "y": 70 },
    { "id": "dex", "label": "DEX Pool", "role": "thin liquidity", "emoji": "💧", "color": "purple", "x": 690, "y": 70 },
    { "id": "attacker", "label": "Attacker", "role": "$0 of own capital", "emoji": "🦹", "color": "red", "x": 380, "y": 210 },
    { "id": "target", "label": "Victim Protocol", "role": "prices collateral", "emoji": "🏛️", "color": "cyan", "x": 690, "y": 350 }
  ],
  "links": [
    { "from": "lender", "to": "attacker" },
    { "from": "attacker", "to": "dex" },
    { "from": "attacker", "to": "target" }
  ],
  "nets": [
    { "id": "atk", "label": "Attacker Net" },
    { "id": "risk", "label": "Attacker's Own Capital Risked" }
  ],
  "legend": [
    { "cls": "token", "label": "value transfer" },
    { "cls": "fail", "label": "reverted / blocked" }
  ],
  "scenarios": {
    "Vulnerable": [
      {
        "note": "The attacker starts with <b>$0</b> of their own capital. The lender's pool is full; the victim prices collateral from a thin DEX pool.",
        "hi": ["attacker"],
        "bal": { "lender": "$100M pool", "attacker": "$0", "dex": "fair price", "target": "healthy" },
        "net": { "atk": "$0", "risk": "$0" }
      },
      {
        "note": "Attacker <b>flash-borrows $100M</b> - no collateral, just a promise to repay before the transaction ends.",
        "hi": ["lender", "attacker"],
        "chip": { "from": "lender", "to": "attacker", "label": "💰 $100M loan", "cls": "token" },
        "bal": { "attacker": "$100M (borrowed)" },
        "net": { "atk": "$0", "risk": "$0" }
      },
      {
        "note": "Dump the $100M into the thin DEX pool, <b>skewing the spot price ~3.2×</b>.",
        "hi": ["attacker", "dex"],
        "chip": { "from": "attacker", "to": "dex", "label": "🔀 swap $100M", "cls": "token" },
        "bal": { "dex": "price ↑↑ 3.2×" },
        "net": { "risk": "$0" }
      },
      {
        "note": "The victim reads the skewed spot price and lets the attacker <b>over-borrow $40M</b> against it.",
        "tone": "bad",
        "hi": ["target", "attacker"],
        "chip": { "from": "target", "to": "attacker", "label": "💸 $40M", "cls": "token" },
        "bal": { "attacker": "$140M held", "target": "-$40M" },
        "net": { "atk": "+$40M", "risk": "$0" }
      },
      {
        "note": "Swap back and <b>repay the $100M loan</b> in the same transaction. The attacker keeps <b>$40M</b> - having risked <b>nothing</b> but gas.",
        "hi": ["attacker", "lender"],
        "chip": { "from": "attacker", "to": "lender", "label": "💰 repay $100M", "cls": "token" },
        "bal": { "attacker": "$40M profit", "lender": "made whole" },
        "net": { "atk": "+$40M", "risk": "$0" }
      }
    ],
    "Fixed (robust oracle)": [
      {
        "note": "Same start, but the victim prices collateral from a <b>Chainlink / TWAP</b> feed, not a single block's spot.",
        "hi": ["attacker"],
        "bal": { "lender": "$100M pool", "attacker": "$0", "dex": "spot ≠ oracle", "target": "healthy" },
        "net": { "atk": "$0", "risk": "$0" }
      },
      {
        "note": "Attacker still <b>flash-borrows $100M</b>.",
        "hi": ["lender", "attacker"],
        "chip": { "from": "lender", "to": "attacker", "label": "💰 $100M loan", "cls": "token" },
        "bal": { "attacker": "$100M (borrowed)" },
        "net": { "atk": "$0", "risk": "$0" }
      },
      {
        "note": "The $100M swap still skews the <b>DEX spot</b> price for one block.",
        "hi": ["attacker", "dex"],
        "chip": { "from": "attacker", "to": "dex", "label": "🔀 swap $100M", "cls": "token" },
        "bal": { "dex": "spot ↑↑ (ignored)" },
        "net": { "risk": "$0" }
      },
      {
        "note": "The oracle is time-weighted - <b>one block can't move it</b>. Collateral is valued correctly and the over-borrow is <b>rejected</b>.",
        "tone": "ok",
        "hi": ["target"],
        "chip": { "from": "target", "to": "attacker", "label": "⛔ borrow ✗", "cls": "fail" },
        "bal": { "target": "safe", "attacker": "$100M (borrowed)" },
        "net": { "atk": "$0" }
      },
      {
        "note": "With no profit, the attacker <b>cannot repay the loan + fee</b> - so the <b>entire transaction reverts</b>. They lose only gas.",
        "tone": "ok",
        "hi": ["attacker", "lender"],
        "chip": { "from": "attacker", "to": "lender", "label": "↩ revert", "cls": "fail" },
        "bal": { "attacker": "$0 (reverted)", "lender": "untouched" },
        "net": { "atk": "$0", "risk": "~gas only" }
      }
    ]
  }
}

The Five Critical Phases

1
Tap to reveal
Borrow Massive Capital

The attacker takes a flash loan for millions (e.g., 100,000 ETH) from Aave or dYdX. No collateral required - only repayment before the transaction ends.

2
Tap to reveal
Manipulate Market Prices

Dump borrowed tokens into a DEX liquidity pool. This massive volume drastically skews the reserve ratio, causing extreme spot price manipulation.

3
Tap to reveal
Exploit the Victim

A victim protocol that checks the DEX's spot price now calculates values incorrectly. The attacker borrows far more than their collateral is actually worth.

4
Tap to reveal
Repay & Profit

Swap stolen funds back, repay the flash loan plus fee, keep the difference. If any step fails, the entire transaction reverts - zero risk for the attacker.

Phase 1: Borrow Massive Capital The attacker takes out a flash loan for a large amount (e.g., 100,000 ETH) from Aave, dYdX, or Uniswap V2. No collateral required - only repayment before transaction ends.

Phase 2: Manipulate Market Prices The attacker dumps borrowed tokens into a DEX liquidity pool. This volume drastically skews the reserve ratio, causing extreme spot price manipulation.

Phase 3: Exploit the Victim Protocol A victim protocol (lending platform, yield aggregator) that checks that DEX's spot price now calculates values incorrectly. The attacker interacts at the artificial rate.

Phase 4: Repay and Profit The attacker swaps stolen funds back, repays the flash loan plus fee, and keeps the difference. Profits range from thousands to hundreds of millions.

Phase 5: Atomicity Ensures Low Risk If any step fails, the entire transaction reverts. The attacker only loses gas fees - typically a few hundred dollars.

Flash loan attack diagram - Where the borrowed capital lives - the whole attack is one atomic transaction
Where the borrowed capital lives - the whole attack is one atomic transaction

Want to understand this beyond theory? The Smart Contract Hacking course includes safe lab exercises where you use flash loans to exploit weak oracle and accounting assumptions, then fix the vulnerable design.


Flash Loan Vulnerable Code Example

Understanding vulnerable code is the first step to securing your protocols.

This contract is intentionally vulnerable. Never use this pattern in production.

The Vulnerable Price Feed

// VULNERABLE CONTRACT - DO NOT USE IN PRODUCTION
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IUniswapV2Pair {
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}

contract VulnerableCollateralEngine {
    IUniswapV2Pair public uniswapPair;

    constructor(address _pair) {
        uniswapPair = IUniswapV2Pair(_pair);
    }

    // CRITICAL VULNERABILITY: Relies on instant spot price from a single DEX pair
    // An attacker can use a flash loan to inject massive capital and skew reserves
    function getTokenPrice() public view returns (uint256) {
        (uint112 reserve0, uint112 reserve1, ) = uniswapPair.getReserves();

        // EXPLOIT SCENARIO:
        // 1. Attacker flash borrows 100,000 Token0
        // 2. Dumps all 100,000 Token0 into this pair
        // 3. reserve0 increases dramatically, reserve1 barely changes
        // 4. Price = reserve1/reserve0 crashes to near-zero
        // 5. Attacker can now over-borrow from any protocol using this price feed
        return (uint256(reserve1) * 1e18) / uint256(reserve0);
    }
}

Why This Code Is Dangerous

The problem is the data source:

  1. Single point of failure - Relies on one DEX's liquidity pool

  2. No time-weighting - Vulnerable to instantaneous manipulation

  3. No validation - Accepts any price without sanity checks

  4. Atomic exploitation - Attacker can manipulate and exploit in same transaction


Flash Loan Attacker Contract Example

Here's how an attacker exploits vulnerable price feeds.

// ATTACKER CONTRACT - Educational purposes only
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IFlashLoanProvider {
    function flashLoan(uint256 amount) external;
}

interface IVictimProtocol {
    function borrow(uint256 amount) external;
}

interface IUniswapV2Router {
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
}

contract FlashLoanAttacker {
    IVictimProtocol public victimProtocol;
    IUniswapV2Router public router;
    IFlashLoanProvider public flashLoanProvider;
    address public tokenA;
    address public tokenB;

    constructor(
        address _victim,
        address _router,
        address _flashLoan,
        address _tokenA,
        address _tokenB
    ) {
        victimProtocol = IVictimProtocol(_victim);
        router = IUniswapV2Router(_router);
        flashLoanProvider = IFlashLoanProvider(_flashLoan);
        tokenA = _tokenA;
        tokenB = _tokenB;
    }

    // STEP 1: Initiate attack - attacker only pays gas fees
    function initiateAttack(uint256 loanAmount) external {
        flashLoanProvider.flashLoan(loanAmount);
    }

    // STEP 2: Flash loan callback - all attack logic executes here
    function executeOperation(uint256 amountBorrowed) external {

        // STEP 2A: PRICE MANIPULATION
        // Dump borrowed tokens into DEX to crash price
        address[] memory path = new address[](2);
        path[0] = tokenA;
        path[1] = tokenB;

        uint256[] memory amounts = router.swapExactTokensForTokens(
            amountBorrowed,
            0,  // Accept any return (no slippage protection)
            path,
            address(this),
            block.timestamp
        );

        // STEP 2B: EXPLOIT VICTIM PROTOCOL
        // Victim reads crashed price from manipulated DEX
        // Attacker borrows far more than they should
        victimProtocol.borrow(100 ether);

        // STEP 2C: RESTORE PRICE & REPAY
        path[0] = tokenB;
        path[1] = tokenA;

        router.swapExactTokensForTokens(
            amounts[1],
            0,
            path,
            address(this),
            block.timestamp
        );

        // STEP 2D: REPAY FLASH LOAN
        // Return borrowed amount + fee, keep the stolen funds
        // IERC20(tokenA).transfer(address(flashLoanProvider), amountBorrowed + fee);
    }

    function withdrawProfit() external {
        // Transfer stolen funds to attacker's wallet
    }
}

Attack Execution Summary

  1. Call initiateAttack() with loan amount (e.g., 100,000 ETH)

  2. Flash loan provider calls back executeOperation()

  3. Swap massive amount on DEX to crash Token A price

  4. Exploit victim protocol using manipulated price

  5. Swap back to restore price and repay flash loan

  6. Keep the difference - attacker profits millions

The beauty (and danger) of this attack is its atomicity: if any step fails, everything reverts except gas fees. This makes it extremely low-risk for attackers.


Ready to write exploits like this yourself? The Smart Contract Hacking course covers flash loans in-depth with real-world scenarios. Learn from JohnnyTime (12+ years in cybersecurity) and Trust (#1 Code4rena warden).


How to Prevent Flash Loan Attacks

The fundamental flaw enabling flash loan attacks is using easily manipulable spot prices as price oracles. Here are proven prevention techniques.

Best Solution: Chainlink Price Feeds

Chainlink aggregates prices from multiple off-chain data sources (Coinbase, Binance, Kraken) and delivers them on-chain through a decentralized network of node operators.

Why Chainlink Prevents Flash Loan Attacks:

  • Price data sourced from high-liquidity CEXs (impossible to manipulate)

  • Multiple independent node operators provide redundancy

  • Updates based on deviation thresholds, not block-by-block

  • Even if an attacker manipulates one DEX, Chainlink price remains unaffected

2. Time-Weighted Average Price (TWAP)

TWAP calculates the average price over a specific time period (typically 10-30 minutes).

While an attacker can manipulate spot price for one block, maintaining manipulated prices over 30 minutes becomes prohibitively expensive.

3. Circuit Breakers and Price Bounds

Implement sanity checks that reject prices outside reasonable bounds.

If a price moves more than X% from the last known value, pause operations until manual review.

4. Multiple Oracle Sources

Use multiple price feeds and take the median or reject outliers.

If one source is compromised, the others provide safety.

Effectiveness95/100

What it does: Aggregates prices from 50+ exchanges via decentralized node operators. Prices cannot be manipulated by single-transaction DEX swaps.

When to use: Any production protocol handling significant TVL. This is the gold standard.

Limitation: Not all tokens have Chainlink feeds. Requires LINK tokens for operation.

Effectiveness75/100

What it does: Calculates average price over a time period. Maintaining manipulation for 30 minutes is prohibitively expensive due to arbitrageurs.

When to use: When Chainlink feeds aren't available for the token pair.

Limitation: Less responsive to real market movements. Requires sufficient pool liquidity.

Effectiveness10/100

What it does: Reads current reserve ratio from a single DEX pool - trivially manipulable within one transaction.

When to use: NEVER in production. This is the root cause of almost every flash loan attack.

Limitation: Attackers can manipulate and exploit in the same atomic transaction with zero capital risk.

Oracle Security Comparison

Oracle Type Flash Loan Resistant Cost Best For
Chainlink Excellent Medium Production protocols
TWAP (30min) Good Low Medium-risk applications
Single DEX Spot Vulnerable Very Low NEVER USE
Multi-Oracle Excellent High Critical infrastructure
Vulnerable

Single DEX Spot Price

Reading getReserves() from one pool is trivially manipulable. Every major flash loan attack exploited this exact pattern. Never use in production.

Partial Defense

TWAP Oracle Only

Time-weighted average prices resist single-block manipulation but require sufficient pool liquidity and can lag behind real market movements.

Recommended

Chainlink + Circuit Breakers

Decentralized oracle feeds with staleness checks, price deviation limits, and multi-oracle validation provide production-grade flash loan resistance.


Quick Reference: Flash Loan Attack Prevention Checklist

Before deploying any DeFi protocol:

  • Never use single DEX spot prices for critical price calculations

  • Use Chainlink oracles or other decentralized oracle networks

  • Implement TWAP (30+ minute windows) if using on-chain oracles

  • Add circuit breakers that pause on suspicious price movements

  • Validate price freshness with staleness checks

  • Get professional audits focused on oracle manipulation vectors

  • Monitor on-chain activity for unusual price movements

  • Implement emergency pause functionality


Flash Loan Secure Code Example

Here's a production-ready implementation using Chainlink price feeds.

// SECURE CONTRACT - Production-ready
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract SecureCollateralEngine {
    AggregatorV3Interface internal priceFeed;

    uint256 public constant MAX_PRICE_AGE = 1 hours;

    event PriceChecked(int256 price, uint256 timestamp);

    /**
     * @notice Initialize with Chainlink price feed address
     * @dev Different networks have different feed addresses
     *
     * Ethereum Mainnet - ETH/USD: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
     * Polygon - ETH/USD: 0xF9680D99D6C9589e2a93a78A04A279e509205945
     * Arbitrum - ETH/USD: 0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612
     */
    constructor(address _priceFeed) {
        require(_priceFeed != address(0), "Invalid price feed");
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

    /**
     * @notice Get latest price from Chainlink oracle
     * @dev This price CANNOT be manipulated by flash loans because:
     *      1. Data sourced from CEXs (Binance, Coinbase, Kraken)
     *      2. Aggregated from multiple independent node operators
     *      3. Updated based on deviation thresholds, not per-block
     */
    function getLatestPrice() public view returns (int256) {
        (
            uint80 roundID,
            int256 price,
            /* uint256 startedAt */,
            uint256 timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        // SECURITY VALIDATIONS

        // 1. Ensure price is positive
        require(price > 0, "Invalid price: negative or zero");

        // 2. Ensure price data is fresh
        require(timeStamp > 0, "Round not complete");
        require(block.timestamp - timeStamp <= MAX_PRICE_AGE, "Stale price data");

        // 3. Ensure the round was answered
        require(answeredInRound >= roundID, "Stale round");

        return price;
    }

    /**
     * @notice Calculate collateral value safely
     */
    function getCollateralValue(uint256 collateralAmount) public view returns (uint256) {
        int256 price = getLatestPrice();
        return (collateralAmount * uint256(price)) / 1e18;
    }

    /**
     * @notice Check if borrower is safely collateralized
     */
    function isSafelyCollateralized(
        uint256 borrowAmount,
        uint256 collateralAmount,
        uint256 minCollateralRatio
    ) public view returns (bool) {
        uint256 collateralValue = getCollateralValue(collateralAmount);
        uint256 actualRatio = (collateralValue * 100) / borrowAmount;
        return actualRatio >= minCollateralRatio;
    }
}

Security Features at a Glance

Feature Protection
Chainlink integration Flash loan resistant prices
Staleness checks Rejects outdated data
Round validation Ensures complete oracle rounds
Positive price check Prevents invalid calculations

This implementation pattern is used by Aave, Compound, MakerDAO, and most major DeFi protocols to prevent oracle manipulation attacks.


These patterns separate junior developers from senior security researchers. The Smart Contract Hacking course covers flash loans, oracle manipulation, and 20+ other attack vectors alongside defensive techniques. Join 2,000+ security researchers in our Discord community.


Common Misconceptions

?

"Flash loans are the vulnerability."

Tap to reveal
MYTH

Flash loans are a legitimate DeFi tool. The real vulnerability is protocols that rely on easily manipulable price sources. Fix the oracle, and flash loans become irrelevant to security.

?

"If the attack fails, the attacker loses everything."

Tap to reveal
MYTH

If any step fails, the entire transaction reverts. The attacker only loses the gas fee - typically a few hundred dollars. Flash loan attacks are essentially risk-free.

?

"Chainlink feeds cannot be manipulated."

Tap to reveal
FACT

No successful Chainlink manipulation has occurred in production. An attacker would need to control a majority of decentralized nodes AND manipulate prices across dozens of exchanges simultaneously.

?

"Flash loan attacks only happen on Ethereum mainnet."

Tap to reveal
MYTH

Flash loan attacks occur on any chain with DeFi liquidity - BSC, Polygon, Arbitrum, Avalanche, and all major EVM-compatible networks.


Flash loans are rarely the vulnerability themselves - they're the capital amplifier that makes other exploits profitable. The most common combination is flash loans with oracle manipulation attacks. Attackers borrow massive amounts to execute huge DEX swaps, artificially skewing prices that vulnerable protocols read as truth. The Harvest Finance and Cream Finance attacks both used this deadly combination.

Flash loans can also enable reentrancy attacks by providing the initial capital needed to deposit into vulnerable protocols and trigger recursive withdrawals. In sophisticated multi-step exploits, flash loans fund the entire attack chain while guaranteeing the attacker risks nothing but gas fees.


Test Your Flash Loan IQ

5 questions - How well do you understand this attack vector?

Question 1 of 5

Flash Loan Attack FAQ

A flash loan attack is when someone borrows millions of dollars, manipulates prices, exploits a vulnerable protocol, and repays the loan - all in a single transaction lasting seconds. If anything fails, they only lose gas fees.

Over $500 million has been stolen through flash loan exploits since 2020. The Euler Finance attack alone accounted for $197 million.

Yes! Use decentralized oracles like Chainlink instead of single DEX spot prices. Implement TWAP oracles, circuit breakers, and multi-oracle validation for defense in depth.

No. Flash loans are a legitimate DeFi primitive. They become dangerous when a protocol assumes attackers cannot temporarily access massive capital. The vulnerability is usually weak oracle design, manipulable accounting, unsafe governance snapshots, or fragile liquidation math.

Auditors first look for same-block assumptions: DEX spot prices, current balances used as voting power, vault share prices that can be inflated, and liquidation math that reacts immediately to manipulable market state.

Flash loans themselves are legal and legitimate. However, using them to exploit vulnerabilities and steal funds is illegal in most jurisdictions and can be prosecuted as theft or fraud.

Yes. Flash loan attacks can occur on any blockchain with smart contracts and sufficient liquidity - including Arbitrum, Optimism, Polygon, BSC, and all major EVM chains.


Conclusion: Flash Loans Expose Broken Assumptions

A flash loan is not the bug. It is the stress test.

If a protocol assumes attackers cannot access massive temporary capital, cannot move a market in one block, cannot inflate a share price, or cannot borrow voting power before a snapshot, a flash loan turns that assumption into an exploit.

Before deployment, review:

  • same-block price dependencies,

  • vault share and LP token accounting,

  • liquidation and collateral valuation paths,

  • governance snapshots and voting delays,

  • donation, rounding, and reserve-manipulation paths,

  • oracle fallback behavior during stress.

The safest auditors do more than recognize the pattern. They write the exploit, confirm the invariant failure, and then prove the fix blocks the same path.

The Smart Contract Hacking course teaches flash loan attacks through hands-on labs alongside oracle manipulation, reentrancy, access control, and other high-impact vulnerability classes.

You can browse the full curriculum or try a free lesson before deciding whether the full course is the right fit.

Sources and editorial notes

Reviewed by JohnnyTime. Last updated .

Master Flash Loans Attacks in a safe lab

Practice the exploit path, debug the vulnerable code, and learn the prevention workflow auditors use in real reviews.

Exploit setup Root-cause tracing Patch review
Practice Flash Loans Attacks Free Trial