Crypto Training

Uniswap v4 Hooks: Secure Design Patterns for Adversarial Integrations

A Uniswap v4 hook is permissionless code on the swap path of every pool that names it. This post covers the v4 mechanics that matter for security, design patterns for reentrancy, MEV, rounding and liveness, and what the hook incidents and audit findings published so far have in common.

Crypto Training•2026-02-10•22 min read

Uniswap hooks security boundary diagram

A Uniswap v4 hook is a contract that the PoolManager calls at fixed points in the life of a pool, around initialization, liquidity changes, swaps and donations. Dynamic fees, on-chain risk checks and custom curves all become possible this way. The price is that your code now sits on the path of every swap in every pool that names your hook.

Three properties of that position drive the rest of this post:

  • It is permissionless, since anyone can trigger the callbacks by trading and anyone can create a new pool that points at your hook.
  • It is composable, since a hook usually calls other contracts and those contracts can call back into the PoolManager.
  • It is order-dependent, since whoever builds the transaction or the block decides whether your callback runs before or after a price move.

A small logic change in a hook moves an invariant across an external-call boundary.

The patterns below were checked against v4-core and the official documentation as of November 2026, and against the hook incidents and audit findings published by then.

The hook threat model#

When one of your callbacks runs, assume all of the following:

  1. The swapper is adversarial. The sender argument is the address that called the PoolManager, which is normally a router, so it identifies neither the end user nor a trusted party.
  2. The pool price may have been moved earlier in the same transaction and may be moved back after your callback.
  3. Tokens may charge fees, rebase, call back or return nothing. The token integration post lists the cases.
  4. Any external call you make can re-enter the PoolManager, including a swap on the pool you are handling.
  5. Rounding can be repeated by anyone who is able to loop an action.
  6. hookData is bytes chosen by whoever built the call.
  7. A pool you never heard of can name your hook, because pool creation is permissionless.

A hook is therefore a set of stateful entry points that outsiders trigger at will, and it should be designed and reviewed as one.

Settle by deltas#

The most common integration failure across DeFi is to read a value from another contract and treat it as fact inside accounting. In v4 the remedy is part of the core, and hooks should build on it.

All pools live in one PoolManager. A caller first calls unlock, the manager calls back unlockCallback, and inside that callback the caller may swap, modifyLiquidity, donate, take, settle, mint and burn. Each operation adjusts a balance per address and currency, called a delta and kept in transient storage. A negative delta is owed to the manager and a positive one is owed by it. When the callback returns, the manager reverts with CurrencyNotSettled unless every delta is zero. Tokens move only at settle and take, which is what the documentation calls flash accounting.

sequenceDiagram autonumber participant R as Router participant PM as PoolManager participant H as Hook R->>PM: unlock(data) PM->>R: unlockCallback(data) R->>PM: swap(key, params, hookData) PM->>H: beforeSwap(sender = router) H-->>PM: selector, BeforeSwapDelta, fee override PM->>PM: pool math, deltas updated in transient storage PM->>H: afterSwap(sender, key, params, delta) H-->>PM: selector, hook delta PM-->>R: BalanceDelta for the swapper R->>PM: settle what is owed, take what is due R-->>PM: unlockCallback returns PM->>PM: revert unless every delta is zero

swap returns a BalanceDelta, a pair of signed 128-bit amounts for currency0 and currency1 from the swapper's point of view. That value, together with the deltas the manager tracks for the hook itself, is what happened. It can differ from what was requested, because a swap on a pool with too little liquidity fills less than amountSpecified, so a hook that pays rewards or fees on the requested amount overpays.

Everything else a hook hears is a claim:

  • transfer() returned true
  • a token's balanceOf(), which can move through rebasing
  • an amount encoded in hookData
  • another contract's statement that it has already paid

A hook whose final settlement is derived from deltas, and from balance changes it measured itself, has fewer ways to be lied to. Finding C-05 in Pashov Audit Group's 2024 review of Bunni v2 shows the opposite: a rebalance callback treated the hook's whole token balance as the output of an order and forwarded it, including bids and rent that managers had posted earlier.

Deltas have a trap of their own. They are netted per address across the whole unlock call, and the hook shares that call with whoever started it. In the GoldPesa incident (October 2026), a hook rebalanced its liquidity through the PositionManager inside a swapper's unlock, and the credit from burning the protocol's position was netted against a debt the attacker had opened on the PositionManager earlier in the same call.

Swap parameters you must get right#

A swap has two independent axes. Direction is zeroForOne, and exactness is carried by the sign of amountSpecified.

ParameterMeaning in v4-coreSecurity relevance
zeroForOne = trueswap currency0 for currency1decides which currency is paid and which is received
amountSpecified < 0exact inputthe caller must enforce a minimum output
amountSpecified > 0exact outputthe caller must enforce a maximum input
sqrtPriceLimitX96the price at which the swap stopsa loose limit lets the swap run through thin ranges

The sign convention is the reverse of Uniswap v3, where a positive amountSpecified means exact input, so habits and snippets carried over from v3 get it backwards. Compute bool exactInput = params.amountSpecified < 0 once and use the name. The same two parameters decide which currency is the "specified" one for hook return deltas, which is currency0 when exactInput == zeroForOne and currency1 otherwise.

Hooks also receive hookData. Treat it as untrusted calldata that can be crafted to reach the worst-case path of whatever decodes it.

What hooks change about the trust boundary#

Earlier AMM integrations had a fixed shape, in which the user calls a router, the router calls the pool and the pool calls the token. A v4 pool adds code chosen by the pool's creator inside the pool's own operations, and that boundary has three new properties.

  • Liveness can be attacked, because a revert in a hook reverts the swap or liquidity change that triggered it.
  • Ordering becomes the hook's problem, because the hook runs wherever its transaction lands in the block.
  • Rounding becomes worth exploiting, because a callback on the swap path runs often and cheaply.

Publishing a hook is therefore close to publishing a protocol. The Uniswap Foundation's security framework treats it that way, with risk tiers that scale the expected audits and monitoring to what the hook does.

Pattern 1. Encode phases as a state machine#

Hooks often need state that lives between two callbacks, for example a value recorded in beforeSwap and consumed in afterSwap. The two callbacks are separate calls from the PoolManager, so that state has to be stored somewhere, and it must be clear which calls are legal while it is set.

The assumption that everything happens in one call stack is too weak to serve as a state machine. A contract the hook calls in beforeSwap can start a second swap on the same pool, and the nested beforeSwap then overwrites what the first one recorded. A downstream revert can also leave a flag set if the flag lives in ordinary storage and the revert is caught.

The pattern is to give each pool an explicit phase and to check it on entry.

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

import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";

/// Per-pool phase kept in transient storage. Requires the Cancun EVM.
abstract contract SwapPhase {
    error WrongPhase();

    uint256 private constant IDLE = 0;
    uint256 private constant IN_SWAP = 1;

    function _move(PoolId id, uint256 from, uint256 to) private {
        bytes32 slot = keccak256(abi.encode("hook.swap.phase", PoolId.unwrap(id)));
        uint256 current;
        assembly ("memory-safe") {
            current := tload(slot)
        }
        if (current != from) revert WrongPhase();
        assembly ("memory-safe") {
            tstore(slot, to)
        }
    }

    /// Call first in beforeSwap. A nested swap on the same pool reverts here.
    function _enterSwap(PoolId id) internal {
        _move(id, IDLE, IN_SWAP);
    }

    /// Call last in afterSwap, once settlement is done.
    function _exitSwap(PoolId id) internal {
        _move(id, IN_SWAP, IDLE);
    }
}

This looks like a reentrancy guard, and the useful property is the semantic one: for every function you can say in which phase it is valid. Three details keep it correct in v4.

The callbacks themselves must reject any caller other than the PoolManager. OpenZeppelin's BaseHook puts onlyPoolManager on each external hook function and forwards to an internal _beforeSwap or _afterSwap, which is where _enterSwap(key.toId()) and _exitSwap(key.toId()) belong. Cork's post-mortem for its loss of 3,761 wstETH in May 2025 names an access control flaw in its hook's beforeSwap as one of two causes.

The phase is keyed by pool because one hook serves many pools. A single contract-wide flag would let activity on one pool block or confuse another.

The hook needs both the beforeSwap and the afterSwap permission for the pair to balance. v4-core skips a hook's callbacks for operations the hook itself starts, so a swap made by the hook neither enters nor exits the phase.

If nesting is a legitimate part of the design, use an explicit depth counter with data stored per depth, because a single boolean cannot represent it.

Pattern 2. Keep dangerous calls behind one choke point#

Many hook bugs sit at the edges of the contract: token transfers, oracle reads, swaps on other venues, delegatecall, and any call that can come back into the hook.

Instead of scattering those calls, route them through one internal function that performs them and returns a structured result. Reviewers then have one place to model the trust boundary, fuzzers have one place to attach adversarial mocks, and you can assert conditions before and after it.

SOLIDITY
struct ExternalOutcome {
    uint256 received;    // balance change measured around the transfer
    uint256 oraclePrice; // value read, after its freshness check
}

function _interact(IERC20 token, address from, uint256 amount)
    internal
    returns (ExternalOutcome memory o)
{
    uint256 balanceBefore = token.balanceOf(address(this));
    token.safeTransferFrom(from, address(this), amount);
    o.received = token.balanceOf(address(this)) - balanceBefore;
    o.oraclePrice = _readOracle();
}

Everything downstream then works from ExternalOutcome and never from the raw calls. The Bunni finding above is what the absence of this pattern looks like, since the callback read balanceOf(this) at a point where the balance also held funds from an unrelated flow.

Pattern 3. Make MEV explicit#

Many hook designs assume, without stating it, that the price at beforeSwap is close to the price at afterSwap, that an oracle read is stable within a block, or that a guard transaction will land before the swap it guards. A searcher or a block builder can break each of these.

If the hook uses a price, pick one of these positions on purpose:

Design choiceWhat it buys youWhat it costs you
commit-reveal (two steps)removes mempool predictabilityworse UX, more state, more DoS surface
private order flow or bundlesresists sandwichingtrust and operational dependencies
in-protocol guardrails (minimum output, TWAP)bounded losspartial protection only
accept MEV and price it insimplicityusers pay the cost

A design that leaves the choice implicit tends to pay twice, with added complexity and value that is still extractable.

Among the hook incidents written up on this site by November 2026, the largest single group reads the pool's own spot price through getSlot0 and lets the same transaction act on it. SpiralHookV2 valued borrow collateral at spot and keyed its same-block guard on tx.origin, so one address moved the price and six others borrowed against it in the same block. BoostHook and KolanHook share that root. The oracles post and the MEV post cover the alternatives.

Pattern 4. Reentrancy in hooks#

In hooks, reentrancy takes several forms:

  • classic, where you call a token's transfer and the token calls you back
  • cross-function, where a call made in beforeSwap reaches an admin function you did not gate
  • cross-contract, where an external module you call reaches your hook through a different path
  • read-only, where a view is read during an intermediate state and used as a price

While a callback runs, the PoolManager is unlocked, so any contract the hook calls can swap or change liquidity on any pool, including the one being handled. Modifiers on individual functions describe that situation poorly, and three rules serve better:

  1. Decide which functions are callable in which phase.
  2. Make admin paths unreachable from swap paths, through separate contracts or explicit phase checks.
  3. Keep intermediate accounting out of view functions unless you can show it is safe to read mid-operation.
stateDiagram-v2 [*] --> Idle Idle --> InSwap: beforeSwap InSwap --> Idle: afterSwap after settlement Idle --> InLiquidity: beforeAddLiquidity or beforeRemoveLiquidity InLiquidity --> Idle: afterAddLiquidity or afterRemoveLiquidity note right of InSwap Admin functions must revert while a pool is in this state. end note

The two reentrancy posts cover the general cases, one on callback surfaces and one on the cross-function, cross-contract and read-only variants.

Pattern 5. Minimize hook permissions#

A hook's permissions are encoded in the lowest 14 bits of its address. Ten flags select callbacks (beforeInitialize, afterInitialize, the four liquidity callbacks, beforeSwap, afterSwap, beforeDonate, afterDonate) and four allow return deltas (beforeSwapReturnDelta, afterSwapReturnDelta, afterAddLiquidityReturnDelta, afterRemoveLiquidityReturnDelta). The address is mined with CREATE2 to carry the right bits, and the flags cannot change afterwards.

A callback that is switched on is a public entry point in practice, because anyone can trigger it through an ordinary pool action. The first pattern is therefore plain and has a large effect:

Only enable the callbacks you need.

A hook that sets a dynamic LP fee probably does not need liquidity callbacks, and a hook that gates swaps probably does not need donation callbacks. Fewer callbacks mean less state to keep consistent, fewer phases to model and fewer paths that can revert, and they shrink the state machine a fuzzer has to explore.

The return-delta flags deserve the most suspicion. With beforeSwapReturnDelta a hook can take the whole input and fill the swap itself, which replaces the pool's curve, and Uniswap's documentation says such hooks need particular care with their internal accounting. VTSwapHook (March 2026) was a custom-curve hook of this kind that added the full input to its reserves while pricing the output on the input net of fees, and two swaps in opposite directions extracted the drift.

Two more checks follow from the address encoding. If the mined address lacks a flag, the PoolManager never calls that function and the logic silently does nothing, so compare getHookPermissions() with the address at deployment, which BaseHook does in its constructor. Since anyone can initialize a pool with your hook, a hook that keeps state per pool or expects a single pool should use beforeInitialize to decide which pools it accepts. HeisenbergHook (May 2026) stored the pool key on every initialization, so an attacker created a second, thin pool with the same hook and had the hook's permissionless fee-processing functions trade through it.

Pattern 6. Treat rounding as a security choice#

Hooks often implement fees, rebates, dynamic spreads and accounting per user, and all of it is fixed-point math. In fixed-point math the rounding direction decides who receives the dust, and a user who can loop an action (many small swaps, repeated mints and burns, repeated claims) can turn dust into profit.

Rules that hold up in practice:

  • Round against the caller when minting value such as shares, credits or rebates.
  • Round in favour of the protocol when charging fees.
  • When two parties are involved, such as LPs and traders, pick a rule and document it, because inconsistency between two code paths is what gets exploited.

Bunni's loss of about $8.4M on 2 September 2025 is the reference case. According to the team's post-mortem, the decrease of the idle balance in withdraw was rounded down on purpose, a choice that was safe for a single withdrawal, and the attacker repeated tiny withdrawals until the pool's liquidity estimate was far from its real balances. The rounding post covers the general technique, and hooks make it pay faster because they run on every swap.

A concrete example with a dynamic fee hook#

Dynamic fees are a natural use of hooks, for instance to raise fees when volatility rises, lower them when liquidity is deep, or enforce a minimum on certain routes. They are also a common way for a hook to become a manipulable oracle:

  • if the fee depends on the spot price, the spot price can be moved
  • if it depends on the size of the last swap, small swaps can be used to grief it
  • if it depends on time, the attacker can choose the block boundary

The mechanics set the limits. A pool opts in by using LPFeeLibrary.DYNAMIC_FEE_FLAG as its fee and starts at a fee of zero. Only the pool's hook may call updateDynamicLPFee, and a hook with the beforeSwap permission can also return a fee for a single swap by setting OVERRIDE_FEE_FLAG. The maximum LP fee is 1,000,000 hundredths of a bip, which is 100%, so nothing in the core stops a hook from charging a swapper everything. Uniswap's security framework lists the corresponding risk, that fees can be raised selectively after a user's trade is visible.

The safer posture is to compute fees from a bounded signal that moves slowly. A windowed TWAP, an external oracle with explicit trust, or a volatility estimate over time is usually safer than spot. If the hook does use spot, bound the damage with a cap on the fee, a cap on the change per update and some hysteresis so that it does not oscillate on noise. Without those bounds a dynamic fee becomes a fee oracle that a searcher can set.

Building on a maintained base#

OpenZeppelin publishes a hooks library with base contracts for dynamic fees, custom curves and other common shapes. Its README labels the code experimental, and the repository carries audit reports for the 1.0 and 1.1 release candidates, so treat it as a reviewed starting point and read the version you pin. A minimal hook on BaseDynamicFee at v1.2.1 looks like this:

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

import {BaseHook} from "@openzeppelin/uniswap-hooks/base/BaseHook.sol";
import {BaseDynamicFee} from "@openzeppelin/uniswap-hooks/fee/BaseDynamicFee.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract DynamicLPFeeHook is BaseDynamicFee, Ownable {
    using PoolIdLibrary for PoolKey;

    uint24 public constant MAX_FEE = 10_000; // 1%, in hundredths of a bip
    mapping(PoolId => uint24) public feeOf;

    error FeeTooHigh();

    constructor(IPoolManager manager, address owner_) BaseHook(manager) Ownable(owner_) {}

    function _getFee(PoolKey calldata key) internal view override returns (uint24) {
        return feeOf[key.toId()];
    }

    /// Stores the fee and applies it to the pool in the same call.
    function setFee(PoolKey calldata key, uint24 newFee) external onlyOwner {
        if (newFee > MAX_FEE) revert FeeTooHigh();
        feeOf[key.toId()] = newFee;
        _poke(key);
    }
}

In this version _poke is internal, so the hook has to expose its own authorised way to apply a new fee, and the fee is stored per pool because one hook can serve several. The security ideas are independent of the exact API:

  • keep the sensitive policy behind a small interface
  • make privileged updates explicit and bounded (onlyOwner or governance, with a maximum)
  • keep fee policy and swap settlement in separate functions

Hook liveness and forced reverts#

Hooks sit on hot paths. v4-core forwards a hook's revert as a revert of the pool operation, so a hook that can be made to revert can halt swaps, liquidity changes and fee collection for its pools. Treat "can be forced to revert" as a vulnerability class.

DoS patternHow it happensTypical fix
untrusted data triggers a revertthe hook decodes user-provided hookData and reverts on its shapereject unknown data early, version it, or default to safe behaviour
too much work per swapthe hook loops over positions or ranges that users can createcap the work, use bounded queues, move heavy work to asynchronous settlement
rounding traprounding up makes a value exceed a balance and the subtraction revertscap or clamp, or design the math to avoid the trap
oracle outagethe hook requires an oracle update in the same transactionaccept bounded staleness, or decide explicitly between failing open and failing closed
wrong caller checka callback authorises the wrong contracttest every callback through the real call path

Cyfrin's 2025 review of Paladin's Valkyrie hooks has examples of the second and the last row. In one finding, creating a range was permissionless and afterSwap iterated over all ranges, so enough ranges made every swap run out of gas. In another, a hooklet's afterSwap accepted calls only from the wrong contract, and swaps on the affected pools reverted. The gas griefing post covers the general patterns.

If the hook must fail closed, document the operational requirement that goes with it. A fail-closed dependency without someone responsible for restoring it means the pool can be bricked.

Testing hooks like protocol code#

A hook that anyone can trigger needs the tests of a permissionless protocol, and three kinds of test cover the ground.

1) Scenario tests#

Write at least one end-to-end test that performs a swap, attempts a reentrant callback through a malicious token or module, and places two swaps back to back to exercise the ordering assumptions.

2) Fuzzing sequences of entry points#

Hooks tend to fail on sequences, such as a swap followed by a swap, liquidity added then a swap then liquidity removed, or a swap on either side of an admin update. Sequence fuzzing is where bugs in callback state show up.

3) Invariants#

Write invariants that match the threat model:

  • balances cannot be created from nothing
  • the phase of every pool is idle between transactions
  • the hook cannot permanently lock a pool
SOLIDITY
// Sketch: reserveOf and owedTo stand for whatever accounting the hook exposes.
function invariant_hookIsSolvent() public view {
    for (uint256 i; i < currencies.length; ++i) {
        assertGe(hook.reserveOf(currencies[i]), hook.owedTo(currencies[i]));
    }
}

If a simple invariant is hard to write, the design is probably keeping too much implicit.

A hook audit checklist#

Five questions cover most of what a review needs to establish.

1) What is the asset you are protecting?#

Examples:

  • the pool invariant (no free liquidity, no free swaps)
  • fee growth (no fee theft through rounding)
  • limits of a risk module (no bypass through callback order)
  • liveness (nobody can brick the pool by forcing a revert)

Write the invariant as a sentence, then write the counterexample you would try.

2) Which external calls can lie to you, and how do you detect it?#

For each external call, write down what it could return that is misleading and what you can measure instead, such as deltas, balance changes or values bounded by a window.

3) Can an attacker force you into a stuck state?#

Stuck states matter more in hooks because hooks run on common paths. The usual shapes are:

  • a flag is set, a downstream call reverts and is caught, and the flag is never cleared
  • a mapping entry is created per user and never deleted, so gas grows without bound
  • expected deltas are stored under (sender, pool) and a reentrant call overwrites them

4) Where does the logic assume the current price is fair?#

If the answer is anywhere, ask how an attacker can move the price, call you and move it back, how a bundle can invalidate the assumption, and whether your logic can be used as a per-block oracle.

5) What breaks if a token is unusual?#

Even Uniswap-centric code ends up touching tokens. Handle these cases explicitly:

  • transfer returns no boolean, or returns garbage
  • a fee on transfer changes amounts
  • the token has callbacks, as ERC-777 tokens do
  • the token rebases between two reads

If the hook depends on a token being ordinary, encode that dependency with an allowlist and a stated rationale, or redesign.

Watch: security considerations for Uniswap v4 hooks#

Jota Carpanelli of OpenZeppelin on security considerations for hook builders, published by the DeFi Security Summit channel.

Further reading#