Oracle manipulation: spot vs TWAP
A protocol is only as safe as its price source: any spot value read from a pool that can be traded within the same transaction is free to manipulate for one block.
Procedure
- Locate every price read:
grep -nE 'getReserves|slot0|latestRoundData|balanceOf\(|getAmountsOut|price0Cumulative' -r src/. - Classify each source: AMM spot reserves (manipulable), AMM TWAP (costly), Chainlink aggregator (needs staleness/heartbeat checks), internal accounting (trust only if the writer is non-reentrant).
- For AMM spot reads, compute the flash-loan cost:
cost ≈ 2 * amountIn * feeon a constant-product pool; a $50m pool with 0.30% fee needs ~$300k to move ~2% — cheap relative to most exploits. - Check TWAP window length in seconds: reject any window under 600s for lending/minting logic (
windowSize < 600is a red flag). - For Chainlink, verify all four:
answer > 0,updatedAt != 0,block.timestamp - updatedAt <= heartbeat, and a non-zeroansweredInRound. - Confirm the price read is not inside the same block as the action that depends on it, and cache the feed decimals:
AggregatorV3Interface(feed).decimals(). - Simulate a manipulation: on a mainnet fork, take a whale-sized flash loan, swap, call the victim, then revert.
uint256 bal = IERC20(WETH).balanceOf(PAIR);
IUniswapV2Pair(PAIR).swap(0, manipAmount, victim, "");
victim.borrow(maxBorrow); // must not under-collateralise
forge test --match-test testOracleManip -vvvvon--fork-url $ETH_RPC_URLand inspect the victim's state deltas.- Check the fallback path when the oracle reverts or returns stale data — a
try/catchthat defaults to a stale value is exploitable. - Record the source, window, manipulation cost, and whether the victim's state changed.
Pitfalls
latestRoundDataread without a staleness check; during an outage the last price is returned forever.- A "TWAP" computed as the average of two spot reads one second apart — still spot-manipulable.
- Reading
token.balanceOf(pool)as the price for a share token; an attacker donates to inflate it. - Chainlink on L2 (Arbitrum/Base) uses sequencer uptime feeds; ignoring the sequencer-down grace period breaks the staleness guard.
- Using
decimals()of the feed but not of the base token, mixing 8- and 18-decimal maths.
Verification
forge test --match-test testOracleManip --fork-url $ETH_RPC_URL -vvvv
Pass: the manipulated-price call reverts or the victim's accounting is unchanged; a failing run shows the victim accepting a position it should refuse.
Report the price source, the manipulation cost in USD, and the test outcome.