Handle timestamp wrap in a Uniswap v2 cumulative price reader
The reference v2 pair intentionally truncates its timestamp to 32 bits. A reader using ordinary signed subtraction can see a negative interval even though three seconds elapsed.
Calculate elapsed time using the pair’s width
Read cumulative values and timestamps for the same pair at two observations. Take the timestamp difference modulo 2^32. For the example, the counter passes through 4294967295 and zero before reaching one.
previous uint32 timestamp = 4294967294
current uint32 timestamp = 1
elapsed modulo 2^32 = 3 seconds
Compute cumulative differences with the accumulator’s unsigned wrap semantics as well, then divide by the nonzero elapsed time. Decode the UQ112x112 scale and retain the distinction between price0 and its opposite direction.
Know when the pair actually updated
The pair accumulates the previous reserve ratio when an update occurs; a passive block read may see the last update timestamp. If extending a cumulative value to a later observation time, account for elapsed seconds and nonzero reserves explicitly. An exact multi-wrap interval cannot be recovered from the truncated timestamps alone. github.com UniswapV2Pair.sol