SolidityIn

Oracle manipulation and flash loans

Lesson 38 of 40 · Case Studies

A flash loan lets anyone borrow a very large amount with no collateral, as long as it is repaid within the same transaction. If the loan is not repaid, the whole transaction reverts as if it never happened. This gives an attacker temporary access to huge funds at almost no cost.

Many attacks combine a flash loan with a manipulable price. The attacker borrows funds, makes a large trade in a thin pool to push the price far from the real market, uses a lending contract that trusts that price to borrow far more than their collateral is worth, then repays the flash loan and keeps the difference. Early flash loan attacks such as bZx in 2020, and later cases like Mango Markets in 2022, which lost over 100 million dollars, followed this idea.

The lesson is never to take a price from a single pool at a single moment. Use a time-weighted average price, or TWAP, which is hard to move within one block, or use a decentralized oracle network such as Chainlink with checks for stale or extreme values. Also set limits on how much can be borrowed or moved in one transaction.

The example has a simple pool, a lender that trusts its spot price, and a TWAP that averages the price over time. Try buying a large amount in the pool and compare what the lender allows with what the TWAP reports. The TWAP only works if update is called regularly, which is often done by a keeper bot.

contract SpotPool {
    uint256 public reserveToken = 1000e18;
    uint256 public reserveEth = 100e18;

    function spotPrice() public view returns (uint256) {      // ETH per token, scaled by 1e18
        return reserveEth * 1e18 / reserveToken;
    }
    function buy(uint256 ethIn) external {                    // simplified swap
        uint256 out = reserveToken * ethIn / (reserveEth + ethIn);
        reserveEth += ethIn;
        reserveToken -= out;
    }
}

// VULNERABLE: trusts the instantaneous pool price
contract BadLender {
    SpotPool public pool;
    mapping(address => uint256) public collateral;

    constructor(SpotPool p) { pool = p; }

    function maxBorrow(address who) public view returns (uint256) {
        return collateral[who] * pool.spotPrice() / 1e18 / 2;
    }
}

// BETTER: average the price over time, so one transaction cannot move it
contract Twap {
    SpotPool public immutable pool;
    uint256 public cumulative;
    uint256 public lastPrice;
    uint256 public lastTime;
    uint256 public windowStart;
    uint256 public windowStartCumulative;

    constructor(SpotPool p) {
        pool = p;
        lastPrice = p.spotPrice();
        lastTime = block.timestamp;
        windowStart = block.timestamp;
    }
    function update() public {
        cumulative += lastPrice * (block.timestamp - lastTime);
        lastTime = block.timestamp;
        lastPrice = pool.spotPrice();
    }
    function startWindow() external {
        update();
        windowStart = block.timestamp;
        windowStartCumulative = cumulative;
    }
    function average() external returns (uint256) {
        update();
        require(block.timestamp > windowStart, "Window is empty");
        return (cumulative - windowStartCumulative) / (block.timestamp - windowStart);
    }
}

Try it yourself

In Remix, call buy with 50e18 on SpotPool and compare spotPrice before and after. Then deploy BadLender, give an address some collateral, and see how maxBorrow jumps for the same collateral.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Why is a time-weighted average price safer than a spot price?