v4 Hook Security Foundations
Security-first guide for building Uniswap v4 hooks. Hook vulnerabilities can drain user funds—understand these concepts before writing any hook code.
Threat Model
Before writing code, understand the v4 security context:
Permission Flags Risk Matrix
All 14 hook permissions with associated risk levels:
Risk Thresholds
- LOW: Unlikely to cause fund loss
- MEDIUM: Requires careful implementation
- HIGH: Can cause fund loss if misimplemented
- CRITICAL: Can enable complete fund theft
CRITICAL: NoOp Rug Pull Attack
The BEFORE_SWAP_RETURNS_DELTA permission (bit 10) is the most dangerous hook permission. A malicious hook can:
- Return a delta claiming it handled the entire swap
- PoolManager accepts this and settles the trade
- Hook keeps all input tokens without providing output
- User loses entire swap amount
Attack Pattern
Detection
Before interacting with ANY hook that has beforeSwapReturnDelta: true:
- Audit the hook code - Verify legitimate use case
- Check ownership - Is it upgradeable? By whom?
- Verify track record - Has it been audited by reputable firms?
- Start small - Test with minimal amounts first
Legitimate Uses
NoOp patterns are valid for:
- Just-in-time liquidity (JIT)
- Custom AMM curves
- Intent-based trading systems
- RFQ/PMM integrations
But each requires careful implementation and audit.
Delta Accounting Fundamentals
v4 uses a credit/debit system through the PoolManager:
Core Invariant
The PoolManager tracks what each address owes or is owed. At transaction end, all debts must be settled.
Key Functions
Settlement Pattern
Common Mistakes
- Forgetting sync: Settlement fails without sync
- Wrong order: Must sync → transfer → settle
- Partial settlement: Leaves transaction in invalid state
- Double settlement: Causes accounting errors
Access Control Patterns
PoolManager Verification
Every hook callback MUST verify the caller:
Why This Matters
Without this check:
- Anyone can call hook functions directly
- Attackers can manipulate hook state
- Funds can be drained through fake callbacks
Router Verification Patterns
The sender parameter is the router, not the end user. For hooks that need user identity:
Allowlisting Pattern
User Identity via hookData
msg.sender Trap
Token Handling Hazards
Not all tokens behave like standard ERC-20s:
Safe Balance Check Pattern
Base Hook Template
Start with all permissions disabled. Enable only what you need:
See references/base-hook-template.md [blocked] for a complete implementation template.
Security Checklist
Before deploying any hook:
Gas Budget Guidelines
Hook callbacks execute inside the PoolManager's transaction context. Excessive gas consumption can make swaps revert or become economically unviable.
Gas Budgets by Callback
Common Gas Pitfalls
- Unbounded loops: Iterating over dynamic arrays (e.g., all active positions) can exceed block gas limits. Cap array sizes or use pagination.
- SSTORE in hot paths: Each new storage slot costs ~20,000 gas. Prefer transient storage (
tstore/tload) for data that doesn't persist beyond the transaction. Requires Solidity >= 0.8.24 with EVM target set tocancunor later. - External calls: Each cross-contract call adds ~2,600 gas base cost plus the callee's execution. Batch calls where possible.
- String operations: Avoid
stringmanipulation in callbacks; usebytes32for identifiers. - Redundant reads: Cache
poolManagercalls — repeatedgetSlot0()orgetLiquidity()reads cost gas each time.
Measuring Gas
Risk Scoring System
Calculate your hook's risk score (0-33):
Audit Tier Recommendations
Absolute Prohibitions
Never do these things in a hook:
- Never trust
msg.senderfor user identity - It's always PoolManager - Never enable
beforeSwapReturnDeltawithout understanding NoOp attacks - Never store passwords, keys, or PII on-chain
- Never use
transfer()for ETH - Usecall{value:}("") - Never assume token decimals - Always query the token
- Never use
block.timestampfor randomness - Never hardcode gas limits in calls
- Never ignore return values from external calls
- Never use
tx.originfor authorization - It's a phishing vector; malicious contracts can relay calls with the original user'stx.origin
Pre-Deployment Audit Checklist
See references/audit-checklist.md [blocked] for detailed audit requirements.
Production Hook References
Learn from audited, production hooks:
External Resources
Official Documentation
Security Resources
Community
- v4-hooks-skill by @igoryuzo - Community skill that inspired this guide
- v4hooks.dev - Community hook resources
Additional References
- Base Hook Template [blocked] - Complete implementation starter
- Vulnerabilities Catalog [blocked] - Common patterns and mitigations
- Audit Checklist [blocked] - Detailed pre-deployment checklist


