$CHEETAH is live!
Type something to search...
Blog

Uniswap v4 Hooks: Engineering Custom AMM Logic

Uniswap v4's hook system fundamentally changes how developers build on top of AMM infrastructure. Here is what production-grade hook development actually looks like.

Uniswap v4 Hooks: Engineering Custom AMM LogicUniswap v4 Hooks: Engineering Custom AMM Logic
Uniswap v4 Hooks: Engineering Custom AMM Logic
Join Our Newsletter

Subscribe to our newsletter to get the latest updates and offers

* Will send you weekly updates on new features, tips, and developer resources.

TL;DR:

  • Uniswap v4 launched on January 30, 2025 across 12 chains, introducing hooks as the protocol's primary extensibility mechanism for custom pool logic without forking the core contracts
  • Hooks are separate smart contracts that attach to liquidity pools and execute at up to eight defined lifecycle points, covering before and after swap, add liquidity, remove liquidity, and initialize events
  • The singleton architecture consolidates all pool state into a single contract, reducing pool deployment costs by approximately 99% compared to v3 and enabling multi-hop swaps within a single transaction
  • Flash accounting, formalized through ERC-6909, defers token settlement until the end of a transaction, which reduces intermediate token transfers and lowers gas costs for complex hook logic
  • By late July 2025, Uniswap v4's TVL had grown to over $1 billion, with protocols building dynamic fee mechanisms, on-chain limit orders, and automated liquidity rebalancing directly on top of the hook system
  • Hook security introduces a new class of risk that did not exist in v3, including reentrancy through callback chains, accounting manipulation, and governance-controlled upgrade paths that can alter pool behavior post-deployment
  • The Uniswap Foundation has published a 12-section self-directed security framework specifically for hook developers, covering nine quantitative risk dimensions and recommending audit, monitoring, and formal verification strategies

The result: Uniswap v4 hooks are not a convenience feature, they are a new programming model for DeFi infrastructure, and building on them correctly requires the same rigor as building the core protocol itself.

The Architecture Shift That Changes Everything

When Uniswap v4 launched on January 30, 2025, the announcement focused heavily on hooks, and for good reason. But to understand why hooks matter, you need to understand the architectural decisions that make them possible in the first place. The most consequential of those decisions is the move to a singleton contract model. In v3, every liquidity pool was its own deployed contract. Creating a new pool meant deploying a new instance of the pool contract, which carried meaningful gas costs and created a fragmented state landscape where each pool managed its own token balances independently. In v4, a single PoolManager contract manages all pools. Every pool is a logical construct within that one contract, identified by a PoolKey struct that encodes the token pair, fee tier, tick spacing, and the address of the attached hook contract.

The practical consequence of this change is significant. Pool creation costs dropped by roughly 99% compared to v3, which means developers can now create pools with highly specific parameters, including custom fee tiers and hook configurations, without the economic friction that previously made experimentation prohibitive. Multi-hop swaps also become more efficient because the router no longer needs to transfer tokens between separate contracts at each hop. The singleton holds all balances, and intermediate transfers are simply accounting entries until the final settlement step. This is the foundation on which the hook system is built, and it is worth internalizing before writing a single line of hook code.

The other architectural change worth understanding upfront is the introduction of ERC-6909 as the internal token standard for the PoolManager. Rather than using ERC-20 transfers for every intermediate operation, the PoolManager tracks claim tokens internally. Liquidity providers receive ERC-6909 claim tokens representing their position, and these can be used across multiple operations within a single transaction before any actual ERC-20 transfer occurs. For hook developers, this means the accounting model you are working within is fundamentally different from what you might expect coming from v3, and misunderstanding it is one of the more common sources of bugs in early hook implementations.

How Hooks Actually Work: The Lifecycle Model

A hook in Uniswap v4 is a smart contract that implements one or more callback functions corresponding to specific points in a pool's operational lifecycle. The PoolManager calls these functions at the appropriate moments during swap execution, liquidity addition, liquidity removal, and pool initialization. The hook contract's address encodes which callbacks it implements through a specific bit-flag pattern in the address itself, which is why hook deployment requires a vanity address mining step using a tool like CREATE2. The address bits tell the PoolManager which callbacks to invoke, avoiding the gas cost of a dynamic lookup on every operation.

The callback model is straightforward in concept but nuanced in practice. Each callback receives a structured set of parameters describing the current state of the operation, and the before-callbacks can modify certain parameters before the core logic executes. The afterSwap callback, for example, receives the actual amounts swapped and the fee collected, which gives you the data you need to implement fee redistribution logic, update an oracle, or trigger a rebalancing operation. The beforeSwap callback can return a modified fee override, which is the mechanism behind dynamic fee hooks. Understanding which data is available at each callback point, and what mutations are permitted, is the first thing you need to map out before designing any hook.

One subtlety that catches developers off guard is the distinction between hooks that take fees and hooks that do not. A hook can be configured to collect a portion of swap fees by setting the appropriate flags in the PoolKey. When a hook takes fees, it receives delta values representing the amounts it is entitled to, and it must handle those deltas correctly or the transaction will revert. This is not optional error handling, it is a hard accounting requirement enforced by the PoolManager's flash accounting system. If your hook claims fees but does not properly settle the resulting delta, the entire transaction fails. Getting this right requires a clear mental model of how the PoolManager tracks outstanding balances throughout a transaction's execution.

The Eight Hook Points and What They Enable

The v4 hook system exposes eight callback points across four pool operations. For swaps, you have beforeSwap and afterSwap. For liquidity addition, you have beforeAddLiquidity and afterAddLiquidity. For liquidity removal, beforeRemoveLiquidity and afterRemoveLiquidity. And for pool initialization, beforeInitialize and afterInitialize. Each of these points unlocks a different category of custom behavior, and the most interesting hook designs tend to combine multiple callbacks to implement a coherent strategy.

The beforeSwap callback is where dynamic fee logic lives. By returning a fee override value, a hook can adjust the swap fee based on any on-chain data available at execution time. A volatility oracle hook, for example, might read a TWAP from an on-chain price feed, compute a volatility estimate, and return a higher fee during periods of elevated volatility to compensate liquidity providers for increased impermanent loss risk. This is a pattern that market makers on centralized exchanges have used for years, and v4 makes it implementable directly at the AMM layer without requiring a separate protocol layer on top.

The afterSwap callback is where post-trade logic executes. This is the right place to update internal accounting, emit custom events, trigger rebalancing checks, or interact with external protocols based on the outcome of a swap. The afterAddLiquidity and afterRemoveLiquidity callbacks serve a similar purpose for position management, giving hooks the ability to track liquidity provider behavior, implement custom reward accrual, or enforce position-level constraints. The beforeInitialize callback is less commonly used but matters for hooks that need to set up initial state when a pool is first created, such as registering the pool with an external registry or initializing an oracle data structure. Together, these eight points give you enough surface area to implement almost any AMM customization you can reason about, which is both the power and the risk of the system.

Dynamic Fees: The Most Immediately Useful Hook Pattern

Dynamic fees are the hook pattern that has attracted the most immediate developer interest, and it is easy to see why. Fixed fee tiers are a blunt instrument. A 0.3% fee might be appropriate for a stable pair during normal market conditions but completely inadequate during a high-volatility event when impermanent loss risk spikes. Conversely, a 1% fee might be justified for an exotic long-tail asset but will drive away volume on a liquid blue-chip pair. The inability to adjust fees in response to market conditions has been a structural disadvantage for AMMs relative to order book venues, and dynamic fee hooks address it directly.

A well-designed dynamic fee hook needs to solve two problems: how to measure the relevant market condition, and how to translate that measurement into a fee value. For volatility-based fees, the most common approach is to maintain a TWAP oracle within the hook itself, using the afterSwap callback to update a rolling price history, and then computing a realized volatility estimate from that history in the beforeSwap callback. The fee is then set as a function of that volatility estimate, typically with a floor at the pool's base fee and a ceiling at some maximum value. The implementation requires careful attention to gas costs, since the beforeSwap callback executes on every swap and any expensive computation there will make the pool less competitive on gas.

A simpler but still useful variant is a time-of-day fee hook, which adjusts fees based on block timestamp to reflect the empirically observed pattern that volatility tends to be higher during certain market hours. This requires no oracle and minimal computation, making it cheap to execute. More sophisticated designs might incorporate external oracle feeds, cross-pool price comparisons, or even off-chain signed data submitted by a trusted relayer. Each of these approaches introduces different trust assumptions and security considerations, which is why the design space for dynamic fee hooks is genuinely large and still being explored by the teams building on v4 today.

Flash Accounting and the ERC-6909 Settlement Model

Flash accounting is the mechanism that makes complex hook logic economically viable. In v3, every token transfer between a user and a pool required an actual ERC-20 transfer, which carries a fixed gas cost regardless of whether the transfer is an intermediate step in a larger operation. In v4, the PoolManager tracks a delta for each token involved in a transaction, representing the net amount owed to or from the caller. These deltas accumulate throughout the transaction as swaps, liquidity operations, and hook callbacks execute. At the end of the transaction, all deltas must be settled to zero, either by transferring tokens into the PoolManager or by claiming tokens out of it.

For hook developers, this model has a direct implication: your hook can perform multiple pool operations within a single callback without paying the gas cost of intermediate token transfers. A hook that rebalances a position by removing liquidity from one range and adding it to another can do so in a single transaction with a single net token transfer at the end. This is not just a gas optimization, it is a qualitative change in what kinds of strategies are economically feasible to implement on-chain. Strategies that would have required multiple transactions in v3, each with its own gas overhead and exposure to front-running between steps, can now execute atomically within a single v4 transaction.

The ERC-6909 claim token system extends this further by allowing liquidity providers to hold their pool positions as fungible tokens that can be used as inputs to other operations without first converting back to ERC-20. A hook can be designed to accept ERC-6909 claim tokens as collateral, use them to open a position in another pool, and settle the entire operation in one transaction. This composability is powerful, but it also means that the accounting surface area in a complex hook is much larger than in a simple v3 pool interaction. Tracking which deltas are outstanding at any point in a transaction's execution requires careful bookkeeping, and the PoolManager will revert the entire transaction if any delta remains unsettled at the end.

Building a Hook in Practice: Tooling and Structure

The practical starting point for hook development is the v4-periphery repository maintained by Uniswap Labs, which provides the BaseHook abstract contract that handles the boilerplate of registering callback permissions and implementing the IHooks interface. Inheriting from BaseHook and overriding the specific callback functions you need is the standard pattern. The toolchain of choice for most teams is Foundry, which provides the forge test framework for unit and integration testing, the anvil local node for fork testing against mainnet state, and the cast tool for deployment scripting. QuickNode's developer guides and the Uniswap Foundation's own documentation both use Foundry as the assumed environment, and the community tooling around v4 hook development is largely built on top of it.

The address mining requirement is one of the more unusual aspects of hook development from a workflow perspective. Because the hook's address encodes its callback permissions through specific bit flags, you cannot simply deploy a hook contract to any address. You need to mine a CREATE2 salt that produces an address with the correct bit pattern for the callbacks your hook implements. Tools like HookMiner, which is included in the v4-template repository, automate this process, but it adds a step to the deployment workflow that developers coming from v3 will not be familiar with. In a local testing environment, this is handled by the test setup scripts. In production, it needs to be part of your deployment pipeline, and the salt needs to be deterministic so that your deployment is reproducible.

Testing hooks thoroughly requires simulating the full pool lifecycle, not just the callback functions in isolation. A hook that works correctly when tested against a mock PoolManager may behave differently when deployed against the real singleton, particularly if it makes assumptions about the order of operations or the state of the pool at callback time. Fork testing against a live v4 deployment on a testnet is the most reliable way to catch these issues before mainnet deployment. The Foundry fork testing workflow, using vm.createFork and vm.selectFork, makes this straightforward, and it is worth building fork tests into your CI pipeline from the beginning rather than treating them as a final pre-deployment check.

The Security Surface Hooks Create

The hook system introduces a security surface that is qualitatively different from anything in v3. In v3, the pool contracts were fixed and audited, and the primary security concern for integrators was the correctness of their own router logic. In v4, hooks are arbitrary smart contracts that execute within the context of pool operations, which means a malicious or buggy hook can affect every user of the pool it is attached to. The Uniswap Foundation's security framework identifies several distinct risk categories that hook developers need to reason about explicitly.

Reentrancy is the most immediately familiar risk, but it manifests differently in the hook context. Because hooks execute as callbacks from the PoolManager, and because the PoolManager itself can be called recursively through the flash accounting system, the reentrancy surface is more complex than in a standard contract. A hook that calls back into the PoolManager during a callback needs to reason carefully about the state of the delta accounting at that point. The PoolManager implements its own reentrancy guard, but hooks that interact with external contracts during callbacks can still create reentrancy paths that bypass the guard if those external contracts call back into the pool.

Accounting manipulation is a risk specific to hooks that take fees or modify swap amounts. A hook that incorrectly calculates the delta it is entitled to, or that fails to settle its delta under certain conditions, can either drain value from the pool or cause legitimate transactions to revert. The Uniswap Foundation's security framework specifically calls out math errors in fee calculations and edge cases in delta settlement as high-risk areas. Upgradeability is another concern: a hook that is upgradeable through a proxy pattern or a governance mechanism gives the hook owner the ability to change pool behavior after liquidity providers have deposited funds, which is a trust assumption that users of the pool may not be aware of. The framework recommends that hook developers explicitly document their upgradeability model and governance controls as part of their security disclosure.

The Uniswap Foundation's Security Framework

The Uniswap Foundation's self-directed security framework for hook developers is one of the more useful documents to come out of the v4 launch ecosystem. It is structured around 12 sections covering everything from understanding hook risk in the abstract to choosing the right combination of audits, monitoring services, and bug bounties for a given hook's risk profile. The framework introduces nine quantitative risk dimensions: complexity, math, external dependencies, governance, upgradeability, liquidity behavior, access control, oracle usage, and cross-contract interactions. Each dimension is scored on a scale, and the aggregate score determines a risk tier that maps to a recommended security posture.

The framework's most practical contribution is its guidance on when different security measures are appropriate. A simple hook with no external dependencies, no upgradeability, and straightforward math might be adequately secured by a single audit from a reputable firm. A hook that integrates an external oracle, implements complex fee math, and is governed by a multisig requires a more comprehensive approach: multiple audits, formal verification of the math, a bug bounty program, and ongoing monitoring with on-chain anomaly detection. The framework does not prescribe a single approach for all hooks, which is the right call given how diverse the hook design space is.

One section of the framework that deserves particular attention is the guidance on liquidity behavior risks. A hook that modifies how liquidity is added or removed can create situations where liquidity providers are unable to withdraw their funds under certain conditions, either due to a bug in the hook logic or due to a deliberate design choice that was not clearly communicated. The framework calls this "liquidity lockup risk" and recommends that hook developers explicitly test withdrawal paths under adversarial conditions, including scenarios where the hook's external dependencies are unavailable or return unexpected values. This is the kind of edge case that is easy to miss in normal testing but that can have severe consequences for users if it occurs in production.

Testing Hooks at Production Scale

Testing a hook for production deployment requires going beyond unit tests of individual callback functions. The most important thing to test is the hook's behavior across the full range of pool states it will encounter in production, including edge cases like zero liquidity, maximum tick range, and extreme price movements. Foundry's fuzzing capabilities are well-suited to this kind of testing. By writing fuzz tests that randomize swap amounts, liquidity positions, and fee parameters, you can surface edge cases in your hook's math that deterministic tests would miss. The v4-template repository includes examples of fuzz test patterns for hooks, and adopting them early in development is significantly cheaper than finding the same bugs in a post-deployment audit.

Fork testing against a live v4 deployment adds another layer of confidence by testing your hook against real pool state and real token contracts. This is particularly important for hooks that interact with external protocols, since the behavior of those protocols in a fork environment will match their production behavior in ways that a mock cannot replicate. A hook that integrates a Chainlink price feed, for example, should be tested against a fork that includes the actual Chainlink aggregator contract, not a mock that returns a fixed value. The difference in behavior between a mock and the real contract can be subtle but consequential, particularly around staleness checks and circuit breaker conditions.

Invariant testing is the third pillar of a robust hook test suite. An invariant test defines a property that should always be true about your hook's state, such as "the total fees collected by the hook should never exceed the total fees generated by swaps" or "the hook's internal accounting should always match the PoolManager's recorded delta for the hook address." Foundry's invariant testing framework runs a stateful fuzzer that tries to violate these properties by executing sequences of arbitrary transactions. Invariant tests are more expensive to write than unit tests, but they are the most effective tool for finding the class of bugs that only manifest after a specific sequence of operations, which is exactly the class of bug that tends to cause production incidents in DeFi protocols.

Real Protocols Already Building on v4

The hook ecosystem has moved quickly since the January 2025 launch. Several protocols have shipped production hook implementations that demonstrate the range of what the system enables. On-chain limit orders are one of the most commonly cited examples, and the implementation pattern is instructive. A limit order hook stores pending orders in a mapping keyed by tick price. In the afterSwap callback, the hook checks whether the current price has crossed any pending order's target tick, and if so, executes the order by removing the corresponding liquidity and transferring the proceeds to the order owner. This gives users a native limit order experience on a constant-product AMM without requiring an off-chain order book or a separate settlement layer.

Automated liquidity rebalancing hooks represent another category of production use case. A rebalancing hook tracks the current price relative to a liquidity provider's active range and, when the price moves outside a defined threshold, automatically removes the out-of-range liquidity and re-adds it centered on the current price. This is the on-chain equivalent of the active management strategies that professional market makers run on v3 using off-chain bots, but implemented as a hook that executes atomically with each swap. The gas efficiency of the singleton architecture and flash accounting makes this economically viable in a way that it would not have been in v3.

Volatility oracle hooks that feed dynamic fee calculations are also in production, with several teams publishing implementations that use TWAP-based volatility estimates to adjust fees in real time. The market maker perspective on these hooks is that they reduce the adverse selection problem that liquidity providers face when trading against informed order flow. By charging higher fees during high-volatility periods, the pool compensates LPs for the increased risk of impermanent loss, which in theory should attract more liquidity and improve depth for traders. Whether this theoretical benefit materializes in practice depends on the quality of the volatility estimate and the calibration of the fee function, which is an active area of research among the teams building on v4.

Where AI-Assisted Development Changes the Equation

Building production-grade hooks is genuinely hard. The combination of a novel accounting model, a complex callback lifecycle, address mining requirements, and a security surface that spans multiple interacting contracts creates a development environment where the cost of mistakes is high and the feedback loops are slow. This is exactly the kind of environment where AI-assisted development tools can provide meaningful leverage, not by generating hook code wholesale, but by helping developers navigate the complexity more efficiently.

The most immediate value is in code comprehension. A developer working with the v4-periphery codebase for the first time is dealing with a large, interconnected set of contracts where understanding any one component requires understanding how it interacts with several others. An AI-powered IDE that can answer questions like "what state is available to me in the afterSwap callback" or "what happens if I return a non-zero delta from beforeSwap without settling it" in the context of the actual codebase reduces the time spent reading documentation and tracing call stacks. This is not a trivial productivity gain in a codebase as complex as v4's.

Security analysis is the other area where AI tooling adds real value in hook development. Static analysis tools like Slither can catch common Solidity vulnerabilities, but they are not designed to reason about the v4-specific accounting invariants that are the most likely source of hook bugs. An AI assistant that understands the PoolManager's delta accounting model can flag patterns in hook code that are likely to produce unsettled deltas or incorrect fee calculations, surfacing issues that a general-purpose static analyzer would miss. The combination of AI-assisted comprehension and AI-assisted security review does not replace a formal audit, but it meaningfully raises the quality of the code that goes into an audit, which reduces both the cost and the duration of the audit process.

Building on v4 with Cheetah AI

Uniswap v4 represents a genuine step change in what is possible at the AMM layer, and the hook system is the mechanism through which most of that potential will be realized. But the complexity of building on v4 correctly is not trivial. The accounting model is unfamiliar, the security surface is new, and the tooling ecosystem, while improving rapidly, is still maturing. Developers who want to ship production hooks need to invest in understanding the system deeply, not just at the level of "how do I implement a callback" but at the level of "what invariants does the PoolManager enforce and how does my hook interact with them."

Cheetah AI is built for exactly this kind of work. As a crypto-native IDE, it understands the DeFi development context natively, from the Foundry toolchain to the Solidity patterns specific to v4 hook development, without requiring developers to context-switch between their editor, documentation, and a general-purpose AI assistant that has no awareness of the on-chain environment they are building for.

When you are working through the address mining step for a new hook deployment, or tracing through a delta accounting bug in a fork test, or trying to understand why your beforeSwap fee override is being ignored, having an AI assistant that can reason about those problems in context is a different experience from pasting code into a general-purpose chat interface. Cheetah AI keeps that context persistent across your development session, so the assistant that helped you design your hook's callback structure is the same one that can help you write the invariant tests for it and review the security implications of your fee math.

If you are building on Uniswap v4, or evaluating whether hooks are the right architecture for a DeFi product you are designing, Cheetah AI is worth spending time with. The hook ecosystem is moving fast, the design space is genuinely open, and the developers who ship production-quality hooks in the next twelve months will define what the next generation of on-chain liquidity infrastructure looks like. Having the right tooling underneath that work is not a secondary concern.


If you are building on Uniswap v4, or evaluating whether hooks are the right architecture for a DeFi product you are designing, Cheetah AI is worth spending time with. The protocol's complexity rewards developers who can move quickly without cutting corners on correctness, and that balance is exactly what a crypto-native AI IDE is designed to support. You can learn more and get early access at cheetah.ai.

Related Posts

Reasoning Agents: Rewriting Smart Contract Development

Reasoning Agents: Rewriting Smart Contract Development

TL;DR:Codex CLI operates as a multi-surface coding agent with OS-level sandboxing, 1M context windows via GPT-5.4, and the ability to read, patch, and execute against live codebases, making it

user
Cheetah AI Team
09 Mar, 2026
Web3 Game Economies: AI Dev Tools That Scale

Web3 Game Economies: AI Dev Tools That Scale

TL;DR:On-chain gaming attracted significant capital throughout 2025, with the Blockchain Game Alliance's State of the Industry Report confirming a decisive shift from speculative token launche

user
Cheetah AI Team
09 Mar, 2026
Token Unlock Engineering: Build Safer Vesting Contracts

Token Unlock Engineering: Build Safer Vesting Contracts

TL;DR:Vesting contracts control token release schedules for teams, investors, and ecosystems, often managing hundreds of millions in locked supply across multi-year unlock windows Time-lock

user
Cheetah AI Team
09 Mar, 2026