Uniswap v4 Hook Integration - AI Technical Reference
Critical Configuration Requirements
Hook Address Permission System
CRITICAL: Hook permissions are determined by deployed contract address bits, NOT by getHookPermissions()
function.
Permission Mapping:
BEFORE_SWAP_FLAG
: Address must have bit 0 set (address ends in odd number)AFTER_SWAP_FLAG
: Address must have bit 1 setBEFORE_SWAP_RETURNS_DELTA_FLAG
: Address must have bit 2 setAFTER_SWAP_RETURNS_DELTA_FLAG
: Address must have bit 3 set
Failure Mode: Hook compiles and deploys successfully but functions never execute
Root Cause: Address permission bits don't match required permissions
Detection: beforeSwap
never called despite beforeSwap: true
in code
Address Mining Requirements
Tool: HookMiner contract from v4-periphery
Time Cost: 30 seconds for simple permissions, 5+ minutes for complex combinations
Implementation:
uint160 flags = uint160(Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG);
(address hookAddress, bytes32 salt) = HookMiner.find(
CREATE2_DEPLOYER,
flags,
type(MyHook).creationCode,
abi.encode(poolManager)
);
Delta Settlement System
Flash Accounting Critical Rules
System: All delta modifications must sum to zero by transaction end
Failure: CurrencyNotSettled
revert if deltas don't balance
Settlement Required: Every delta your hook creates must be explicitly settled
Delta Direction Convention:
- Taking tokens: Return negative delta (
-feeAmount
) - Giving tokens: Return positive delta (
+rebateAmount
)
Settlement Implementation:
// Hook takes 0.1% fee
int128 fee = int128(swapAmount * 10 / 10000);
hookDelta = BalanceDeltaLibrary.toBalanceDelta(-fee, 0);
// REQUIRED: Settle the delta
IERC20(token0).transfer(address(poolManager), uint256(fee));
poolManager.settle(Currency.wrap(address(token0)));
Common Failure Patterns
Transaction Reverts
Error | Root Cause | Fix |
---|---|---|
"Hook address not valid" | Address permission bits don't match hook requirements | Use HookMiner to find correct address |
"CurrencyNotSettled" | Hook modifies deltas but doesn't settle them | Call settle() for taken tokens, take() for given tokens |
"Hook delta exceeds swap amount" | Hook tries to take more than swap amount | Validate delta amounts against swap parameters |
"Transaction reverted without reason" | SDK misconfiguration or missing approvals | Check testnet vs mainnet configs, verify token approvals |
Function Execution Failures
Symptom: Hook functions not called despite correct permissions
Causes:
- Function signature mismatch (missing
calldata
keywords) - Wrong return types
- Missing BaseHook inheritance
Correct Function Signatures:
function beforeSwap(
address sender,
PoolKey calldata key, // Must be calldata
SwapParams calldata params, // Must be calldata
bytes calldata hookData // Must be calldata
) external returns (bytes4, BeforeSwapDelta, uint24) {
return (BaseHook.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
}
Security Vulnerabilities
Access Control Requirements
CRITICAL: All hook callback functions must have onlyPoolManager
modifier
Risk: Without access control, anyone can call hook functions directly and drain funds
// VULNERABLE
function afterSwap(...) external returns (...) {
feeToken.transfer(msg.sender, collectedFees); // Anyone can call this
}
// SECURE
function afterSwap(...) external onlyPoolManager returns (...) {
feeToken.transfer(owner, collectedFees); // Only PoolManager can call
}
Async Hook Risks
Risk Level: CRITICAL - Can steal all user funds
Attack: Malicious async hooks can take tokens instead of executing swaps
Mitigation: Only use async hooks from trusted sources, validate pool tokens
Token Compatibility Issues
Problem Tokens:
- USDT: No return value on
transfer()
- Fee-on-transfer tokens: Balance changes don't match transfer amounts
- Rebasing tokens: Balances change automatically
Solution: Use OpenZeppelin's SafeERC20 for all token operations
Gas Optimization Critical Points
Loop Optimization
Failure Pattern: Unbounded loops cause "out of gas" on certain swaps
// BAD - Gas scales with array size
for (uint i = 0; i < authorizedUsers.length; i++) {
require(validateUser(authorizedUsers[i]), "Invalid user");
}
// GOOD - Constant gas
require(isAuthorized[msg.sender], "Unauthorized");
External Call Management
Risk: Oracle calls can fail or consume excessive gas
Solution: Implement fallback patterns with cached values
uint256 price = cachedPrice;
if (block.timestamp > lastUpdate + 3600) {
try priceOracle.getPrice(token) returns (uint256 newPrice) {
price = newPrice;
cachedPrice = newPrice;
lastUpdate = block.timestamp;
} catch {
// Use stale price if oracle fails
}
}
Production Deployment Requirements
Testing Prerequisites
- Mainnet Fork Testing: Test with real token balances and current block state
- Gas Usage Verification: Test with realistic large swap amounts (1000+ ETH)
- Oracle Failure Testing: Mock external dependencies failures
- Edge Case Coverage: Test extreme token amounts for overflow conditions
Monitoring Requirements
Critical Metrics:
- Hook execution success rate
- Gas usage per call type
- Delta settlement success rate
- External call failure rate
Monitoring Implementation:
event HookExecuted(string functionName, bool success, uint256 gasUsed);
event DeltaSettlementFailed(address token, int256 amount);
event ExternalCallFailed(address target, bytes data);
Emergency Response System
Circuit Breaker Pattern (Required for production):
bool public emergencyPause = false;
address public emergencyAdmin;
modifier whenNotPaused() {
require(!emergencyPause, "Hook paused for emergency");
_;
}
function emergencyPauseHook() external {
require(msg.sender == emergencyAdmin, "Only emergency admin");
emergencyPause = true;
emit EmergencyPause(block.timestamp);
}
Resource Requirements
Development Time Investment
- Basic hook implementation: 2-3 days
- Security audit and testing: 1-2 weeks
- Production deployment and monitoring setup: 3-5 days
- Address mining for complex permissions: 5+ minutes per deployment
Expertise Requirements
- Essential: Solidity development, Uniswap v4 architecture understanding
- Critical: Gas optimization techniques, MEV protection strategies
- Required: Testing frameworks (Foundry), security audit practices
Infrastructure Dependencies
- Testing: Mainnet fork access (Infura/Alchemy)
- Deployment: CREATE2 deployer contract
- Monitoring: Transaction debugging tools (Tenderly)
- Security: Emergency response procedures
Decision Criteria for Implementation
When to Use Hooks
Suitable for:
- Custom fee structures
- MEV protection mechanisms
- Liquidity incentive programs
- Integration with external protocols
Avoid for:
- Simple token transfers (use standard DEX)
- High-frequency trading (gas costs too high)
- Experimental features without emergency stops
Alternative Considerations
Instead of Hooks:
- Simple swaps: Use Uniswap Universal Router
- Custom logic: Build separate contract that calls Uniswap
- Fee collection: Use pool fee mechanisms instead of hook deltas
Critical Warnings
Production Failures That Will Occur
- Delta calculation overflow: Use safe math for large token amounts
- External protocol dependency: All external calls will fail eventually
- Permission mismatch after upgrades: Re-mine addresses after code changes
- MEV exploitation: Hook modifications are visible and exploitable
Breaking Points
- Gas limit: Hooks hit 300k+ gas with complex logic
- Token compatibility: Non-standard ERC20 tokens break assumptions
- Oracle manipulation: Price feeds can be manipulated during low liquidity
- Sandwich attacks: Predictable hook behavior enables MEV exploitation
Support Quality Assessment
- Official documentation: Incomplete, missing production edge cases
- Community support: Variable quality, verify all advice
- Security audit availability: Limited auditors familiar with v4 hooks
- Emergency response: No official incident response procedures
Tool Requirements for Implementation
Essential Development Tools
- Foundry: Only testing framework that properly handles v4 state
- HookMiner: Required for address mining with correct permissions
- Cast CLI: Quick permission verification and debugging
- BaseHook contract: Always inherit from v4-periphery BaseHook
Security Analysis Tools
- Tenderly: Best transaction debugging for failed hooks
- OpenZeppelin Defender: Contract monitoring and alerting
- CertiK/Hacken audit guides: Security checklist for hooks
Production Monitoring
- Gas tracking: Monitor hook execution costs
- Delta settlement monitoring: Track settlement success rates
- External dependency monitoring: Alert on oracle/protocol failures
- Circuit breaker implementation: Emergency stop functionality
This technical reference provides the operational intelligence needed for successful Uniswap v4 hook implementation while highlighting critical failure modes and their solutions.
Useful Links for Further Investigation
Essential Hook Debugging Tools and Resources
Link | Description |
---|---|
Foundry Testing Framework | The only testing framework that properly handles Uniswap v4's complex state management. Use `vm.createFork()` to test against real mainnet state. |
HookMiner Tool | Essential for finding deployment addresses with correct permission bits. Slow but necessary - factor mining time into deployment scripts. |
Uniswap v4 Periphery BaseHook | Always inherit from BaseHook. It handles permission validation, access control, and provides correct function signatures. Don't roll your own. |
Cast CLI Tool | For quick permission checking and contract debugging. Use `cast call` to verify hook permissions match deployed address. |
CertiK's Uniswap v4 Security Analysis | Comprehensive security analysis from actual auditors. Covers permission mismatches, delta handling, access control, and centralization risks. Required reading. |
Hacken's Hook Auditing Guide | Step-by-step security audit methodology for hooks. Includes real vulnerability examples and common attack patterns. Use as a checklist before production deployment. |
GitHub Issues - v4-periphery | Track known issues and bugs in the periphery contracts. Check before implementing BaseHook patterns. |
Stack Overflow - Uniswap v4 SDK Issues | Typical "transaction reverted without reason" problems with SDK integration. Most SDK examples are broken or outdated. |
QuickNode Hook Tutorial | Working hook examples with proper error handling. One of the few tutorials that includes debugging techniques. |
SolidityDeveloper Integration Guide | Practical examples with real code that works. Covers hook integration patterns and common pitfalls. |
Uniswap v4 Core Documentation | Official docs are accurate but incomplete. Missing all the edge cases that'll fuck you in production. Whoever wrote these docs never actually deployed hooks. |
v4-core GitHub Repository | Source of truth for how hooks actually work. Read the Hooks.sol library and PoolManager.sol for real behavior. |
Hook Examples Repository | Community-maintained collection of hook examples. Quality varies wildly - some are security disasters, others are excellent. Use carefully. |
EIP-1153 Transient Storage | Understanding transient storage is critical for hook development. This is how v4 achieves gas savings through flash accounting. |
Gas Optimization Patterns | Study PoolManager.sol for gas optimization techniques. Pay attention to how they minimize storage writes and external calls. |
Flipside Crypto Uniswap Analytics | Community dashboard analyzing Uniswap pool metrics including volume, swaps, and liquidity data. Monitor hook performance and gas usage across v4 implementations. |
OKLink Ethereum Explorer | Alternative blockchain explorer for Ethereum with comprehensive transaction analysis. Essential for verifying hook contracts - users won't trust unverified contracts handling their funds. |
Tenderly Debugging Platform | Best tool for debugging failed transactions. Shows exact revert reasons and gas usage breakdown for complex hook interactions. |
OpenZeppelin Pausable Contracts | Implement emergency stops in your hooks. You will need them when things go wrong. |
Flashbots Protect | If your hook is vulnerable to MEV attacks, protect users by routing through Flashbots. Front-running is real and profitable. |
MEV Protection Guide | Understanding MEV is essential for hook developers. Your hook modifications can be exploited by MEV bots. |
Discord - Uniswap Developers | Active developer community, but quality of advice varies. Verify everything you learn here. |
Ethereum Developer Forum | Official Ethereum technical forum with developer discussions, protocol updates, and troubleshooting support for Uniswap v4 development. |
Related Tools & Recommendations
Deploy Smart Contracts on Optimism Without Going Broke
Stop paying $200 to deploy hello world contracts. Here's how to use Optimism like a normal person.
Optimism Production Troubleshooting - Fix It When It Breaks
The real-world debugging guide for when Optimism doesn't do what the docs promise
Optimism - Yeah, It's Actually Pretty Good
The L2 that doesn't completely suck at being Ethereum
Build Custom Arbitrum Bridges That Don't Suck
integrates with Arbitrum
Arbitrum Orbit - Launch Your Own L2/L3 Chain (Without the Headaches)
integrates with Arbitrum Orbit
Arbitrum Gas Optimization - Stop Wasting Money on Transactions
integrates with Arbitrum One
Set Up Your Complete Polygon Development Environment - Step-by-Step Guide
Fix the bullshit Node.js conflicts, MetaMask fuckups, and gas estimation errors that waste your Saturday debugging sessions
Polygon Edge Enterprise Deployment - The Abandoned Blockchain Framework Guide
Deploy Ethereum-compatible blockchain networks that work until they don't - now with 100% chance of no official support.
Polygon - Makes Ethereum Actually Usable
integrates with Polygon
Firebase Alternatives That Don't Suck - Real Options for 2025
Your Firebase bills are killing your budget. Here are the alternatives that actually work.
RAG on Kubernetes: Why You Probably Don't Need It (But If You Do, Here's How)
Running RAG Systems on K8s Will Make You Hate Your Life, But Sometimes You Don't Have a Choice
Pinecone Production Reality: What I Learned After $3200 in Surprise Bills
Six months of debugging RAG systems in production so you don't have to make the same expensive mistakes I did
MetaMask vs Coinbase Wallet vs Trust Wallet vs Ledger Live - Which Won't Screw You Over?
I've Lost Money With 3 of These 4 Wallets - Here's What I Learned
MetaMask Web3 Integration - Stop Fighting Mobile Connections
integrates with MetaMask SDK
MetaMask - Your Gateway to Web3 Hell
The world's most popular crypto wallet that everyone uses and everyone complains about.
SaaSReviews - Software Reviews Without the Fake Crap
Finally, a review platform that gives a damn about quality
Fresh - Zero JavaScript by Default Web Framework
Discover Fresh, the zero JavaScript by default web framework for Deno. Get started with installation, understand its architecture, and see how it compares to Ne
Anthropic Raises $13B at $183B Valuation: AI Bubble Peak or Actual Revenue?
Another AI funding round that makes no sense - $183 billion for a chatbot company that burns through investor money faster than AWS bills in a misconfigured k8s
Google Pixel 10 Phones Launch with Triple Cameras and Tensor G5
Google unveils 10th-generation Pixel lineup including Pro XL model and foldable, hitting retail stores August 28 - August 23, 2025
Dutch Axelera AI Seeks €150M+ as Europe Bets on Chip Sovereignty
Axelera AI - Edge AI Processing Solutions
Recommendations combine user behavior, content similarity, research intelligence, and SEO optimization