Section 4 of 16
Pair: Reserve Updates and TWAP Oracle
Key takeaway: Uniswap V2's TWAP oracle accumulates
price0CumulativeLastandprice1CumulativeLaston every reserve update, encoded in a custom UQ112x112 fixed-point format (224 bits, 112 integer + 112 fractional). The_update()function holds two opposite arithmetic regimes in one body: reserve writes must revert on overflow (the uint112 cast is guarded by require), while accumulator increments must allow overflow so modular subtraction over an oracle window produces the correct average price.
What You Are Building
The _update() function is called after every mint, burn, and swap. It does two things: store the new reserves and accumulate prices for the TWAP (time-weighted average price) oracle. This is one of the most elegant pieces of Uniswap V2. A few lines of code give the entire DeFi ecosystem a manipulation-resistant price feed, and the design decisions behind each line are worth understanding deeply.
Your Code
Requirements
Sign up free — keep reading + earn 15 Lynx
Zealynx Academy is free. Track your progress, earn Lynx, and climb the leaderboard.
Sign up free to continueAlready have an account? Log in