DeFi

TWAP Oracle

A TWAP oracle reports a time-weighted average price over a chosen window instead of relying on a single spot price.

A TWAP oracle averages price over time so one instant of price movement has less influence.

TWAP Oracle Explained in Detail

A TWAP oracle reports the average price over a time window. Instead of trusting the current AMM price at one moment, it compares cumulative observations across time and divides by the elapsed interval.

TWAPs can make manipulation more expensive, but they are not automatically secure. Their safety depends on the pool liquidity, observation window, update cadence, market depth outside the pool, and how the protocol consumes the result.

Smart contract example

The risky version reads a spot price:

function priceNow() external view returns (uint256) {
    (uint112 r0, uint112 r1,) = pair.getReserves();
    return uint256(r1) * 1e18 / uint256(r0);
}

A TWAP design reads observations from different times so one spot-price move has less control over the result, though multi-block manipulation can still matter.

TWAP Oracle in Auditing

TWAP review overlaps with oracle manipulation, but the narrower question is whether the averaging window, liquidity, and observation mechanics match the protocol's value at risk.

Short windows, low-liquidity pools, stale observations, and fallback behavior can still lead to price manipulation.

Red flags in code

  • TWAP window is shorter than the time and cost needed to manipulate the pool relative to protocol value at risk.

  • Pool has thin liquidity, concentrated liquidity, or one-sided market depth.

  • Observations are stale, missing, low-cardinality, or only refreshed when the pool is interacted with.

  • Decimal normalization differs between tokens, feeds, or AMM versions.

  • A failed TWAP read silently falls back to a manipulable spot price.

How to test or review it

  • Simulate swaps across the full TWAP window, not only in one transaction.

  • Compare attack cost against collateral, mint, redeem, or liquidation value at risk.

  • Test zero liquidity, stale observations, and low observation cardinality.

  • Verify decimals and token ordering in every price conversion.

  • Pair TWAP checks with invariant testing, such as limiting collateral-value jumps per window unless governance explicitly allows them.

Sources