4 min read

Finance

DeFi Attacks

DeFi protocols manage billions in assets and present unique attack vectors including flash loans, oracle manipulation, and economic exploits.

Authorised Targets Only

Run these contracts against protocols you deployed on a local fork (Anvil or Hardhat with anvil --fork-url) or a testnet you control. Borrowing against a live pool to drain it is theft — unauthorised exploitation is a criminal offence in most jurisdictions and may also be a securities or commodities violation.

Flash Loan Attacks

A flash loan is uncollateralised only because repayment is enforced by the transaction itself: the lender hands over the funds, calls back into the borrower, and reverts the entire transaction if the balance is not returned by the time the call unwinds. The sample targets solc 0.8.34 and declares the lender interface and the lender reference it calls — the earlier version of this listing called an undeclared lender variable, so it could not compile.

flashloan-attack.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

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

contract FlashLoanAttacker {
    IFlashLender public immutable lender;

    constructor(address lender_) {
        lender = IFlashLender(lender_);
    }

    function attack() external {
        // 1. Borrow a large amount, repayable in this same transaction
        lender.flashLoan(1_000_000 ether);

        // 2. Manipulate a spot-price oracle
        //    - swap on the DEX to move the reserves
        //    - read the now-wrong price from the victim protocol

        // 3. Exploit the protocol using that price
        //    - borrow past the collateral limit
        //    - or liquidate positions at a false price

        // 4. Keep the difference

        // 5. Repayment happens inside the callback below, before this
        //    transaction can complete
    }

    // The lender calls this; if the loan is not repaid before it
    // returns, the lender reverts and nothing happened.
    function executeOperation(uint256 amount) external {
        require(msg.sender == address(lender), "not the lender");

        // ... attack body: swap, read price, exploit, swap back ...

        // repay amount + fee to the lender here
    }
}

The contract is the easy half. What makes a flash loan profitable is a protocol that trusts a value an attacker can move inside one block — which is the next section.

Price Oracle Manipulation

Two defects usually appear together in this pattern. The price is read from live pool reserves, which a swap can move arbitrarily; and it is computed with integer division, so reserve1 / reserve0 truncates to 0 or 1 for almost every real pool and is not a price at all. The corrected function below declares its reserves and scales the result by 1e18; it is still vulnerable to same-block manipulation, which is the point of the example.

oracle-manipulation.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

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

contract SpotPriceOracle {
    // VULNERABLE: a spot price straight from the reserves.
    // Safe from truncation, still manipulable within one block.
    function getPrice(address pair) public view returns (uint256) {
        (uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(pair).getReserves();
        require(reserve0 != 0, "empty pool");

        // Scale by 1e18 so the result is a price, not 0 or 1
        return (uint256(reserve1) * 1e18) / uint256(reserve0);
    }
}

// Attack pattern:
// 1. Flash loan a large amount
// 2. Swap to move the pool's reserves (and therefore getPrice)
// 3. Interact with the victim protocol using the manipulated price
// 4. Swap back, repaying the loan and keeping the profit

// Mitigations:
// - TWAP (time-weighted average price) over a window longer than one block
// - Chainlink or another aggregated oracle with multiple sources
// - Sanity bounds and a circuit breaker on how far a price may move

Real incidents that follow this shape — note the first one is frequently misquoted:

  • bZx (2020): two attacks in February 2020, with published losses totalling roughly $1M across both — not the $8M that gets repeated. The larger figure was the value put at risk, most of which was recovered or never left.
  • Harvest Finance (2020): about $24M, from repeated USDC/USDT arbitrage against a manipulated Curve pool price.
  • Cream Finance (2021): about $130M, an oracle-manipulation attack that also exploited a reentrancy path in the same transaction.