Zokyo Security Research
Flash Loan Attacks in DeFi
How uncollateralized lending mechanisms are exploited through oracle manipulation, and the defense strategies protocols can adopt to protect against them.

Flash Loans represent one of the most groundbreaking innovations in Decentralized Finance (DeFi), offering immense potential for creative financial strategies. However, the same mechanism that enables permissionless, uncollateralized borrowing has also opened the door to sophisticated attacks that have drained millions of dollars from protocols. Understanding how flash loan attacks work - and how to defend against them - is essential for any team building in the DeFi space.

What Are Flash Loans?

Flash Loans offer a mechanism for uncollateralized borrowing that is inherently tied to the atomic nature of blockchain transactions. Unlike traditional financial systems, where loans typically require significant collateral and undergo lengthy approval processes, Flash Loans allow users to borrow substantial amounts of assets without any upfront security, provided that the loan is repaid within the scope of a single blockchain transaction.

The Ethereum Virtual Machine (EVM) is a state machine that executes atomic transactions - a series of diverse operations can be executed as a "package," all within the same exact moment. This atomicity is the key property that makes flash loans possible. If any step in the transaction fails, including the repayment of the loan, the entire transaction is reverted as if it never happened.

How Flash Loans Work

A flash loan follows a specific lifecycle within a single transaction block:

  1. Borrow: The user requests a loan from a flash loan provider (such as Aave, dYdX, or Uniswap). No collateral is required at this stage.
  2. Execute: The borrowed funds are used to perform any number of operations - trades, liquidations, collateral swaps, arbitrage, or other DeFi interactions.
  3. Repay: The original loan amount plus any associated fees must be returned to the lending protocol before the transaction concludes.
  4. Revert or Finalize: If the repayment condition is not met, the entire transaction is reverted by the EVM. If repayment succeeds, the transaction is finalized on-chain.

The ERC-3156 standard formalizes this pattern, defining a callback-based interface between a lender smart contract and a receiver smart contract. The lender transfers assets to the receiver, the receiver executes its operations, and then returns the assets plus fees - all within a single atomic call.

Solidity ERC-3156 Flash Loan Interface
// Simplified ERC-3156 flash loan flow
interface IERC3156FlashLender {
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
}

interface IERC3156FlashBorrower {
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}

Legitimate Uses of Flash Loans

Before examining the attack vectors, it is important to recognize that flash loans have several legitimate applications in DeFi. The technology itself is not inherently malicious - it is a powerful financial primitive that can be used constructively.

Arbitrage

Flash loans enable traders to exploit price discrepancies between decentralized exchanges (DEXes) without needing upfront capital. A trader can borrow a large sum, buy an underpriced asset on one exchange, sell it at a higher price on another, repay the loan, and pocket the difference - all in a single transaction. This kind of arbitrage activity actually benefits the market by helping to equalize prices across platforms.

Self-Liquidation

Users with existing loans on platforms like Aave or Compound may find their collateral ratio approaching the liquidation threshold. Rather than being liquidated by a third party at a penalty, they can use a flash loan to repay the debt, withdraw their collateral, swap a portion to cover the flash loan, and avoid the liquidation penalty entirely. This saves the user from paying the liquidation discount that would otherwise go to a liquidator.

Collateral Swaps

Users with active loans can use flash loans to swap their collateral type without needing to close their position. For example, if a user has locked ETH as collateral on a lending platform but wants to switch to DAI, they can use a flash loan to repay the ETH-backed debt, withdraw their ETH, swap it for DAI, deposit the DAI as new collateral, borrow again, and repay the flash loan - all within a single transaction.

Third-Party Liquidation

Liquidators can use flash loans to participate in liquidation events on lending protocols without needing their own capital. They borrow funds via a flash loan, repay the undercollateralized position, claim the discounted collateral, sell it on the open market, and repay the flash loan with profit. This increases market efficiency by ensuring undercollateralized positions are liquidated promptly.

Oracle Price Manipulation: The Primary Attack Vector

The most common and damaging flash loan attack vector is oracle price manipulation. This type of attack exploits the way a protocol determines the price of an asset, particularly when it relies on the spot price from a liquidity pool (such as those on Uniswap or other Automated Market Makers) as its price oracle.

How Oracle Manipulation Works

The attack follows a predictable sequence:

  1. Flash loan initiation: The attacker borrows a large amount of one asset (e.g., ETH) from a flash loan provider such as dYdX or Aave.
  2. Price manipulation: The attacker uses the borrowed funds to execute a large trade in a liquidity pool that the targeted protocol uses as its price oracle. For instance, buying a massive amount of Token A from a pool containing ETH and Token A will dramatically increase Token A's spot price relative to ETH.
  3. Exploitation: With the oracle now reporting an inflated price for Token A, the attacker interacts with the target protocol. This could mean depositing a small amount of Token A (now overvalued) as collateral and borrowing a disproportionately large amount of other assets against it.
  4. Restoration: The attacker reverses the initial trade, restoring the liquidity pool to approximately its original state.
  5. Repayment and profit: The flash loan is repaid, and the attacker keeps the difference - the assets drained from the target protocol.
Critical Vulnerability

Protocols that rely on the spot price of a single Automated Market Maker (AMM) as their price oracle are inherently vulnerable to flash loan manipulation. The spot price merely mirrors the current ratio of reserves in the pool and can be moved arbitrarily within a single transaction.

Why Spot Prices Fail as Oracles

An AMM like Uniswap uses the constant product formula x * y = k to determine prices. The "spot price" at any moment is simply the ratio of the two reserves. When someone executes a very large trade, they shift the reserves significantly, creating an artificially distorted price. Because flash loans provide the attacker with enormous temporary capital, they can manipulate these ratios far beyond what would be possible with their own funds.

The fundamental problem is that spot prices reflect the pool's state at a single point in time. They contain no information about whether that state is the result of organic market activity or a deliberate manipulation within the same transaction block.

Real-World Flash Loan Attacks

Multiple high-profile protocols have lost significant funds to flash loan attacks. These incidents illustrate both the severity of the threat and the common patterns that enable it.

Cheese Bank - $3.3 Million (November 2020)

On November 6, 2020, Cheese Bank - a decentralized lending protocol on Ethereum - was exploited for approximately $3.3 million in USDC, USDT, and DAI. The attacker used a flash loan of 21,000 ETH from dYdX to manipulate the collateral price on Uniswap V2.

The attack sequence involved swapping 50 ETH for 107,000 CHEESE tokens on Uniswap V2, which dramatically inflated the CHEESE token price. The attacker then refreshed the price feeds in Cheese Bank to reflect this manipulated value and used the overvalued CHEESE tokens as collateral to borrow approximately 2 million USDC, 1.23 million USDT, and 87,000 DAI from the protocol. The core vulnerability was Cheese Bank's reliance on an AMM-based oracle (Uniswap spot price) for collateral valuation.

bZx Protocol Attacks (February 2020)

The bZx protocol suffered two flash loan attacks in rapid succession in February 2020, losing nearly $1 million in total. These were among the first major flash loan exploits and served as a wake-up call for the entire DeFi industry. The attacker exploited bZx's reliance on a single oracle (Uniswap spot price) for price determination, allowing them to manipulate the collateral pool and extract funds.

Euler Finance - $197 Million (March 2023)

In one of the largest DeFi exploits to date, Euler Finance lost approximately $197 million due to a vulnerability in its eToken functions. The attacker obtained a $30 million DAI flash loan from Aave, deposited the funds, leveraged the protocol's borrowing capabilities, and accumulated approximately $1.5 billion in crYUSD before draining the available assets. Notably, in this case, the attacker eventually returned the funds to the protocol.

Cream Finance - $130 Million (October 2021)

Cream Finance was exploited for approximately $130 million through a flash loan attack that targeted vulnerabilities in the yUSDVault mechanics. By manipulating token valuation - reducing total token supply while depositing equivalent value, effectively doubling the perceived value - the attacker was able to drain the platform's liquidity.

Pancake Bunny - $45 Million (May 2021)

The Pancake Bunny yield aggregator on Binance Smart Chain was exploited for $45 million when an attacker used flash loans from PancakeSwap to manipulate the price of the BUNNY token. The attacker borrowed a large amount of BNB, used it to manipulate the BUNNY/BNB price on PancakeSwap, and then exploited the protocol's reward distribution mechanism to mint an excessive amount of BUNNY tokens at the inflated value.

Pattern Recognition

Nearly all of these attacks share the same fundamental pattern: the protocol relied on a single, easily manipulable price source (typically an AMM spot price) to make critical financial decisions such as collateral valuation, loan issuance, or reward distribution.

Attack Avoidance Strategies

Defending against flash loan attacks requires a multi-layered approach that addresses the root causes rather than attempting to block flash loans themselves. Flash loans are a feature of the ecosystem, and attempting to prevent their use is neither practical nor desirable. Instead, protocols must ensure their core logic is resistant to manipulation.

Time-Weighted Average Price (TWAP) Oracles

The most effective defense against oracle manipulation is to use a Time-Weighted Average Price (TWAP) oracle rather than relying on spot prices. TWAP oracles calculate the average price of an asset over a defined time period, making them resistant to single-transaction manipulation.

Uniswap V2 and V3 provide built-in TWAP functionality through their price0CumulativeLast and price1CumulativeLast variables. These accumulators track the sum of prices at every block, allowing contracts to compute the average price over any desired interval.

Solidity TWAP Oracle Example
// Simplified TWAP calculation using Uniswap V2 cumulative prices
function computeTWAP(
    uint256 priceCumulativeStart,
    uint256 priceCumulativeEnd,
    uint256 timeElapsed
) internal pure returns (uint256) {
    // The TWAP is the difference in cumulative prices
    // divided by the time elapsed
    return (priceCumulativeEnd - priceCumulativeStart) / timeElapsed;
}

// An attacker would need to sustain the manipulated price
// across multiple blocks to significantly affect the TWAP,
// which is economically infeasible in most cases.

The key insight is that incorporating time into price calculations forces an attacker to sustain an artificial price across multiple blocks. Since the attacker cannot control when new blocks are produced and would need to lock up enormous capital across multiple transactions, the attack becomes economically infeasible.

Decentralized Oracle Networks

Using a decentralized oracle network such as Chainlink provides price feeds that aggregate data from multiple independent sources, including centralized exchanges, DEXes, and OTC desks. Because these feeds are not derived from a single on-chain liquidity pool, they cannot be manipulated through flash loans.

Chainlink price feeds use a network of independent node operators that each fetch data from multiple sources and submit it on-chain. The final price is determined by aggregating these submissions, typically using a median. An attacker would need to compromise multiple independent data providers simultaneously, which is orders of magnitude more difficult than manipulating a single liquidity pool.

Using Multiple Oracle Sources

Even when using TWAP or Chainlink, protocols should consider aggregating price data from multiple independent sources. This defense-in-depth approach means that even if one oracle source is compromised or returns stale data, the protocol can compare across sources and detect anomalies.

  • Primary + fallback: Use Chainlink as the primary oracle with a TWAP-based on-chain oracle as a fallback.
  • Cross-validation: Compare prices from two or more independent sources and reject transactions where the price deviation exceeds a configurable threshold.
  • Circuit breakers: Implement automatic pause mechanisms when price feeds diverge significantly from each other or from historical norms.

Slippage Limits and Trade Size Caps

Limiting the maximum slippage allowed in trades that interact with a protocol's pricing mechanism can reduce the effectiveness of price manipulation. If a protocol caps how much the price can move in a single transaction, it becomes harder for an attacker to push the price far enough to extract meaningful profit.

Similarly, imposing maximum trade sizes or requiring multiple smaller transactions can limit the impact of any single manipulation attempt. While this does not eliminate the risk entirely, it raises the bar significantly.

Reentrancy Guards and Access Controls

Flash loan attacks often exploit reentrancy vulnerabilities or missing access controls in conjunction with oracle manipulation. Implementing robust reentrancy guards (such as OpenZeppelin's ReentrancyGuard) and proper access control mechanisms ensures that even if an attacker manages to manipulate a price feed, they cannot re-enter critical functions to compound the exploit.

Solidity Reentrancy Guard Pattern
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract SecureLending is ReentrancyGuard {
    function borrow(
        address asset,
        uint256 amount
    ) external nonReentrant {
        // Validate collateral using TWAP oracle
        uint256 collateralValue = getTWAPPrice(msg.sender);
        require(
            collateralValue >= amount * COLLATERAL_RATIO / 100,
            "Insufficient collateral"
        );

        // Execute borrow logic
        _executeBorrow(msg.sender, asset, amount);
    }
}

Comprehensive Security Audits

Regular third-party security audits are essential for identifying flash loan vulnerabilities before they can be exploited. Auditors specifically examine oracle integration patterns, looking for reliance on spot prices, missing validation checks, and potential manipulation vectors.

Beyond traditional audits, protocols should also invest in:

  • Formal verification: Mathematical proofs that critical invariants hold under all possible input combinations, including flash loan scenarios.
  • Fuzzing: Automated testing that generates thousands of random transaction sequences to uncover edge cases that manual review might miss.
  • Economic modeling: Simulating attack scenarios with realistic capital amounts to quantify the potential impact and validate that defenses are economically sound.
  • Bug bounty programs: Incentivizing white-hat researchers to discover and responsibly disclose vulnerabilities before malicious actors find them.

Emerging Defense Mechanisms

As the DeFi ecosystem matures, new defense strategies continue to emerge that build on the foundational approaches described above.

Flash Loan Detection

Some protocols implement transaction-level checks to detect whether the current transaction involves a flash loan. While not a standalone defense, this detection can trigger additional validation requirements - such as stricter collateral ratios or delayed execution - when flash-loaned funds are detected.

Delayed Execution and Commit-Reveal Schemes

Breaking critical operations across multiple blocks eliminates the atomic advantage that flash loans provide. In a commit-reveal scheme, a user first commits to an action (such as a trade or collateral deposit) in one transaction, and the action is only executed in a subsequent block. Since flash loans must be repaid within a single transaction, they cannot be used to fund operations that span multiple blocks.

Real-Time Monitoring and Emergency Response

Implementing real-time monitoring systems that track unusual on-chain activity - large borrows, sudden price movements, or abnormal trading volumes - enables protocols to detect attacks in progress. Combining monitoring with automated circuit breakers that can pause protocol operations when suspicious patterns are detected provides a critical safety net.

Conclusion

Flash loans are a double-edged sword in DeFi. They democratize access to capital and enable innovative financial strategies, but they also amplify the impact of oracle vulnerabilities and smart contract weaknesses. The attacks we have examined share a common thread: they exploit protocols that rely on easily manipulable price sources to make critical financial decisions.

The defenses are well understood and proven effective. Using TWAP oracles instead of spot prices, integrating decentralized oracle networks like Chainlink, implementing reentrancy guards, and conducting thorough security audits can significantly reduce a protocol's attack surface. No single defense is sufficient on its own, but a layered approach that combines multiple strategies creates a robust security posture.

For protocol developers and DeFi builders, the message is clear: treat oracle design as a first-class security concern, invest in comprehensive auditing, and never assume that the spot price of a single liquidity pool is a reliable foundation for financial decisions worth millions of dollars.