Skip to content
← Build a market on Uniswap v4 — the PoolManager and hooks, read from two open projects
Part 1 — Pools, unlock and hook addresses

Build a new market · Uniswap v4

2 of 9 in this course35 min

Lesson 2 — PoolManager, unlock and flash accounting

Sources: Uniswap/v4-core v4.0.0, psyto/summon-stocks d4debb7, fabrknt/shadowbook 7d07439.

About 12 minutes to read, 35 if you run everything.

Every swap has to net to zero before unlock returns

On v4 you can't swap or add liquidity by calling the PoolManager once.

You call unlock. The PoolManager calls you back.

Inside that callback, every swap and every liquidity change only writes down what you owe and what you're owed, per currency.

You pay with sync + transfer + settle. You collect with take.

And unlock reverts unless everything nets to zero before it returns.

In a real trace you'll watch alice sell 100 USDC: the router owes -100000000 USDC and is owed +404972057 of the stock. settle and take bring both back to zero. Remove one settle, and the test fails with CurrencyNotSettled().

In this lesson we read that mechanism in v4-core, walk Summon's swap router and its pool seeding through it, and read the real call trace of a test. You'll learn:

  • unlock, unlockCallback and the onlyWhenUnlocked guard
  • Currency deltas: where they're kept, their sign, and the counter that unlock checks
  • sync, settle and take, and why sync comes before the transfer
  • How Summon's SummonSwap and SummonRound use one unlock each, and how a hook can join the same accounting

Why can't you just call swap?

Because everything that moves balances sits behind one modifier (PoolManager.sol L95-L98):

modifier onlyWhenUnlocked() {
    if (!Lock.isUnlocked()) ManagerLocked.selector.revertWith();
    _;
}

swap, modifyLiquidity, donate, take, settle, mint and burn all carry it.

The only way to unlock is unlock itself (PoolManager.sol L103-L113):

function unlock(bytes calldata data) external override returns (bytes memory result) {
    if (Lock.isUnlocked()) AlreadyUnlocked.selector.revertWith();

    Lock.unlock();

    // the caller does everything in this callback, including paying what they owe via calls to settle
    result = IUnlockCallback(msg.sender).unlockCallback(data);

    if (NonzeroDeltaCount.read() != 0) CurrencyNotSettled.selector.revertWith();
    Lock.lock();
}

So the caller has to be a contract that implements unlockCallback(bytes) (IUnlockCallback.sol L9).

Which calls need no unlock? The interface says so (IPoolManager.sol L108-L110): "The only functions callable without an unlocking are initialize and updateDynamicLPFee."

A swap moves no tokens. It writes down a delta

Inside the callback, a swap doesn't move tokens.

It ends by recording the result against the caller (PoolManager.sol L224): _accountPoolBalanceDelta(key, swapDelta, msg.sender);. That calls _accountDelta once per currency (L366-L376):

function _accountDelta(Currency currency, int128 delta, address target) internal {
    if (delta == 0) return;

    (int256 previous, int256 next) = currency.applyDelta(target, delta);

    if (next == 0) {
        NonzeroDeltaCount.decrement();
    } else if (previous == 0) {
        NonzeroDeltaCount.increment();
    }
}

The delta per (address, currency) lives in transient storage (tload / tstore in CurrencyDelta.sol L28-L41). So does the count of nonzero deltas (NonzeroDeltaCount.sol).

Both vanish at the end of the transaction.

That's why unlock only has to check that one counter is zero.

Which way does the sign point? From the caller's side. swap returns "the balance delta of the address swapping" (IPoolManager.sol L159).

  • Negative means the caller owes the PoolManager.
  • Positive means the PoolManager owes the caller.

An exact-input swap passes a negative amountSpecified (L149).

Why sync has to come before the transfer

Three calls settle up:

  • take(currency, to, amount) (L289-L295) sends tokens out and adds -amount to the caller's delta. It clears a positive delta.
  • sync(currency) (L277-L286) records the PoolManager's current balance of that currency.
  • settle() (L298-L300, body in _settle L347-L363) credits the caller with what arrived since sync:
uint256 reservesBefore = CurrencyReserves.getSyncedReserves();
uint256 reservesNow = currency.balanceOfSelf();
paid = reservesNow - reservesBefore;
CurrencyReserves.resetCurrency();
...
_accountDelta(currency, paid.toInt128(), recipient);

That's why the order is sync, then transfer, then settle.

settle can't see who sent a token. It only sees that the balance grew since the last sync.

The interface says sync "MUST be called before any ERC20 tokens are sent into the contract" (IPoolManager.sol L183-L186).

(Note: for the native currency, settle counts msg.value instead.)

Two more calls touch deltas without moving tokens: mint and burn of ERC-6909 claims (L320-L335).

Minting a claim adds a debt. Burning one adds a credit. Shadowbook uses them below.

Summon's swap router, call by call

SummonSwap.swapExactIn (src/SummonSwap.sol L56-L64) first checks the pool is one a Summon round created. Then it packs the request and unlocks:

amountOut = abi.decode(poolManager.unlock(abi.encode(Call(msg.sender, key, zeroForOne, amountIn, minOut, to))), (uint256));

The work happens in the callback (L66-L90, trimmed):

function unlockCallback(bytes calldata data) external returns (bytes memory) {
    if (msg.sender != address(poolManager)) revert NotPoolManager();
    Call memory c = abi.decode(data, (Call));
    BalanceDelta delta = poolManager.swap(c.key, IPoolManager.SwapParams({
        zeroForOne: c.zeroForOne,
        amountSpecified: -int256(uint256(c.amountIn)),
        sqrtPriceLimitX96: c.zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
    }), "");
    (Currency cin, Currency cout) = c.zeroForOne ? (c.key.currency0, c.key.currency1) : (c.key.currency1, c.key.currency0);
    (int128 dIn, int128 dOut) = c.zeroForOne ? (delta.amount0(), delta.amount1()) : (delta.amount1(), delta.amount0());
    // a price limit can stop a swap early; the caller pays only what the pool took
    uint256 paid = uint256(uint128(-dIn));
    uint256 out = uint256(uint128(dOut));
    if (out < c.minOut) revert TooLittleReceived(out, c.minOut);

    poolManager.sync(cin);
    if (!IERC20Pull(Currency.unwrap(cin)).transferFrom(c.payer, address(poolManager), paid)) revert TransferFailed();
    poolManager.settle();
    poolManager.take(cout, c.to, out);
    return abi.encode(out);
}

With the signs above, -dIn is what the router owes and dOut is what it's owed.

Three more things are worth a look.

The msg.sender check. Anyone can call unlockCallback, so the router accepts only the PoolManager.

The router holds nothing. The input goes from the user straight into the PoolManager (transferFrom(c.payer, address(poolManager), paid)). So the router "Holds nothing between calls" (L22-L25).

Slippage is checked before any payment. If it fails, the whole unlock reverts.

Summon creates a pool and seeds it in one unlock

When a round fills, part of the USDC and part of the stock seed the pool (src/SummonRound.sol L315): _seed(qLp, usdcLp).

_seed (L465-L468) unlocks with an operation code:

bytes memory r = IPoolManager(d.poolManager).unlock(abi.encode(OP_SEED, tokenAmt, usdcAmt));

The round's unlockCallback (L413-L436) serves three operations: seed, unwind and realign.

Seeding creates the pool and adds the position in the same callback:

if (op == OP_SEED) {
    uint160 sqrtP = tokenIs0 ? SummonPool.sqrtPriceX96(a, b) : SummonPool.sqrtPriceX96(b, a);
    pm.initialize(key, sqrtP);
    (uint256 tokenUsed, uint256 usdcUsed, uint128 l) = _addFullRange(pm, key, sqrtP, a, b);
    return abi.encode(tokenUsed, usdcUsed, l);
}

"But initialize doesn't need the lock," you might say. True.

Calling it here means the pool exists only together with its first position, in one transaction.

_addFullRange (L438-L451) calls modifyLiquidity. It pays each negative delta through _settleOwed (L470-L476):

function _settleOwed(IPoolManager pm, Currency c, int128 amount) internal returns (uint256 paid) {
    if (amount >= 0) return 0;
    paid = uint256(uint128(-amount));
    pm.sync(c);
    _push(Currency.unwrap(c), address(pm), paid);
    pm.settle();
}

The reverse is unwindLP (L357-L370). It removes the position and collects each positive delta with take in _takeOwed (L478-L482).

Hooks join the same accounting

Hooks run inside the caller's unlock. So they can create and clear deltas too.

Shadowbook fills a swap from its own inventory in beforeSwap (src/Shadowbook.sol L232-L265):

  • For the input, it mints itself ERC-6909 claims (poolManager.mint(address(this), cin.toId(), amountIn), L257).
  • For the output, it pays by burning claims or settling real tokens (_payOut and _settle, L285-L300).

Why does the input arrive as claims? Its contract comment explains (L31-L33): "the swapper settles after the hook returns, so the manager holds no real tokens yet".

How a hook hands its deltas to the swapper is for a later lesson.

For now, note that the same rule holds. By the end of unlock, every delta is zero.

Exercise: read a swap and a seeding in a real trace

In your summon-stocks checkout at d4debb7, run the test that fills a round and swaps on the pool (test/SummonRound.t.sol L847-L879), with full traces:

git checkout d4debb7 && git submodule update --init --recursive   # if your checkout moved on
forge test --mt test_swapOnSummonedPool -vvvv

The trace is about 400 lines.

Find the seeding first: the first PoolManager::unlock under SummonRound::fill. Here's what we got, trimmed to the calls, with long arguments cut (…):

├─ [564750] SummonRound::fill{value: 1}(…)
│   ├─ [300767] PoolManager::unlock(0x…01…01fc5aed09…77359400)
│   │   ├─ [298533] SummonRound::unlockCallback(…)
│   │   │   ├─ [41738] PoolManager::initialize(PoolKey({ currency0: 0x5991…76A9, currency1: 0xc718…0bB1, fee: 8388608, tickSpacing: 60, hooks: 0x0500000000000000000000000000000000002880 }), 38366396192605457038975870283)
│   │   │   │   ├─ [8787] 0x0500…2880::beforeInitialize(SummonRound: […], …)
│   │   │   ├─ [168519] PoolManager::modifyLiquidity(…, ModifyLiquidityParams({ tickLower: -887220, tickUpper: 887220, liquidityDelta: 4130081028, … }), 0x)
│   │   │   │   ├─ [2320] 0x0500…2880::beforeAddLiquidity(SummonRound: […], …)
│   │   │   ├─ [4105] PoolManager::sync(MockB20: [0x5991…76A9])
│   │   │   ├─ [23483] MockB20::transfer(PoolManager: […], 8528784649)
│   │   │   ├─ [2831] PoolManager::settle()
│   │   │   │   └─ ← [Return] 8528784649
│   │   │   ├─ [3995] PoolManager::sync(MockERC20: [0xc718…0bB1])
│   │   │   ├─ [21022] MockERC20::transfer(PoolManager: […], 2000000000)
│   │   │   ├─ [2721] PoolManager::settle()
│   │   │   │   └─ ← [Return] 2000000000

Then the first swap: alice sells 100 USDC (100000000, 6 decimals) for the stock.

├─ [101504] SummonSwap::swapExactIn(…, false, 100000000, 1, 0x…0A11cE)
│   ├─ [498] SummonFactory::roundForPool(0x44765c…bc68) [staticcall]
│   ├─ [94722] PoolManager::unlock(…)
│   │   ├─ [92488] SummonSwap::unlockCallback(…)
│   │   │   ├─ [56353] PoolManager::swap(…, SwapParams({ zeroForOne: false, amountSpecified: -100000000, … }), 0x)
│   │   │   │   ├─ [17430] 0x0500…2880::beforeSwap(SummonSwap: […], …)
│   │   │   │   │   └─ ← [Return] 0x575e24b4, 0, 4197304
│   │   │   │   ├─ emit Swap(id: 0x44765c…bc68, sender: SummonSwap: […], amount0: 404972057, amount1: -100000000, …)
│   │   │   ├─ [1995] PoolManager::sync(MockERC20: [0xc718…0bB1])
│   │   │   ├─ [1381] MockERC20::transferFrom(0x…0A11cE, PoolManager: […], 100000000)
│   │   │   ├─ [2721] PoolManager::settle()
│   │   │   │   └─ ← [Return] 100000000
│   │   │   ├─ [25215] PoolManager::take(MockB20: [0x5991…76A9], 0x…0A11cE, 404972057)

Read it against the code:

  1. unlock → unlockCallback → swap → the hook's beforeSwap. The hook runs inside the caller's unlock.
  2. The Swap event carries the swap's delta for the caller (emit Swap(id, msg.sender, delta.amount0(), delta.amount1(), …), PoolManager.sol L239-L248). That's -100000000 USDC owed by the router, and +404972057 stock owed to it.
  3. settle returns exactly 100000000, and take sends exactly 404972057. Both deltas are back to zero, so unlock returns.
  4. The hook returned 4197304 as its fee. That's 3000 | 0x400000: 0.30% with LPFeeLibrary.OVERRIDE_FEE_FLAG (LPFeeLibrary.sol L19) set. The fee rules belong to a later lesson.

Now break it.

Do this in a scratch copy, not your checkout. Comment out the router's settle:

# from the directory that holds your summon-stocks checkout (at d4debb7)
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/^        poolManager.settle();$/        \/\/ poolManager.settle();/' src/SummonSwap.sol   # GNU sed: sed -i without ''
forge test --mt test_swapOnSummonedPool -vvv

What we got:

[FAIL: CurrencyNotSettled()] test_swapOnSummonedPool() (gas: 1975125)
    │   │   └─ ← [Revert] CurrencyNotSettled()
    │   └─ ← [Revert] CurrencyNotSettled()
    └─ ← [Revert] CurrencyNotSettled()

"The USDC was transferred, though. Why does it fail?"

The USDC did reach the PoolManager. But without settle, it was never credited.

So the router's USDC delta is still negative when the callback returns, and unlock reverts at L111.

Undo the edit (git checkout -- src).

What to check

  • You found unlock → unlockCallback → swap / modifyLiquidity → sync → transfer → settle → take in your own trace.
  • You can say why sync must come before the transfer, and what settle would credit without it.
  • You can explain why SummonSwap.unlockCallback checks msg.sender.
  • You saw CurrencyNotSettled() with one settle removed, and the test pass again after undoing it.