Overview
On-chain, we need a price that is:
- Resistant to manipulation (not easily affected by flash loans)
- Reflects the true price over a period of time
- Does not rely on off-chain records
So time-weighted average prices are introduced:
TWAP (Time Weighted Average Price)
V2's approach is to accumulate prices:
a(t)=a(t−1)+price⋅Δt
Query range price:
p(t1,t2)=t2−t1a(t2)−a(t1)
The key improvement in V3 is that it no longer records price directly, but records:
tick=log1.0001(price)
Therefore:
price=1.0001tick
The essential change is to convert price⋅Δt into tick⋅Δt.
using:
log(p1⋅p2)=logp1+logp2
1. tickCumulative (core accumulator)
Definition:
tickCumulative(t)=∑tick⋅Δt
Update method:
tickCumulative=tickCumulative+tickcurrent⋅(tnow−tlast)
2. TWAP calculation
Given two points in time:
t1,t2
Step 1: Average tick
tickˉ=t2−t1tickCumulative(t2)−tickCumulative(t1)
Step 2: Restore price
p(t1,t2)=1.0001tickˉ
3. Why use tick(log)
Geometric mean
log(p1)+log(p2)=log(p1⋅p2)
Corresponding price relationship
price=1.0001tick
4. Observation (historical snapshot)
V3 stores the state of multiple time points on-chain, and each record contains:
- timestamp
- tickCumulative
- secondsPerLiquidityCumulative
Each observation represents a snapshot of the accumulator at a point in time.
5. secondsPerLiquidity Oracle
definition:
secondsPerLiquidityCumulative=∑liquidityΔt
Meaning:
Indicates the time during which one unit of liquidity participates in market making.
- The greater the liquidity → the less time it takes to distribute units
- The smaller the liquidity → the more time units will be allocated
6. Oracle query
Query two points in time:
t1,t2
calculate:
TWAP=t2−t1tickCumulative(t2)−tickCumulative(t1)
A unified perspective with the fee system
Fee system:
f(ilower,iupper)=fg−fb−fa
Oracle system:
p(t1,t2)=ΔtΔtickCumulative
Therefore, V2 and V3 are essentially unified, and both are expressed as:
value=cumulative(end)−cumulative(start)
The difference is only in the dimensions:
- fee: make difference in tick space
- oracle: make differences in the time dimension
The essence of Oracle in V3 is:
- Time integration of tick (log price)
- Restore the average price through difference when querying
Finally got:
TWAP=ΔtΔtickCumulative
Its core design is completely consistent with the fee system:
- Accumulator (cumulative)
- Interval difference (delta)
Just applied in different dimensions:
- fee → space (price range)
- oracle → time (time)