Section 9 of 10
TWAP Oracle + Fee Accumulation
TWAP Oracle + Fee Accumulation
What You Are Building
Your AMM's spot price can be manipulated within a single transaction (flash loans). A TWAP (Time-Weighted Average Price) oracle tracks cumulative prices over time, making manipulation expensive because the attacker would need to sustain the manipulated price across multiple blocks.
In this section, you will implement:
- Cumulative price tracking in
_update() - The protocol fee mechanism (optional 0.05% fee split)
kLasttracking for fee calculation
How the TWAP Oracle Works
Every time reserves change, _update() accumulates the current price multiplied by time elapsed:
price0CumulativeLast += (reserve1 / reserve0) * timeElapsed
price1CumulativeLast += (reserve0 / reserve1) * timeElapsed
To read the average price over a period, an external contract snapshots price0CumulativeLast at two points in time and divides the difference by the time elapsed. This gives a price that is resistant to single-block manipulation.
Protocol Fee Mechanism
Uniswap V2 has a switch for a 0.05% protocol fee (1/6 of the 0.3% trading fee). When enabled, the protocol mints LP tokens to a feeTo address proportional to the growth in sqrt(k).
This is calculated in _mintFee():
rootK = sqrt(reserve0 * reserve1)
rootKLast = sqrt(kLast)
feeLP = totalSupply * (rootK - rootKLast) / (5 * rootK + rootKLast)
Your Task
Add cumulative price tracking to _update() and implement the _mintFee() function. The fee mechanism should be optional (only active when feeTo != address(0)).