TWAP (Time-Weighted Average Price) is a price calculation methodology that averages an asset's price over a specified time window — creating a manipulation-resistant price reference for DeFi smart contracts. By averaging across many time intervals rather than relying on a single spot price, TWAP prevents flash loan-based price manipulation attacks that have drained hundreds of millions from DeFi protocols. THE MANIPULATION PROBLEM TWAP SOLVES Imagine a lending protocol using the current spot DEX price as its oracle. An attacker with a $100M flash loan could: Borrow $100M. Manipulate the DEX price of a small-cap token 10x higher in a single block. Use the inflated price as collateral on the lending protocol to borrow against it. Default on the loan, repay the flash loan. Net profit from the artificially inflated collateral borrow. This attack would take milliseconds — a single transaction. A TWAP over 30 minutes cannot be manipulated in this way because the attacker would need to sustain the price manipulation across many blocks (at enormous cost) rather than in a single atomic transaction. HOW UNISWAP V2/V3 TWAP WORKS Uniswap stores cumulative price data in each pool: Every block, the contract records the current price multiplied by the number of seconds since the last update. TWAP = (Cumulative Price at Time T2 - Cumulative Price at Time T1) / (T2 - T1). By reading the cumulative price at two points in time and dividing by the elapsed seconds, any contract can compute an accurate time-weighted average without trusting Uniswap to report the price correctly. TWAP LIMITATIONS TWAP introduces price lag — a 30-minute TWAP lags reality by up to 30 minutes. During fast-moving markets, this lag can create other risks (stale prices causing incorrect liquidations). Manipulable with enough capital and sustained effort — thin liquidity pools are more susceptible even to TWAP manipulation. Most protocols combine TWAP with Chainlink price feeds for defence-in-depth.