Lesson 6 — Fees that change
Sources: Uniswap/v4-core
v4.0.0, psyto/summon-stocksb1dd190, fabrknt/shadowbook7d07439.Shadowbook builds against the v4-core inside its v4-periphery (
59d3ecf, v4.0.0 plus 12 commits).LPFeeLibrary.solandPool.solare the same there;Hooks.solandPoolManager.soldiffer only in where the swap and liquidity parameter structs live (types/PoolOperation.sol). The v4-core lines below are cited at v4.0.0.About 15 minutes to read, 40 if you run everything.
Same pool, same hook. One swap pays 102 bp, the next pays 30.
Normally a pool's LP fee is fixed in its key.
The exception is a key whose fee is the dynamic-fee flag 0x800000. Such a pool starts at a fee of 0, and its hook decides the fee. There are two ways to do it:
- store one with
updateDynamicLPFee - or return one from
beforeSwapwith the override flag0x400000set, for that swap only
v4-core uses the returned fee only for a dynamic-fee pool with the flag set. If the fee is over 100%, the swap reverts.
We'll read two hooks that use this.
Summon returns 0.30% or 1.00%, from the stock's market state.
Shadowbook's DirectionalFee returns a higher fee for swaps that move the pool's price toward a reference a keeper pushes.
Why charge those swaps more? Because they're the ones that take the LPs' stale quotes.
In this lesson we read both, then read the fees off real traces. In the trace, one swap pays 10200 pips (102 bp) and the next pays 3000 (30 bp). Along the way you'll learn:
- How a pool becomes a dynamic-fee pool, and what its fee is before any hook sets one
- The two ways a hook sets the fee, and the rules v4-core applies to a fee returned from
beforeSwap - Summon's two fees and when each applies
- DirectionalFee: its parameters as the code defines them, how it measures direction and distance, and what it guarantees
- Where to see the fee a swap actually paid
What makes a pool's fee dynamic?
The flags and limits are in LPFeeLibrary (libraries/LPFeeLibrary.sol L14-L25):
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
Fees are in hundredths of a basis point ("pips"). 3000 is 0.30%. 1_000_000 is 100%.
A pool is dynamic when its key's fee is exactly 0x800000. As Lessons 1 and 3 showed, initialize then starts it at 0 (getInitialLPFee), and refuses it without a hook (isValidHookAddress).
A hook that requires the flag can check it in beforeInitialize. DirectionalFee does: if (!LPFeeLibrary.isDynamicFee(key.fee)) revert NotDynamicFee(); (src/DirectionalFee.sol L194).
Summon needs no such check. The round builds its key with SummonPool.FEE, which is the flag, and only the round may initialize (Lesson 4).
How does a hook set the fee? Two ways
Way 1: store it.
The hook calls updateDynamicLPFee (PoolManager.sol L337-L344):
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external {
if (!key.fee.isDynamicFee() || msg.sender != address(key.hooks)) {
UnauthorizedDynamicLPFeeUpdate.selector.revertWith();
}
newDynamicLPFee.validate();
PoolId id = key.toId();
_pools[id].setLPFee(newDynamicLPFee);
}
Only the pool's own hook may call it. The fee stays until the hook changes it again. It needs no unlock (Lesson 2).
Way 2: return it, per swap.
beforeSwap returns a fee as its third value. The PoolManager reads it only for a dynamic-fee pool (libraries/Hooks.sol L260-L262):
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
And the swap uses it only if the override flag is set (libraries/Pool.sol L300-L308):
// if the beforeSwap hook returned a valid fee override, use that as the LP fee, otherwise load from storage
// lpFee, swapFee, and protocolFee are all in pips
{
uint24 lpFee = params.lpFeeOverride.isOverride()
? params.lpFeeOverride.removeOverrideFlagAndValidate()
: slot0Start.lpFee();
swapFee = protocolFee == 0 ? lpFee : uint16(protocolFee).calculateSwapFee(lpFee);
}
removeOverrideFlagAndValidate clears the flag bit and calls validate. Above MAX_LP_FEE, that reverts with LPFeeTooLarge(fee) (LPFeeLibrary.sol L41-L45, L72-L78).
Put together:
| the hook returns | on a static-fee pool | on a dynamic-fee pool |
|---|---|---|
a fee without 0x400000 | ignored | ignored: the stored fee is used |
a fee with 0x400000, at most 1_000_000 after the flag is removed | ignored | used for this swap; nothing is stored |
a fee with 0x400000, over 1_000_000 after the flag is removed | ignored | the swap reverts LPFeeTooLarge |
"Doesn't a fee that's too large just get skipped?" you might ask.
That's how IHooks reads. It describes the returned fee as "only used if three conditions are met", the third being "the value is less than or equal to the maximum fee (1 million)" (interfaces/IHooks.sol L102).
But be precise about the last row. With the flag set, a larger value is not skipped. The swap reverts, as the comment in Hooks.sol above says.
(Note: on top of the LP fee, a pool may have a protocol fee. swapFee combines the two, and the Swap event's last field is that swapFee (PoolManager.sol L239-L248). Neither project's tests set a protocol fee except one DirectionalFee test, so in the traces below the event's fee is the LP fee.)
Summon and DirectionalFee both use the per-swap way. They never call updateDynamicLPFee, so their pools' stored fee stays 0.
That's why, in Lesson 3's exercise B, a pool whose hook lost BEFORE_SWAP traded at 0.
Summon: 0.30% or 1.00%, and nothing else
The constants (src/SummonPool.sol L16-L17):
uint24 internal constant OPEN_FEE = 3000; // 0.30%, while the listing exchange is open
uint24 internal constant CLOSED_FEE = 10_000; // 1.00%, while it is closed or the guard is quiet
beforeSwap returns fee | LPFeeLibrary.OVERRIDE_FEE_FLAG (src/SummonHook.sol L84). _swapFee's last two lines choose which (L111-L113):
// 4. closed, or the guard has not confirmed the state lately
if (s.halted || uint256(s.updatedAt) + p.maxGuardAge < block.timestamp) return SummonPool.CLOSED_FEE;
return SummonPool.OPEN_FEE;
At this point, s.halted can only be a closed session. Rule 3 (Lesson 5) has already refused every other halt.
The round's own swap in realign always gets OPEN_FEE.
The fee depends on nothing about the swap itself. Not its size, not its direction.
test_swapFeeRisesWhileClosed (test/SummonRound.t.sol L909-L924) buys with 100 USDC three times from the same snapshot:
- open
- with the session recorded closed
- with the guard 301 s quiet
It checks the closed fill against the open one with assertApproxEqRel(closed * 1e18 / open, uint256(990_000e18) / 997_000, 1e15).
Where does that ratio come from? 1.00% instead of 0.30% leaves 990,000/997,000 of the output. The test checks that within 0.1%.
DirectionalFee: a swap toward the reference pays more
DirectionalFee is Shadowbook's second hook, for an ordinary liquidity pool. Its contract comment states the rule (src/DirectionalFee.sol L20-L26):
/// A swap whose direction moves the pool price toward the reference pays `towardFloor` or `slope`
/// times the distance, whichever is more, up to `maxFee`: those are the swaps that take the LPs'
/// stale quotes. A swap in the other direction, and every swap while the reference is missing or
/// older than `maxAge`, pays `baseFee`. Direction and distance are taken from the pool price
/// before the swap, and one fee applies to the whole swap: a swap large enough to cross the
/// reference pays the toward fee on all of it, including the part past the reference. The fee
/// never depends on the swap's size, so `getFee` quotes it exactly.
The reference is a square-root price in the pool's own terms. It comes with the time the keeper observed it and a sequence number.
The keeper pushes it with setRef(sqrtPriceX96, asOf, seq). That refuses a future, stale or out-of-order update (L114-L126).
The parameters, as the code declares them (L54-L58):
uint24 public baseFee; // away from the reference, and whenever the reference is unusable
uint24 public towardFloor; // least a swap toward the reference pays
uint24 public slope; // fee per bp of distance, in hundredths of a bp: 100 = 1x the distance
uint24 public maxFee; // most any swap pays
uint32 public maxAge; // seconds
The owner sets them. _setFees requires baseFee <= towardFloor <= maxFee <= MAX_FEE, with MAX_FEE = 50_000, 5% (L135-L141, L37): "a swap toward the reference never pays less than one away from it."
The fee itself (L163-L172):
/// zeroForOne lowers the pool price, so it moves toward a reference below the pool price.
function _fee(uint160 sqrtPriceX96, bool zeroForOne) internal view returns (uint24) {
Ref memory r = ref;
if (r.updatedAt == 0 || block.timestamp - r.updatedAt > maxAge) return baseFee;
if (zeroForOne ? sqrtPriceX96 <= r.sqrtPriceX96 : sqrtPriceX96 >= r.sqrtPriceX96) return baseFee;
uint256 f = _distBps(sqrtPriceX96, r.sqrtPriceX96) * slope;
if (f < towardFloor) f = towardFloor;
if (f > maxFee) f = maxFee;
return uint24(f);
}
beforeSwap reads the pool's current price from the PoolManager, and returns that fee with the override flag (L199-L209):
function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
view
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
if (PoolId.unwrap(key.toId()) != PoolId.unwrap(poolId)) revert WrongPool();
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
uint24 fee = _fee(sqrtPriceX96, params.zeroForOne);
return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, fee | LPFeeLibrary.OVERRIDE_FEE_FLAG);
}
Distance is |P / R − 1| in basis points, computed from the two square-root prices. (With d = |p / r − 1|, it is 2d + d² above the reference and 2d − d² below.)
It's rounded up, so the fee errs toward the LPs, and capped at 50,000 bp (_distBps, L174-L187).
"Could a wild price make beforeSwap revert?" you might ask.
No. Because of the cap, distance × slope can't overflow. And maxFee ≤ 5% keeps the result valid for v4-core.
So, in the README's words, "no price or parameter can make beforeSwap revert" and "Swaps are never refused" (README L147-L152).
The test suite uses the demo's defaults ("30 bp base and floor, 1× the distance, at most 300 bp", README L156), with a 60-second maxAge (test/DirectionalFee.t.sol L23-L27):
uint24 constant BASE = 3_000; // 30 bp
uint24 constant FLOOR = 3_000; // 30 bp
uint24 constant SLOPE = 100; // 1x the distance
uint24 constant MAXF = 30_000; // 300 bp
uint32 constant MAX_AGE = 60;
slope is in pips per basis point of distance. So 100 means a 1 bp move costs 1 bp of fee.
Here's an example. The pool is at 1:1 and the reference is 1% below.
- Selling token0 lowers the price toward the reference, and pays about 101 bp.
- Buying token0 pays the 30 bp base.
The test (L107-L114):
function test_refBelow_sellingToken0IsToward() public {
_ref(_sqrtAt(-100)); // reference 1% below the pool
(uint24 down, uint24 up) = hook.getFee(key);
assertEq(up, BASE, "away");
assertApproxEqAbs(down, 10_100, 100, "toward: 1x of 101 bp (1 / 0.99 - 1)");
assertEq(_swapFee(true), down);
assertEq(_swapFee(false), BASE);
}
_swapFee performs a swap and reads the fee back from the PoolManager's Swap event, not from the hook (L78-L95). So the test checks what the swap actually paid.
What if the keeper is wrong? The README states the trust model: "Given those, a wrong or compromised keeper cannot make the pool worse for LPs than a plain pool at baseFee: a bad reference only moves swaps between baseFee and a higher fee." (README L153-L155).
Side by side: when the source goes quiet, they do opposite things
| Summon | DirectionalFee | |
|---|---|---|
| input | the stock's market state | the pool's price against a keeper's reference |
| fees | 0.30% or 1.00% | baseFee, or max(towardFloor, slope × distance) up to maxFee |
| depends on direction | no | yes |
| when its source is stale | the higher fee (1.00%) | the lower fee (baseFee) |
| refuses swaps | yes, in the cases of Lesson 5 | never |
Look at the fourth row. When the outside source goes quiet, the defaults are opposite.
Summon assumes something may be wrong, and charges more.
DirectionalFee falls back to a plain pool. A reference it can't trust shouldn't make anyone pay more.
Exercise: read the fees off the traces
DirectionalFee. In your shadowbook checkout at 7d07439:
forge test --mt test_refBelow_sellingToken0IsToward -vv
forge test --mt test_refBelow_sellingToken0IsToward -vvvv | grep -E "::getFee|Return\] 10200|0x575e24b4|emit Swap"
-vv shows only [PASS] test_refBelow_sellingToken0IsToward() (gas: 445329).
Why so little? Neither the test nor the hook logs anything, and Foundry prints traces of passing tests only from -vvvv.
Here's what the second command printed (forge 1.7.1, 2026-11-14). The key, ids and addresses are cut (…), and the event's tail is removed:
├─ [17745] 0x4444000000000000000000000000000000002080::getFee(PoolKey(…)) [staticcall]
│ └─ ← [Return] 10200 [1.02e4], 3000
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 0, 4204504 [4.204e6]
│ │ │ │ ├─ emit Swap(id: 0x13806e…, sender: PoolSwapTest: […], amount0: -1000000000000 [-1e12], amount1: 989799020296 [9.897e11], …, fee: 10200 [1.02e4])
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 0, 4197304 [4.197e6]
│ │ │ │ ├─ emit Swap(id: 0x13806e…, sender: PoolSwapTest: […], amount0: 997000979651 [9.97e11], amount1: -1000000000000 [-1e12], …, fee: 3000)
Read it against the code:
getFeequotes 10200 toward (102 bp: 101.01 bp rounded up by_distBps) and 3000 away.- The first swap sells token0 (
amount0negative: the swapper pays token0). The hook returns4204504=10200 | 0x400000, and theSwapevent recordsfee: 10200. - The second swap buys token0. The hook returns
4197304=3000 | 0x400000, and the event recordsfee: 3000.
Summon. In your summon-stocks checkout at b1dd190:
forge test --mt test_swapFeeRisesWhileClosed -vvvv | grep -E "0x575e24b4|emit Swap\(|setState|VM::warp"
What we got, trimmed the same way:
├─ [0] VM::warp(1800000060 [1.8e9])
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 0, 4197304 [4.197e6]
│ │ │ │ ├─ emit Swap(id: 0x44765c…, sender: SummonSwap: […], amount0: 404972057 [4.049e8], amount1: -100000000 [-1e8], …, fee: 3000)
├─ [3722] MarketStateRegistry::setState(MockB20: […], true, 3, 0)
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 0, 4204304 [4.204e6]
│ │ │ │ ├─ emit Swap(id: 0x44765c…, sender: SummonSwap: […], amount0: 402262830 [4.022e8], amount1: -100000000 [-1e8], …, fee: 10000 [1e4])
├─ [0] VM::warp(1800000361 [1.8e9])
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 0, 4204304 [4.204e6]
│ │ │ │ ├─ emit Swap(id: 0x44765c…, sender: SummonSwap: […], amount0: 402262830 [4.022e8], amount1: -100000000 [-1e8], …, fee: 10000 [1e4])
Three buys of 100 USDC:
- Open:
3000, 404972057 units of the stock (the same number as in Lesson 2). - Session closed (
setState(…, true, 3, 0), reason 3):10000, 402262830. - Guard quiet:
10000again, and the same 402262830. Here the clock moved 301 s past the guard's last heartbeat, which_fillAftersent at the fill.maxGuardAgeis 300.
Change a fee and see which test notices. In a scratch copy, from the directory that holds your checkouts:
rm -rf /tmp/summon-scratch
cp -R summon-stocks /tmp/summon-scratch && cd /tmp/summon-scratch
rm -rf cache/fuzz # no fuzz failures replayed from earlier runs
sed -i '' 's/CLOSED_FEE = 10_000;/CLOSED_FEE = 5_000;/' src/SummonPool.sol # GNU sed: sed -i without ''
forge test --mc SummonRoundTest
[FAIL: assertion failed: 998089050869996198 !~= 992978936810431293 (max delta: 0.1000000000000000%, real delta: 0.5146246179177990%)] test_swapFeeRisesWhileClosed() (gas: 2111754)
Suite result: FAILED. 51 passed; 1 failed; 0 skipped; …
992978936810431293 is 990,000/997,000 in 1e18 units, the ratio the test expects. At 0.50%, the closed buy got 0.998 of the open one.
Only this test pins the closed fee. Undo with git checkout -- src.
Now the same in DirectionalFee.
Make a fresh copy of shadowbook (rm -rf /tmp/shadowbook-scratch && cp -R shadowbook /tmp/shadowbook-scratch && rm -rf /tmp/shadowbook-scratch/cache/fuzz). Comment out if (f < towardFloor) f = towardFloor; in _fee, and run forge test --mc DirectionalFeeTest.
We ran it six times, on a fresh copy each time. Five times we got 19 passed; 2 failed:
[FAIL: assertion failed: 600 != 3000] test_nearRef_towardPaysFloor(). A reference 5 bp away measures 6 bp after rounding up, which at 1× is 600, below the 3000 floor.testFuzz_feeFormula, whose counterexample differs from run to run.
Fuzz cases vary. testFuzz_feeWithinBounds also fails on the rare run where the fuzzed reference lands within 30 bp of the pool price (it did in an earlier run of ours). And in one of the six runs, a third test failed for an unrelated reason, below.
Undo with git checkout -- src.
A flaky test at the pin (2026-11-14).
At 7d07439, testFuzz_distance bounds both square-root prices to [2**64, 2**128] inclusive, then squares them. That overflows at exactly 2**128.
So now and then it fails on its own with panic: arithmetic underflow or overflow (0x11). The hook's _distBps is not involved.
Forge saves a fuzz failure in cache/fuzz/ and replays it on later runs in the same directory. That's why every scratch copy in this course removes cache/fuzz.
Shadowbook fixed the bound in 7ae1dd1 (2 ** 128 - 1). This lesson stays on 7d07439.
What to check
- You can say what fee a dynamic-fee pool has before its hook does anything, and the two ways a hook can change it.
- You can decode
4197304,4204304and4204504into a flag and a fee. - You can say what happens to a returned fee without the override flag, on a static-fee pool, and over 1,000,000.
- You can say in which direction DirectionalFee charges more when the reference is below the pool, and what it charges when the reference is 61 seconds old in the test setup.
- You read
fee: 3000,fee: 10000andfee: 10200in theSwapevents of your own traces, and saw the test that pins Summon's closed fee fail when you changed it.
Next, Lesson 7 goes further than the fee: a hook that prices the swap itself and fills it from its own inventory, with beforeSwapReturnDelta (Shadowbook).