07 Position Fee Settlement
Overview
In the previous chapter, we derived:
This gives us a unified expression for the accumulated fees within an interval. However, one key question remains: how are LP gains recorded and settled in the contract?
1. Core question: Why can’t fees be allocated in real time?
In V2:
- All liquidity is global
- Fees go directly into the pool reserves
- LPs earn fees through their share of the pool
But in V3:
- Liquidity is split across price intervals
- Different LPs participate in swaps at different times
- Fees cannot be allocated on a tranche-by-tranche basis
If every LP had to be updated for every swap, gas usage would explode.
2. The core idea of V3: Lazy Settlement
V3 does not allocate fees to LPs for each swap. Instead, it accumulates them first and settles them later.
Each position will be recorded:
feeGrowthInside0LastX128
feeGrowthInside1LastX128
tokensOwed0
tokensOwed1
When an LP creates or updates a position, it stores:
Stored as:
Current moment:
Revenue calculation:
From feeGrowth to real income
It represents the return per unit of liquidity. Therefore, the actual LP return is:
Where:
- = LP liquidity
- = accumulated fee within the current range
- = snapshot from the last settlement
Core formula:
3. When is settlement triggered?
V3 does not automatically send funds. Settlement is triggered only when the following operations are performed:
1. mint (open position)
- Initialize the position
- Record the initial snapshot:
2. increaseLiquidity (increase position)
Fees must be settled before adding liquidity:
Then update:
Then update f_last = f_inside. Newly added liquidity should not receive historical returns.
3. decreaseLiquidity (reduce position)
Same idea:
- Settle the old income first
- Then reduce liquidity
4. collect (receive proceeds)
collect does not calculate returns. It only does one thing: transfer(tokensOwed) and then set tokensOwed = 0.
Example:
Assumptions:
LP provides liquidity:
S = 100Initial:
Unit: token / liquidity
After some time:
Then:
means that each unit of liquidity earns 5 more tokens, so the total income is:
Note: In the real Uniswap V3 contract, feeGrowthInsideX128 is actually:
LP income calculation, using the real on-chain formula:
Note: f here represents the cumulative income per unit of liquidity (fee / liquidity), not the actual number of tokens.