Lesson 8 — Hook safety and taking it to production
Sources: Uniswap/v4-core
v4.0.0, Uniswap/v4-peripheryc6e4754(the version Shadowbook pins), psyto/summon-stocks8a8b464, fabrknt/shadowbook7ae1dd1, fabrknt/market-statecbfc651(v0.4.0, Summon's pin at8a8b464) ande685ced.Summon moves to
8a8b464, its currentmain. Fromb1dd190(lessons 4–6) it changes onlyREADME.mdandtest/SummonRound.t.sol. The hook-refusal tests now expect the exact wrapped error, and there is a test for the swap-sideMultiplierMismatch(59 tests).src/andscript/are unchanged.About 25 minutes to read, 45 if you run everything.
Delete a check, and all 28 tests still pass
Comment out Shadowbook's NoQuote line, and all 28 Shadowbook tests still pass. The hook still refuses the swap, just for a different reason, and a bare vm.expectRevert() accepts any reason.
That's the kind of gap this lesson is about.
A hook is code the PoolManager calls in the middle of every swap. So its mistakes are the pool's.
This lesson gathers what the two projects do about that.
- The address. The callbacks a hook gets are fixed by its address. So the hook should check its own address at deploy, and the deploy should mine a salt for exactly those bits.
- Refusals. A hook refuses by reverting. The swapper sees the reason wrapped in
WrappedError, and tests should pin that reason, not just "something reverted". - Keepers. Most hooks read state that a keeper moves. Decide what happens when the keeper is wrong or quiet, bound what it can do, and check the keeper's own inputs before it writes.
The lesson ends with a checklist. Then comes the last exercise of the course's core: mine an address, deploy to it, and pin a revert reason that a test was missing.
You'll learn:
- How the self-check and the salt search fit together, and what changes the address
- How a hook's refusal reaches the caller, and how to test it exactly in two ways
- What each project does when its keeper goes quiet, and how it bounds a keeper that is wrong
- What went wrong once with a keeper on a live testnet deployment, and what changed after
- A checklist for a hook before real funds
The address: check it, mine it, require it
The PoolManager calls only the callbacks whose bits are set in the hook's address (Lesson 3).
There are three places to get this right.
1. In the constructor.
Lesson 3's exercise showed a hook running with BEFORE_SWAP missing, and nothing reverting. After that, Summon added the check in b1dd190 (src/SummonHook.sol L40-L53):
constructor(address poolManager_, address deployer_) {
poolManager = poolManager_;
deployer = deployer_;
// The PoolManager calls only the callbacks whose bits are set in this address. Refuse to exist at an
// address that would skip one of ours (a hook deployed without BEFORE_SWAP would never stop a swap).
Hooks.validateHookPermissions(IHooks(address(this)), getHookPermissions());
}
/// The callbacks this hook implements; its address must carry exactly these bits.
function getHookPermissions() public pure returns (Hooks.Permissions memory p) {
p.beforeInitialize = true;
p.beforeAddLiquidity = true;
p.beforeSwap = true;
}
It also added a test. The test deploys the hook with plain new, at an address with no chosen bits, and expects the refusal (test/SummonRound.t.sol L663-L671):
/// The PoolManager calls a hook only for the bits set in its address. A hook at an address missing one of
/// its bits (here: an ordinary CREATE address) must refuse to deploy, not run with a callback skipped.
function test_hookRefusesAnAddressWithoutItsPermissionBits() public {
try new SummonHook(address(pm), address(this)) returns (SummonHook h) {
revert(string.concat("deployed at ", vm.toString(address(h))));
} catch (bytes memory err) {
assertEq(bytes4(err), Hooks.HookAddressNotValid.selector);
}
}
validateHookPermissions is exact (Lesson 3). So an extra bit fails as surely as a missing one.
That matters more for SummonHook than for Shadowbook.
SummonHook declares only its three callbacks (contract SummonHook {, with no IHooks and no fallback, L25). A call to any other callback would revert. Shadowbook, by contrast, implements all of them and reverts HookNotImplemented in the unused ones.
2. In the deploy script.
CREATE2 puts a contract at the last 20 bytes of keccak256(0xff ++ deployer ++ salt ++ keccak256(initCode)) (HookMiner.sol L48-L56). The init code includes the constructor arguments.
v4-periphery's HookMiner tries salts until the low 14 bits match and nothing is deployed there yet (test/shared/HookMiner.sol L16-L41, trimmed):
/// @param deployer The address that will deploy the hook. In `forge test`, this will be the test contract `address(this)` or the pranking address
/// In `forge script`, this should be `0x4e59b44847b379578588920cA78FbF26c0B4956C` (CREATE2 Deployer Proxy)
...
for (uint256 salt; salt < MAX_LOOP; salt++) {
hookAddress = computeAddress(deployer, salt, creationCodeWithArgs);
// if the hook's bottom 14 bits match the desired flags AND the address does not have bytecode, we found a match
if (uint160(hookAddress) & FLAG_MASK == flags && hookAddress.code.length == 0) {
return (hookAddress, bytes32(salt));
}
}
So a mined salt is valid for one deployer, one build of the contract and one set of constructor arguments.
Change any of them, and the address moves. The exercise shows this.
3. After the deploy.
Both scripts compare the deployed address with the mined one.
- Summon:
require(address(hook) == hookAddr, "hook address")(script/Deploy.s.sol L49-L55) - Shadowbook:
require(address(hook) == at, "hook address")(Lesson 3)
The result is public. Summon's hook on Base Sepolia is at 0x13F9D81A93Ae3906551cC7D89A99D5b949D3e880 (deployments/84532.json L4). Its low 14 bits are 0x2880, the same three callbacks as in the tests.
"Then the deployed hook has the constructor check?" No.
That hook was deployed on 2026-11-11 (README L70), before b1dd190. So it's the version without the check. Its bits are right because the script mined them.
The checked version has different init code, and would need a new salt.
A refusal is a revert. So test the reason.
Both hooks refuse by reverting.
So a refused swap doesn't happen at all. The whole transaction rolls back, including whatever else the router did in its unlock.
The PoolManager wraps the revert in WrappedError(hook, callback, reason, HookCallFailed) (libraries/Hooks.sol L130-L136, libraries/CustomRevert.sol L10-L11. Lesson 5 reads it). Lesson 7's exercise A showed the same wrapper around a token transfer.
"Isn't it enough that the test reverts?"
No. A test that only says "it reverted" can't tell one refusal from another, or from an unrelated bug.
The two projects pin the reason in two different ways.
Expect the whole wrapped error.
Summon's tests at 8a8b464 build it once (test/SummonRound.t.sol L182-L195):
/// The PoolManager (v4-core v4.0.0) wraps a hook's revert: WrappedError(hook, callback, reason, HookCallFailed).
function _hookError(bytes4 callback, bytes memory reason) internal view returns (bytes memory) {
return abi.encodeWithSelector(
CustomRevert.WrappedError.selector,
address(hook),
callback,
reason,
abi.encodeWithSelector(Hooks.HookCallFailed.selector)
);
}
function _expectSwapRevert(bytes memory reason) internal {
vm.expectRevert(_hookError(IHooks.beforeSwap.selector, reason));
}
Then they use it on every refusal. For example _expectSwapRevert(abi.encodeWithSelector(SummonHook.MarketHalted.selector, halt)); (L951).
Before 8a8b464 these were bare vm.expectRevert().
Call the callback directly as the PoolManager.
Shadowbook does this in one test (test/Shadowbook.t.sol L335-L343):
function test_closedSide_errorIsSideClosed() public {
uint16 closed = hook.CLOSED();
vm.prank(quoter);
_post(hook, MID, HALF, closed);
// the PoolManager wraps hook reverts; check the inner reason via a direct beforeSwap call
vm.prank(address(manager));
vm.expectRevert(abi.encodeWithSelector(Shadowbook.SideClosed.selector, false));
hook.beforeSwap(address(this), key, SwapParams(false, 1e18, MAX_PRICE_LIMIT), ZERO_BYTES);
}
That's shorter. But it skips the PoolManager, so it doesn't show what a swapper receives.
Shadowbook's other refusal tests (stale quote, no quote, pause, band, closed side, cap, dust, empty inventory) use a bare vm.expectRevert() (for example L153-L160).
We found one place where that hides a missing check.
With the NoQuote line (L240) commented out, all 28 Shadowbook tests still pass. Why? A hook with no quote then fails the next check, StaleQuote, instead.
The exercise pins it.
One more guard belongs here.
Anyone can call an external function. So every callback must check that its caller is the PoolManager.
SummonHook does it first thing (L81, L121). It tests two of them called directly (test_hookRejectsDirectCalls, test_hookRejectsDirectSwapCalls, L683-L687, L1060-L1064).
Shadowbook uses an onlyPoolManager modifier (src/Shadowbook.sol L92-L95).
What does the hook do when its keeper is quiet, or wrong?
All three hooks in this course read state that an off-chain program writes. Shadowbook's quote, DirectionalFee's reference, Summon's market state.
Two questions decide how safe that is.
When the keeper goes quiet.
| the keeper writes | quiet for longer than allowed | never written | |
|---|---|---|---|
| Shadowbook | setQuote (quoter) | swaps revert StaleQuote (L241) | swaps revert NoQuote (L240) |
| DirectionalFee | setRef (keeper) | swaps pay baseFee (Lesson 6) | swaps pay baseFee |
| Summon, swaps | setState, heartbeat (guard) | swaps pay 1.00% (Lesson 5) | (no pool exists before a fill) |
| Summon, fills | the same | fills revert MarketStateStale | fills revert: updatedAt 0 counts as stale (src/MarketStateCheck.sol L17-L18) |
"Why do they behave so differently?"
Each choice follows from what the hook protects.
- Shadowbook sells its own inventory at the keeper's price. So without a fresh price, it stops.
- DirectionalFee only adds fees on top of an ordinary pool. So without a reference, it's an ordinary pool.
- Summon stops new fills, but keeps an existing pool trading at the higher fee.
None of these is "keep going as if nothing happened".
Write your choice down in the contract's comment, as all three do.
When the keeper is wrong.
Bound it in the contract, so a wrong or stolen keeper key can do limited harm.
- Shadowbook. The quoter can't post a mid outside the owner's band, so "a bad or compromised quoter can at worst sell inventory at the band's edge" (src/Shadowbook.sol L27-L29). A notional cap per rolling window limits volume. The README says plainly that it "limits volume, not loss from a wrong price; the band does that" (README L123-L130). Each quote carries the time its prices were observed and a sequence number. So a delayed transaction can't revive an old price or overwrite a newer one (L137-L153).
- DirectionalFee. The owner's bounds mean a wrong reference "only moves swaps between
baseFeeand a higher fee" (Lesson 6). - market-state. Here the bound is stated, not enforced: "A malicious or compromised updater can mark a halted stock as open. A stopped updater only closes markets. Run the updater yourself, and show users who holds the key." (README L62-L65).
The keeper's own inputs.
Summon's guard (ts/guard.ts) writes nothing when it can't read its source, so rounds fail closed (ts/guard.ts L11-L12): "A closed market writes nothing (a stale state reads as closed). An unreadable feed or price writes nothing either, so rounds fail closed."
It writes a changed state at once.
Unchanged ones it confirms in one batched heartbeat, when the last confirmation nears the rounds' 300-second limit (L26-L29, L64-L88).
The hook was right. The keeper's install was stale.
It went wrong once on testnet.
Summon's README records it (L71): "a stale v0.2.0 build once read the session as always open, so swaps after the close paid 0.30%."
How did that happen?
The guard decides "open" or "closed" with market-state's TypeScript half. Its node_modules still held a v0.2.0 build, which didn't know the core-hours session name.
An unknown name meant no session check at all, "so the market read open around the clock" (market-state README L86-L89).
The guard reported the stock open after the close. The hook read a fresh, open state, and charged the open fee.
Two changes followed, one in each place.
- The part fails closed. market-state
v0.4.0reads an unknown session name as closed (ts/guard.ts L227-L229):
} else if (name !== "always") {
// a policy read from JSON can carry any string: an unknown session is not evidence the market is open
return { halted: true, reason: MARKET_REASON.SESSION_CLOSED, resumeAfter: 0, detail: `unknown session ${JSON.stringify(name)}` };
- The keeper checks itself before it starts. Summon's guard refuses to run unless the installed copy reads a known weekend time and the first minutes of a session as closed (ts/guard.ts L156-L170).
The hook was right throughout. It trusted its input.
That's the usual shape. The contract can be checked by tests. The keeper's environment is where production differs from them.
A smaller one, from writing this course.
market-state's setState says it "emits only when the state itself changes". But with halted = false and a non-zero reason, it emitted on every call. It compared the reason as sent, while storing REASON_NONE.
e685ced compares the stored value (src/MarketStateRegistry.sol L60-L73) and adds a test (forge test: 9 tests, up from 8). It was released as v0.4.1 on 2026-11-15, and Summon now pins it (64bdf98).
"Is an extra event really a bug?"
The registry calls its event log "the machine-readable halt notice for participants". So an event that fires when nothing changed is a bug too.
Before real funds: neither project is audited
Neither project has been audited.
- Summon: "testnet only (Base Sepolia), unaudited, not for real funds" (README L5).
- Shadowbook: "early and unaudited; not yet deployed" (README L15).
Both went through rounds of review by another model (Codex) until approved. Both READMEs still say unaudited.
Keep that line in yours until it's no longer true. And start small. Shadowbook's plan is "a small inventory and a narrow band" (README L281).
Two more habits from these code bases:
- Fail at deploy, not on the first swap. Shadowbook's constructor refuses a zero owner or quoter, a
PoolManagerwithout code, a bad band and a bad cap window. A test tries each (src/Shadowbook.sol L102-L124, test L218-L251). - Keep the admin surface small, and say what it is. SummonHook's only admin call is a one-time
setFactoryby its deployer (L55-L60). Its inputs have owners instead (the registries). Shadowbook's owner is fully trusted, and its README lists every role with what it can and can't do (README L115-L121), including a pause (L176-L178).
Checklist
Address and permissions
-
getHookPermissionslists exactly the callbacks the contract implements, and the constructor callsHooks.validateHookPermissions. - A test deploys the hook at a wrong address and expects
HookAddressNotValid. - The deploy script mines with the deployer that will actually deploy (
0x4e59…956Cunderforge script), the final constructor arguments, and requires the deployed address to equal the mined one.
Callbacks
- Every callback checks
msg.sender == poolManager, and a test calls each directly. - Callbacks you do not use either have no bit or revert.
- A hook meant for one pool binds it in
beforeInitializeand checks it in every callback.
Refusals and deltas
- Every refusal has a test that expects the exact
WrappedError(or the exact reason, called as thePoolManager), and removing each refusing line fails a test. - If the hook returns deltas, its own account nets to zero in every path, and a test runs each swap kind (exact in and out, both directions).
- Every rounding favours the pool or the hook, checked by a fuzz test of the inequality.
Keepers
- For each keeper input: what the hook does when it is stale and when it was never written, in the contract's comment and in a test.
- What a wrong or stolen keeper key can do at worst, bounded in the contract and stated in the README.
- The keeper writes nothing when it cannot read its sources, and checks its own dependencies before it starts.
Shipping
- Constructor arguments are validated at deploy.
- The README says who holds which key, what is audited, and what is not.
- Start with small limits (inventory, cap, band, round size) on a real network before anything else.
Exercise: mine an address, then pin a reason
Use your shadowbook-7ae1dd1 clone from Lesson 7, in a fresh scratch copy:
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. Mine, deploy, and move the address.
Create test/Mine.t.sol:
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.26;
import {Deployers} from "v4-core/test/utils/Deployers.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {HookMiner} from "v4-periphery/test/shared/HookMiner.sol";
import {Shadowbook} from "../src/Shadowbook.sol";
contract MineTest is Deployers {
address quoter = makeAddr("quoter");
uint160 constant FLAGS = uint160(
Hooks.BEFORE_INITIALIZE_FLAG | Hooks.BEFORE_ADD_LIQUIDITY_FLAG | Hooks.BEFORE_SWAP_FLAG
| Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG
);
function _args(uint32 maxAge) internal view returns (bytes memory) {
return abi.encode(manager, address(this), quoter, uint128(50e24), uint128(100e24), maxAge, uint192(100_000e6), uint64(60));
}
function _deploy(bytes32 salt, uint32 maxAge) internal returns (Shadowbook) {
return new Shadowbook{salt: salt}(manager, address(this), quoter, 50e24, 100e24, maxAge, 100_000e6, 60);
}
/// In a test the deployer is this contract; under forge script it is the CREATE2 deployer proxy.
function test_mineAndDeploy() public {
deployFreshManagerAndRouters();
(address at, bytes32 salt) = HookMiner.find(address(this), FLAGS, type(Shadowbook).creationCode, _args(2));
emit log_named_uint("salt", uint256(salt));
emit log_named_address("hook", at);
assertEq(address(_deploy(salt, 2)), at);
}
/// Mined without BEFORE_SWAP_RETURNS_DELTA: the constructor refuses the address.
function test_mineWithoutTheDeltaBit() public {
deployFreshManagerAndRouters();
uint160 flags = FLAGS & ~uint160(Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG);
(, bytes32 salt) = HookMiner.find(address(this), flags, type(Shadowbook).creationCode, _args(2));
_deploy(salt, 2);
}
/// The right salt for maxAge 2, used with maxAge 3: another address.
function test_otherArgsSameSalt() public {
deployFreshManagerAndRouters();
(, bytes32 salt) = HookMiner.find(address(this), FLAGS, type(Shadowbook).creationCode, _args(2));
_deploy(salt, 3);
}
}
forge test --mc MineTest -vv
What we got (logs and the summary):
[PASS] test_mineAndDeploy() (gas: 49219603)
Logs:
salt: 3029
hook: 0x8F9E0C82aA5856154b0c8f4d7792a82D7f112888
[FAIL: HookAddressNotValid(0x4094aF20E4757AE390183f1f1396c16A37b0a880)] test_mineWithoutTheDeltaBit() (gas: 105672011)
[FAIL: HookAddressNotValid(0x1133842cFB53cd74c26eD9abDcb4B6efC9e91d56)] test_otherArgsSameSalt() (gas: 45154524)
Suite result: FAILED. 1 passed; 2 failed; 0 skipped; …
The two failures are the point. Decode the low 14 bits.
0x2888is bits 13, 11, 7 and 3, the four Shadowbook wants.0x4094…a880masked to its low 14 bits (0xa880 & 0x3fff) is0x2880. That's bits 13, 11 and 7, with the delta bit missing, so the constructor refused.0x1d56is whatever the changed arguments produced.
On a real deploy, that last case is a script that mined with one set of arguments and deployed with another. The require after new is what catches it.
Your salt and addresses should match ours at 7ae1dd1. They depend only on the build and the test's own addresses.
B. Pin a reason that a test was missing.
Comment out the NoQuote line and run the existing suite:
sed -i '' '240s|^ if (q.updatedAt == 0) revert NoQuote();| // if (q.updatedAt == 0) revert NoQuote();|' src/Shadowbook.sol # GNU sed: sed -i without ''
forge test --mc ShadowbookTest
Suite result: ok. 28 passed; 0 failed; 0 skipped; …
test_noQuote_reverts still passes. Its vm.expectRevert() accepts the StaleQuote that now fires instead.
Undo with git checkout -- src. Then add test/NoQuoteExact.t.sol, the same test with the reason pinned:
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.26;
import {IHooks} from "v4-core/src/interfaces/IHooks.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {CustomRevert} from "v4-core/src/libraries/CustomRevert.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {MockERC20} from "solmate/src/test/utils/mocks/MockERC20.sol";
import {Shadowbook} from "../src/Shadowbook.sol";
import {ShadowbookTest} from "./Shadowbook.t.sol";
contract NoQuoteExactTest is ShadowbookTest {
/// test_noQuote_reverts, with the reason pinned: the PoolManager wraps the hook's NoQuote.
function test_noQuote_revertsNoQuote() public {
Shadowbook h2 = _deployHook(address(uint160(FLAGS) ^ (0x5555 << 144)));
(PoolKey memory k2,) = initPool(currency0, currency1, IHooks(address(h2)), 0, 60, SQRT_PRICE_1_1);
MockERC20(Currency.unwrap(currency1)).transfer(address(h2), 1_000e6);
vm.expectRevert(
abi.encodeWithSelector(
CustomRevert.WrappedError.selector,
address(h2),
IHooks.beforeSwap.selector,
abi.encodeWithSelector(Shadowbook.NoQuote.selector),
abi.encodeWithSelector(Hooks.HookCallFailed.selector)
)
);
_swap(k2, true, -1e18);
}
}
It inherits ShadowbookTest, so a plain forge test would run the 28 inherited tests a second time. Select the new one:
forge test --mt test_noQuote_revertsNoQuote
[PASS] test_noQuote_revertsNoQuote() (gas: 393187)
Now comment out line 240 again (the same sed) and rerun it:
[FAIL: Error != expected error: WrappedError(0x5555000000000000000000000000000000002888, 0x575e24b4, 0xdaf34ce100000000000000000000000000000000000000000000000000000000000f4240, 0xa9e35b2f) != WrappedError(0x5555000000000000000000000000000000002888, 0x575e24b4, 0xc3186163, 0xa9e35b2f)] test_noQuote_revertsNoQuote() (gas: 393352)
The hook still refused. But the reason is 0xdaf34ce1 = StaleQuote(uint256), with an age of 0xf4240 = 1,000,000 seconds (the test's clock minus a timestamp of 0). It's not 0xc3186163 = NoQuote().
(Note: you can check both with cast sig.)
Undo with git checkout -- src.
C. The same, from the other side (Summon).
Summon's tests pinned their reasons in 8a8b464.
Make the halt rule (line 109) revert with the wrong error, and run the suite at both commits. From the directory that holds your summon-stocks checkout:
rm -rf /tmp/summon-scratch
cp -R summon-stocks /tmp/summon-scratch && cd /tmp/summon-scratch
git fetch origin && git checkout 8a8b464 && git submodule update --init --recursive
rm -rf cache/fuzz
sed -i '' '109s|revert MarketHalted(s.reason);|revert IssuerPaused();|' src/SummonHook.sol
forge test --mc SummonRoundTest
git stash && git checkout b1dd190 && git stash pop
forge test --mc SummonRoundTest
# at 8a8b464
[FAIL: Error != expected error: WrappedError(0x0500000000000000000000000000000000002880, 0x575e24b4, 0x26bbf01b, 0xa9e35b2f) != WrappedError(0x0500000000000000000000000000000000002880, 0x575e24b4, 0x46510f530000000000000000000000000000000000000000000000000000000000000001, 0xa9e35b2f)] test_swapStopsWhileHalted() (gas: 1932917)
Suite result: FAILED. 52 passed; 1 failed; 0 skipped; …
# at b1dd190
Suite result: ok. 52 passed; 0 failed; 0 skipped; …
At b1dd190, the halt test expected any revert, and got IssuerPaused (0x26bbf01b).
At 8a8b464, it expected MarketHalted(1) and said so.
(Note: the suite has 53 tests at 8a8b464 and 52 at b1dd190, hence 52 passed both times.)
Undo with git checkout -- src.
What to check
- You can say which three things a mined salt depends on, and saw an address move when one constructor argument changed.
- You can decode
0x2888,0x2880and Summon's deployed0x…e880into callbacks. - You saw a bare
vm.expectRevert()pass with a check removed, and your exactWrappedErrortest fail on the same edit. - For each keeper in this course, you can say what its hook does when the keeper is quiet, and what bounds a wrong one.
- You have the checklist above for your own hook.
Where to go from here: build one end to end
That's the core of the course. Lesson 9 takes the same hook to Monad.
- A pool is its key.
- Every balance change goes through
unlock. - A hook's address fixes its callbacks.
- A hook can decide who may add liquidity, when swaps stop, what they pay, and at what price they fill.
To build one end to end, the recipe Open a Uniswap v4 pool that knows its stock's market runs Summon on your machine against Base Sepolia.
/parts lists the parts these projects use, market-state among them, with the line that installs each.