A suite of median price oracles: an alternative to manipulation-prone TWAP
The Uniswap v3 TWAP oracle is no longer provided with base v4 pools. This change opens up the opportunity for oracle choice and advanced oracle implementations. Despite being relatively safe, the v3-style TWAP oracle is still susceptible to price manipulation. This project explores various implementations of a median price oracle as an alternative to TWAP.
Because manipulators need to control 50% of the observations, the median price oracle is considered much more robust and manipulation resistant. Calculating the median from an unsorted list of price observations is noticeably gas intensive so I opted to experiment with an approximation algorithm Frugal-2U https://arxiv.org/pdf/1407.1121v1.pdf
The project implements the oracles through Uniswap v4's hook pattern. The price observations are tightly packed with bit shifting in order to support up to 18 hours of price data
The Frugal-2U algorithm works by observing new data points, and then adjusting the approximated median (relative to the data point) via a dynamic step. With a running median approximation, less than 5000 gas is required for reads.
Foundry <3