Executive Summary & Direct Answer

Uniswap v4 hooks execute at specific points in a pool operation, while the PoolManager settles token deltas during an unlock callback. A router that treats its entire token balance as belonging to the current operation can accidentally spend tokens left by an earlier call. The production rule is to account for each operation’s inputs and outputs as deltas, constrain the callback sequence, and require the router to finish with no unexpected balance changes. Persistent balances are not a substitute for PoolManager accounting.

The May 28, 2025 Cork exploit post-mortem is a useful case study in why hook integrations must be reviewed as complete call sequences—not as isolated swap functions. The safeguards below focus on that class of failure: stale router balances combined with callback-driven execution.

Environment and baseline specs

The examples target Solidity ^0.8.26, Foundry, and the Uniswap v4 core/periphery APIs available at the integration’s pinned commit. Pin the exact v4-core and v4-periphery revisions in production; do not assume an interface or callback behavior from a moving branch. Use OpenZeppelin Contracts 5.x where applicable, but note that the example’s balance-delta logic is application-specific.

Uniswap v4’s PoolManager uses an unlock / unlockCallback flow and tracks unsettled currency deltas during the unlocked operation. Hooks can run at configured points in that lifecycle. The router’s ERC-20 balances are separate persistent token balances: a successful PoolManager settlement does not automatically prove that the router has no leftover tokens, nor that any leftover tokens belong to the current caller.

The failure mode: treating balance as operation input

The dangerous pattern is to use the router’s entire token balance as the amount available for a swap or settlement:

// Vulnerable pattern: pre-existing tokens are treated as this operation's funds.
function execute(address tokenIn, address tokenOut, uint256 amountIn) external {
    IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);

    uint256 available = IERC20(tokenIn).balanceOf(address(this));
    IERC20(tokenIn).approve(address(poolManager), available);

    poolManager.unlock(abi.encode(tokenIn, tokenOut, available));
}

If a previous operation leaves tokens in the router—through an unexpected hook result, an incomplete refund, a transfer to the wrong recipient, or an accounting bug—available includes those old tokens. The current caller can then trigger a path that spends value they did not supply. Repeated operations can make the defect look intermittent: the first call appears correct, while a later call consumes accumulated residue.

A related mistake is to assume a callback is safe because it is only reachable through PoolManager. The unlock callback is an execution boundary, not a proof of caller intent. A callback that accepts arbitrary encoded actions, lacks an operation-state check, or uses the router’s total balance can turn hook sequencing into an asset-drain path.

Root cause: confusing persistent balances with transient deltas

The essential distinction is:

  • Persistent ERC-20 balance: the tokens currently held by the router, possibly from earlier calls.
  • Operation delta: the amount attributable to this specific call, measured relative to a defined starting state.
  • PoolManager delta: the amount the manager records as owed or claimable during an unlock.

These values are not interchangeable. A safe integration must reconcile the manager’s deltas and the router’s token movements independently. The Cork post-mortem’s relevant lesson is to examine how a complete hook/callback sequence handles assets across calls, including whether funds remain available in a reusable router after the sequence ends. Treating a router’s balance as a fresh operation amount erases that boundary.

Production pattern: snapshot, constrain, reconcile

A safer router records balances before the operation, transfers only the requested amount, and verifies the resulting balance changes. It also restricts the callback to the expected manager and to one active operation. This simplified pattern illustrates the controls; adapt settlement calls to the exact pinned v4 APIs and currency types.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

interface IERC20Minimal {
    function balanceOf(address) external view returns (uint256);
    function transferFrom(address, address, uint256) external returns (bool);
    function transfer(address, uint256) external returns (bool);
}

interface IPoolManagerMinimal {
    function unlock(bytes calldata data) external returns (bytes memory);
}

contract DeltaCheckedRouter {
    error UnauthorizedCallback();
    error OperationAlreadyActive();
    error UnexpectedInputDelta(uint256 expected, uint256 actual);
    error UnexpectedOutputDelta(uint256 expected, uint256 actual);
    error ResidualBalance(uint256 tokenInBalance, uint256 tokenOutBalance);
    error TransferFailed();

    IPoolManagerMinimal public immutable poolManager;
    bool private active;

    constructor(IPoolManagerMinimal manager) {
        poolManager = manager;
    }

    function execute(
        IERC20Minimal tokenIn,
        IERC20Minimal tokenOut,
        uint256 amountIn,
        address recipient
    ) external returns (uint256 amountOut) {
        if (active) revert OperationAlreadyActive();
        active = true;

        uint256 inBefore = tokenIn.balanceOf(address(this));
        uint256 outBefore = tokenOut.balanceOf(address(this));

        if (!tokenIn.transferFrom(msg.sender, address(this), amountIn)) {
            revert TransferFailed();
        }

        uint256 received = tokenIn.balanceOf(address(this)) - inBefore;
        if (received != amountIn) {
            revert UnexpectedInputDelta(amountIn, received);
        }

        bytes memory result = poolManager.unlock(
            abi.encode(tokenIn, tokenOut, received, recipient, inBefore, outBefore)
        );
        amountOut = abi.decode(result, (uint256));

        uint256 inAfter = tokenIn.balanceOf(address(this));
        uint256 outAfter = tokenOut.balanceOf(address(this));

        // This minimal example assumes inputs and outputs are fully forwarded
        // within the callback. Real implementations must account for refunds.
        if (inAfter != inBefore || outAfter != outBefore) {
            revert ResidualBalance(inAfter, outAfter);
        }

        active = false;
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager) || !active) {
            revert UnauthorizedCallback();
        }

        // Decode a constrained operation and execute only the intended actions.
        // Do not accept arbitrary targets, arbitrary selectors, or caller-supplied
        // callback programs unless they are independently validated.
        (IERC20Minimal tokenIn, IERC20Minimal tokenOut, uint256 amountIn,
         address recipient,,) =
            abi.decode(data, (IERC20Minimal, IERC20Minimal, uint256, address, uint256, uint256));

        uint256 amountOut = _performPinnedV4Swap(tokenIn, tokenOut, amountIn, recipient);
        return abi.encode(amountOut);
    }

    function _performPinnedV4Swap(
        IERC20Minimal,
        IERC20Minimal,
        uint256,
        address
    ) internal pure returns (uint256) {
        // Replace with PoolManager swap, settle, and take calls for the
        // project's pinned v4 interfaces. Enforce exact delta settlement.
        return 0;
    }
}

This is a design skeleton, not drop-in Uniswap v4 code. In a real implementation, store operation parameters in tightly scoped state or validate callback data against a hash established before unlock. Verify that every settle corresponds to the expected currency and amount, and that every take goes to the intended recipient. Avoid making the callback a generic command dispatcher.

The example’s final balance equality is deliberately strict. If the design permits donations or dust, define an explicit policy: track the expected residue per token and reject any amount above that bound. Never silently fold old residue into the next operation. For tokens with transfer fees or nonstandard balance behavior, use an explicit support policy and measure actual received amounts; see Preventing ERC-20 Fee-On-Transfer Accounting Bugs in Solidity.

Hook sequencing: define a state machine

Before implementing a hook-enabled route, write down the permitted sequence and its state transitions. For each path, identify:

  1. Which contract may call the hook or callback.
  2. Whether the current operation is active and which pool/currencies it covers.
  3. Which deltas are owed to or claimable from the PoolManager.
  4. Which recipient receives output and refunds.
  5. What must be true when control returns to the external caller.

Reject duplicate, out-of-order, or unexpected callback invocations. If multiple pools or nested operations are supported, key operation state by a unique operation identifier and ensure that nested calls cannot overwrite it. If a hook can make external calls, consider whether another contract can observe intermediate state; Preventing Read-Only Reentrancy in Solidity covers that adjacent risk.

The implementation should also avoid broad approvals. Approve only what the current operation needs, reset approvals where the token requires it, and do not leave allowances that let a later route spend previously held funds. Any authorization to call arbitrary targets expands the problem from swap accounting to arbitrary-call safety.

Quantitative trade-offs

The exact gas cost depends on token behavior, compiler settings, hook configuration, and the v4 revision. The table compares relative costs and guarantees rather than claiming universal gas figures.

ApproachBalance reads / checksGas impactSecurity property
Spend balanceOf(router) as input1 read; no delta reconciliationLowest apparent costUnsafe: old funds may be consumed
Snapshot input and verify received deltaAt least 2 input readsLow additional costDetects unexpected transfer amount
Snapshot both tokens and reconcile after callbackTypically 4 reads plus checksModerate additional costDetects residue and output-accounting drift
Track operation state and validate callbackState reads/writes and hash or parameter checksModerate; state writes may dominateRejects unauthorized or out-of-sequence callbacks
Permit arbitrary callback action arraysDepends on actionsVariableHigh audit burden; can broaden asset-control surface

Benchmark the deployed bytecode with the actual token and hook implementations. A balance check that costs a few hundred gas is usually preferable to allowing a router to accumulate user funds across operations; the relevant comparison is not only gas, but the value exposed by an accounting failure.

Edge cases and differential verification

Pre-funded router. Test calls where the router starts with nonzero input and output token balances. The operation must either preserve those balances exactly or reject the call; it must not spend them as caller input.

Partial fills and refunds. If a swap can consume less than amountIn, the callback must return the unused amount to the correct caller and reconcile the remaining delta. “Balance went down” is not sufficient proof that the right user received the refund.

Fee-on-transfer and rebasing tokens. Equality between requested amount and received amount may fail by design. Either reject these tokens explicitly or define accounting around observed deltas, including the PoolManager’s settlement requirements.

Hook reverts and nested calls. Verify that a revert leaves no persistent operation flag or partial token movement. Solidity reverts roll back state within the transaction, but test callbacks that attempt reentry and routes that invoke multiple pools.

Use a pinned Foundry toolchain and run focused tests, including pre-funded balances and malformed callback data:

forge test --match-path test/HookRouterAccounting.t.sol -vvv
forge test --match-path test/HookRouterAccounting.t.sol --fuzz-runs 10000
forge test --match-path test/HookRouterSequence.t.sol -vvvv

For compiler-profile comparison, compile the same sources with the pinned production compiler and optimizer configuration, then inspect generated IR:

solc --version
solc --optimize --ir-optimized src/DeltaCheckedRouter.sol
forge build --force

Keep the compiler version, optimizer runs, EVM target, and v4 dependency revisions identical between CI and deployment. Add invariant tests asserting that a completed operation leaves no unaccounted router balance and that the PoolManager’s currency deltas are settled. Foundry invariant testing is particularly useful for sequences of swaps, callbacks, pre-funding, and reverts. Where a router intentionally retains dust, assert a documented bound rather than asserting zero.

Frequently Asked Questions (FAQ)

Can a Uniswap v4 router safely use its token balance as swap input?

Not when that balance may include tokens from earlier operations. Measure the current operation’s input delta and settle only the amount attributable to it. If the router intentionally holds funds, maintain separate, explicit accounting for those funds.

Does PoolManager settlement guarantee the router has no persistent token balance?

No. PoolManager settlement addresses the manager’s tracked currency deltas during an unlock; it does not by itself establish that the router’s ERC-20 balances are zero or belong to the current caller. Reconcile router balances separately at the end of each operation.

Which Solidity compiler version should a v4 hook router use?

Use the Solidity version required by the pinned Uniswap v4 dependencies and validate it in CI; this guide’s examples target ^0.8.26. Do not change compiler, optimizer, or EVM target settings without recompiling and rerunning the full callback-sequence and accounting test suite.

Learn more with useful resources