30 min read
Overview
Uniswap V4 introduces hooks, a powerful way to add custom logic at important points during pool operations. Hooks are separate smart contracts that work with Uniswap pools, allowing developers to change swap behavior, create complex strategies, and make custom AMM logic without changing the entire protocol.
In this guide, we'll show you how to build a simple hook that adds a basic feature. This will help you learn how to develop more complex custom hooks. Let's get started!
What You Will Do
- Learn about Uniswap V4 Hooks
- Create a custom Hook smart contract that identifies the real swapper behind a router
- Test the Hook smart contract with Foundry
- Deploy and test the Hook smart contract on a local Sepolia fork powered by Quicknode
- Learn what it takes to deploy a hook to a live network and get it routed by Uniswap
What You Will Need
- Experience with Ethereum and DeFi
- Foundry installed
| Dependency | Version |
|---|---|
| foundry (forge, anvil, cast) | 1.8.6 |
| solc | 0.8.30 |
| OpenZeppelin uniswap-hooks | 1.1.0 |
| Uniswap v4-template commit | 1fbf955 |
Uniswap Hooks
Uniswap V4 hooks are smart contracts that the PoolManager calls at specific points in a pool's lifecycle, letting developers customize and expand what liquidity pools can do. Hooks plug into the core protocol at set points, allowing for more features without making the core contracts less secure.
Key points about Uniswap V4 hooks:
- Hooks can be triggered before or after important actions like initializing a pool, adding or removing liquidity, swapping, and donating
- Each hook is its own smart contract, so you can develop and test it on its own
- Each pool has exactly one hook address, set in its
PoolKeywhen the pool is created and never changed. To combine behaviors, build them into a single hook contract - One hook contract can serve many pools, so per-pool state should be keyed by
PoolId - Devs can add new hooks without changing the main Uniswap protocol
V4's gas savings come from its architecture rather than from hooks themselves: all pools live in a single PoolManager contract (the singleton design), and flash accounting settles only the net token balances at the end of a transaction. Hooks add an external call on top of that, so keep hook logic lean.
Hooks let you control pool operations in detail. They allow for custom fee structures, changing liquidity distribution, and complex trading strategies right in the pool logic.
Some examples of what you can do with hooks:
- Orders that only happen under certain conditions (like limit orders or stop-loss)
- Changing fees based on market conditions (dynamic fees)
- Automatic liquidity management strategies
- Rewarding swappers or liquidity providers (for example, with points)
- Creating new AMM curves or ways to set prices
In the following sections, we'll cover the core concepts of hooks you'll want to know: the hook lifecycle, the IHooks interface, and hook flags.
Hook Lifecycle
The PoolManager can call a hook at these points:
- Before / After Initialize: Runs before and after a pool is initialized
- Before / After Add Liquidity: Runs before and after liquidity is added to a pool
- Before / After Remove Liquidity: Runs before and after liquidity is taken out of a pool
- Before / After Swap: Runs before and after a swap happens
- Before / After Donate: Runs before and after tokens are donated to a pool's liquidity providers
There are also four return delta permissions: beforeSwapReturnDelta, afterSwapReturnDelta, afterAddLiquidityReturnDelta, and afterRemoveLiquidityReturnDelta. These let a hook change the token amounts of an operation, for example taking a custom fee or replacing the pool's pricing curve entirely. They are the most powerful permissions and also the highest risk. A buggy or malicious return-delta hook can take value from swappers or LPs.
By creating these hook functions, developers can make custom behaviors that happen at specific times during pool operations.
IHooks Interface
The IHooks interface in v4-core defines every function the PoolManager can call on a hook. Each callback receives the address that called the PoolManager (sender), the pool's PoolKey, the operation's parameters, and arbitrary hookData passed in by the caller. Here are the swap callbacks:
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
Each callback returns its own function selector. Some return more values: beforeSwap also returns a BeforeSwapDelta and an optional LP fee override (used only by dynamic-fee pools), and afterSwap returns the hook's delta in the unspecified currency. afterAddLiquidity and afterRemoveLiquidity return a BalanceDelta. The extra delta values only take effect when the matching return-delta permission is enabled.
SwapParams holds zeroForOne, a signed int256 amountSpecified (negative for exact input, positive for exact output), and sqrtPriceLimitX96.
In practice, you rarely implement IHooks directly. The OpenZeppelin Uniswap Hooks library, which ships with the v4-template, provides a BaseHook contract. It implements the external functions, restricts them to the PoolManager, and lets you override internal versions such as _beforeSwap.
The sender argument is the contract that called the PoolManager, which is almost always a router (such as the Universal Router), not the user. This is one of the most common mistakes in hook development, and the example hook in this guide shows how to handle it.
Hook Flags
V4 decides which hook functions to call by inspecting the least significant bits of the hook contract's address. Each callback has a flag in the Hooks library, and the hook is called only if that bit is set in its address. For example, BEFORE_SWAP_FLAG is 1 << 7 and AFTER_SWAP_FLAG is 1 << 6. The 14 flags run from BEFORE_INITIALIZE_FLAG (1 << 13) down to AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG (1 << 0).
Don't hand-define these constants; import them from the Hooks library and combine them:
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
uint160 flags = uint160(Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG);
Because the permissions live in the address, you have to mine a CREATE2 salt that produces an address with exactly the right bits set. The v4-template includes a HookMiner utility for this, which we'll use later. When the hook is deployed, BaseHook checks that the address matches what getHookPermissions() returns.
In the following sections, we'll walk through creating a simple hook to show how you can use these tools in practice.
Project Prerequisite: Create a Quicknode Endpoint
Before getting into the code, let's set up some prerequisites like getting a RPC URL. You're welcome to use public nodes or deploy and manage your own infrastructure; however, if you'd like 8x faster response times, you can leave the heavy lifting to us. Sign up for an account here.
Once logged into Quicknode, click the New endpoint button, then select the Ethereum chain and Sepolia network.
After creating your endpoint, copy the HTTP Provider URL link and keep it handy. You'll use it to fork Sepolia locally and, later, to deploy to Sepolia.
In each terminal where you need the endpoint, enter it at the hidden prompt below. This keeps it out of your shell history:
printf 'Sepolia RPC URL: '
read -rs SEPOLIA_RPC_URL
printf '\n'
export SEPOLIA_RPC_URL
Implementing Your First Uniswap Hook
Now that we've covered the core concepts and got our prerequisites completed, let's dive into creating your first Uniswap V4 hook. We'll use the v4-template as our starting point, which provides a solid foundation for hook development.
Directory Set Up
Clone the v4-template and check out the revision tested in this guide so the scripts and dependency versions match:
git clone https://github.com/Uniswap/v4-template.git
cd v4-template
git checkout 1fbf95547791f0821a170b88c750cb2e04e6818b
The template includes an example hook Counter.sol which demonstrates beforeSwap() and afterSwap() hooks (feel free to take a glance now). The test template Counter.t.sol preconfigures the v4 pool manager, test tokens, and test liquidity, which will be helpful for testing our hook.
Install Dependencies
Install the tested Foundry version:
foundryup --install 1.8.6
Check forge --version and anvil --version before continuing. Both should report 1.8.6.
Next, install the project dependencies:
forge install
Configure Sepolia Execution Rules
Keep the template's solc_version = "0.8.30" and evm_version = "cancun" settings for compilation. Append this runtime profile to foundry.toml:
[profile.sepolia]
hardfork = "amsterdam"
Select it in every terminal where you run this guide's Forge commands:
export FOUNDRY_PROFILE=sepolia
The profile inherits the template's compiler settings while using Amsterdam rules for tests and script execution. Sepolia activated Glamsterdam, whose execution layer is Amsterdam, on October 6, 2026. Its state-creation costs differ from Cancun's, so an older runtime can pass a simulation and still underestimate the gas needed on Sepolia. Upgrading Foundry alone does not override the template's Cancun runtime default. Foundry's runtime hardfork setting lets you select the execution rules independently of the compiler target.
Although you could technically run the forge test command now, we will hold off until we add our own custom hook logic.
Customize the Hook Contract
Now, let's create our own hook. We'll implement a "Swap Limiter" hook that restricts the number of swaps a single user can perform in a pool within a certain time frame.
There's a catch. As mentioned earlier, the sender the hook receives is the router contract, not the user. If we counted swaps per sender, every user who swaps through the same router would share one limit, and after five swaps the pool would be blocked for everyone using that router. To find the real swapper, we'll follow the trusted router pattern from the Uniswap docs:
- The hook keeps an owner-managed list of trusted routers.
- When a swap comes in, the hook checks that
senderis a trusted router. - If it is, the hook calls the router's
msgSender()view function to get the original caller.
Routers such as the Universal Router and the swap router bundled with the v4-template implement msgSender() (the IMsgSender interface in v4-periphery).
First, create a file called src/SwapLimiterHook.sol. Then, open the file and include the following code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {BaseHook} from "@openzeppelin/uniswap-hooks/src/base/BaseHook.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager, SwapParams} 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 {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {IMsgSender} from "@uniswap/v4-periphery/src/interfaces/IMsgSender.sol";
contract SwapLimiterHook is BaseHook, Ownable {
using PoolIdLibrary for PoolKey;
uint256 public constant MAX_SWAPS_PER_HOUR = 5;
uint256 public constant HOUR = 3600;
struct SwapWindow {
uint256 windowStart;
uint256 swapCount;
}
// Routers that are trusted to report the original swapper via msgSender()
mapping(address router => bool trusted) public trustedRouters;
// Swap windows are tracked per pool and per swapper
mapping(PoolId => mapping(address swapper => SwapWindow)) public swapWindows;
event TrustedRouterSet(address indexed router, bool trusted);
event SwapLimitReached(PoolId indexed poolId, address indexed swapper, uint256 timestamp);
error UntrustedRouter(address router);
error SwapLimitExceeded(address swapper);
// The owner is passed in explicitly because CREATE2 deployments through a factory
// would otherwise make the factory the owner
constructor(IPoolManager _poolManager, address _owner) BaseHook(_poolManager) Ownable(_owner) {}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: false,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function setTrustedRouter(address router, bool trusted) external onlyOwner {
trustedRouters[router] = trusted;
emit TrustedRouterSet(router, trusted);
}
// Main function to enforce the swap limit
function _beforeSwap(address sender, PoolKey calldata key, SwapParams calldata, bytes calldata)
internal
override
returns (bytes4, BeforeSwapDelta, uint24)
{
// `sender` is the contract that called PoolManager.swap (usually a router), not the user.
// Only trusted routers can tell us who the user is.
if (!trustedRouters[sender]) revert UntrustedRouter(sender);
address swapper = IMsgSender(sender).msgSender();
PoolId poolId = key.toId();
SwapWindow storage window = swapWindows[poolId][swapper];
if (block.timestamp - window.windowStart >= HOUR) {
window.windowStart = block.timestamp;
window.swapCount = 0;
}
if (window.swapCount >= MAX_SWAPS_PER_HOUR) revert SwapLimitExceeded(swapper);
window.swapCount++;
if (window.swapCount == MAX_SWAPS_PER_HOUR) {
emit SwapLimitReached(poolId, swapper, block.timestamp);
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function getRemainingSwaps(PoolId poolId, address swapper) public view returns (uint256) {
SwapWindow memory window = swapWindows[poolId][swapper];
if (block.timestamp - window.windowStart >= HOUR) {
return MAX_SWAPS_PER_HOUR;
}
return MAX_SWAPS_PER_HOUR - window.swapCount;
}
}
This "Swap Limiter" hook contract implements the following features:
- Trusted Routers: The owner registers routers with
setTrustedRouter. Swaps from any other caller revert withUntrustedRouter, because the hook has no reliable way to tell who the user is. The owner is a constructor argument, since a CREATE2 factory deploys the hook and would otherwise become its owner. - Swap Limit: It restricts each swapper to a maximum of 5 swaps per hour in each pool (configurable via
MAX_SWAPS_PER_HOUR). State is keyed byPoolIdand swapper address, so one hook can safely serve many pools. - Time-based Reset: Each swapper's window starts with their first swap and resets once an hour has passed.
- beforeSwap Hook: We override the internal
_beforeSwapfunction (rather than the externalbeforeSwap). The OpenZeppelinBaseHookexposes the externalbeforeSwapwith anonlyPoolManagerguard and delegates to our_beforeSwapimplementation, so the PoolManager is the only caller that can trigger it. - Custom Errors:
SwapLimitExceededandUntrustedRouterare cheaper than revert strings and let tests (and front ends) check exactly why a swap failed. - Remaining Swaps Check: A
getRemainingSwapsfunction allows users (or the front-end) to check how many swaps they have left in the current window. - Event Logging: An event is emitted when a swapper reaches their limit, which could be useful for monitoring or alerting purposes.
This is a simple fixed-window limiter. Because a window resets exactly one hour after it starts, a swapper who times their swaps around a reset can make up to 2 * MAX_SWAPS_PER_HOUR - 1 swaps in quick succession. Use a sliding window or a token-bucket design if you need a strict rate.
Optionally, to check that your file syntax is set up properly, you can run the forge build command.
Create a Test File
Now that we've created our hook, we need to create a test file. First, create a file called test/SwapLimiterHook.t.sol. Then, include the following code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Test} from "forge-std/Test.sol";
import {IERC20} from "forge-std/interfaces/IERC20.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {CustomRevert} from "@uniswap/v4-core/src/libraries/CustomRevert.sol";
import {IPoolManager, SwapParams} 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 {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import {Constants} from "@uniswap/v4-core/test/utils/Constants.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {EasyPosm} from "./utils/libraries/EasyPosm.sol";
import {BaseTest} from "./utils/BaseTest.sol";
import {SwapLimiterHook} from "../src/SwapLimiterHook.sol";
contract SwapLimiterHookTest is BaseTest {
using EasyPosm for IPositionManager;
using PoolIdLibrary for PoolKey;
Currency currency0;
Currency currency1;
PoolKey poolKey;
PoolId poolId;
SwapLimiterHook hook;
address alice = makeAddr("alice");
address bob = makeAddr("bob");
event SwapLimitReached(PoolId indexed poolId, address indexed swapper, uint256 timestamp);
function setUp() public {
// Deploys all required artifacts (PoolManager, PositionManager, SwapRouter, Permit2)
deployArtifactsAndLabel();
(currency0, currency1) = deployCurrencyPair();
// Deploy the hook to an address with the correct flags
address flags = address(
uint160(Hooks.BEFORE_SWAP_FLAG) ^ (0x4444 << 144) // Namespace the hook to avoid collisions
);
bytes memory constructorArgs = abi.encode(poolManager, address(this));
deployCodeTo("SwapLimiterHook.sol:SwapLimiterHook", constructorArgs, flags);
hook = SwapLimiterHook(flags);
// Trust the template's swap router so the hook can read the original swapper
hook.setTrustedRouter(address(swapRouter), true);
// Create the pool
poolKey = PoolKey(currency0, currency1, 3000, 60, IHooks(hook));
poolId = poolKey.toId();
poolManager.initialize(poolKey, Constants.SQRT_PRICE_1_1);
// Provide full-range liquidity to the pool
int24 tickLower = TickMath.minUsableTick(poolKey.tickSpacing);
int24 tickUpper = TickMath.maxUsableTick(poolKey.tickSpacing);
uint128 liquidityAmount = 10_000e18;
(uint256 amount0Expected, uint256 amount1Expected) = LiquidityAmounts.getAmountsForLiquidity(
Constants.SQRT_PRICE_1_1,
TickMath.getSqrtPriceAtTick(tickLower),
TickMath.getSqrtPriceAtTick(tickUpper),
liquidityAmount
);
positionManager.mint(
poolKey,
tickLower,
tickUpper,
liquidityAmount,
amount0Expected + 1,
amount1Expected + 1,
address(this),
block.timestamp,
Constants.ZERO_BYTES
);
// Fund two swappers and let the router pull their tokens
_fund(alice);
_fund(bob);
}
function testLimitIsPerSwapper() public {
for (uint256 i = 0; i < 5; i++) {
_swap(alice);
}
assertEq(hook.getRemainingSwaps(poolId, alice), 0);
// Alice's 6th swap reverts. The PoolManager wraps the hook's revert reason.
vm.expectRevert(
abi.encodeWithSelector(
CustomRevert.WrappedError.selector,
address(hook),
IHooks.beforeSwap.selector,
abi.encodeWithSelector(SwapLimiterHook.SwapLimitExceeded.selector, alice),
abi.encodeWithSelector(Hooks.HookCallFailed.selector)
)
);
_swap(alice);
// Bob swaps through the same router and is not affected by Alice's limit
_swap(bob);
assertEq(hook.getRemainingSwaps(poolId, bob), 4);
}
function testLimitResetsAfterAnHour() public {
for (uint256 i = 0; i < 5; i++) {
_swap(alice);
}
vm.warp(block.timestamp + hook.HOUR());
assertEq(hook.getRemainingSwaps(poolId, alice), 5);
_swap(alice);
assertEq(hook.getRemainingSwaps(poolId, alice), 4);
}
function testSwapLimitReachedEvent() public {
for (uint256 i = 0; i < 4; i++) {
_swap(alice);
}
vm.expectEmit(true, true, false, true, address(hook));
emit SwapLimitReached(poolId, alice, block.timestamp);
_swap(alice);
}
function testUntrustedRouterReverts() public {
address untrustedRouter = makeAddr("untrustedRouter");
SwapParams memory params;
// Hook functions can only be called by the PoolManager (onlyPoolManager guard)
vm.prank(address(poolManager));
vm.expectRevert(abi.encodeWithSelector(SwapLimiterHook.UntrustedRouter.selector, untrustedRouter));
hook.beforeSwap(untrustedRouter, poolKey, params, Constants.ZERO_BYTES);
}
function _fund(address user) internal {
IERC20(Currency.unwrap(currency0)).transfer(user, 100e18);
IERC20(Currency.unwrap(currency1)).transfer(user, 100e18);
vm.startPrank(user);
IERC20(Currency.unwrap(currency0)).approve(address(swapRouter), type(uint256).max);
IERC20(Currency.unwrap(currency1)).approve(address(swapRouter), type(uint256).max);
vm.stopPrank();
}
function _swap(address user) internal {
vm.prank(user);
swapRouter.swapExactTokensForTokens({
amountIn: 1e18,
amountOutMin: 0, // Very bad, but we want to allow for unlimited price impact
zeroForOne: true,
poolKey: poolKey,
hookData: Constants.ZERO_BYTES,
receiver: user,
deadline: block.timestamp + 1
});
}
}
These tests make real swaps through the template's swap router as two different users, Alice and Bob. Let's recap what each test checks.
-
testLimitIsPerSwapperfunction:- Alice makes 5 swaps, leaving her with 0 remaining swaps
- Alice's 6th swap reverts. The PoolManager wraps any hook revert in a
WrappedErrorthat records the hook address, the hook function, the hook's own revert reason (SwapLimitExceeded(alice)), andHookCallFailed. Asserting on the full wrapped error proves the swap failed for the right reason, not just that it failed. - Bob then swaps through the same router and succeeds, which shows that the limit is tracked per user and not per router
-
testLimitResetsAfterAnHourfunction:- Alice uses up her 5 swaps
vm.warpmoves the block timestamp forward by one hour- Alice's limit is back to 5, and she can swap again
-
testSwapLimitReachedEventfunction:- Alice makes 4 swaps
- Expects the
SwapLimitReachedevent to be emitted by the hook on the 5th swap
-
testUntrustedRouterRevertsfunction:- Pranks the PoolManager (the
onlyPoolManagerguard means only the PoolManager can call the hook) and callsbeforeSwapwith an unknown router assender - Expects the hook to revert with
UntrustedRouter
- Pranks the PoolManager (the
Execute the tests with the following command:
forge test --match-contract SwapLimiterHookTest
You'll see this when the tests finish:
Ran 4 tests for test/SwapLimiterHook.t.sol:SwapLimiterHookTest
[PASS] testLimitIsPerSwapper() (gas: 1471329)
[PASS] testLimitResetsAfterAnHour() (gas: 1435856)
[PASS] testSwapLimitReachedEvent() (gas: 1106949)
[PASS] testUntrustedRouterReverts() (gas: 62314)
Suite result: ok. 4 passed; 0 failed; 0 skipped
Optionally, pass -v multiple times to increase the verbosity (e.g., -vv, -vvv, -vvvv) to see logs and execution traces.
Remember to adjust the tests as needed based on your specific implementation and any additional features you may add to the hook.
Local Development with Anvil and Quicknode
Unit tests run against a fresh set of V4 contracts. To test your hook against the real, already-deployed V4 contracts, you can run Anvil as a local fork of Sepolia using your Quicknode endpoint. A fork keeps Sepolia's chain ID (11155111) and state, so the template's scripts automatically use Uniswap's official Sepolia PoolManager, PositionManager, and Permit2 deployments, plus the simple V4 swap router that the template's hookmate dependency has deployed on Sepolia (0xf13D190e9117920c703d79B5F33732e10049b115). That router isn't an official Uniswap deployment, but like the Universal Router, it exposes msgSender(). Every transaction stays on your local machine, so nothing costs real testnet ETH.
The template's scripts pick V4 contract addresses based on the chain ID. On a Sepolia fork they use the existing Sepolia deployments, so you don't need script/testing/00_DeployV4.s.sol. That script only runs on chain ID 31337 and fails with Local deployment only on a fork. On a plain anvil node (chain ID 31337), the other scripts don't use its deployments unless you also edit test/utils/Deployers.sol, so a fork is the simplest way to exercise your hook end to end.
First, start Anvil in a separate terminal window, forking from your Quicknode endpoint and selecting the same execution rules as the Forge profile:
anvil --fork-url "$SEPOLIA_RPC_URL" --hardfork amsterdam
Anvil listens on http://localhost:8545 by default, which the commands below assume. If you start it on another port with --port, use that port in --rpc-url. The commands also use the first account that Anvil generates and funds. Its private key is printed in Anvil's output and is safe to use only on local networks:
export PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
Step 1: Deploy test tokens
The template's pool and swap scripts need two ERC-20 tokens. Create a file called script/DeployTestTokens.s.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Script, console2} from "forge-std/Script.sol";
import {MockERC20} from "solmate/src/test/utils/mocks/MockERC20.sol";
/// @notice Deploys two test tokens and mints a balance to the broadcaster
contract DeployTestTokensScript is Script {
function run() public {
vm.startBroadcast();
MockERC20 tokenA = new MockERC20("Token A", "TKA", 18);
MockERC20 tokenB = new MockERC20("Token B", "TKB", 18);
tokenA.mint(msg.sender, 1_000_000e18);
tokenB.mint(msg.sender, 1_000_000e18);
vm.stopBroadcast();
console2.log("Token A deployed at:", address(tokenA));
console2.log("Token B deployed at:", address(tokenB));
}
}
Then run it:
forge script script/DeployTestTokens.s.sol \
--rpc-url http://localhost:8545 \
--private-key $PRIVATE_KEY \
--broadcast
Open script/base/BaseScript.sol. In the Configure These block, replace the placeholder addresses in the existing token0 and token1 constants with the two logged addresses (the order doesn't matter; the script sorts them):
IERC20 internal constant token0 = IERC20(<TOKEN_A_ADDRESS>);
IERC20 internal constant token1 = IERC20(<TOKEN_B_ADDRESS>);
Step 2: Deploy your hook
Hooks must be deployed to an address whose lowest bits encode the permissions they use, so we use HookMiner to find a salt that produces a matching CREATE2 address. Create a file called script/DeploySwapLimiter.s.sol with the following code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {console2} from "forge-std/Script.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {HookMiner} from "@uniswap/v4-periphery/src/utils/HookMiner.sol";
import {BaseScript} from "./base/BaseScript.sol";
import {SwapLimiterHook} from "../src/SwapLimiterHook.sol";
/// @notice Mines the address and deploys the SwapLimiterHook contract
contract DeploySwapLimiterScript is BaseScript {
function run() public {
// Hook contracts must have specific flags encoded in the address
uint160 flags = uint160(Hooks.BEFORE_SWAP_FLAG);
// Mine a salt that will produce a hook address with the correct flags
bytes memory constructorArgs = abi.encode(poolManager, deployerAddress);
(address hookAddress, bytes32 salt) =
HookMiner.find(CREATE2_FACTORY, flags, type(SwapLimiterHook).creationCode, constructorArgs);
vm.startBroadcast();
// Deploy the hook using CREATE2
SwapLimiterHook swapLimiter = new SwapLimiterHook{salt: salt}(poolManager, deployerAddress);
// Trust the V4 swap router used by the template scripts
swapLimiter.setTrustedRouter(address(swapRouter), true);
vm.stopBroadcast();
require(address(swapLimiter) == hookAddress, "DeploySwapLimiterScript: Hook Address Mismatch");
console2.log("SwapLimiterHook deployed at:", address(swapLimiter));
}
}
This script inherits from the template's BaseScript, which wires up the V4 contract addresses for you (poolManager, positionManager, swapRouter, and permit2), provides the canonical CREATE2_FACTORY address, and exposes the broadcasting account as deployerAddress, which becomes the hook's owner. Run it against the same Anvil node:
forge script script/DeploySwapLimiter.s.sol \
--rpc-url http://localhost:8545 \
--private-key $PRIVATE_KEY \
--broadcast
When it finishes, you'll see Script ran successfully followed by the mined hook address, which ends in bits that encode the BEFORE_SWAP_FLAG (0x80):
SwapLimiterHook deployed at: 0x3462898e73da607921ebDC40ED948D70341e4080
If you used Anvil's default account and the code exactly as shown, you'll get this same address, because CREATE2 addresses are deterministic. It will differ if you change the hook's code or use another deployer. You can confirm the hook is wired to Sepolia's PoolManager (0xE03A1074c86CFeDd5C142C4F04F1a1536e203543) and trusts the template's router:
cast call <YOUR_HOOK_ADDRESS> "poolManager()(address)" --rpc-url http://localhost:8545
cast call <YOUR_HOOK_ADDRESS> "trustedRouters(address)(bool)" 0xf13D190e9117920c703d79B5F33732e10049b115 --rpc-url http://localhost:8545
Step 3: Create a pool and swap
In script/base/BaseScript.sol, replace address(0) in the hookContract constant with your hook's address:
IHooks constant hookContract = IHooks(<YOUR_HOOK_ADDRESS>);
Then create a pool with the hook and add liquidity using the template's numbered script:
forge script script/01_CreatePoolAndAddLiquidity.s.sol \
--rpc-url http://localhost:8545 \
--private-key $PRIVATE_KEY \
--broadcast
Before swapping, open script/03_Swap.s.sol and make these two changes:
- Change
receiver: address(this)toreceiver: deployerAddress. Foundry refuses to run scripts that useaddress(this), because script contracts are ephemeral. - Change
deadline: block.timestamp + 30todeadline: block.timestamp + 600. This gives the approvals and swap ten minutes to be included when you repeat the workflow on a live network, including when transactions are sent sequentially.
The following optional quote check runs before you use up the swap allowance. You can skip it and continue to Run Swaps.
Quote a Swap (Optional)
The hook checks the caller of PoolManager.swap, including during a quote. Before using the Sepolia V4Quoter, trust its address as the hook owner. This quoter implements msgSender(), so the hook can apply the same per-user limit during its simulation. Confirm the address against Uniswap's deployments page.
Set these public addresses using the hook and token addresses from your deployment. CURRENCY_0 must be the numerically lower token address and CURRENCY_1 the higher one, matching the pool's sorted currencies:
export HOOK_ADDRESS="<YOUR_HOOK_ADDRESS>"
export CURRENCY_0="<LOWER_TOKEN_ADDRESS>"
export CURRENCY_1="<HIGHER_TOKEN_ADDRESS>"
export V4_QUOTER=0x68aFa8b853cAa7a2D40B0F6AEE5C4DbC147C8244
export SWAPPER_ADDRESS=$(cast wallet address --private-key "$PRIVATE_KEY")
cast send "$HOOK_ADDRESS" "setTrustedRouter(address,bool)" "$V4_QUOTER" true \
--rpc-url http://localhost:8545 \
--private-key "$PRIVATE_KEY"
Call the quoter with --from set to the intended swapper. This example quotes one token of exact input, from CURRENCY_0 to CURRENCY_1:
cast call "$V4_QUOTER" \
"quoteExactInputSingle(((address,address,uint24,int24,address),bool,uint128,bytes))(uint256,uint256)" \
"(($CURRENCY_0,$CURRENCY_1,3000,60,$HOOK_ADDRESS),true,1000000000000000000,0x)" \
--from "$SWAPPER_ADDRESS" \
--rpc-url http://localhost:8545
The two returned values are the output amount in the output token's smallest units and the quoter's gas estimate. The quote does not consume a swap allowance because the quoter reverts its simulated swap state. A swapper who has already reached the limit will still receive SwapLimitExceeded; trusting the quoter does not bypass the limit.
Run Swaps
Now run the swap script six times:
forge script script/03_Swap.s.sol \
--rpc-url http://localhost:8545 \
--private-key $PRIVATE_KEY \
--broadcast
The first five runs end with ONCHAIN EXECUTION COMPLETE & SUCCESSFUL. The sixth fails during simulation, so nothing is broadcast:
Error: script failed: WrappedError(0x3462898e73da607921ebDC40ED948D70341e4080, 0x575e24b4, 0xbbecdd50000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266, 0xa9e35b2f)
The PoolManager wrapped the hook's revert. The arguments are the hook address, the beforeSwap selector (0x575e24b4), the hook's own revert reason, and the HookCallFailed selector (0xa9e35b2f). The third argument is SwapLimitExceeded (selector 0xbbecdd50) encoded with your account address, which you can decode with cast:
cast decode-error 0xbbecdd50000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266 --sig "SwapLimitExceeded(address)"
The router reported your account, not its own address, so the limit applies to you rather than to everyone who uses the router.
Troubleshooting
Hook Address Mismatch: The flags passed toHookMiner.findmust matchgetHookPermissions(), and the deployer passed toHookMiner.findmust be the one that actually deploys the hook. Inforge script, that's the CREATE2 deployer proxy0x4e59b44847b379578588920cA78FbF26c0B4956C(CREATE2_FACTORY). Inforge test, it's the test contract (or the pranked address).- Contract size errors on Anvil: Some Foundry versions limit contract size to about 24 KB. Start Anvil with
--code-size-limit 40000and pass the same flag toforge script. Local deployment only: You ranscript/testing/00_DeployV4.s.solon a fork. You don't need it there; skip to deploying your hook.Usage of address(this) detected in script contract: Changereceiver: address(this)toreceiver: deployerAddressinscript/03_Swap.s.sol.- A simulation passes but a Sepolia deployment runs out of gas: Check that Forge and Anvil are version
1.8.6, exportFOUNDRY_PROFILE=sepoliain the Forge terminal, and start Anvil with--hardfork amsterdam. Anvil forks state, but its execution rules must also match the network. If you still need node-side gas estimation for a live broadcast, first dry-run the script, then add--skip-simulationto the broadcast command. In the tested Foundry version, this makes Forge estimate each transaction through the RPC node and send transactions sequentially. Keep the 600-second swap deadline so the approvals have time to confirm.
Deploying to a Live Network
Once the hook works on your fork, deploying to Sepolia uses the same scripts. Keep FOUNDRY_PROFILE=sepolia selected, point --rpc-url at "$SEPOLIA_RPC_URL" instead of localhost, and use a funded Sepolia account. Check the gas estimates before broadcasting. For another network, select that network's execution rules rather than reusing the Sepolia profile.
Don't put a real private key in .env or on the command line. Import it into Foundry's encrypted keystore instead:
cast wallet import my-deployer --interactive
First dry-run the hook deployment using the --account flag:
forge script script/DeploySwapLimiter.s.sol \
--rpc-url "$SEPOLIA_RPC_URL" \
--account my-deployer \
--sender <YOUR_WALLET_ADDRESS>
After the dry run succeeds, repeat the command with --broadcast. To create a pool and swap on Sepolia, repeat the fork workflow against "$SEPOLIA_RPC_URL", passing --account my-deployer --sender <YOUR_WALLET_ADDRESS> instead of --private-key to each script. Dry-run each script before adding --broadcast:
- Deploy ERC-20 tokens on Sepolia with
script/DeployTestTokens.s.sol(or use existing Sepolia tokens you hold). - Update
token0,token1, andhookContractinscript/base/BaseScript.solwith the Sepolia addresses. - Run
script/01_CreatePoolAndAddLiquidity.s.solandscript/03_Swap.s.sol.
For the optional quote check, set the live addresses below, keeping the token addresses in ascending order. Trust the Sepolia quoter using the hook owner's keystore:
export HOOK_ADDRESS="<YOUR_LIVE_HOOK_ADDRESS>"
export CURRENCY_0="<LOWER_LIVE_TOKEN_ADDRESS>"
export CURRENCY_1="<HIGHER_LIVE_TOKEN_ADDRESS>"
export V4_QUOTER=0x68aFa8b853cAa7a2D40B0F6AEE5C4DbC147C8244
export SWAPPER_ADDRESS="<YOUR_LIVE_SWAPPER_ADDRESS>"
cast send "$HOOK_ADDRESS" "setTrustedRouter(address,bool)" "$V4_QUOTER" true \
--rpc-url "$SEPOLIA_RPC_URL" \
--account my-deployer
Then repeat the cast call quote command against "$SEPOLIA_RPC_URL", setting SWAPPER_ADDRESS to the intended live swapper rather than Anvil's account. Quote before exhausting that account's allowance.
Next, verify the hook's source on the block explorer. Uniswap rejects unverified hooks when reviewing them for routing. Enter the Etherscan API key at a hidden prompt:
printf 'Etherscan API key: '
read -rs ETHERSCAN_API_KEY
printf '\n'
export ETHERSCAN_API_KEY
forge verify-contract <YOUR_HOOK_ADDRESS> src/SwapLimiterHook.sol:SwapLimiterHook \
--chain sepolia \
--verifier etherscan \
--verifier-api-key "$ETHERSCAN_API_KEY" \
--constructor-args $(cast abi-encode "constructor(address,address)" 0xE03A1074c86CFeDd5C142C4F04F1a1536e203543 <YOUR_WALLET_ADDRESS>) \
--watch
0xE03A1074c86CFeDd5C142C4F04F1a1536e203543 is the Sepolia PoolManager. For other networks, look up the addresses on Uniswap's deployments page. To use your hook with routers other than the template's, such as the Universal Router, call setTrustedRouter with that router's address from the same deployments page.
Getting Your Hook Routed by Uniswap
Deploying a hook doesn't mean the Uniswap app or the Uniswap API will send swaps to your pool. Uniswap Labs' routing picks up many hooks automatically, but others must be reviewed and allowlisted first. As of October 2026, Uniswap's Routing for hooked pools article says a hook needs review if it's deployed to an address starting with 0x91, or if it uses any of beforeSwap, afterSwap, beforeSwapReturnsDelta, afterSwapReturnsDelta, or dynamic fees. Check the article for the current rules, as they have changed over time.
The SwapLimiterHook uses beforeSwap, so it would need review. The article's approval criteria include that the hook is deployed on a supported mainnet, verified on a block explorer, not upgradeable through a proxy, doesn't modify or bypass the AMM protocol fee, isn't malicious or extractive toward swappers or LPs, and doesn't require custom calldata that Uniswap Labs' router can't produce. A hook that rejects swaps after a fixed count, or that only accepts specific routers, may not meet these criteria, so think about routing before you design a hook you want users to reach through the Uniswap app. Approved or not, you can still route to your pool from your own front end or contracts. Uniswap also documents running a UniswapX filler for your hooked pools as another way to receive order flow from its interface.
A few more practical notes for testing beyond unit tests:
- The Uniswap app's routing and the public subgraphs on testnets are unreliable, so don't expect a Sepolia pool to show up in the Uniswap app.
- The Uniswap Trading API applies minimum liquidity requirements and can return an insufficient-liquidity error for thin pools.
- To check swap pricing directly, follow the optional quote steps above. Trust a compatible
V4Quoterand quote as the intended swapper so the hook checks the correct allowance.
Security Considerations
Hooks sit in the path of every swap or liquidity change in their pools, so mistakes are costly. Before deploying a hook that holds or moves real value, keep these points in mind:
- Router vs. user identity:
senderis the router, not the user. Only trust identity information from routers you've vetted, as shown in this guide. - Return-delta permissions: Hooks with
beforeSwapReturnDeltaor other return-delta flags can change how much users pay or receive. Treat them as high risk and test them extensively. - External calls and reentrancy: Any external call from a hook (like the
msgSender()call in this guide) hands control to another contract mid-operation. Only call contracts you trust, and reason about reentrancy into the same pool and into other pools that share the hook. - Upgradeability and admin powers: Owner-controlled settings, like the trusted router list here, are a trust assumption for your users.
Uniswap's v4 Security Framework covers these risks in depth. Uniswap also publishes a v4-security-foundations AI skill for reviewing hook designs.
Next Steps
- Explore the OpenZeppelin Uniswap Hooks library, which is included in the v4-template and provides reusable base contracts for dynamic fees, custom curves, and more.
- Look at Uniswap's production hooks in v4-hooks-public, such as
BaseTokenWrapperHook. - Monitor your hook in production by streaming its events (like
SwapLimitReached) with Quicknode Streams.
Frequently Asked Questions
Why does the hook need a trusted router to identify the swapper?
PoolManager passes its immediate caller as sender, which is usually a router. This guide's hook reads the original swapper through the router's msgSender() function and accepts that identity only from an owner-approved router. A router without that interface or approval cannot swap through this hook.
Does quoting a swap consume the user's swap allowance?
No. V4Quoter reverts its simulated swap state, so a successful quote leaves the allowance unchanged. The hook owner must first trust the compatible quoter, and the quote must use the intended swapper as its caller. A user who has exhausted the allowance still receives SwapLimitExceeded.
Why can a Sepolia deployment run out of gas after simulation succeeds?
A simulation using older execution rules can underestimate Sepolia's state-creation costs. Use the tested Foundry 1.8.6 release, select FOUNDRY_PROFILE=sepolia for Forge, and start the fork with Anvil's --hardfork amsterdam option. The profile selects runtime rules while the compiler target remains Cancun.
Does the five-swap limit apply separately to each pool?
Yes. This example tracks each user's allowance separately for each pool ID. Swapping in one pool does not consume that user's allowance in another pool, even when both pools use the same hook. The window resets on the first swap after at least one hour has passed since that user's window started for that pool.
Wrap Up
Congrats! You've now learned how to create, test, and deploy a custom hook for Uniswap V4. You built a hook that correctly identifies swappers behind a router, tested it with Foundry, deployed it to a local Sepolia fork with Quicknode, and learned what it takes to get a hook routed on a live network.
Stay up to date with the latest in blockchain development by following Quicknode on Twitter (@Quicknode) or joining the Discord community.
