Building secure Uniswap v4 hooks
Trail of Bits analyzed dozens of audit findings and real-world exploits to identify seven recurring failure patterns in Uniswap v4 hook development. The Cork ($12M) and Bunni ($8.4M) exploits demonstrate that while the v4 PoolManager enforces protocol-level settlement invariants, application-specific hook code remains vulnerable to missing caller checks, unvalidated pool trust, accounting bugs, hook timing errors, permission bit mismatches, callback blocking, and state mutation during nested callbacks. These patterns serve as a secure-development checklist for builders and a review framework for auditors.
Detection / Hunteropenrouter
What Happened
Uniswap v4 is a new version of a popular decentralized exchange protocol that lets developers add custom logic called 'hooks' to trading pools. These hooks add flexibility but also introduce new security risks. Two real-world exploits — Cork (~$12M lost) and Bunni ($8.4M lost) — show that attackers can drain funds by exploiting mistakes in the custom code developers write around hooks, not by breaking Uniswap itself. The article identifies seven common mistakes developers make, such as forgetting to check who is calling a hook, trusting unverified pools, or having rounding errors in accounting logic. Developers building on Uniswap v4 should review these patterns carefully, use recommended security templates, and test their code with adversarial scenarios. Auditors can use these patterns as a checklist when reviewing hook code.
Key Takeaways
- Seven recurring failure patterns identified in Uniswap v4 hook code: missing caller checks, unvalidated pool trust, custom accounting leaks, wrong hook timing, permission bit mismatches, hook failures blocking pool actions, and state changes during callback sequences.
- Cork exploit (~$12M, May 2025) exploited an access-control gap allowing untrusted data to reach hook logic affecting redemptions, combined with a pricing issue.
- Bunni exploit ($8.4M, September 2025) was a rounding bug in idle-balance accounting where an attacker used a flash loan to manipulate price ticks, then made 44 tiny withdrawals that disproportionately shrank active balances relative to shares burned.
- Neither exploit stemmed from Uniswap v4 core protocol flaws; both arose from application-specific authorization and accounting logic built around hooks.
- Developers should use BaseHook for hook entrypoints and SafeCallback for unlockCallback, maintain strict pool allowlists, separate balance buckets, and fuzz test with adversarial scenarios using Echidna and Medusa.
Affected Systems
- Uniswap v4 PoolManager singleton contract
- Uniswap v4 hook contracts (custom application logic)
- ERC-20 tokens interacting with v4 hooks (including fee-on-transfer, rebasing, callback-enabled, pausable, and blacklistable tokens)
Vulnerabilities (CVEs)
None identified.
Attack Chain
- Reconnaissance: Attacker identifies a Uniswap v4 hook with missing caller checks, unvalidated pool trust, or accounting bugs
- Initial Access: Attacker calls hook callbacks directly with malicious parameters or creates a malicious pool with the target hook address attached
- Manipulation: Attacker uses flash loans to manipulate pool price ticks or routes logic through attacker-controlled pools with malicious ERC-20 tokens
- Exploitation: Attacker exploits accounting bugs (e.g., rounding errors, balance bucket mixing) or access-control gaps to extract value that satisfies PoolManager settlement but leaks from hook internal accounting
- Exfiltration: Attacker completes withdrawals or swaps that extract profit, with each individual transaction passing the PoolManager's settlement invariant checks
Detection Availability
- YARA Rules: No
- Sigma Rules: No
- Snort/Suricata Rules: No
- KQL Queries: No
- Splunk SPL Queries: No
- EQL Queries: No
- Other Detection Logic: No
No detection rules are provided. The article is a secure-development guide focused on smart contract audit patterns rather than traditional SOC detection logic.
Detection Engineering Assessment
| Dimension | Rating | Rationale |
|---|---|---|
| EDR Visibility | None | This article concerns smart contract security on blockchain networks, not endpoint or host-based threats. EDR tooling is not applicable to this threat surface. |
| Network Visibility | None | The exploits described operate entirely on-chain within smart contract execution. Traditional network monitoring does not provide visibility into blockchain transaction-level exploitation. |
| Detection Difficulty | Hard | Detecting these exploits requires real-time blockchain transaction analysis, understanding of smart contract state, and the ability to identify anomalous patterns such as repeated tiny withdrawals or flash-loan-assisted price tick manipulation. Few organizations have this capability deployed as automated detection. |
Required Log Sources
- Blockchain transaction mempool monitoring
- On-chain event logs from Uniswap v4 PoolManager and hook contracts
- Flash loan monitoring services
Hunting Hypotheses
| Hypothesis | Telemetry | ATT&CK Stage | FP Risk |
|---|---|---|---|
| Consider monitoring for transactions that call hook callback functions directly from non-PoolManager addresses, which may indicate exploitation of missing caller checks. | On-chain transaction logs showing msg.sender values for hook callback invocations | Initial Access | Low — legitimate PoolManager-routed calls will always have the PoolManager as msg.sender; direct calls from other addresses are inherently suspicious. |
| Consider hunting for pools created with a known hook address but with attacker-chosen currency pairs or parameters, which may indicate malicious pool creation targeting a vulnerable hook. | Pool initialization events from the PoolManager contract | Initial Access | Medium — legitimate new pool creation is common; correlation with known hook addresses and unusual token pairs is needed to reduce noise. |
| Consider monitoring for patterns of many small withdrawals from the same pool in rapid succession, especially following a flash-loan-assisted price tick manipulation, which may indicate an accounting exploit similar to the Bunni incident. | On-chain swap and liquidity event logs with transaction ordering analysis | Exploitation | Medium — legitimate users may make multiple small withdrawals; the signal is strengthened when combined with recent flash loan activity and tick manipulation. |
Control Gaps
- Traditional SIEM/EDR tooling provides no visibility into on-chain smart contract exploitation
- Network security monitoring cannot detect or prevent blockchain transaction-level attacks
- Standard endpoint controls are irrelevant to smart contract security
Key Behavioral Indicators
- Hook callback functions called by addresses other than the PoolManager contract
- New pools initialized with a known hook address but non-standard or attacker-chosen currency pairs
- Rapid sequence of small withdrawals from a single pool following flash loan activity
- Dynamic fee overrides that move fees to extreme values within a single transaction
- Nested swap or liquidity operations across multiple pools sharing the same hook contract
False Positive Assessment
Low — The described patterns (direct callback calls, malicious pool creation, accounting exploits) are specific to Uniswap v4 hook exploitation and would rarely occur in legitimate usage. However, on-chain detection signals such as small repeated withdrawals may generate false positives from legitimate user behavior.
Recommendations
Immediate Mitigation
- Verify against your organization's incident response runbook and team escalation paths before acting. If you operate Uniswap v4 hooks, consider immediately auditing all external callback functions for missing caller checks (msg.sender != address(poolManager)).
- Consider reviewing any deployed hooks for pool validation logic — ensure beforeInitialize restricts pool creation to allowlisted PoolKey values.
- If your hooks use custom accounting with deltas, consider reviewing for rounding errors, balance bucket mixing, and conservation-of-value invariants across all supported token types.
Infrastructure Hardening
- Consider using BaseHook for hook entrypoints and SafeCallback for unlockCallback to enforce caller checks on covered paths.
- Evaluate binding hooks to canonical pools during deployment or maintaining strict pool allowlists with PoolId re-validation on every user-controlled path.
- Consider keeping LP funds, fees, and incentives in separate balance buckets with clear ownership labeling for each delta.
- If hooks are upgradeable via proxy, consider reviewing the upgrade admin, delay, storage layout, and implementation checks as part of the security boundary.
- Where possible, prefer immutable, versioned deployments over upgradeable proxies.
User Protection
- Consider wrapping non-essential external calls (reward distribution, dust cleanup, oracle reads) in try/catch blocks to prevent callback reverts from blocking core user flows like withdrawals and swaps.
- Evaluate providing explicit exit-safe fallback paths for safety-critical dependencies such as price feeds.
- Consider validating freshness and bounds for all external price data, and never silently use stale pricing data.
Security Awareness
- Consider incorporating the seven failure patterns into your smart contract development lifecycle as a pre-deployment checklist.
- If your team builds on Uniswap v4, consider training developers on the session-based unlock/callback model and the distinction between PoolManager guarantees and hook developer responsibilities.
- Evaluate running adversarial fuzz tests using Echidna and Medusa covering nested callbacks, fee extremes, malicious pools, and non-standard tokens before deployment.
- Consider reviewing the Uniswap v4 Security Framework for operational guidance beyond code review.