What is a TWAP in smart contracts?

A TWAP, or time-weighted average price, is a price averaged over a window of time, with each price weighted by how long it held. Contracts read TWAPs from DEX pools because moving the average means holding a false price for much of the window, which costs far more than moving the spot price for one transaction.

Last updated . 2 minute read. By the QuillAudits Team.

How is a TWAP computed on chain?

The pool keeps a running total, not a price history. Uniswap V2 adds each price, weighted by the seconds it held, to a cumulative variable, so the difference between two readings divided by the seconds between them is the average for that interval (Uniswap V2). Uniswap V3 accumulates the tick instead, and the mean tick it gives corresponds to a geometric mean price (Uniswap V3).

Reading a mean tick from a Uniswap V3 pool (illustrative, not audited code) TwapReader.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IUniswapV3PoolOracle {
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityX128);
}

contract TwapReader {
    function meanTick(IUniswapV3PoolOracle pool, uint32 window) external view returns (int56 mean) {
        uint32[] memory ages = new uint32[](2);
        ages[0] = window; // ages[1] = 0 means now
        (int56[] memory cumulatives, ) = pool.observe(ages);
        int56 delta = cumulatives[1] - cumulatives[0];
        mean = delta / int56(uint56(window));
        if (delta < 0 && delta % int56(uint56(window)) != 0) mean--; // round toward minus infinity
    }
}

Can a TWAP be manipulated?

Yes, at a cost that depends on the window and the liquidity. Uniswap puts the cost of moving a V2 TWAP at roughly what the attacker loses to arbitrage and fees every block for the whole period (Uniswap V2), so a short window over a pool with little liquidity is cheap. On 2 April 2022 the Keep3r TWAP that Inverse Finance used for INV was pushed through trades on thin SushiSwap pools, and the attacker borrowed $15.6M (Inverse Finance). The oracle price manipulation page covers the case.

  • Would holding the price off for the whole window cost more than the loans it allows?
  • Does the pool keep enough history? A V3 pool tracks one observation until someone pays for more, up to 65,535 (Uniswap V3).
  • Is a lagging average safe for liquidations when the market moves fast?

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts