What is TWAP?
TWAP (Time-Weighted Average Price) is a pricing methodology that calculates an asset's average price over a specified time period. By averaging prices over time, TWAP oracles resist manipulation that affects only instantaneous prices.
How TWAP Works
Instead of using the current spot price, TWAP:
- Continuously tracks price observations
- Records cumulative price times time values
- Calculates average over the observation window
- Returns time-weighted average as the price
TWAP Formula
TWAP = (CumulativePriceend - CumulativePricestart) / (Timeend - Timestart)
Each price is weighted by the duration it persisted, giving stable prices more influence.
TWAP Windows
Common observation periods:
- Short (5-15 minutes): More responsive but less resistant
- Medium (30-60 minutes): Balanced security and freshness
- Long (24 hours): Maximum manipulation resistance
Longer windows resist manipulation better but may lag during rapid price changes.
TWAP in Uniswap
Uniswap V2 introduced on-chain TWAP oracles:
- Price accumulators track cumulative prices
- Anyone can read current and historical values
- External contracts calculate TWAP over desired window
Uniswap V3 enhanced this with improved precision and efficiency.
TWAP vs Spot Price
| Aspect | TWAP | Spot Price |
|---|---|---|
| . . . . | . . . | . . . . . . |
| Manipulation Resistance | High | Low |
| Latency | Higher | Immediate |
| Flash Loan Attack Risk | Resistant | Vulnerable |
| Cost to Manipulate | Expensive | Cheaper |
When to Use TWAP
Good for:- Lending protocol liquidations
- Long-term value assessments
- Governance-related pricing
- Manipulation-sensitive operations
- High-frequency trading
- Arbitrage requiring real-time prices
- Fast-moving markets where latency matters
TWAP Limitations
- Lags during rapid price movements
- Extended manipulation can still work
- Requires sufficient liquidity in source pool
- Multi-block attacks possible with resources
Implementing TWAP Safely
- Use adequate time windows (30+ minutes recommended)
- Monitor source pool liquidity
- Combine with other validation mechanisms
- Add sanity checks for extreme deviations
- Have fallback pricing mechanisms
TWAP in Other Protocols
Many protocols implement TWAP-based pricing:
- Compound uses TWAP for price anchoring
- MakerDAO considers TWAP for certain collateral
- Various yield aggregators use TWAP for asset valuation