Crypto Training
Oracles and TWAPs: How Price Feeds Get Manipulated
A price is safe to integrate when you know who can move it, for how long and at what cost. This post covers how Uniswap v2 and v3 build TWAPs, what changed in v4, how Chainlink feeds update and go stale, and what manipulation costs under proof of stake.
A price that a contract reads is only as good as the cost of moving it. Two sources can report the same number today and differ by orders of magnitude in what an attacker would have to spend to change it for the few blocks that count. Most of the work in an oracle integration is finding out that cost and comparing it with what the protocol hands out when the price is wrong.
This post covers the mechanics, meaning how Uniswap v2 and v3 build time-weighted prices and what v4 changed, how Chainlink data feeds update and go stale, and what manipulation costs under proof of stake. The recurring incident shapes are in DeFi incident patterns, and the rollup-specific problems are in L2 oracle failure modes.
Start with the attacker's question#
How much does it cost to move this price far enough, for long enough, to make money?
If the answer is less than what the protocol will lend, mint or pay out at the moved price, the integration is profitable to attack. The cost has two parts, capital and time exposed to arbitrage. A flash loan makes capital free for the length of one transaction, which is why anything that can be both moved and read inside a single transaction should be treated as attacker-controlled. Time is the part an oracle design can charge for.
External feeds and on-chain markets#
| Oracle type | Example | Who can move it | What you need to know |
|---|---|---|---|
| External feed | Chainlink data feed | the node operators and the markets they sample | update triggers, staleness, decimals, who can replace the aggregator |
| AMM-derived | Uniswap v2 or v3 TWAP | anyone with capital, for as long as they can hold the price | liquidity across the price range, window length, who proposes the next blocks |
Spot price and TWAP#
Spot price is the pool's state at this instant, and a TWAP is an average of that state over a window. Averaging raises the cost of manipulation by forcing the attacker to keep the price displaced across block boundaries, where arbitrageurs can trade against them.
| Price input | Strength | Weakness |
|---|---|---|
| Spot | follows the market immediately | can be moved and restored inside one transaction |
| TWAP | a single-transaction move has little or no weight | can be walked on thin pools, and lags real moves |
Uniswap v2 keeps an accumulator you sample yourself#
A v2 pair keeps two running sums, one per direction, and adds to them the first time its reserves change in a block. The code is short (from UniswapV2Pair.sol at v1.0.1):
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
_reserve0 and _reserve1 are the reserves before the current trade, so the price that gets weighted by timeElapsed is the one the previous block ended on. A consumer reads the cumulative value twice and divides the difference by the time between the readings, which gives an arithmetic mean of the price.
The pair stores no history. The integrating contract has to take the first reading itself, and the window is whatever lies between its two readings. Uniswap's own example oracle refuses to update until a full 24 hours have passed for that reason. An adapter that computes "current cumulative minus last stored cumulative" without enforcing a minimum age can end up averaging over a few seconds.
Uniswap v3 stores ticks in a ring buffer#
A v3 pool stores the observations itself. Each one holds a timestamp and tickCumulative, the running sum of the active tick multiplied by seconds elapsed, and observe(secondsAgos) returns the cumulative values at the requested ages, interpolating when needed. Three properties follow from the oracle library and the pool code.
- The average is over ticks, which are logarithms of price, so the result is a geometric mean of the price. A short extreme spike moves a geometric mean far less than an arithmetic one.
- An observation is written at most once per block, with the tick as it was before the first tick-changing action of that block. A price that is moved and restored inside one block therefore adds nothing to the accumulator.
- A new pool keeps a single observation. Anyone can pay to enlarge the buffer with
increaseObservationCardinalityNext, up to 65,535 slots, which the documentation puts at roughly nine days of history.
Uniswap v4 has no built-in oracle#
The same documentation page states that v4 does not include built-in oracle functionality. A v4 pool has an oracle only if it was created with a hook that records observations, so the hook's code, its permissions and its update rules become part of the price source you are trusting. Our post on v4 hooks covers what to review there.
A real TWAP attack at Rodeo Finance#
Rodeo Finance on Arbitrum priced unshETH collateral with its own TWAP contract, which averaged the last four samples taken 30 minutes apart from a thin Camelot v2 pool. In July 2023 an attacker moved that pool around each sampling time over several cycles until all four samples were poisoned and the oracle reported about 4,219 ETH per unshETH for a token worth about one. A borrow of 400,000 USDC against almost nothing then passed the health check. The campaign took about 472 ETH in total, and our replay starts from the already-poisoned oracle.
The samples covered roughly two hours, which sounds long. The oracle was weak because it had only four discrete samples, read a pool that was cheap to move, and compared the result with no second source.
Estimating manipulation cost#
The quantity to estimate is how far the price must sit away from the market, and for how long, to move the average by a target amount. Take a 30-minute window on Ethereum, which is 150 blocks of 12 seconds, and a target of 20%.
With an arithmetic mean, as in v2, one block at 31 times the market price is enough, since (149 + 31) / 150 = 1.2. With a geometric mean, as in v3, one block has to sit at 1.2^150 times the market price, which is about 7.5 × 10^11. In tick terms that is roughly 273,500 ticks for a single block, or 1,823 ticks held for the whole window.
A displacement of that size is affordable only when there is almost no liquidity between the current price and the extremes of the range, and it pays only if nobody arbitrages it back before the next block. Under proof of work that second condition was a meaningful defence, since nobody knew who would produce the next block. Under proof of stake, proposers are known at least an epoch ahead, and a validator who controls two consecutive slots can move the price at the end of one block and restore it at the start of the next without competition.
Uniswap Labs analysed this in Uniswap v3 TWAP oracles in proof of stake (October 2022) and concluded that the capital required for the deep USDC/WETH pool was out of reach, while showing how much the cost depends on liquidity far from the current price: in their example a single $1M full-range position raised the cost of a two-block attack by about $360B. Mackinga, Nadahalli and Wattenhofer model the same attack in TWAP Oracle Attacks: Easier Done than Said? and find that a proposer with two blocks in a row can manipulate a TWAP orders of magnitude more cheaply than the classical multi-block estimate.
The check we would run first on any AMM-derived price is therefore the liquidity profile across the full range of the pool. In-range depth says what a small move costs, and the liquidity out at the extremes says what a one-block spike costs. For the rest, simulate the swaps on a fork, add fees for every block the position must be held, and compare the total with the largest amount the protocol would release at the moved price.
Reading a v3 TWAP correctly#
Uniswap's periphery library already contains the read. The core of OracleLibrary.consult at v1.3.0 is:
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
// ...
arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;
The last line is the one hand-written versions tend to drop. Solidity division truncates toward zero, so without the correction a negative mean tick comes out one tick higher than the library's result. The tagged library targets compilers below 0.8, and the repository's 0.8 branch has a version for newer ones.
A minimal adapter on top of it looks like this.
import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
/// Reverts with "OLD" if the pool's history is shorter than `window`.
function twapQuote(address pool, uint32 window, uint128 baseAmount, address base, address quote)
internal
view
returns (uint256)
{
(int24 meanTick, ) = OracleLibrary.consult(pool, window);
return OracleLibrary.getQuoteAtTick(meanTick, baseAmount, base, quote);
}
The integration mistakes we see most often sit around this function.
- The pool is chosen by fee tier or by habit, without checking that it is the deepest one for the pair.
- The window is copied from another protocol whose pool and exposure were different.
- The observation buffer was never enlarged, so the call reverts in production.
- A
try/catcharound the read falls back to spot, which hands the attacker the weaker oracle whenever they can make the stronger one revert.
Observation cardinality and startup#
observe reverts with OLD when the requested age is older than the oldest stored observation. A fresh pool has a cardinality of one, so any window fails until someone has called increaseObservationCardinalityNext and enough blocks with activity have passed to fill the new slots. The buffer needs at least one slot per block in which the pool trades during the window, which on Ethereum is about 150 slots for 30 minutes.
A protocol should decide in advance what it does while the oracle is warming up. Refusing new borrows and leaving repayments and withdrawals open is the usual answer. Silently shortening the window is the dangerous one, because it reproduces the short-window bug on purpose.
Window choice#
| Window | Blocks on Ethereum | What it buys | What usually breaks |
|---|---|---|---|
| 30 s to 2 min | 3 to 10 | protection against same-block moves only | a few held blocks move it |
| 10 to 30 min | 50 to 150 | a sustained move must outlast arbitrage | lag during fast markets |
| 1 hour or more | 300 or more | very expensive to hold on a deep pool | stale prices in crashes, late liquidations |
No row is safe in itself. The window has to be set against the profit available per action and the liquidity of the specific pool, and a long window on a thin pool is still cheap to walk.
Heartbeat, deviation and staleness in external feeds#
A Chainlink data feed is a pushed price. The aggregator writes a new answer when the off-chain value moves beyond a deviation threshold or when a heartbeat interval has passed, whichever comes first. For ETH/USD on Ethereum mainnet the feed directory listed 0.5% and 3,600 seconds when we checked in November 2026, so a healthy feed can be nearly an hour old and nearly half a percent off. Stablecoin feeds are slower, with USDC/USD at 0.25% and about a day.
The documentation tells consumers to check updatedAt from latestRoundData() against a limit they choose, and to pause or switch mode when the answer is too old. The limit has to be set per feed from its heartbeat. One global constant is either too tight for the daily feeds or too loose for the hourly ones.
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
error InvalidPrice();
error StalePrice(uint256 updatedAt);
/// `maxAge` is per feed: its heartbeat plus a margin for congestion.
function _readFeed(AggregatorV3Interface feed, uint256 maxAge) internal view returns (uint256 price, uint8 decimals) {
(, int256 answer,, uint256 updatedAt,) = feed.latestRoundData();
if (answer <= 0) revert InvalidPrice();
if (block.timestamp - updatedAt > maxAge) revert StalePrice(updatedAt);
return (uint256(answer), feed.decimals());
}
Two older habits need updating. The API reference marks answeredInRound as deprecated, so comparing it with roundId no longer tells you anything. It also says minAnswer and maxAnswer are no longer used on most feeds, which means the aggregator applies no price band for you and any plausibility bound has to be your own.
That last point has a recent example. On 4 November 2025 the wrsETH/ETH feed that Moonwell used on Base reported 1,649,934.6 ETH per wrsETH. Moonwell multiplied it by ETH/USD, and its oracle contracts checked little beyond the answer being positive, so one wrsETH was valued at about $5.8 billion. The incident report puts the bad debt at $3.7M, and our replay shows a deposit worth about seven cents backing a borrow of roughly $88,000. An exchange-rate feed for a staking token has a natural band around its last value, and a bound on that band would have rejected the reading. The reverse case, a collateral price that was far too low and triggered liquidations, is covered in our post on liquidation as a security property.
Failure modes that involve no attacker#
| Failure | How it happens | Safe response |
|---|---|---|
| Stale answer | updates stop or are delayed | block new risk, keep repayments and withdrawals open |
| Read reverts | the adapter breaks, or the TWAP history is shorter than the window | a bounded fallback or a pause, never a silent switch to spot |
| Zero or negative answer | a bad round | reject it, since a zero price means free collateral or free borrowing somewhere |
| Scale error | feed or token decimals are assumed | normalise in one function, test with real feeds |
| Thin market | liquidity leaves the pool that is read | minimum-liquidity checks and a second source |
Defensive controls that compose#
The controls named so far are all partial. A liquidity floor, a plausibility bound, a second independent source, caps on what one block can borrow, and a delay on large actions each close one gap and leave others. Our incident patterns post compares what each one stops and gives the code for a deviation bound between two sources. The rest of this post covers the three pieces that belong to the oracle adapter itself, which are scale handling, a clamp, and the choice of failure direction.
The decimals footgun#
Most USD-denominated Chainlink feeds report 8 decimals and ETH-denominated ones 18, and the feed directory also lists USD feeds with 18 decimals on some networks, while tokens use 6, 8 or 18. Every adapter therefore contains a scale factor, and a wrong one is exploitable at once by anyone, with no manipulation needed.
The PAXG/USDC market on Morpho Blue in October 2024 is the cleanest example we have. The oracle was deployed with the decimals of PAXG (18) and USDC (6) swapped, which made its immutable scale factor 10^12 too large. The feeds reported correct prices, and 0.13 PAXG was accepted as collateral for 230,000 USDC. Read decimals() at deployment instead of passing it by hand, keep the normalisation in one function, and add a deployment test that compares the adapter's output with a known price.
A clamp for single-update moves#
A clamp limits how far the accepted price can move from the last accepted one. It cannot make a manipulable source safe, and it reduces what a single bad reading can do.
/// Limits the accepted price to within maxBpsMove of the last accepted price.
/// Requires maxBpsMove <= 10_000.
function clamp(uint256 lastPrice, uint256 nextPrice, uint256 maxBpsMove) internal pure returns (uint256) {
uint256 delta = lastPrice * maxBpsMove / 10_000;
uint256 upper = lastPrice + delta;
uint256 lower = lastPrice - delta;
if (nextPrice > upper) return upper;
if (nextPrice < lower) return lower;
return nextPrice;
}
The cost is lag. During a real crash the clamped price trails the market, so liquidations start late and the protocol can accumulate bad debt that a faster oracle would have avoided. Size the step so that a real move is caught within a few updates.
Fail open or fail closed#
Reverting when the oracle is stale or implausible is the right default for operations that add risk, which are borrowing, minting and withdrawing collateral from a position with debt. Applied everywhere, the same revert freezes repayments and plain withdrawals during exactly the periods when users most want to act.
Liquidations are the hard case, since they need a price and blocking them lets bad debt grow. The designs we find convincing treat the three groups separately: risk-increasing actions fail closed, risk-reducing actions stay open without a price where possible, and liquidations run on a conservative price with a bound on what one call can seize.
Audit questions#
- Can the caller influence which pool or feed is read?
- What is the lowest liquidity the pool has had since launch, across the whole range?
- What is the largest amount one transaction can extract at a wrong price?
- What is the staleness limit for each feed, and how does it compare with that feed's heartbeat?
- What happens on a revert, a zero, a stale answer and a value that is fresh and absurd?
- What happens during startup, before the TWAP has a full window?
An integration is ready when each of these has an answer with a number in it.
Sources#
- Uniswap v2 oracle documentation and
UniswapV2Pair.solat v1.0.1: the cumulative price and how it is sampled. - Uniswap v3 price oracle documentation,
Oracle.solandOracleLibrary.sol: observations, cardinality, the geometric mean, and the note that v4 has no built-in oracle. - Uniswap Labs, Uniswap v3 TWAP oracles in proof of stake: multi-block manipulation by a proposer and the effect of full-range liquidity.
- Mackinga, Nadahalli and Wattenhofer, TWAP Oracle Attacks: Easier Done than Said?: cost model for multi-block attacks.
- Chainlink data feeds overview and API reference: heartbeat and deviation, the timestamp check, deprecated fields.
- samczsun, So you want to use a price oracle: a survey of oracle designs and their trade-offs.