Skip to content
← Build a market on Uniswap v4 — the PoolManager and hooks, read from two open projects
Part 2 — A pool's own rules: who, when, at what fee

Build a new market · Uniswap v4

5 of 9 in this course40 min

Lesson 5 — A pool that knows its stock's market

Sources: Uniswap/v4-core v4.0.0, psyto/summon-stocks b1dd190, fabrknt/market-state v0.4.0 (cbfc651, the tag Summon pins as a submodule at the commits this lesson reads).

About 15 minutes to read, 40 if you run everything.

A quiet guard doesn't stop swaps. It raises the fee to 1.00%.

A tokenized stock can keep trading onchain while its listing exchange has stopped it.

SummonHook's beforeSwap closes that gap. On every swap it reads three sources:

  • the stock token: its multiplier, and any scheduled change
  • the issuer's registry: paused, and its own multiplier
  • a market-state registry that an off-chain guard writes: halted, why, when it last confirmed, not before when

The swap reverts in a corporate action window, on a stale multiplier, while the issuer pauses, while the registries disagree, while the stock is halted, and before it may resume.

"So if the guard stops writing, trading stops too?" you might ask.

Not in the pool. While the session is closed, or the guard hasn't confirmed the state for longer than allowed, the swap goes through at 1.00% instead of 0.30%.

A quiet guard raises the fee. It doesn't stop swaps.

In this lesson we read the rules in order, follow the realign path after a split, and see how a hook's revert reaches the swapper. Then you write a test of your own. Along the way you'll learn:

  • The market-state registry: what the guard writes, and what updatedAt and resumeAfter mean
  • SummonHook's rules in the order it applies them, the error each one raises, and the test that covers it
  • What exactly happens when the guard goes quiet: for swaps, and for fills
  • How the pool is re-priced after a split (realign), and why the round's own swap skips the rules
  • How the PoolManager wraps a hook's revert, and how to assert the exact error in a test

Where does the hook get its facts?

The guard's registry.

market-state is a small package. It has two halves: an off-chain guard that reads Nasdaq Trader's halts feed and the trading session, and a registry the guard writes onchain.

Its README describes the Solidity half (README L15-L18): "MarketStateCheck.requireOpen reverts when a token is halted, before its resumption time, or when the guard has not confirmed its state within maxStateAge. A guard that goes quiet therefore stops trading."

Keep that last sentence in mind. We'll come back to it.

Here's the state it keeps per token (src/MarketStateRegistry.sol L9-L22):

uint8 public constant REASON_NONE = 0;
uint8 public constant REASON_PRIMARY_HALT = 1; // halted or suspended on the primary listing exchange
uint8 public constant REASON_BAD_PRINT = 2; // reference price moved outside the band
uint8 public constant REASON_SESSION_CLOSED = 3; // scenario only trades during a session
uint8 public constant REASON_CORPORATE_ACTION = 4; // issuer-announced pause around an action
uint8 public constant REASON_MANUAL = 5;
uint8 public constant REASON_ISSUER_PAUSED = 6;

struct State {
    bool halted;
    uint8 reason;
    uint64 updatedAt; // last time the guard confirmed this state (heartbeat)
    uint64 resumeAfter; // even when not halted, no trading before this time
}

The guard calls setState when something changes, and heartbeat to confirm nothing has (L62-L77). Both set updatedAt to the block time.

setState stores reason only while halted. Otherwise it stores REASON_NONE.

The token.

A B20 stock token carries a multiplier(): how many shares one token is worth, scaled by 1e18. It also carries an effectiveAt(): the time a scheduled change to it takes effect, or 0 (src/SummonRound.sol L28-L32).

The issuer's registry.

getOracleParams(token) returns the issuer's multiplier and a paused flag (L34-L37).

On a chain without one, its address may be address(0) (L60).

And the hook itself keeps no settings.

It finds the round through the factory, as in Lesson 4. It reads the addresses (round.deps()) and the limits (round.params(): cooldownSeconds, maxGuardAge) from the round.

In the test suite those limits are 3600 s and 300 s (test/SummonRound.t.sol L112-L121).

Which swaps does the hook refuse, and in what order?

beforeSwap picks the fee. On the way, it decides whether the swap may happen at all (src/SummonHook.sol L76-L85):

function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata, bytes calldata)
    external
    view
    returns (bytes4, BeforeSwapDelta, uint24)
{
    if (msg.sender != poolManager) revert NotPoolManager();
    SummonRound round = SummonRound(_roundOf(key));
    uint24 fee = sender == address(round) ? SummonPool.OPEN_FEE : _swapFee(round);
    return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, fee | LPFeeLibrary.OVERRIDE_FEE_FLAG);
}

The fee and the flag are Lesson 6's subject. The rules live in _swapFee (L87-L114):

/// The fee a swap pays now (§5.5 rules 1-5); reverts where swaps stop. The round's own swap inside
/// `realign` skips these rules.
function _swapFee(SummonRound round) internal view returns (uint24) {
    SummonRound.Params memory p = round.params();
    // 1. corporate action window, the same one the fill conditions use
    uint256 eff = IB20AssetMin(p.token).effectiveAt();
    if (eff != 0 && block.timestamp + p.cooldownSeconds >= eff && block.timestamp <= eff + p.cooldownSeconds) {
        revert CorporateActionWindow(eff);
    }
    // 2. the pool was priced at another multiplier
    uint256 m = IB20AssetMin(p.token).multiplier();
    if (m != round.poolMultiplier()) revert StaleMultiplier(round.poolMultiplier(), m);
    // 2a. the issuer's registry: paused, or disagreeing with the token, stops swaps as it stops fills (Codex r3 #4)
    address reg = round.deps().oracleRegistry;
    if (reg != address(0)) {
        (uint256 rm, bool paused) = IOracleParams(reg).getOracleParams(p.token);
        if (paused) revert IssuerPaused();
        if (rm != m) revert MultiplierMismatch(rm, m);
    }
    // 3. halted, or not yet resumed
    MarketStateRegistry ms = MarketStateRegistry(round.deps().marketState);
    MarketStateRegistry.State memory s = ms.stateOf(p.token);
    if (s.halted && s.reason != ms.REASON_SESSION_CLOSED()) revert MarketHalted(s.reason);
    if (block.timestamp < s.resumeAfter) revert MarketHalted(s.reason);
    // 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;
}

Here they are as a table:

ruleswap stops whenerrortest
1a multiplier change is scheduled within cooldownSeconds either side of nowCorporateActionWindow(effectiveAt)test_swapStopsInCorporateActionWindow
2the token's multiplier is not the one the pool was priced atStaleMultiplier(pool, token)test_realignAfterMultiplierChange
2athe issuer's registry is pausedIssuerPaused()test_swapStopsWhileTheIssuerPauses
2athe issuer's registry and the token disagree on the multiplierMultiplierMismatch(registry, token)none for swaps (see below)
3the stock is halted for any reason but a closed sessionMarketHalted(reason)test_swapStopsWhileHalted
3it is before resumeAfterMarketHalted(reason)test_swapStopsWhileHalted
4never: the session is closed, or the guard is quiet(fee 1.00%)test_swapFeeRisesWhileClosed

Four details in the code are easy to miss.

The window runs both ways.

Rule 1 refuses from cooldownSeconds before effectiveAt until cooldownSeconds after it. In the tests that's an hour each side.

The comment says it's "the same one the fill conditions use". It is: the round's _inActionWindow has the same expression (src/SummonRound.sol L526-L528).

A closed session is not a halt.

The guard records a closed session as halted with REASON_SESSION_CLOSED. Rule 3 lets that through, and rule 4 charges it the closed fee.

resumeAfter applies when not halted too.

That's what its comment in the registry says. After a halt, the guard can mark the stock open but not tradable until a later time.

The error is still MarketHalted(s.reason). And since setState stores REASON_NONE while not halted, it reads MarketHalted(0).

MultiplierMismatch has no swap test.

The fill path has one (test_registryMultiplierMismatch). For swaps, there's none.

How do we know? We commented out that line in a scratch copy, and all 52 tests in SummonRoundTest still passed. The other five refusing lines each failed a test when removed.

Since then (2026-11-14): Summon commit 8a8b464 adds test_swapStopsWhileTheRegistryDisagrees (test/SummonRound.t.sol L975-L984, at that commit). It also makes the hook-refusal tests expect the exact wrapped error instead of a bare vm.expectRevert(). This lesson and its exercise stay on b1dd190.

(Note: the rules read live state, so every swap in the summoned pool pays for these external calls. In Lesson 2's trace, the hook's beforeSwap used 17430 gas.)

When the guard goes quiet, swaps pay more and fills stop

Rule 4 compares updatedAt + maxGuardAge with the block time.

A guard that has stopped writing makes the state stale. If that stale state was last "open", the hook returns CLOSED_FEE. Swaps continue at 1.00%.

The test says so in a comment, at the end of test_swapFeeRisesWhileClosed (test/SummonRound.t.sol L920-L923):

vm.revertToState(snap);
// a guard that has gone quiet counts as closed too
vm.warp(vm.getBlockTimestamp() + 301);
assertEq(_buy(router, key, usdcIs0), closed);

What if the stale state was last "halted"? Then swaps are still refused. Rule 3 runs before rule 4, and it doesn't look at updatedAt.

Fills are stricter.

The round checks the market with market-state's own reader, which fails closed (src/MarketStateCheck.sol L14-L20):

function requireOpen(MarketStateRegistry registry, address token, uint256 maxStateAge) internal view {
    MarketStateRegistry.State memory s = registry.stateOf(token);
    if (s.halted) revert MarketHalted(s.reason);
    // a token the guard never wrote has updatedAt 0, so it is stale too
    if (uint256(s.updatedAt) + maxStateAge < block.timestamp) revert MarketStateStale(s.updatedAt);
    if (block.timestamp < s.resumeAfter) revert NotYetResumed(s.resumeAfter);
}

It's called at src/SummonRound.sol L488-L489 (// 2. market state, fail closed).

So a quiet guard stops new fills. But it doesn't stop trading in a pool that already exists. It makes that trading cost more.

"Isn't that the opposite of what the README said?" you might ask.

It is, and it's a design choice. SummonHook's notice states it (L18-L23): "While the session is closed, or the guard has gone quiet, swaps pay a higher fee."

The registry's own notice says "Readers fail closed when the guard goes quiet" (src/MarketStateRegistry.sol L5-L7). So if you read SummonHook, know that its swap path is the exception.

After a split, the first trader could buy at half price

Say the multiplier changes: a 2-for-1 split makes one token worth two shares.

The pool still prices the token at the old multiplier. So the first trader could buy at half price.

Rule 2 stops swaps until the pool is re-priced. Once the window has passed, anyone may re-price it (src/SummonRound.sol L372-L395, trimmed):

/// §5.5a: after a corporate action, re-prices the backers' pool by the multiplier's change, so the first
/// trader cannot take the difference. Anyone may call it once the action window has passed.
function realign() external nonReentrant {
    ...
    uint256 m = IB20AssetMin(p.token).multiplier();
    uint256 from = poolMultiplier;
    if (m == from) revert NothingToDo();
    uint256 eff = IB20AssetMin(p.token).effectiveAt();
    if (_inActionWindow(eff)) revert CorporateActionWindow(eff);
    if (d.oracleRegistry != address(0)) {
        (uint256 rm,) = IOracleParams(d.oracleRegistry).getOracleParams(p.token);
        if (rm != m) revert MultiplierMismatch(rm, m);
    }
    (uint256 t, uint256 u, uint128 l, uint160 sqrtP) = abi.decode(
        IPoolManager(d.poolManager).unlock(abi.encode(OP_REALIGN, m, from)), (uint256, uint256, uint128, uint160)
    );
    ...
    poolMultiplier = m;
    emit Realigned(from, m, sqrtP, l);
}

Inside the callback (L425-L435), the round does three things. It removes its whole position. It moves the empty pool's price with a swap. Then it adds the position back at the new price:

(uint256 t, uint256 u) = _removeAll(pm, key);
if (op == OP_UNWIND) return abi.encode(t, u);
// realign: the pool is empty now, so a swap moves its price and moves no tokens. The price is
// currency1 per currency0, so it scales by new/old multiplier when the token is currency0.
(uint160 sqrtNow,,,) = pm.getSlot0(key.toId());
uint160 target = tokenIs0 ? SummonPool.scaledSqrtPrice(sqrtNow, a, b) : SummonPool.scaledSqrtPrice(sqrtNow, b, a);
if (target != sqrtNow) {
    pm.swap(key, IPoolManager.SwapParams({zeroForOne: target < sqrtNow, amountSpecified: -1, sqrtPriceLimitX96: target}), "");
}
(uint256 tUsed, uint256 uUsed, uint128 l2) = _addFullRange(pm, key, target, t, u);
return abi.encode(t - tUsed, u - uUsed, l2, target);

"But wouldn't rule 2 refuse that swap?" you might ask.

It would. That swap goes through beforeSwap like any other, and at that moment the multiplier is still stale.

That's why beforeSwap skips the rules when sender == address(round), and returns the open fee.

(Note: "The pool is empty now" is Lesson 4's other reason for keeping outsiders' liquidity out.)

test_realignAfterMultiplierChange (test/SummonRound.t.sol L950-L998) walks the whole path:

  1. The token's multiplier goes to 2e18, and a swap reverts (StaleMultiplier).
  2. realign is refused inside the window, and while the issuer's registry still says 1e18.
  3. Once both agree, it succeeds.

The pool's square-root price has moved by a factor of √2. $100 then buys about half as many tokens as before.

What does the swapper see when a hook reverts?

Not the hook's own error. The PoolManager doesn't let a hook's revert through as is. callHook wraps it (libraries/Hooks.sol L130-L136):

function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
    bool success;
    assembly ("memory-safe") {
        success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
    }
    // Revert with FailedHookCall, containing any error message to bubble up
    if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

It wraps it into an ERC-7751 error (libraries/CustomRevert.sol L10-L11):

/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

The four fields:

  • target is the hook
  • selector is the callback (beforeSwap is 0x575e24b4)
  • reason is the hook's own revert data
  • details is the selector of HookCallFailed()

Neither unlock nor a router like SummonSwap catches it, so it reaches the caller unchanged.

Summon's tests don't check for it. They use a bare vm.expectRevert() with a comment instead ("the PoolManager wraps the hook's MarketHalted").

That passes on any revert at all. The exercise asserts the exact error.

Exercise: write your own test, then remove the rule

Start from the directory that holds your checkouts:

git -C summon-stocks fetch origin
git -C summon-stocks checkout b1dd190 && git -C summon-stocks submodule update --init --recursive
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

Now add a test for a halt the suite doesn't try: a bad print (REASON_BAD_PRINT, 2). It asserts the full wrapped error:

cat > test/BadPrint.t.sol <<'EOF'
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.26;

import {PoolKey} from "v4-core/src/types/PoolKey.sol";
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 {SummonHook} from "../src/SummonHook.sol";
import {SummonSwap} from "../src/SummonSwap.sol";
import {SummonRoundTest} from "./SummonRound.t.sol";

contract BadPrintTest is SummonRoundTest {
    function test_swapStopsOnABadPrint() public {
        (SummonSwap router, PoolKey memory key, bool usdcIs0) = _summoned();
        // the guard freezes the token: its reference price moved outside the band
        market.setState(address(token), true, market.REASON_BAD_PRINT(), 0);
        vm.prank(alice);
        vm.expectRevert(
            abi.encodeWithSelector(
                CustomRevert.WrappedError.selector,
                address(hook),
                IHooks.beforeSwap.selector,
                abi.encodeWithSelector(SummonHook.MarketHalted.selector, uint8(2)),
                abi.encodeWithSelector(Hooks.HookCallFailed.selector)
            )
        );
        router.swapExactIn(key, usdcIs0, 100e6, 1, alice);
    }
}
EOF
forge test --mt test_swapStopsOnABadPrint
forge test --mt test_swapStopsOnABadPrint -vvvv | grep -E "MarketHalted|WrappedError"

_summoned() (L894-L902) fills a round and returns a router and the pool key.

Here's what we got. Timings are cut (…), and the trace lines are trimmed to the innermost revert and the first wrapped one:

Ran 1 test for test/BadPrint.t.sol:BadPrintTest
[PASS] test_swapStopsOnABadPrint() (gas: 1898907)
Suite result: ok. 1 passed; 0 failed; 0 skipped; …

    │   │   │   │   │   └─ ← [Revert] MarketHalted(2)
    │   │   │   │   └─ ← [Revert] WrappedError(0x0500000000000000000000000000000000002880, 0x575e24b4, 0x46510f530000000000000000000000000000000000000000000000000000000000000002, 0xa9e35b2f)

0x46510f53 is MarketHalted(uint8), followed by the reason 2. 0xa9e35b2f is HookCallFailed(). (Check with cast sig "MarketHalted(uint8)".)

The same WrappedError repeats on each frame up to the test.

Now remove rule 3's halt check (line 109), and run your test and the suite:

sed -i '' '109s|^|//|' src/SummonHook.sol   # GNU sed: sed -i without ''
forge test --mt test_swapStopsOnABadPrint
forge test --mc SummonRoundTest
[FAIL: next call did not revert as expected] test_swapStopsOnABadPrint() (gas: 2006492)
Suite result: FAILED. 0 passed; 1 failed; 0 skipped; …

[FAIL: next call did not revert as expected] test_swapStopsWhileHalted() (gas: 2003663)
Suite result: FAILED. 51 passed; 1 failed; 0 skipped; …

The swap wasn't refused. Did it go through at the open fee, then?

No. Rule 4 still sees halted and charges 1.00%.

(Note: in test_swapStopsWhileHalted's -vvvv trace with this edit, the hook returns 4204304, which is 10000 | 0x400000, and the Swap event shows fee: 10000.)

Undo with git checkout -- src and rm test/BadPrint.t.sol. forge test is back to 58 passing.

What to check

  • You can name the three sources beforeSwap reads and which fields of each it uses.
  • For each refusing rule, you can give its error and the test that catches its removal, and you know which one has no swap test.
  • You can say what a quiet guard does to a swap (1.00%) and to a fill (MarketStateStale), and why a stale halt still refuses swaps.
  • You can explain why the round's own swap in realign skips the rules.
  • Your test_swapStopsOnABadPrint passed with the exact WrappedError, failed with line 109 removed, and the scratch copy is back to 58 passing.

Next, Lesson 6 looks at the fee itself: how a hook returns one, what v4-core checks, and a hook that prices by direction.