Building Custom Uniswap v4 Pools with Hooks

Building a custom Uniswap v4 pool? The architecture shift to hooks introduces both flexibility and complexity. Hooks let you execute arbitrary code before and after any pool operation — initialization, swap, liquidity addition/removal, donation. This unlocks mechanics unavailable in v2 and v3: dynam

Blockchain Development Services

Frequently Asked Questions

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1450
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1308
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    1003
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1269
  • image_logo-advance_0.webp
    B2B Advance company logo design
    717
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    1008

Building a custom Uniswap v4 pool? The architecture shift to hooks introduces both flexibility and complexity. Hooks let you execute arbitrary code before and after any pool operation — initialization, swap, liquidity addition/removal, donation. This unlocks mechanics unavailable in v2 and v3: dynamic fees, on-chain order books, automatic rebalancing, MEV protection right in the pool. The cost of flexibility is complexity: the hook contract runs inside PoolManager via an unlock callback with a BalanceDelta accounting system. One error in the hook can lock the entire pool or drain liquidity. Our 10+ years in DeFi and 50+ blockchain projects guarantee safety and efficiency.

Starting Custom Uniswap v4 Pool Development

Uniswap v4 Architecture: What Changed Fundamentally

In v2/v3, each pool is a separate contract. In v4, all pools live inside a single PoolManager. This cuts pool creation gas from ~500k to ~150k gas, and makes multi-hop swaps much cheaper (no transfers between contracts). Token accounting uses BalanceDelta — not real transfers, but deltas that accumulate and settle at the end of the unlock callback. While PoolManager is locked (within one unlock), tokens do not physically move. This enables flash accounting: swap, use the received tokens for anything, repay the debt — all in one transaction without a flash loan. Gas savings reach 40% compared to v3.

Hook System: Address as a Bitmask

The hook contract is registered at pool creation via PoolKey. The hook address encodes allowed callbacks through leading bits: specific bits must be set to activate corresponding hooks. beforeSwap — bit 7, afterSwap — bit 6, beforeAddLiquidity — bit 5, and so on. This means you cannot arbitrarily choose the hook address — you must mine a vanity address with the required bits via CREATE2. Tools: v4-template from Uniswap, Foundry scripts for address mining. There are 14 possible hooks:

Hook Description
beforeInitialize / afterInitialize Before/after pool creation
beforeAddLiquidity / afterAddLiquidity Before/after adding liquidity
beforeRemoveLiquidity / afterRemoveLiquidity Before/after removal
beforeSwap / afterSwap Before/after swap
beforeDonate / afterDonate Before/after donation to pool
beforeSwapReturnDelta Modify swap output
afterSwapReturnDelta Take fees after swap
afterAddLiquidityReturnDelta Adjust LP balance
afterRemoveLiquidityReturnDelta Adjust balance on removal

How Uniswap v4 Hooks Work?

Dynamic Fees via beforeSwap

In v3, fees are fixed (0.05%, 0.3%, 1%). In v4, the hook can return lpFeeOverride directly in beforeSwap, changing the fee for each swap dynamically. This enables:

  • Volatility-dependent fees: Chainlink price feed + sliding window volatility → 1% fee during high volatility, 0.05% during low. LPs get fair compensation for impermanent loss risk.
  • TWAP-based fees: if current price deviates from TWAP by more than X%, increase fee — protection against oracle-driven arbitrage.

Limit Orders via Tick-Based Hooks

With afterSwap, the hook knows a swap occurred and the price moved. If the current tick crosses a preset level — execute a limit order: buy/sell liquidity from a mapping of orders. This is a full on-chain limit order book without a centralized sequencer. Complexity: gas for iterating over orders. Solution: lazy execution — orders execute on the next tick interaction.

TWAMM (Time-Weighted Average Market Maker)

Large orders are split into small virtual orders executed continuously over time. The hook accumulates tokens from TWAMM orders and gradually executes them through the pool, avoiding slippage. This solves the whale order problem — a $10M swap in one block moves the price and creates sandwich opportunities. A TWAMM hook spreads it over 1000 blocks. Math: virtual orders are computed via exponential distribution formula.

In one project, we built a volatility-dependent fee hook: during a market crash, fees automatically increased to 1% protecting LPs, while in calm periods they dropped to 0.05%. This reduced impermanent loss by 30% compared to a static 0.3% pool.

Typical Hook Development Mistakes

  • Reentrancy via PoolManager. PoolManager has its own lock, but the hook can call external contracts that re-enter the pool. NoSuchPool, AlreadyUnlocked — common errors. Rule: in hooks, avoid external calls except read-only requests.
  • Incorrect BalanceDelta. The hook returns token delta. If incorrectly calculated — PoolManager reverts with DeltaNotSettled. Common case: afterSwapReturnDelta tries to take more than the delta after the swap.
  • Address mining for production. CREATE2 mining takes from minutes to hours depending on the number of needed bits. For 14 hooks — ~16,384 attempts on average.

Why Custom v4 Pools Are Better Than v3?

Since all code executes within a single PoolManager, overhead from inter-contract calls is reduced. Dynamic fees attract LPs during high volatility, and MEV protection reduces sandwich attack losses. As a result, pools become more efficient and safer. Gas savings on pool creation — up to 350k gas, on multi-hop swaps — up to 40%.

How We Develop a Custom Pool: 5 Steps

  1. Analysis and design (2–3 days). Determine pool mechanics, hook set, BalanceDelta logic. Formal invariant specification.
  2. Hook contract development (3–5 days). Implement callbacks, address mining, auxiliary contracts.
  3. Testing (3–5 days). Unit tests, integration tests via PoolSwapTest, fuzz tests, fork tests.
  4. Audit (2–3 days). Slither, manual review focusing on reentrancy and BalanceDelta.
  5. Deployment and verification (1 day). Via Foundry forge script with Etherscan verification.

Total: 1–2 weeks for a single-mechanism hook. Complex systems — 4–6 weeks.

What Is Included in the Work

  • Requirements analysis and mechanic design
  • Smart contract development (hooks, auxiliary contracts)
  • Testing (unit, integration, fuzz, fork)
  • Security audit (Slither, manual review)
  • Deployment with verification
  • Documentation and operational recommendations
  • Launch support

Contact us to discuss your project. We'll assess complexity and offer a turnkey optimal solution. Get a consultation for your project — leave a request.