Uniswap v4

Uniswap v4 Hooks and Security Considerations

Understand Uniswap v4’s hook mechanism and essential security considerations to build safer, more efficient decentralized finance applications.

Last updated: 8/28/2025

A strong and adaptable method for improving and expanding the ability of decentralised exchanges (DEXs) is provided by Univ4 Hooks. Hooks, that were patterned after the innovative architecture of Uniswap v4, allow developers add custom logic at strategic points in a pool's lifecycle, such as before or after swaps, liquidity provision, or position changes.


In this article we are talking about:

  • Types of Hooks – Different categories of hooks.
  • Use Cases – Practical applications of hooks in DeFi.
  • Security Considerations – Best practices to ensure hooks are safe.
     

What Are Univ4 Hooks?

Univ4 Hooks are smart contract callbacks that allow developers to inject custom logic at specific stages of a pool’s operations in Uniswap v4 (or similar DEXs). Hooks allow for dynamic adjustments, such as changing fees, imposing restrictions, or initiating external contracts, which makes DEXs more adaptable, effective, and programmable than traditional AMMs with fixed behaviour.
 

Types of Hooks in Univ4

Hooks can execute logic at different stages of a pool’s lifecycle. Here are the key hook types:

1
2beforeInitialize  // Executes before pool creation
3afterInitialize   // Executes after pool setup completes
4
5beforeAddLiquidity     // Runs before liquidity deposits
6afterAddLiquidity      // Executes after successful deposits
7beforeRemoveLiquidity  // Runs before liquidity withdrawals
8afterRemoveLiquidity   // Executes after successful withdrawals
9
10beforeSwap  // Triggers before each trade execution
11afterSwap   // Triggers after trade completion
12
13beforeDonate  // Runs before fee donations to pools
14afterDonate   // Runs after donation processing
15


Overview of Initialization Hooks

Developers can intercept and change the pool setup using initialization hooks. These hooks run once during pool creation. They’re ideal for setting parameters, configuring the pool, and defining initial conditions. Unlike swap or liquidity hooks, initialization hooks don’t trigger during regular operations.
 

Deep Dive into beforeInitialize

beforeInitialize hook is the first place where devs can step in during pool creation. It runs before the main pool data is set. So, devs get full control to decide how the pool should be setup.
 

Function Signature

1function beforeInitialize(
2    address sender,
3    PoolKey calldata key,
4    uint160 sqrtPriceX96,
5    bytes calldata hookData
6) external returns (bytes4);
7


beforeInitialize Hook Use Cases

  • Dynamic Fee Models: Pools can use algorithmic fee discovery, which examines similar markets, volatility trends, and predicted volumes to identify the best pricing structure, in place of static fees.
     
  • Risk Assessment: The hook can score risk by checking market in real-time. It looks at how much prices move, how tokens are linked, and current market state. Stable pairs get better setup. Risky ones can be blocked or get other settings.
     
  • Token Screening: Organisations can use accurate token validation that looks into supply mechanics, verifies regulatory compliance, and scans contract code for vulnerabilities. This makes sure that trading pools have only assets that have been approved / whitelisted.
     

afterInitialize Hook Use Cases

  • Oracle Networks: Automatically establish robust price feed systems with multiple providers, validation mechanisms against manipulation, and price aggregation for enhanced reliability across the DeFi ecosystem.
     
  • Yield Optimization: Integrate with lending protocols for additional returns, enable LP token collateralization, and create leveraged liquidity strategies that amplify yields while managing risk.
     
  • Incentive Programs: Launch adaptive reward systems where early providers get larger incentives, performance-based rewards for volatile periods, and community-voted reward distribution.

Screenshot 2025-08-27 154003.png

Overview of Liquidity Hooks

Uniswap v4's liquidity hooks offer complete control over the liquidity management lifecycle, facilitating advanced system for tracking, validation, and rewards related to liquidity provision and withdrawal.

beforeAddLiquidity Hook

Function Signature

1function beforeAddLiquidity(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.ModifyLiquidityParams calldata params,
5    bytes calldata hookData
6) external returns (bytes4);

Use Cases

  • Liquidity Provider Screening: Put in place thorough screening procedures that confirm accredited investor status, compare LP credentials to sanctions lists, or impose regional limitations.
     
  • Position Size Limits: To avoid liquidity concentration that could influence markets or pose systemic risks, enforce maximum position sizes per user or per tick range.
     
  • Market Condition Restrictions: Prevent liquidity addition during extreme market volatility, oracle failures, or suspected manipulation attempts.
     
  • Fee Tier Optimization: Analyze proposed liquidity positions and suggest optimal fee tiers or automatically route LPs to the most suitable pools based on their risk tolerance and expected trading patterns.
     

Strategic Positioning

  • Liquidity Bootstrapping Controls: During new pool launches, implement staged liquidity addition that prevents large positions from dominating early price discovery or creating unfair advantages for sophisticated actors.
     
  • Anti-MEV Protections: Implement mechanisms to detect and prevent MEV attacks that exploit liquidity addition transactions, protecting LPs from sandwich attacks and other forms of value extraction.
     
  • Coordination Mechanisms: Enable coordinated liquidity provision strategies where multiple LPs can work together to establish optimal liquidity distributions, particularly useful for market making services and institutional coordination.
     

afterAddLiquidity Hook

Function Signature

1function afterAddLiquidity(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.ModifyLiquidityParams calldata params,
5    BalanceDelta delta,
6    bytes calldata hookData
7) external returns (bytes4, BalanceDelta);
8
9

Use Cases

Position Tracking and NFT Management

  • Comprehensive LP Portfolio Management: Advanced liquidity tracking systems are able to keep thorough records of every liquidity position, including yield analytics, impermanent loss computations, and historical performance metrics.
     
  • Dynamic NFT Minting: Each liquidity position can be automatically minted as a unique NFT containing metadata about the position's characteristics, performance history, and current status. These NFTs can evolve over time, displaying real-time analytics, accrued rewards, and even artistic representations of the position's performance.
     
  • Cross-Pool Position Aggregation: Track liquidity positions across multiple pools to provide users with consolidated views of their entire liquidity portfolio, including risk exposure analysis, correlation between positions, and optimization recommendations.
     

Reward and Incentive Systems

  • Adaptive Reward Distribution: Put in place advanced reward schemes that change according to user behaviour, pool usage, and market conditions. Stability bonuses are given to reliable providers during volatile times, while bonus multipliers are given to early liquidity providers.
     
  • Performance-Based Incentives: Reward systems are able to evaluate the performance of individual LPs by taking into account variables such as market timing, position duration, and price stability contribution. In subsequent reward distributions, high-performing LPs are given preference.
     

beforeRemoveLiquidity Hook

Function Signature

1function beforeRemoveLiquidity(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.ModifyLiquidityParams calldata params,
5    bytes calldata hookData
6) external returns (bytes4);


Use Cases

Access Control and Governance

  • Time-Based Lockups: Implement sophisticated lockup mechanisms that prevent premature liquidity withdrawal, supporting various strategies like linear vesting, cliff periods, or performance-based unlocking. This helps maintain pool stability and rewards long-term commitment.
     
  • Governance-Based Restrictions: Enable DAO governance over liquidity withdrawal permissions, where certain market conditions or governance proposals can temporarily restrict withdrawals to protect the ecosystem during critical periods.
     
  • Whitelisting and Permissioned Pools: For institutional or regulated environments, implement access controls that ensure only authorized participants can withdraw liquidity, maintaining compliance with regulatory requirements.
     

Economic Incentive Alignment

  • Dynamic Exit Fees: Implement exit fees that adjust based on market conditions, pool utilization, and timing. During high-volatility periods or low liquidity situations, higher exit fees encourage LPs to maintain their positions, stabilizing the pool.
     

afterRemoveLiquidity Hook

Function Signature

1function afterRemoveLiquidity(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.ModifyLiquidityParams calldata params,
5    BalanceDelta delta,
6    bytes calldata hookData
7) external returns (bytes4, BalanceDelta);


Use Cases

  • Comprehensive Reward Settlement: Calculate and distribute all accumulated rewards including trading fees, liquidity mining rewards, governance tokens, and any special incentives. This can include complex calculations based on position duration, performance metrics, and market contribution.
     
  • Performance Analysis: Generate detailed reports on LP position performance including total returns, impermanent loss analysis, fee earnings breakdown, and comparison to holding underlying assets. This information can be stored on-chain or in decentralized storage systems.
     
  • Automatic Position Closure: Handle all aspects of position closure including final reward calculations, cleanup of associated data structures, and optimization of gas costs for the withdrawal process.
     
  • Reinvestment Strategies: Provide options for automatic reinvestment of withdrawn liquidity into other positions, implementing dollar-cost averaging, rebalancing, or yield optimization strategies.
     

Swap Hooks - Complete Reference

Swap hooks in Uniswap v4 provide comprehensive control over the trading process, enabling sophisticated customization of trade execution, fee structures, MEV protection, and user experience enhancements.

beforeSwap // Triggers before each trade execution afterSwap // Triggers after trade completion
 

Overview

Swap hooks execute at critical moments during trade execution, allowing developers to implement custom logic for price validation, dynamic fees, trade routing optimization, and advanced trading features. These hooks operate in pairs around the core swap operation, providing complete visibility and control over the trading process.
 

beforeSwap Hook

Function Signature

1function beforeSwap(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.SwapParams calldata params,
5    bytes calldata hookData
6) external returns (bytes4, BeforeSwapDelta, uint24);


Use Cases

Dynamic Fee Optimization

  • Volatility-Based Fee Adjustment: Implement dynamic fee structures that adjust based on market volatility, trading volume, and liquidity utilization. During high-volatility periods, fees can increase to compensate liquidity providers for increased risk, while stable periods enable lower fees for better user experience.
     
  • Time-Based Fee Structures: Create fee schedules that vary based on time of day, day of week, or market session activity. This can encourage trading during optimal liquidity periods or provide discounts during typically low-activity times.
     

Advanced Trading Features

  • Limit Order : Enable conditional orders that execute based on market conditions, time triggers, or external events. This includes stop-loss orders, take-profit orders, and complex multi-condition strategies.
     
  • Trade Aggregation and Batching: Collect multiple small trades and execute them as optimized batches, reducing gas costs and improving execution efficiency for users while maintaining MEV protection.
     
  • Cross-Chain Trade Coordination: For multi-chain strategies, coordinate trades across different blockchain networks to optimize execution, maintain portfolio balance, and exploit arbitrage opportunities.
     

afterSwap Hook

Function Signature

1function afterSwap(
2    address sender,
3    PoolKey calldata key,
4    IPoolManager.SwapParams calldata params,
5    BalanceDelta delta,
6    bytes calldata hookData
7) external returns (bytes4, int128);


Use Cases

Trade Analytics and Tracking

  • Comprehensive Trade Analysis: Generate detailed analytics on each trade including price impact analysis, execution quality metrics, comparison to benchmark prices, and slippage realization. This data can be used for performance optimization and user feedback.
     

Reward and Loyalty Systems

  • Trade-Based Reward Distribution: Implement reward systems that distribute tokens based on trading activity, volume milestones, or contribution to market efficiency. Rewards can be immediate or accumulated over time with vesting schedules.
     

Market Making and Arbitrage

  • Arbitrage Opportunity Detection: Identify arbitrage opportunities created by completed trades and either execute them directly or alert specialized arbitrage systems to capture value for the protocol or users.
     
  • Cross-Market Synchronization: Coordinate price updates and liquidity adjustments across multiple markets or chains to maintain consistent pricing and optimal capital allocation.
     

Donate Hooks - Complete Reference

Donate hooks in Uniswap v4 provide comprehensive control over direct token donations to liquidity pools, enabling sophisticated customization of incentive mechanisms, treasury management, yield enhancement strategies, and community-driven liquidity bootstrapping programs.
 

Overview

Donate hooks execute at critical moments during direct token donation processes, allowing developers to implement custom logic for donation validation, dynamic incentive distribution, liquidity optimization, and advanced DeFi treasury management features. These hooks operate in pairs around the core donation operation, providing complete visibility and control over value injection into liquidity pools.
 

beforeDonate Hook

Function Signature

1function beforeDonate(
2    address sender,
3    PoolKey calldata key,
4    uint256 amount0,
5    uint256 amount1,
6    bytes calldata hookData
7) external returns (bytes4);


Use Cases

Treasury and Protocol Management

  • Strategic Treasury Allocation: Implement sophisticated treasury management strategies that analyze market conditions, liquidity utilization, and protocol health metrics before approving donations. This includes dynamic allocation across multiple pools based on yield opportunities, strategic partnerships, and ecosystem development goals.
     
  • Governance-Driven Allocation: Implement governance mechanisms that require community approval for large donations, with voting thresholds, time delays, and transparent allocation criteria. This ensures community alignment and prevents centralized control over significant protocol resources.
     
  • Risk-Adjusted Donation Strategies: Analyze pool health, impermanent loss risks, and market volatility before approving donations, ensuring that contributed capital is allocated to pools with appropriate risk-return profiles and strategic importance.
     
  • Donation Source Verification: Implement comprehensive checks to verify the legitimacy and source of donation funds, including sanctions list screening, regulatory compliance validation, and anti-money laundering (AML) procedures for institutional donors.
     

Liquidity Optimization

  • Pool Health Assessment: Analyze current pool conditions including liquidity depth, price stability, trading activity, and yield generation before accepting donations, ensuring that additional capital will be utilized effectively.
     
  • Strategic Liquidity Placement: Direct donations to specific price ranges or liquidity positions that maximize trading efficiency, reduce price impact for traders, and optimize capital utilization across the entire pool.
     

afterDonate Hook

Function Signature

1function afterDonate(
2    address sender,
3    PoolKey calldata key,
4    uint256 amount0,
5    uint256 amount1,
6    bytes calldata hookData
7) external returns (bytes4);
8
9


Use Cases

Reward Distribution and Tokenomics

  • Proportional Reward Distribution: Automatically distribute rewards to existing liquidity providers based on their proportional contribution to the pool, donation amounts, and time-weighted participation metrics. This includes sophisticated algorithms that account for position duration, size, and active management.
     
  • Vesting and Lock-up Mechanisms: Implement sophisticated vesting schedules for donation-based rewards that encourage long-term participation while preventing immediate sell pressure on reward tokens.
     

Analytics and Performance Tracking

  • ROI and Performance Metrics: Calculate detailed return on investment metrics for donation programs, measuring effectiveness in terms of user acquisition, liquidity growth, trading volume generation, and protocol revenue increases.
     
  • Ecosystem Health Monitoring: Track broader ecosystem metrics that improve as a result of donations including user growth, developer activity, integration partnerships, and overall protocol adoption.
     

Treasury Management and Accounting

  • Automated Bookkeeping: Maintain comprehensive records of all donations including source addresses, amounts, timestamps, and associated pool performance data for treasury management and regulatory compliance purposes.
     
  • Derivatives and Hedging: Implement advanced financial strategies that use donations to provide hedging services for liquidity providers, reducing impermanent loss risks and improving risk-adjusted returns.
     
  • Flash Loan Integration: Utilize donations in conjunction with flash loan strategies to provide enhanced arbitrage opportunities, MEV capture, and market efficiency improvements that benefit all pool participants.
     
  • Cross-Protocol Composability: Leverage donations to enable complex multi-protocol strategies that span lending, derivatives, yield farming, and governance participation across the broader DeFi ecosystem.
     

Uniswap v4 Hooks Security

This security assessment identifies critical vulnerabilities and attack vectors across Uniswap v4 hook implementations, providing actionable recommendations to mitigate risks during hook development and deployment.
 

Security Considerations for Hook Development

Access Control

Access control issues in Uniswap v4 hooks are very common and might be found in almost every hook. The following issue is found in the Gamma Strategy limit order hooks:

The vulnerability in the LimitOrderHook contract arises due to the lack of access control in the beforeSwap() and afterSwap() hook callback functions, which are critical to the proper execution of limit orders during swaps. Specifically, the beforeSwap() function stores the tick value before a swap, while the afterSwap() function processes limit orders based on the state change between the previous and new ticks.

1    function _beforeSwap(
2        address,
3        PoolKey calldata key, 
4        SwapParams calldata,
5        bytes calldata
6    ) external override returns (bytes4, BeforeSwapDelta, uint24) {
7        PoolId poolId = key.toId();
8        (,int24 tickBeforeSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
9        
10        TransientSlot.Int256Slot slot = TransientSlot.asInt256(PREVIOUS_TICK_SLOT);
11        TransientSlot.tstore(slot, int256(tickBeforeSwap));
12        
13        return (BaseHook.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
14    }
15
16 
17    function _afterSwap(
18        address,
19        PoolKey calldata key,
20        SwapParams calldata params,
21        BalanceDelta,
22        bytes calldata
23    ) external override returns (bytes4, int128) {
24        PoolId poolId = key.toId();
25        (,int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
26        
27        TransientSlot.Int256Slot slot = TransientSlot.asInt256(PREVIOUS_TICK_SLOT);
28        int24 tickBeforeSwap = int24(int256(TransientSlot.tload(slot)));
29        
30        limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);
31        return (BaseHook.afterSwap.selector, 0);
32    }
33
34


However, these functions do not have proper access control to restrict who can invoke them. Without mechanisms like the onlyByPoolManager() modifier, unauthorized users can call these functions directly, including malicious actors who may manipulate swap behavior. This could lead to serious consequences such as unauthorized order executions, where users could trigger limit orders to be processed without them actually being filled or meet the conditions of the swap.


For example, the executeOrder() function, which is designed to be executed only by the LimitOrderHook contract after a legitimate swap, can currently be called by any user. This allows for orders to be executed or cleared arbitrarily, completely undermining the protocol's limit order mechanism and breaking its core functionality. Given that these hooks are integral to the protocol's operation, this access control vulnerability has the potential to severely disrupt the system, leading to manipulation of the limit order functionality.
 

Tick Spacing Edge Case Vulnerability in DeFi Order ExecutionTick Spacing Edge Case Vulnerability in DeFi Order Execution:

vulnerability stems from inconsistent implementation of tick traversal logic between standard Uniswap mechanisms and custom order management systems. In Uniswap's nextInitializedTickWithinOneWord function, the protocol correctly handles directional tick searching by adjusting the starting position based on the search direction - when searching downward (zeroForOne = true), it starts from tickNext - 1, and when searching upward (zeroForOne = false), it starts from tickNext.

1// Correct Uniswap implementation
2tick = zeroForOne ? 
3    nextInitializedTick - 1 : // When going down, start before
4    nextInitializedTick;      // When going up, start at position
5
6// Flawed protocol implementation  
7tick = zeroForOne ?
8    nextInitializedTick - 1 : 
9    nextInitializedTick + 1;  // Incorrectly starts after position
10

However, in affected protocols' _findOverlappingPositions function, the implementation incorrectly sets the next tick as nextInitializedTick + 1 regardless of direction when zeroForOne is false. This creates a critical flaw: when tick spacing is 1, the algorithm attempts to search from nextInitializedTick + 1, but since the next initialized tick is actually at nextInitializedTick, the search effectively skips over all valid positions.
 

Share Rounding Exploitation in DeFi Protocols

Share-based uniswap hooks protocols face critical rounding vulnerabilities where attackers exploit integer arithmetic precision loss to systematically drain funds. By making minimal initial deposits and manipulating the share-to-asset exchange rate through direct token transfers, malicious actors can cause subsequent user deposits to round down to zero shares while retaining the underlying assets, effectively stealing deposited funds through mathematical precision attacks.
 

Range Order Arbitrage Vulnerability

Range order creation mechanism that allows malicious actors to exploit the timing difference between transaction submission and block inclusion. When users create range orders, the system calculates the starting position based on the current pool's rounded tick price. However, since uses a distinct Uniswap V4 pool with potentially minimal liquidity below market price, attackers can manipulate the pool by executing a zero-input swap with an extremely low sqrtPriceLimit just before the user's transaction is processed.

This artificially depresses the pool price, causing the user's range order to be created at the manipulated lower price point. Once the user's liquidity is deployed at this disadvantageous level, the attacker can immediately purchase the tokens at the artificially low price and profit from the difference. The recommended mitigation involves implementing user-defined minimum and maximum tick parameters, similar to slippage tolerance controls, allowing users to specify acceptable price ranges for their orders and preventing execution if the pool price has moved beyond their specified bounds during the transaction processing window.
 

Liquidity Management and Fee Distribution

Position Ownership Complexity: Hooks that call modifyLiquidity become position owners, inheriting complex responsibilities for fee management and user fund protection. Critical considerations include:

  • Fee Delta Separation: Properly distinguish between protocol fees and caller deltas to prevent fee misallocation
     
  • Slippage Protection: Apply slippage controls only to principal deltas, not fee accruals, to prevent manipulation
     
  • Salt Uniqueness: Ensure position salt generation creates truly unique identifiers to prevent position collision attacks

Fee Accrual Vulnerabilities: Since anyone can trigger fee accruals at any time, hooks must account for just-in-time liquidity modifications that could conflict with custom fee logic. Implement robust tracking mechanisms that can handle concurrent fee accrual events without corruption or loss.
 

Swap Logic Symmetry and Custom Calculations

Asymmetric Swap Handling: Hooks must handle both exact-input and exact-output swaps symmetrically across beforeSwap and afterSwap callbacks. Asymmetric implementations create arbitrage opportunities where attackers can exploit differences in swap direction handling to extract value from the protocol.
 

Custom Swap Logic Risks: Hooks implementing custom swap calculations face price manipulation vulnerabilities, especially when calculations depend on manipulable balances or exhibit rounding errors. Custom logic must be extensively tested against adversarial conditions and flash loan attacks.
 

Pool Management and State Isolation

Multi-Pool Hook Vulnerabilities: When designing hooks that support multiple pools, developers must implement strict state isolation to prevent cross-pool contamination. Without proper separation, malicious pools can overwrite or corrupt state variables belonging to legitimate pools, leading to accounting errors, fund misallocation, or complete protocol breakdown. Each pool must maintain its own dedicated storage space within the hook contract, with clear boundaries preventing unauthorized access to other pools' data.
 

Single-Pool Restriction: For hooks designed for exclusive single-pool operation, implement initialization controls in the afterInitialize callback to prevent unauthorized pool registration. Failing to restrict pool access can allow malicious actors to create competing pools that exploit the hook's logic or drain resources intended for the legitimate pool.
 

Native Token Handling Vulnerabilities

Reentrancy Attack Vectors: Native token support introduces reentrancy risks during msg.value handling and settlement operations. Attackers can exploit reentrancy to manipulate pool or hook state, especially in systems with custom accounting logic that depends on token balances. Implement comprehensive reentrancy guards and follow checks-effects-interactions patterns.
 

Value Handling Errors: Improper msg.value management can lead to fund loss through failed excess returns or incorrect settlement calculations. Implement precise value tracking and validation throughout native token operations.
 

Callback Skipping and Execution Flow

Skipped Callback Logic: When hooks initiate PoolManager calls, permissioned callbacks are skipped for self-initiated operations but trigger for external callers. This asymmetric behavior can create logic gaps where hooks assume certain validations or state updates occur during self-initiated operations, potentially leaving the system vulnerable to manipulation.

Previous
Swap Mechanics in Uniswap v4 C...

STAY IN THE LOOP

Get updates on our community, partners, events, and everything happening across the ecosystem — delivered straight to your inbox.

Subscribe Now!

newsletter
DeFi SecurityplumeUniswap FoundationAethiropt-collectivePolygon SPNBNB Chain Kickstart

Office 104/105 Level 1, Emaar Square, Building 4 Sheikh Mohammed Bin Rashid Boulevard Downtown Dubai, United Arab Emirates P.O box: 416654

audits@quillaudits.com

All Rights Reserved. © 2025. QuillAudits - LLC

Privacy Policy