Lesson 7 — Pricing it yourself: beforeSwapReturnDelta
Sources: Uniswap/v4-core
v4.0.0, fabrknt/shadowbook7ae1dd1.Shadowbook moves from
7d07439(lessons 1–6) to7ae1dd1, its currentmain. The only change between them is the fuzz bound intest/DirectionalFee.t.sol(Lesson 6).src/,script/,README.mdandtest/Shadowbook.t.solare identical, so every Shadowbook line cited earlier still holds. Shadowbook builds against v4-core59d3ecf(inside v4-peripheryc6e4754).BeforeSwapDelta.sol,Pool.solandCurrency.solare the same there.Hooks.sol,PoolManager.solandIHooks.soldiffer only in where the swap and liquidity parameter structs live, which movesHooks.soldown by one line. The v4-core lines below are cited at v4.0.0.About 25 minutes to read, 45 if you run everything.
The curve swaps nothing. The hook fills the whole swap itself.
Give a hook's address the BEFORE_SWAP_RETURNS_DELTA bit, and beforeSwap can return a BeforeSwapDelta. That's two signed amounts. One is in the currency the swapper specified, the other in the other currency.
The PoolManager reduces the amount the curve will swap by the first. It charges both to the hook, and passes the opposite to the swapper.
So what if the hook returns exactly the swap's amount?
Then the curve has nothing left to do. The hook has taken the whole swap and priced it itself.
Shadowbook does this on every swap. It prices from a quote a keeper posts. It takes the input as ERC-6909 claims, pays the output from its own inventory, and returns the delta that brings its own balance back to zero.
In this lesson we read that path in v4-core and in Shadowbook, then break it three ways:
- How the
PoolManageruses a delta returned frombeforeSwap, and why a delta equal to the swap amount skips the curve BeforeSwapDelta: which currency is "specified", and the sign convention- The pattern in v4-core's own test hook, and how Shadowbook differs from it
- How Shadowbook prices a swap, rounds it, and settles its side with the
PoolManager - What a sign mistake, a missing settlement and rounding the wrong way each look like
Where does the delta enter the swap?
PoolManager.swap calls the hook first. Then it swaps what is left, and accounts two deltas (PoolManager.sol L196-L224, trimmed):
BeforeSwapDelta beforeSwapDelta;
{
int256 amountToSwap;
uint24 lpFeeOverride;
(amountToSwap, beforeSwapDelta, lpFeeOverride) = key.hooks.beforeSwap(key, params, hookData);
...
}
BalanceDelta hookDelta;
(swapDelta, hookDelta) = key.hooks.afterSwap(key, params, swapDelta, hookData, beforeSwapDelta);
// if the hook doesn't have the flag to be able to return deltas, hookDelta will always be 0
if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks));
_accountPoolBalanceDelta(key, swapDelta, msg.sender);
The curve gets amountToSwap, not the swapper's amount.
Hooks.beforeSwap computes it. It only reads the hook's delta if the address carries the bit (libraries/Hooks.sol L264-L279):
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
An exact-input swap has a negative amountSpecified (Lesson 2).
If the hook returns +|amountSpecified| as its specified delta, amountToSwap becomes 0. The pool's swap then returns at once with a zero delta (libraries/Pool.sol L320):
if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, result);
"Can the hook return more than the swap?" It can try. A delta larger than the swap would flip it from exact input to exact output, so it reverts HookDeltaExceedsSwapAmount.
Then Hooks.afterSwap turns the two numbers into token0 and token1, and moves them from the swapper to the hook (L304-L313):
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
BeforeSwapDelta: two numbers in one word
The type packs two int128 into one int256 (types/BeforeSwapDelta.sol L4-L16):
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
So which currency is "specified"?
It's the currency of amountSpecified. From the condition in afterSwap above:
zeroForOne (sell token0) | !zeroForOne (buy token0) | |
|---|---|---|
exact input (amountSpecified < 0) | specified = token0, the input | specified = token1, the input |
exact output (amountSpecified > 0) | specified = token1, the output | specified = token0, the output |
The sign is the hook's side. It's the same convention as every other delta: "Positive: the hook is owed/took currency, negative: the hook owes/sent currency" (interfaces/IHooks.sol L101).
The swapper gets the opposite.
The pattern in v4-core: a 1:1 curve
v4-core ships a test hook that replaces the curve with a straight line (src/test/CustomCurveHook.sol L40-L47):
// this "custom curve" is a line, 1-1
// take the full input amount, and give the full output amount
manager.take(inputCurrency, address(this), amount);
outputCurrency.settle(manager, address(this), amount, false);
// return -amountSpecified as specified to no-op the concentrated liquidity swap
BeforeSwapDelta hookDelta = toBeforeSwapDelta(int128(-params.amountSpecified), int128(params.amountSpecified));
return (IHooks.beforeSwap.selector, hookDelta, 0);
Every hook of this kind takes three steps:
- Collect the input
- Pay the output
- Return the delta that cancels both on the hook's own account
Take an exact-input swap of a.
takeleaves the hook at−ain the input.settleleaves it at+ain the output.- The returned delta (
+aspecified,−aunspecified) brings both to zero.
The swapper ends at −a input and +a output. Its router pays and collects that, as in Lesson 2.
Shadowbook's beforeSwap: the same three steps, its own price
Shadowbook follows the same three steps with a price of its own (src/Shadowbook.sol L232-L265):
function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
if (PoolId.unwrap(key.toId()) != PoolId.unwrap(poolId)) revert WrongPool();
if (paused) revert Paused();
Quote memory q = quote;
if (q.updatedAt == 0) revert NoQuote();
if (block.timestamp - q.updatedAt > maxAge) revert StaleQuote(block.timestamp - q.updatedAt);
if (q.mid < minMid || q.mid > maxMid) revert OutOfBand(q.mid);
if ((params.zeroForOne ? q.bidBps : q.askBps) == CLOSED) revert SideClosed(params.zeroForOne);
bool exactInput = params.amountSpecified < 0;
uint256 specified = exactInput ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
uint256 unspecified = _price(params.zeroForOne, exactInput, specified, q);
(uint256 amountIn, uint256 amountOut) = exactInput ? (specified, unspecified) : (unspecified, specified);
if (amountOut == 0) revert ZeroOutput();
(Currency cin, Currency cout) =
params.zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
uint256 notional1 = params.zeroForOne ? amountOut : amountIn;
budget.spend(notional1, notionalCap, capWindow);
poolManager.mint(address(this), cin.toId(), amountIn);
_payOut(cout, amountOut);
emit Filled(params.zeroForOne, amountIn, amountOut, notional1);
BeforeSwapDelta d = exactInput
? toBeforeSwapDelta(int128(int256(specified)), -int128(int256(unspecified)))
: toBeforeSwapDelta(-int128(int256(specified)), int128(int256(unspecified)));
return (IHooks.beforeSwap.selector, d, 0);
}
Read it in four parts.
1. Refusals.
One pool. Not paused. A quote that exists, is no older than maxAge, has its mid inside the owner's band, and has the requested side open.
Each is a revert, so the swap doesn't happen. Lesson 8 comes back to these.
2. The price.
_price gives the side the swapper didn't specify (below).
3. Its own side of the accounting.
It mints itself ERC-6909 claims for the input (−amountIn on its account, Lesson 2), and pays the output (+amountOut).
"Why not take the input, like v4-core's test hook does?"
Its contract comment says why (L31-L33): "A swap's input arrives as claims (the swapper settles after the hook returns, so the manager holds no real tokens yet); its output burns claims first and pays the rest from real balances."
4. The delta.
- Exact input:
+specified(the input it is owed),−unspecified(the output it owes). - Exact output:
−specified(the output),+unspecified(the input).
Both signs follow the table above.
The fee is 0. In Shadowbook's key the fee is 0 and the curve never runs (README L205-L207). The spread is the hook's income.
Here's how it pays the output (L285-L300):
function _payOut(Currency c, uint256 amount) internal {
uint256 claims = poolManager.balanceOf(address(this), c.toId());
uint256 burnAmt = claims < amount ? claims : amount;
if (burnAmt != 0) poolManager.burn(address(this), c.toId(), burnAmt);
if (amount > burnAmt) _settle(c, amount - burnAmt);
}
function _settle(Currency c, uint256 amount) internal {
if (c.isAddressZero()) {
poolManager.settle{value: amount}();
} else {
poolManager.sync(c);
c.transfer(address(poolManager), amount);
poolManager.settle();
}
}
Claims from earlier swaps go first (burning one credits the hook). Then real tokens, through sync, transfer, settle.
So the hook's inventory is two things: tokens it holds, and claims in the PoolManager.
inventory(currency) adds them up (L205-L208). The owner turns claims back into tokens with redeem, which runs its own unlock (L193-L203).
Take an exact-input sale of 1 token0 at a bid of 71.964 token1. The hook's account in the PoolManager goes like this:
| step | token0 | token1 |
|---|---|---|
mint claims for the input | −1e18 | |
_payOut: sync, transfer, settle | +71,964,000 | |
| returned delta: specified +1e18, unspecified −71,964,000 | +1e18 | −71,964,000 |
| the hook, after the swap | 0 | 0 |
The swapper's swapDelta from the curve is 0. So swapDelta − hookDelta leaves it at −1e18 token0 and +71,964,000 token1.
Its router settles and takes those. Only then does unlock check that every delta is zero.
Which way does the price round?
The quote is a mid and a distance per side.
Prices are token1 raw units per token0 raw unit, times PRICE_SCALE, 1e36 (L21-L25, L39).
Here's _price (L267-L283):
/// The unspecified side of a swap at the quoted bid (user sells token0) or ask (user buys
/// token0). Rounding always favours the hook.
function _price(bool zeroForOne, bool exactInput, uint256 amount, Quote memory q) internal pure returns (uint256) {
uint256 px = zeroForOne
? uint256(q.mid) * (BPS - q.bidBps) / BPS // bid
: FullMath.mulDivRoundingUp(q.mid, BPS + q.askBps, BPS); // ask
if (zeroForOne) {
// in: token0, out: token1
return exactInput
? FullMath.mulDiv(amount, px, PRICE_SCALE) // out1
: FullMath.mulDivRoundingUp(amount, PRICE_SCALE, px); // in0
}
// in: token1, out: token0
return exactInput
? FullMath.mulDiv(amount, PRICE_SCALE, px) // out0
: FullMath.mulDivRoundingUp(amount, px, PRICE_SCALE); // in1
}
| the swapper | the hook computes | rounded |
|---|---|---|
| sells token0, exact input | token1 out = in × bid | down |
| sells token0, exact output | token0 in = out ÷ bid | up |
| buys token0, exact input | token0 out = in ÷ ask | down |
| buys token0, exact output | token1 in = out × ask | up |
The bid itself rounds down, and the ask up.
Every rounding goes against the swapper. So no swap, however small, gets a better price than the quote.
The tests pin the numbers with a mid of 72e24 (72 USDC per 18-decimal token) and 5 bp each side (test/Shadowbook.t.sol L91-L124).
- Selling 1e18 pays 71,964,000.
- Buying 1e18 costs 72,036,000.
A fuzz test checks the inequality for any size and spread (L126-L149): "Whatever the size, the hook never pays out more than the quoted price allows."
What changes when the curve is skipped?
The Swap event shows zeros.
It carries the curve's delta, which is 0. The amounts are in the hook's own Filled event (L69).
Anything that reads volume from Swap events alone will see none here. (The exercise shows both.)
The price limit does nothing.
In the README's words (L132-L134): "Swaps fill entirely in beforeSwap, so the PoolManager's concentrated-liquidity step gets zero and the swapper's sqrtPriceLimitX96 has no effect. Callers must protect themselves with a minimum output (exact input) or maximum input (exact output), as aggregators already do."
No outside liquidity.
Shadowbook's beforeAddLiquidity always reverts NoExternalLiquidity (Lesson 4).
Any position added to the curve would never trade anyway, since the hook takes every swap whole.
What can go wrong?
| mistake | what happens | where it shows |
|---|---|---|
| a delta sign flipped | the curve is asked to swap twice the amount; the swapper's deltas point the wrong way | the router's own checks, or CurrencyNotSettled (exercise B) |
| the output never paid | the hook's account stays negative | CurrencyNotSettled, or earlier if the PoolManager cannot pay the swapper (exercise A) |
| rounding toward the swapper | each fill gives away up to one raw unit | only a test that checks the inequality (exercise C) |
| a specified delta larger than the swap | the swap would change type | HookDeltaExceedsSwapAmount |
the address lacks BEFORE_SWAP_RETURNS_DELTA | the PoolManager never reads the delta (hasPermission, above) | Shadowbook's constructor refuses such an address (Lesson 3) |
Exercise: read a fill, then break it three ways
Clone Shadowbook fresh at the commit this lesson cites:
git clone https://github.com/fabrknt/shadowbook shadowbook-7ae1dd1
cd shadowbook-7ae1dd1
git checkout 7ae1dd1
forge install
forge test
What we got (forge 1.7.1, macOS, 2026-11-14; per-test lines removed):
Compiling 88 files with Solc 0.8.26
Ran 21 tests for test/DirectionalFee.t.sol:DirectionalFeeTest
Suite result: ok. 21 passed; 0 failed; 0 skipped; …
Ran 28 tests for test/Shadowbook.t.sol:ShadowbookTest
Suite result: ok. 28 passed; 0 failed; 0 skipped; …
Ran 2 test suites in …: 49 tests passed, 0 failed, 0 skipped (49 total tests)
(Note: forge install rewrites foundry.lock without its final newline, so git status shows it modified. That's harmless.)
Read a fill.
Run the exact-input sale with full traces, and keep the calls that matter:
forge test --mt test_sellToken0_exactIn_atBid -vvvv | grep -E "::beforeSwap|::mint|::sync|::transfer|::settle\(|::take|emit Filled|emit Swap|Return\] 0x575e24b4"
What we got, with long arguments cut (…):
│ │ │ │ ├─ [150243] 0x4444000000000000000000000000000000002888::beforeSwap(PoolSwapTest: […], PoolKey({ … }), SwapParams({ zeroForOne: true, amountSpecified: -1000000000000000000 [-1e18], … }), 0x)
│ │ │ │ │ ├─ [25484] PoolManager::mint(0x4444000000000000000000000000000000002888, 124512733235148509670984850249661524172173354937 [1.245e47], 1000000000000000000 [1e18])
│ │ │ │ │ ├─ [2497] PoolManager::sync(MockERC20: [0x212224D2F2d262cd093eE13240ca4873fcCBbA3C])
│ │ │ │ │ ├─ [26329] MockERC20::transfer(PoolManager: […], 71964000 [7.196e7])
│ │ │ │ │ ├─ [4036] PoolManager::settle()
│ │ │ │ │ ├─ emit Filled(zeroForOne: true, amountIn: 1000000000000000000 [1e18], amountOut: 71964000 [7.196e7], notional1: 71964000 [7.196e7])
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 340282366920938463803656974352706674919374607431696247456 [3.402e56], 0
│ │ │ │ ├─ emit Swap(id: 0x7d5d05…, sender: PoolSwapTest: […], amount0: 0, amount1: 0, sqrtPriceX96: 79228162514264337593543950336 [7.922e28], liquidity: 0, tick: 0, fee: 0)
│ │ │ ├─ [2497] PoolManager::sync(MockERC20: [0x15cF58144EF33af1e14b5208015d11F9143E27b9])
│ │ │ ├─ [28836] MockERC20::transferFrom(ShadowbookTest: […], PoolManager: […], 1000000000000000000 [1e18])
│ │ │ ├─ [4024] PoolManager::settle()
│ │ │ ├─ [9062] PoolManager::take(MockERC20: [0x212224D2F2d262cd093eE13240ca4873fcCBbA3C], ShadowbookTest: […], 71964000 [7.196e7])
│ │ │ │ ├─ [6429] MockERC20::transfer(ShadowbookTest: […], 71964000 [7.196e7])
Read it against the code:
- Inside
beforeSwap, there's amintof 1e18 token0 claims (the id is the token's address as a number). Thensync, transfer andsettleof 71,964,000 token1, thenFilled. Without| grep, the full trace also shows that at thissyncthePoolManagerheld 0 token1. It has no other pools' tokens in this test. - The second return value is the
BeforeSwapDeltaas one number. Split it:python3 -c "v=340282366920938463803656974352706674919374607431696247456; lo=v&(2**128-1); print(v>>128, lo-2**128 if lo>=2**127 else lo)"prints1000000000000000000 -71964000. That's specified +1e18, unspecified −71,964,000. Swaprecordsamount0: 0, amount1: 0, liquidity: 0, fee: 0. The curve did nothing. The amounts are inFilled.- Only after the hook returns does the router (
PoolSwapTest) pay 1e18 token0 (sync,transferFrom,settle) and take 71,964,000 token1. That's the order the contract comment describes. The swapper settles after the hook returns.
Now break it, in scratch copies. Start each step from a fresh copy:
# from the directory that holds shadowbook-7ae1dd1
rm -rf /tmp/shadowbook-scratch
cp -R shadowbook-7ae1dd1 /tmp/shadowbook-scratch && cd /tmp/shadowbook-scratch
rm -rf cache/fuzz # no fuzz failures replayed from earlier runs
A. Never pay the output.
Comment out line 258, _payOut(cout, amountOut);:
sed -i '' '258s|^ _payOut| // _payOut|' src/Shadowbook.sol # GNU sed: sed -i without ''
forge test --mt test_sellToken0_exactIn_atBid
[FAIL: WrappedError(0x212224D2F2d262cd093eE13240ca4873fcCBbA3C, 0xa9059cbb, 0x4e487b710000000000000000000000000000000000000000000000000000000000000011, 0xf27f64e4)] test_sellToken0_exactIn_atBid() (gas: 275334)
You might expect CurrencyNotSettled here. But it fails before unlock can check anything.
The router's take asks the PoolManager to send 71,964,000 token1 that nobody paid in. The token's transfer (0xa9059cbb) underflows (0x4e487b71…11 is Panic(0x11)). v4-core wraps that as ERC20TransferFailed (0xf27f64e4, types/Currency.sol L81-L85).
A PoolManager in production holds the tokens of every pool it serves. So there, the take can succeed.
Let's simulate that. Keep the edit, and add one line at the top of test_sellToken0_exactIn_atBid in test/Shadowbook.t.sol:
function test_sellToken0_exactIn_atBid() public {
MockERC20(Currency.unwrap(currency1)).transfer(address(manager), 100e6); // the manager holds other pools' USDC
[FAIL: CurrencyNotSettled()] test_sellToken0_exactIn_atBid() (gas: 308901)
Now the swapper is paid out of other pools' tokens. The hook's −71,964,000 is still open when the router's callback returns, so unlock reverts.
Undo with git checkout -- src test. (With only the added line, the test passes.)
B. Flip the signs.
In line 262, move the minus sign from the second argument to the first:
sed -i '' '262s|toBeforeSwapDelta(int128(int256(specified)), -int128(int256(unspecified)))|toBeforeSwapDelta(-int128(int256(specified)), int128(int256(unspecified)))|' src/Shadowbook.sol
forge test --mt test_sellToken0_exactIn_atBid -vvv | grep -E "FAIL|emit Swap"
[FAIL: deltaAfter1 is not greater than or equal to 0] test_sellToken0_exactIn_atBid() (gas: 671433)
│ │ │ │ ├─ emit Swap(id: 0x7d5d05…, sender: PoolSwapTest: […], amount0: 0, amount1: 0, sqrtPriceX96: 4295128740 [4.295e9], liquidity: 0, tick: -887272 [-8.872e5], fee: 0)
With −1e18 as the specified delta, amountToSwap became −2e18. That's still exact input, so v4-core let it through.
The curve then swapped against zero liquidity. That moved the pool's price to the swapper's limit (sqrtPriceX96: 4295128740, tick: -887272) and filled nothing.
The swapper's token1 delta came out negative, the opposite of a sale. The test router's own check (PoolSwapTest.sol L64-L72, in the v4-core Shadowbook builds against) stopped it.
"And without that check?" The hook's own account would still be off, at −2e18 token0 and +143,928,000 token1 by the table above. unlock would revert CurrencyNotSettled.
Either way, the message names a router or the lock, not the hook.
Undo with git checkout -- src.
C. Round the wrong way.
Make the exact-output sale round its input down (line 277):
sed -i '' '277s|FullMath.mulDivRoundingUp(amount, PRICE_SCALE, px)|FullMath.mulDiv(amount, PRICE_SCALE, px)|' src/Shadowbook.sol
forge test --mc ShadowbookTest
In nine runs (a fresh copy each time) we got 27 passed; 1 failed every time.
The one is the fuzz test. Its counterexample differs per run, but it's always a sale with exact output (true, false in args). That's the only path the edit touches. One of ours:
[FAIL: assertion failed: 2462000000000000000000000000000000000000 > 2461999999999957401600000000000000000000; counterexample: calldata=0x… args=[2462, true, false, 144, 500]] testFuzz_roundingFavoursHook(uint96,bool,bool,uint16,uint16) (runs: 29, …)
Suite result: FAILED. 27 passed; 1 failed; 0 skipped; …
The swapper asked for 2,462 raw units of token1 and paid one raw unit of token0 too few. Out × 1e36 exceeds in × bid.
"Doesn't the rounding test catch it?" No. test_sellToken0_exactOut_roundsUpInput still passes, because its amounts divide exactly or keep the input above zero.
Only the inequality, checked over many sizes, finds a rounding error of one unit.
Undo with git checkout -- src. forge test is back to 49 passing.
What to check
- You can say what
amountToSwapis after a hook returns a specified delta of+|amountSpecified|, and what the pool's swap then does. - You can name the specified currency for each of the four swap kinds, and the sign of each half of Shadowbook's delta.
- You can explain why Shadowbook mints claims for the input instead of taking it, and where its output comes from.
- In your trace you found
mint, thesettleof the output,Filled, aSwapof zeros, then the router paying and taking. - You saw
ERC20TransferFailed, thenCurrencyNotSettled, with the output unpaid; the router's check with the signs flipped; and the fuzz test fail with one rounding reversed.
Next, Lesson 8 collects what the course has shown about hooks that refuse, keepers that move their inputs, and getting a hook to the right address.
It ends with a checklist for production.