MCPInstall

v4-hook-generator

Generate Uniswap v4 hook contracts via OpenZeppelin MCP. Use when building custom swap logic, async swaps, hook-owned liquidity, custom curves, dynamic fees, MEV protection, limit orders, or oracle hooks.

Installs
687
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/uniswap/uniswap-ai --skill v4-hook-generator
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads v4-hook-generator automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

v4 Hook Generator

Generate Uniswap v4 hook contracts via the OpenZeppelin Contracts Wizard MCP tool. This skill guides you through selecting the right hook type, configuring permissions and utilities, assembling the canonical MCP JSON, and invoking the MCP tool to produce ready-to-compile Solidity code.

Security companion: Generated hook code touches fund-handling contracts. Always apply the v4-security-foundations skill immediately after generation to audit permissions, delta accounting, and access control before deploying to any network.

When to Use This Skill

Use this skill when you need to:

  • Scaffold a new Uniswap v4 hook contract from scratch
  • Select the right base hook type for a specific use case (fees, MEV protection, oracles, etc.)
  • Configure hook permissions, utility libraries, shares, and access control
  • Produce the canonical MCP tool call JSON to invoke the OpenZeppelin Contracts Wizard
  • Understand trade-offs between hook configuration options before committing to an implementation

Prerequisite / companion skill: v4-security-foundations — run it before writing custom logic and again before deployment. Hook misconfiguration can drain user funds.

Hook Type Decision Table

Choose the base hook type that matches your primary goal. If your hook has multiple goals, choose the type that covers the most critical concern and layer additional logic on top.

GoalUse Hook
Custom swap logicBaseHook
Async/delayed swapsBaseAsyncSwap
Hook-owned liquidityBaseCustomAccounting
Custom curveBaseCustomCurve
Dynamic LP feesBaseDynamicFee
Dynamic swap feesBaseOverrideFee
Post-swap feesBaseDynamicAfterFee
Fixed hook feesBaseHookFee
MEV protectionAntiSandwichHook
JIT protectionLiquidityPenaltyHook
Limit ordersLimitOrderHook
Yield on idleReHypothecationHook
OracleBaseOracleHook
V3-compatible oracleOracleHookWithV3Adapters

Selection tips:

  • BaseHook is the general-purpose starting point — choose a specialized type only when the built-in logic provides concrete value.
  • BaseCustomCurve replaces the entire AMM math; only use it if you are implementing a novel pricing algorithm.
  • AntiSandwichHook and LiquidityPenaltyHook both address MEV but target different actors (traders vs. JIT LPs). Clarify which attack vector you are mitigating.
  • OracleHookWithV3Adapters is appropriate when downstream integrations expect a Uniswap v3 IUniswapV3Pool-compatible oracle interface.

Minimal Decision Checklist

Before calling the MCP tool, confirm all six decisions:

  1. Hook type — chosen from the decision table above
  2. Permissions to enable — only the callbacks your logic actually uses (beforeSwap, afterSwap, etc.)
  3. Utility libraries — currencySettler, safeCast, transientStorage as needed
  4. Shares — false, ERC20, ERC6909, or ERC1155
  5. Access control — ownable, roles, or managed
  6. Hook inputs — blockNumberOffset, maxAbsTickDelta (only for hook types that use them)

Permission Configuration

All 14 permission flags with guidance on when to enable each. Start with all flags false and enable only what your hook logic requires. Every enabled permission increases the hook's attack surface and requires a specific bit to be set in the hook's deployed address (see address encoding note below).

Permission FlagEnable WhenRisk
beforeInitializeYou need to validate or restrict pool creation paramsLOW
afterInitializeYou need to set up state after a pool is createdLOW
beforeAddLiquidityYou need to gate or transform LP depositsMEDIUM
afterAddLiquidityYou track LP positions or distribute rewardsLOW
beforeRemoveLiquidityYou need lock-up periods or fee-on-exit logicHIGH
afterRemoveLiquidityYou track position removals for accountingLOW
beforeSwapYou modify swap behavior, apply dynamic fees, or blockHIGH
afterSwapYou observe final swap state for oracles or accountingMEDIUM
beforeDonateYou restrict who may donate to the poolLOW
afterDonateYou track donation eventsLOW
beforeSwapReturnDeltaYou implement custom AMM curves or JIT liquidity (CRITICAL: NoOp attack vector — see v4-security-foundations)CRITICAL
afterSwapReturnDeltaYou extract a hook fee from swap outputHIGH
afterAddLiquidityReturnDeltaYou adjust LP token amounts on depositHIGH
afterRemoveLiquidityReturnDeltaYou adjust withdrawal amountsHIGH

Address encoding note: Permissions are encoded as bits in the hook contract's deployed address. The address must have the correct bits set at deployment time or the PoolManager will revert. Use HookMiner (from v4-periphery) to mine a salt that produces an address with the correct bit pattern. Never change permissions after deployment — the address is immutable.

Utility Library Selection

Three optional utility libraries can be included in the generated hook. Include only what your hook logic uses.

LibraryInclude When
currencySettlerYour hook moves tokens between itself and the PoolManager (e.g., custom accounting, fee collection)
safeCastYour hook performs arithmetic that could overflow when casting between integer types
transientStorageYour hook needs to pass data between callbacks within a single transaction without persisting to storage (requires EVM Cancun or later, Solidity >= 0.8.24)

Guidance:

  • currencySettler is almost always needed when beforeSwapReturnDelta, afterSwapReturnDelta, afterAddLiquidityReturnDelta, or afterRemoveLiquidityReturnDelta are enabled — it provides settle and take helpers that implement the correct sync → transfer → settle sequence.
  • transientStorage is a gas-efficient alternative to storage slots for intra-transaction state. Use it to pass a flag or value from beforeSwap to afterSwap without paying 20k gas for a cold SSTORE.
  • safeCast is advisable whenever you compute amounts derived from int256/uint256 conversions, especially for fee calculations.

Shares Configuration

The shares option controls whether the generated hook issues a token representing user shares (e.g., LP positions in hook-owned liquidity pools).

OptionDescriptionUse When
falseNo share token — hook does not track ownership of deposited assetsSimple hooks that do not hold user funds
ERC20Fungible share token — one token represents proportional ownership of all hook-held assetsHook-managed liquidity pools with interchangeable shares
ERC6909Multi-token (minimal) — one contract manages many token IDs with lower overhead than ERC1155Hook manages multiple distinct asset classes efficiently
ERC1155Multi-token (standard) — full ERC1155 with metadata URI supportHook needs broad wallet and marketplace compatibility

Trade-offs:

  • false: smallest bytecode, no share accounting overhead; appropriate for fee hooks and oracles.
  • ERC20: simplest fungible share; good DeFi composability (e.g., used as collateral).
  • ERC6909: gas-efficient multi-token with a minimal interface; preferred for new protocol designs.
  • ERC1155: widest ecosystem support (wallets, explorers, NFT marketplaces); higher gas cost per transfer than ERC6909.

Access Control Options

The access option shapes the constructor and administrative interface of the generated hook.

OptionConstructor ShapeUse When
ownableconstructor(IPoolManager, address initialOwner)Single owner controls all admin functions
rolesconstructor(IPoolManager, address admin)Multiple roles with granular permissions (OpenZeppelin AccessControl)
managedconstructor(IPoolManager, address authority)External authority contract governs permissions (OpenZeppelin AccessManaged)

Guidance:

  • ownable is the simplest — one address can perform all privileged operations. Suitable for early-stage hooks and personal tools.
  • roles adds ADMIN_ROLE, PAUSER_ROLE, etc. via OpenZeppelin AccessControl. Use when different team members need different privileges (e.g., a keeper bot that can update fees but cannot upgrade the contract).
  • managed delegates all permission checks to a separate AccessManager contract. Use when you need a unified governance layer across multiple contracts or want timelocked admin actions.

Note: Changing the access option changes the constructor signature. Update deployment scripts and initialization logic accordingly. When using ownable, ensure the initialOwner is not the zero address — OpenZeppelin's Ownable reverts on zero address since v5.

Hook Inputs Reference

Some hook types accept numeric configuration inputs that tune behavior. These are passed as the inputs object in the MCP tool call.

InputTypeUsed ByDescription
blockNumberOffsetuint256AntiSandwichHook, LiquidityPenaltyHookNumber of blocks before sandwich/JIT detection window opens
maxAbsTickDeltaint24AntiSandwichHookMaximum tick movement allowed per block before MEV protection triggers

For hook types that do not use these inputs, omit the inputs field or pass an empty object {}. Passing unsupported inputs to the MCP tool will not cause an error but the values will be ignored.

MCP Tool Call (Canonical)

The OpenZeppelin Contracts Wizard exposes a generate_hook MCP tool. The following is the canonical JSON schema — populate each field according to your decisions from the sections above, then pass this object as the tool's argument.

{
  "hook": "BaseHook",
  "name": "MyHook",
  "pausable": false,
  "currencySettler": true,
  "safeCast": true,
  "transientStorage": false,
  "shares": { "options": false },
  "permissions": {
    "beforeInitialize": false,
    "afterInitialize": false,
    "beforeAddLiquidity": false,
    "beforeRemoveLiquidity": false,
    "afterAddLiquidity": false,
    "afterRemoveLiquidity": false,
    "beforeSwap": true,
    "afterSwap": false,
    "beforeDonate": false,
    "afterDonate": false,
    "beforeSwapReturnDelta": false,
    "afterSwapReturnDelta": false,
    "afterAddLiquidityReturnDelta": false,
    "afterRemoveLiquidityReturnDelta": false
  },
  "inputs": {
    "blockNumberOffset": 1,
    "maxAbsTickDelta": 100
  },
  "access": "ownable",
  "info": { "license": "MIT" }
}

Field notes:

  • hook: string — one of the 14 hook types from the decision table
  • name: string — the Solidity contract name (PascalCase, no spaces)
  • pausable: boolean — wraps the hook in OpenZeppelin Pausable; adds pause()/unpause() admin functions
  • shares.options: false | "ERC20" | "ERC6909" | "ERC1155"
  • access: "ownable" | "roles" | "managed"
  • info.license: SPDX license identifier — use "MIT" for open-source hooks
  • inputs: omit or pass {} for hook types that do not use blockNumberOffset/maxAbsTickDelta

Workflow: Gather → Configure → Generate → Secure

Follow these steps in order every time you use this skill.

Step 1: Gather Requirements

Ask the user (or infer from context):

  1. What is the hook's primary goal? (Map to the decision table.)
  2. Which lifecycle events does the hook need to intercept? (Map to permissions.)
  3. Does the hook hold or move user funds? (Determines currencySettler and shares.)
  4. Who administers the hook? (Single owner, role-based team, or external governance?)
  5. Does the hook need to pass state between callbacks within a single transaction?
  6. Is this for a chain with EVM Cancun support? (Required for transientStorage.)

Step 2: Select Hook Type

Using the decision table, identify the single best hook type. If the user's goal maps to multiple types, explain the trade-offs and ask them to confirm. Document the chosen type and the reasoning.

Step 3: Configure All Six Decisions

Work through the minimal decision checklist:

  1. Set hook to the chosen type.
  2. Set each permission flag — default false, enable only what the logic requires.
  3. Set currencySettler, safeCast, transientStorage based on utility library guidance.
  4. Set shares.options based on shares guidance.
  5. Set access based on access control guidance.
  6. Set inputs only if the hook type uses blockNumberOffset or maxAbsTickDelta.

Step 4: Assemble and Call the MCP Tool

Construct the JSON object from Step 3 and call the OpenZeppelin Contracts Wizard MCP tool with it. The tool returns Solidity source code — it does not write files automatically.

After receiving the generated code:

  1. Display the code to the user.
  2. Explain the key generated sections (constructor, getHookPermissions, enabled callbacks).
  3. Note any manual steps required (HookMiner for address mining, deployment script updates for constructor args if access is roles or managed).

Step 5: Apply Security Foundations

Always remind the user — and invoke v4-security-foundations — before the code is deployed:

  • Verify all enabled callbacks check msg.sender == address(poolManager).
  • Review any enabled *ReturnDelta permissions for NoOp attack exposure.
  • Confirm delta accounting sums to zero for every execution path.
  • Run the full pre-deployment audit checklist from v4-security-foundations.

Important Notes

  • Access control changes constructor shape: Choosing ownable adds an initialOwner parameter; roles adds an admin parameter; managed adds an authority parameter. Update deployment scripts and factory contracts accordingly.
  • Permissions encode in the hook address: Each enabled permission flag corresponds to a specific bit in the lower bytes of the hook's deployed address. The PoolManager validates these bits on every callback. Use HookMiner from v4-periphery to mine a deployment salt that produces a matching address.
  • MCP returns code only — it does not write files: The generated Solidity is returned as a string. You must write it to disk yourself (e.g., packages/contracts/src/hooks/MyHook.sol).

Related Skills

  • v4-security-foundations — Run this after generation. Security audit for Uniswap v4 hooks: permission risk matrix, NoOp attack patterns, delta accounting, access control verification, and the full pre-deployment audit checklist. Generated hook code should never be deployed without completing this review.
  • viem-integration — Deploy generated hook contracts and interact with them using viem/wagmi
  • v4-sdk-integration — Interact with deployed hooks via the Uniswap v4 SDK

FAQ

What does the v4-hook-generator skill do?

Generate Uniswap v4 hook contracts via OpenZeppelin MCP. Use when building custom swap logic, async swaps, hook-owned liquidity, custom curves, dynamic fees, MEV protection, limit orders, or oracle hooks.

How do I install v4-hook-generator?

Run npx skills add https://github.com/uniswap/uniswap-ai --skill v4-hook-generator in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/v4-hook-generator/ (personal) or .claude/skills/v4-hook-generator/ (project).

Which AI agents can use v4-hook-generator?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is v4-hook-generator safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains v4-hook-generator?

It is published by uniswap in uniswap/uniswap-ai. It has 687 recorded installs.

More from uniswap/uniswap-ai

View all →

swap-integration

uniswap/uniswap-ai

Integrate Uniswap swaps into applications. Use when user says "integrate swaps", "uniswap", "trading api", "add swap functionality", "build a swap frontend", "create a swap script", "smart contract swap integration", "use Universal Router", "Trading API", or mentions swapping tokens via Uniswap.

Business & Finance2.2K installs

viem-integration

uniswap/uniswap-ai

Integrate EVM blockchains using viem. Use when user says "read blockchain data", "send transaction", "interact with smart contract", "connect to Ethereum", "use viem", "use wagmi", "wallet integration", "viem setup", or mentions blockchain/EVM development with TypeScript.

Business & Finance1.7K installs

liquidity-planner

uniswap/uniswap-ai

This skill should be used when the user asks to "provide liquidity", "create LP position", "add liquidity to pool", "become a liquidity provider", "create v3 position", "create v4 position", "concentrated liquidity", "set price range", or mentions providing liquidity, LP positions, or liquidity pools on Uniswap. Generates deep links to create positions in the Uniswap interface.

1.2K installs

swap-planner

uniswap/uniswap-ai

This skill should be used when the user asks to "swap tokens", "trade ETH for USDC", "exchange tokens on Uniswap", "buy tokens", "sell tokens", "convert ETH to stablecoins", "find memecoins", "discover tokens", "research tokens", "tokens to buy", "find tokens to swap", "what should I buy", or mentions swapping, trading, researching, discovering, buying, or exchanging tokens on any Uniswap-supported chain. Supports both known token swaps and token discovery workflows (discovery uses keyword search and web search — there is no live "trending" feed). Generates deep links to execute swaps in the Uniswap interface.

v4-security-foundations

uniswap/uniswap-ai

Security-first Uniswap v4 hook development. Use when user mentions "v4 hooks", "hook security", "PoolManager", "beforeSwap", "afterSwap", or asks about V4 hook best practices, vulnerabilities, or audit requirements.

Security1.2K installs

deployer

uniswap/uniswap-ai

Deploy CCA (Continuous Clearing Auction) smart contracts using the Factory pattern. Use when user says "deploy auction", "deploy cca", "factory deployment", or wants to deploy a configured auction.

DevOps & Cloud1.1K installs

Popular ai & agents skills

View category →

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents513.9K installs

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents513.5K installs

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents416.4K installs

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents402.1K installs

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401K installs

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents245.7K installs