[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78DYR3MZT5KZZ1FWYM4VNP8":3,"skill-same:01M78DYR3MZT5KZZ1FWYM4VNP8":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":35,"ownerDescription":36,"updatedAt":37,"install":38,"resources":51},"01M78DYR3MZT5KZZ1FWYM4VNP8","v4-security-foundations",null,"Security-first Uniswap v4 hook development. Use when user mentions \"v4 hooks\", \"hook security\", \"PoolManager\", \"beforeSwap\", \"afterSwap\", or asks about V4 hook best practices, vulnerabilities, or audit requirements.","Solizardking\u002Fskillhub-main","Solizardking","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F108096810?v=4","01M786KDB10AYV042N0F9BD5B5","Clawd","01M786NYYXSZK1D05WM8JQPC48",0,"MIT","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fv4-security-foundations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: v4-security-foundations\ndescription: Security-first Uniswap v4 hook development. Use when user mentions \"v4 hooks\", \"hook security\", \"PoolManager\", \"beforeSwap\", \"afterSwap\", or asks about V4 hook best practices, vulnerabilities, or audit requirements.\nallowed-tools: Read, Glob, Grep, WebFetch, Task(subagent_type:Explore)\nmodel: opus\nlicense: MIT\nmetadata:\n  author: uniswap\n  version: '1.1.0'\n---\n\n# v4 Hook Security Foundations\n\nSecurity-first guide for building Uniswap v4 hooks. Hook vulnerabilities can drain user funds—understand these concepts before writing any hook code.\n\n## Threat Model\n\nBefore writing code, understand the v4 security context:\n\n| Threat Area             | Description                                                | Mitigation                                     |\n| ----------------------- | ---------------------------------------------------------- | ---------------------------------------------- |\n| **Caller Verification** | Only `PoolManager` should invoke hook functions            | Verify `msg.sender == address(poolManager)`    |\n| **Sender Identity**     | `msg.sender` always equals PoolManager, never the end user | Use `sender` parameter for user identity       |\n| **Router Context**      | The `sender` parameter identifies the router, not the user | Implement router allowlisting                  |\n| **State Exposure**      | Hook state is readable during mid-transaction execution    | Avoid storing sensitive data on-chain          |\n| **Reentrancy Surface**  | External calls from hooks can enable reentrancy            | Use reentrancy guards; minimize external calls |\n\n## Permission Flags Risk Matrix\n\nAll 14 hook permissions with associated risk levels:\n\n| Permission Flag                   | Risk Level | Description                 | Security Notes                |\n| --------------------------------- | ---------- | --------------------------- | ----------------------------- |\n| `beforeInitialize`                | LOW        | Called before pool creation | Validate pool parameters      |\n| `afterInitialize`                 | LOW        | Called after pool creation  | Safe for state initialization |\n| `beforeAddLiquidity`              | MEDIUM     | Before LP deposits          | Can block legitimate LPs      |\n| `afterAddLiquidity`               | LOW        | After LP deposits           | Safe for tracking\u002Frewards     |\n| `beforeRemoveLiquidity`           | HIGH       | Before LP withdrawals       | Can trap user funds           |\n| `afterRemoveLiquidity`            | LOW        | After LP withdrawals        | Safe for tracking             |\n| `beforeSwap`                      | HIGH       | Before swap execution       | Can manipulate prices         |\n| `afterSwap`                       | MEDIUM     | After swap execution        | Can observe final state       |\n| `beforeDonate`                    | LOW        | Before donations            | Access control only           |\n| `afterDonate`                     | LOW        | After donations             | Safe for tracking             |\n| `beforeSwapReturnDelta`           | CRITICAL   | Returns custom swap amounts | **NoOp attack vector**        |\n| `afterSwapReturnDelta`            | HIGH       | Modifies post-swap amounts  | Can extract value             |\n| `afterAddLiquidityReturnDelta`    | HIGH       | Modifies LP token amounts   | Can shortchange LPs           |\n| `afterRemoveLiquidityReturnDelta` | HIGH       | Modifies withdrawal amounts | Can steal funds               |\n\n### Risk Thresholds\n\n- **LOW**: Unlikely to cause fund loss\n- **MEDIUM**: Requires careful implementation\n- **HIGH**: Can cause fund loss if misimplemented\n- **CRITICAL**: Can enable complete fund theft\n\n## CRITICAL: NoOp Rug Pull Attack\n\nThe `BEFORE_SWAP_RETURNS_DELTA` permission (bit 10) is the most dangerous hook permission. A malicious hook can:\n\n1. Return a delta claiming it handled the entire swap\n2. PoolManager accepts this and settles the trade\n3. Hook keeps all input tokens without providing output\n4. User loses entire swap amount\n\n### Attack Pattern\n\n```solidity\n\u002F\u002F MALICIOUS - DO NOT USE\nfunction beforeSwap(\n    address,\n    PoolKey calldata,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata\n) external override returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Claim to handle the swap but steal tokens\n    int128 amountSpecified = int128(params.amountSpecified);\n    BeforeSwapDelta delta = toBeforeSwapDelta(amountSpecified, 0);\n    return (BaseHook.beforeSwap.selector, delta, 0);\n}\n```\n\n### Detection\n\nBefore interacting with ANY hook that has `beforeSwapReturnDelta: true`:\n\n1. **Audit the hook code** - Verify legitimate use case\n2. **Check ownership** - Is it upgradeable? By whom?\n3. **Verify track record** - Has it been audited by reputable firms?\n4. **Start small** - Test with minimal amounts first\n\n### Legitimate Uses\n\nNoOp patterns are valid for:\n\n- Just-in-time liquidity (JIT)\n- Custom AMM curves\n- Intent-based trading systems\n- RFQ\u002FPMM integrations\n\nBut each requires careful implementation and audit.\n\n## Delta Accounting Fundamentals\n\nv4 uses a credit\u002Fdebit system through the PoolManager:\n\n### Core Invariant\n\n```text\nFor every transaction: sum(deltas) == 0\n```\n\nThe PoolManager tracks what each address owes or is owed. At transaction end, all debts must be settled.\n\n### Key Functions\n\n| Function                     | Purpose                             | Direction              |\n| ---------------------------- | ----------------------------------- | ---------------------- |\n| `take(currency, to, amount)` | Withdraw tokens from PoolManager    | You receive tokens     |\n| `settle(currency)`           | Pay tokens to PoolManager           | You send tokens        |\n| `sync(currency)`             | Update PoolManager balance tracking | Preparation for settle |\n\n### Settlement Pattern\n\n```solidity\n\u002F\u002F Correct pattern: sync before settle\npoolManager.sync(currency);\ncurrency.transfer(address(poolManager), amount);\npoolManager.settle(currency);\n```\n\n### Common Mistakes\n\n1. **Forgetting sync**: Settlement fails without sync\n2. **Wrong order**: Must sync → transfer → settle\n3. **Partial settlement**: Leaves transaction in invalid state\n4. **Double settlement**: Causes accounting errors\n\n## Access Control Patterns\n\n### PoolManager Verification\n\nEvery hook callback MUST verify the caller:\n\n```solidity\nmodifier onlyPoolManager() {\n    require(msg.sender == address(poolManager), \"Not PoolManager\");\n    _;\n}\n\nfunction beforeSwap(\n    address sender,\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Safe to proceed\n}\n```\n\n### Why This Matters\n\nWithout this check:\n\n- Anyone can call hook functions directly\n- Attackers can manipulate hook state\n- Funds can be drained through fake callbacks\n\n## Router Verification Patterns\n\nThe `sender` parameter is the router, not the end user. For hooks that need user identity:\n\n### Allowlisting Pattern\n\n```solidity\nmapping(address => bool) public allowedRouters;\n\nfunction beforeSwap(\n    address sender,  \u002F\u002F This is the router\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    require(allowedRouters[sender], \"Router not allowed\");\n    \u002F\u002F Proceed with swap\n}\n```\n\n### User Identity via hookData\n\n```solidity\nfunction beforeSwap(\n    address sender,\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Decode user address from hookData (router must include it)\n    address user = abi.decode(hookData, (address));\n    \u002F\u002F CAUTION: Router must be trusted to provide accurate user\n}\n```\n\n### msg.sender Trap\n\n```solidity\n\u002F\u002F WRONG - msg.sender is always PoolManager in hooks\nfunction beforeSwap(...) external {\n    require(msg.sender == someUser); \u002F\u002F Always fails or wrong\n}\n\n\u002F\u002F CORRECT - Use sender parameter\nfunction beforeSwap(address sender, ...) external {\n    require(allowedRouters[sender], \"Invalid router\");\n}\n```\n\n## Token Handling Hazards\n\nNot all tokens behave like standard ERC-20s:\n\n| Token Type          | Hazard                               | Mitigation                          |\n| ------------------- | ------------------------------------ | ----------------------------------- |\n| **Fee-on-transfer** | Received amount \u003C sent amount        | Measure actual balance changes      |\n| **Rebasing**        | Balance changes without transfers    | Avoid storing raw balances          |\n| **ERC-777**         | Transfer callbacks enable reentrancy | Use reentrancy guards               |\n| **Pausable**        | Transfers can be blocked             | Handle transfer failures gracefully |\n| **Blocklist**       | Specific addresses blocked           | Test with production addresses      |\n| **Low decimals**    | Precision loss in calculations       | Use appropriate scaling             |\n\n### Safe Balance Check Pattern\n\n```solidity\nfunction safeTransferIn(\n    IERC20 token,\n    address from,\n    uint256 amount\n) internal returns (uint256 received) {\n    uint256 balanceBefore = token.balanceOf(address(this));\n    token.safeTransferFrom(from, address(this), amount);\n    received = token.balanceOf(address(this)) - balanceBefore;\n}\n```\n\n## Base Hook Template\n\nStart with all permissions disabled. Enable only what you need:\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {BaseHook} from \"v4-periphery\u002Fsrc\u002Fbase\u002Fhooks\u002FBaseHook.sol\";\nimport {Hooks} from \"v4-core\u002Fsrc\u002Flibraries\u002FHooks.sol\";\nimport {IPoolManager} from \"v4-core\u002Fsrc\u002Finterfaces\u002FIPoolManager.sol\";\nimport {PoolKey} from \"v4-core\u002Fsrc\u002Ftypes\u002FPoolKey.sol\";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from \"v4-core\u002Fsrc\u002Ftypes\u002FBeforeSwapDelta.sol\";\n\ncontract SecureHook is BaseHook {\n    constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}\n\n    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {\n        return Hooks.Permissions({\n            beforeInitialize: false,\n            afterInitialize: false,\n            beforeAddLiquidity: false,\n            afterAddLiquidity: false,\n            beforeRemoveLiquidity: false,\n            afterRemoveLiquidity: false,\n            beforeSwap: false,           \u002F\u002F Enable only if needed\n            afterSwap: false,            \u002F\u002F Enable only if needed\n            beforeDonate: false,\n            afterDonate: false,\n            beforeSwapReturnDelta: false,      \u002F\u002F DANGER: NoOp attack vector\n            afterSwapReturnDelta: false,       \u002F\u002F DANGER: Can extract value\n            afterAddLiquidityReturnDelta: false,\n            afterRemoveLiquidityReturnDelta: false\n        });\n    }\n\n    \u002F\u002F Implement only the callbacks you enabled above\n}\n```\n\nSee [references\u002Fbase-hook-template.md](references\u002Fbase-hook-template.md) for a complete implementation template.\n\n## Security Checklist\n\nBefore deploying any hook:\n\n| #   | Check                                                 | Status |\n| --- | ----------------------------------------------------- | ------ |\n| 1   | All hook callbacks verify `msg.sender == poolManager` | [ ]    |\n| 2   | Router allowlisting implemented if needed             | [ ]    |\n| 3   | No unbounded loops that can cause OOG                 | [ ]    |\n| 4   | Reentrancy guards on external calls                   | [ ]    |\n| 5   | Delta accounting sums to zero                         | [ ]    |\n| 6   | Fee-on-transfer tokens handled                        | [ ]    |\n| 7   | No hardcoded addresses                                | [ ]    |\n| 8   | Slippage parameters respected                         | [ ]    |\n| 9   | No sensitive data stored on-chain                     | [ ]    |\n| 10  | Upgrade mechanisms secured (if applicable)            | [ ]    |\n| 11  | `beforeSwapReturnDelta` justified if enabled          | [ ]    |\n| 12  | Fuzz testing completed                                | [ ]    |\n| 13  | Invariant testing completed                           | [ ]    |\n\n## Gas Budget Guidelines\n\nHook callbacks execute inside the PoolManager's transaction context. Excessive gas consumption can make swaps revert or become economically unviable.\n\n### Gas Budgets by Callback\n\n| Callback                      | Target Budget | Hard Ceiling | Notes                         |\n| ----------------------------- | ------------- | ------------ | ----------------------------- |\n| `beforeSwap`                  | \u003C 50,000 gas  | 150,000 gas  | Runs on every swap; keep lean |\n| `afterSwap`                   | \u003C 30,000 gas  | 100,000 gas  | Analytics\u002Ftracking only       |\n| `beforeAddLiquidity`          | \u003C 50,000 gas  | 200,000 gas  | May include access control    |\n| `afterAddLiquidity`           | \u003C 30,000 gas  | 100,000 gas  | Reward tracking               |\n| `beforeRemoveLiquidity`       | \u003C 50,000 gas  | 200,000 gas  | Lock validation               |\n| `afterRemoveLiquidity`        | \u003C 30,000 gas  | 100,000 gas  | Tracking\u002Faccounting           |\n| Callbacks with external calls | \u003C 100,000 gas | 300,000 gas  | External DEX routing, oracles |\n\n### Common Gas Pitfalls\n\n1. **Unbounded loops**: Iterating over dynamic arrays (e.g., all active positions) can exceed block gas limits. Cap array sizes or use pagination.\n2. **SSTORE in hot paths**: Each new storage slot costs ~20,000 gas. Prefer transient storage (`tstore`\u002F`tload`) for data that doesn't persist beyond the transaction. Requires Solidity >= 0.8.24 with EVM target set to `cancun` or later.\n3. **External calls**: Each cross-contract call adds ~2,600 gas base cost plus the callee's execution. Batch calls where possible.\n4. **String operations**: Avoid `string` manipulation in callbacks; use `bytes32` for identifiers.\n5. **Redundant reads**: Cache `poolManager` calls — repeated `getSlot0()` or `getLiquidity()` reads cost gas each time.\n\n### Measuring Gas\n\n```bash\n# Profile a specific hook callback with Foundry\nforge test --match-test test_beforeSwapGas --gas-report\n\n# Snapshot gas usage across all tests\nforge snapshot --match-contract MyHookTest\n```\n\n---\n\n## Risk Scoring System\n\nCalculate your hook's risk score (0-33):\n\n| Category              | Points | Criteria                                 |\n| --------------------- | ------ | ---------------------------------------- |\n| **Permissions**       | 0-14   | Sum of enabled permission risk levels    |\n| **External Calls**    | 0-5    | Number and type of external interactions |\n| **State Complexity**  | 0-5    | Amount of mutable state                  |\n| **Upgrade Mechanism** | 0-5    | Proxy, admin functions, etc.             |\n| **Token Handling**    | 0-4    | Non-standard token support               |\n\n### Audit Tier Recommendations\n\n| Score | Risk Level | Recommendation                 |\n| ----- | ---------- | ------------------------------ |\n| 0-5   | Low        | Self-audit + peer review       |\n| 6-12  | Medium     | Professional audit recommended |\n| 13-20 | High       | Professional audit required    |\n| 21-33 | Critical   | Multiple audits required       |\n\n## Absolute Prohibitions\n\n**Never do these things in a hook:**\n\n1. **Never trust `msg.sender` for user identity** - It's always PoolManager\n2. **Never enable `beforeSwapReturnDelta` without understanding NoOp attacks**\n3. **Never store passwords, keys, or PII on-chain**\n4. **Never use `transfer()` for ETH** - Use `call{value:}(\"\")`\n5. **Never assume token decimals** - Always query the token\n6. **Never use `block.timestamp` for randomness**\n7. **Never hardcode gas limits in calls**\n8. **Never ignore return values from external calls**\n9. **Never use `tx.origin` for authorization** - It's a phishing vector; malicious contracts can relay calls with the original user's `tx.origin`\n\n## Pre-Deployment Audit Checklist\n\n| #   | Item                                      | Required For             |\n| --- | ----------------------------------------- | ------------------------ |\n| 1   | Code review by security-focused developer | All hooks                |\n| 2   | Unit tests for all callbacks              | All hooks                |\n| 3   | Fuzz testing with Foundry                 | All hooks                |\n| 4   | Invariant testing                         | Hooks with delta returns |\n| 5   | Fork testing on mainnet                   | All hooks                |\n| 6   | Gas profiling                             | All hooks                |\n| 7   | Formal verification                       | Critical hooks           |\n| 8   | Slither\u002FMythril analysis                  | All hooks                |\n| 9   | External audit                            | Medium+ risk hooks       |\n| 10  | Bug bounty program                        | High+ risk hooks         |\n| 11  | Monitoring\u002Falerting setup                 | All production hooks     |\n\nSee [references\u002Faudit-checklist.md](references\u002Faudit-checklist.md) for detailed audit requirements.\n\n## Production Hook References\n\nLearn from audited, production hooks:\n\n| Project        | Description           | Notable Security Features     |\n| -------------- | --------------------- | ----------------------------- |\n| **Flaunch**    | Token launch platform | Multi-sig admin, timelocks    |\n| **EulerSwap**  | Lending integration   | Isolated risk per market      |\n| **Zaha TWAMM** | Time-weighted AMM     | Gradual execution reduces MEV |\n| **Bunni**      | LP management         | Concentrated liquidity guards |\n\n## External Resources\n\n### Official Documentation\n\n- [v4-core Repository](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fv4-core)\n- [v4-periphery Repository](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fv4-periphery)\n- [Uniswap v4 Docs](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Foverview)\n- [Hook Permissions Guide](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Fconcepts\u002Fhooks)\n\n### Security Resources\n\n- [Trail of Bits Audits](https:\u002F\u002Fgithub.com\u002Ftrailofbits\u002Fpublications)\n- [Certora v4 Analysis](https:\u002F\u002Fwww.certora.com\u002F)\n- [ABDK Consulting](https:\u002F\u002Fabdk.consulting\u002F)\n\n### Community\n\n- [v4-hooks-skill by @igoryuzo](https:\u002F\u002Fgithub.com\u002Figoryuzo\u002FuniswapV4-hooks-skill) - Community skill that inspired this guide\n- [v4hooks.dev](https:\u002F\u002Fwww.v4hooks.dev) - Community hook resources\n\n---\n\n## Additional References\n\n- [Base Hook Template](references\u002Fbase-hook-template.md) - Complete implementation starter\n- [Vulnerabilities Catalog](references\u002Fvulnerabilities-catalog.md) - Common patterns and mitigations\n- [Audit Checklist](references\u002Faudit-checklist.md) - Detailed pre-deployment checklist\n","# v4 Hook Security Foundations\n\nSecurity-first guide for building Uniswap v4 hooks. Hook vulnerabilities can drain user funds—understand these concepts before writing any hook code.\n\n## Threat Model\n\nBefore writing code, understand the v4 security context:\n\n| Threat Area             | Description                                                | Mitigation                                     |\n| ----------------------- | ---------------------------------------------------------- | ---------------------------------------------- |\n| **Caller Verification** | Only `PoolManager` should invoke hook functions            | Verify `msg.sender == address(poolManager)`    |\n| **Sender Identity**     | `msg.sender` always equals PoolManager, never the end user | Use `sender` parameter for user identity       |\n| **Router Context**      | The `sender` parameter identifies the router, not the user | Implement router allowlisting                  |\n| **State Exposure**      | Hook state is readable during mid-transaction execution    | Avoid storing sensitive data on-chain          |\n| **Reentrancy Surface**  | External calls from hooks can enable reentrancy            | Use reentrancy guards; minimize external calls |\n\n## Permission Flags Risk Matrix\n\nAll 14 hook permissions with associated risk levels:\n\n| Permission Flag                   | Risk Level | Description                 | Security Notes                |\n| --------------------------------- | ---------- | --------------------------- | ----------------------------- |\n| `beforeInitialize`                | LOW        | Called before pool creation | Validate pool parameters      |\n| `afterInitialize`                 | LOW        | Called after pool creation  | Safe for state initialization |\n| `beforeAddLiquidity`              | MEDIUM     | Before LP deposits          | Can block legitimate LPs      |\n| `afterAddLiquidity`               | LOW        | After LP deposits           | Safe for tracking\u002Frewards     |\n| `beforeRemoveLiquidity`           | HIGH       | Before LP withdrawals       | Can trap user funds           |\n| `afterRemoveLiquidity`            | LOW        | After LP withdrawals        | Safe for tracking             |\n| `beforeSwap`                      | HIGH       | Before swap execution       | Can manipulate prices         |\n| `afterSwap`                       | MEDIUM     | After swap execution        | Can observe final state       |\n| `beforeDonate`                    | LOW        | Before donations            | Access control only           |\n| `afterDonate`                     | LOW        | After donations             | Safe for tracking             |\n| `beforeSwapReturnDelta`           | CRITICAL   | Returns custom swap amounts | **NoOp attack vector**        |\n| `afterSwapReturnDelta`            | HIGH       | Modifies post-swap amounts  | Can extract value             |\n| `afterAddLiquidityReturnDelta`    | HIGH       | Modifies LP token amounts   | Can shortchange LPs           |\n| `afterRemoveLiquidityReturnDelta` | HIGH       | Modifies withdrawal amounts | Can steal funds               |\n\n### Risk Thresholds\n\n- **LOW**: Unlikely to cause fund loss\n- **MEDIUM**: Requires careful implementation\n- **HIGH**: Can cause fund loss if misimplemented\n- **CRITICAL**: Can enable complete fund theft\n\n## CRITICAL: NoOp Rug Pull Attack\n\nThe `BEFORE_SWAP_RETURNS_DELTA` permission (bit 10) is the most dangerous hook permission. A malicious hook can:\n\n1. Return a delta claiming it handled the entire swap\n2. PoolManager accepts this and settles the trade\n3. Hook keeps all input tokens without providing output\n4. User loses entire swap amount\n\n### Attack Pattern\n\n```solidity\n\u002F\u002F MALICIOUS - DO NOT USE\nfunction beforeSwap(\n    address,\n    PoolKey calldata,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata\n) external override returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Claim to handle the swap but steal tokens\n    int128 amountSpecified = int128(params.amountSpecified);\n    BeforeSwapDelta delta = toBeforeSwapDelta(amountSpecified, 0);\n    return (BaseHook.beforeSwap.selector, delta, 0);\n}\n```\n\n### Detection\n\nBefore interacting with ANY hook that has `beforeSwapReturnDelta: true`:\n\n1. **Audit the hook code** - Verify legitimate use case\n2. **Check ownership** - Is it upgradeable? By whom?\n3. **Verify track record** - Has it been audited by reputable firms?\n4. **Start small** - Test with minimal amounts first\n\n### Legitimate Uses\n\nNoOp patterns are valid for:\n\n- Just-in-time liquidity (JIT)\n- Custom AMM curves\n- Intent-based trading systems\n- RFQ\u002FPMM integrations\n\nBut each requires careful implementation and audit.\n\n## Delta Accounting Fundamentals\n\nv4 uses a credit\u002Fdebit system through the PoolManager:\n\n### Core Invariant\n\n```text\nFor every transaction: sum(deltas) == 0\n```\n\nThe PoolManager tracks what each address owes or is owed. At transaction end, all debts must be settled.\n\n### Key Functions\n\n| Function                     | Purpose                             | Direction              |\n| ---------------------------- | ----------------------------------- | ---------------------- |\n| `take(currency, to, amount)` | Withdraw tokens from PoolManager    | You receive tokens     |\n| `settle(currency)`           | Pay tokens to PoolManager           | You send tokens        |\n| `sync(currency)`             | Update PoolManager balance tracking | Preparation for settle |\n\n### Settlement Pattern\n\n```solidity\n\u002F\u002F Correct pattern: sync before settle\npoolManager.sync(currency);\ncurrency.transfer(address(poolManager), amount);\npoolManager.settle(currency);\n```\n\n### Common Mistakes\n\n1. **Forgetting sync**: Settlement fails without sync\n2. **Wrong order**: Must sync → transfer → settle\n3. **Partial settlement**: Leaves transaction in invalid state\n4. **Double settlement**: Causes accounting errors\n\n## Access Control Patterns\n\n### PoolManager Verification\n\nEvery hook callback MUST verify the caller:\n\n```solidity\nmodifier onlyPoolManager() {\n    require(msg.sender == address(poolManager), \"Not PoolManager\");\n    _;\n}\n\nfunction beforeSwap(\n    address sender,\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Safe to proceed\n}\n```\n\n### Why This Matters\n\nWithout this check:\n\n- Anyone can call hook functions directly\n- Attackers can manipulate hook state\n- Funds can be drained through fake callbacks\n\n## Router Verification Patterns\n\nThe `sender` parameter is the router, not the end user. For hooks that need user identity:\n\n### Allowlisting Pattern\n\n```solidity\nmapping(address => bool) public allowedRouters;\n\nfunction beforeSwap(\n    address sender,  \u002F\u002F This is the router\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    require(allowedRouters[sender], \"Router not allowed\");\n    \u002F\u002F Proceed with swap\n}\n```\n\n### User Identity via hookData\n\n```solidity\nfunction beforeSwap(\n    address sender,\n    PoolKey calldata key,\n    IPoolManager.SwapParams calldata params,\n    bytes calldata hookData\n) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {\n    \u002F\u002F Decode user address from hookData (router must include it)\n    address user = abi.decode(hookData, (address));\n    \u002F\u002F CAUTION: Router must be trusted to provide accurate user\n}\n```\n\n### msg.sender Trap\n\n```solidity\n\u002F\u002F WRONG - msg.sender is always PoolManager in hooks\nfunction beforeSwap(...) external {\n    require(msg.sender == someUser); \u002F\u002F Always fails or wrong\n}\n\n\u002F\u002F CORRECT - Use sender parameter\nfunction beforeSwap(address sender, ...) external {\n    require(allowedRouters[sender], \"Invalid router\");\n}\n```\n\n## Token Handling Hazards\n\nNot all tokens behave like standard ERC-20s:\n\n| Token Type          | Hazard                               | Mitigation                          |\n| ------------------- | ------------------------------------ | ----------------------------------- |\n| **Fee-on-transfer** | Received amount \u003C sent amount        | Measure actual balance changes      |\n| **Rebasing**        | Balance changes without transfers    | Avoid storing raw balances          |\n| **ERC-777**         | Transfer callbacks enable reentrancy | Use reentrancy guards               |\n| **Pausable**        | Transfers can be blocked             | Handle transfer failures gracefully |\n| **Blocklist**       | Specific addresses blocked           | Test with production addresses      |\n| **Low decimals**    | Precision loss in calculations       | Use appropriate scaling             |\n\n### Safe Balance Check Pattern\n\n```solidity\nfunction safeTransferIn(\n    IERC20 token,\n    address from,\n    uint256 amount\n) internal returns (uint256 received) {\n    uint256 balanceBefore = token.balanceOf(address(this));\n    token.safeTransferFrom(from, address(this), amount);\n    received = token.balanceOf(address(this)) - balanceBefore;\n}\n```\n\n## Base Hook Template\n\nStart with all permissions disabled. Enable only what you need:\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {BaseHook} from \"v4-periphery\u002Fsrc\u002Fbase\u002Fhooks\u002FBaseHook.sol\";\nimport {Hooks} from \"v4-core\u002Fsrc\u002Flibraries\u002FHooks.sol\";\nimport {IPoolManager} from \"v4-core\u002Fsrc\u002Finterfaces\u002FIPoolManager.sol\";\nimport {PoolKey} from \"v4-core\u002Fsrc\u002Ftypes\u002FPoolKey.sol\";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from \"v4-core\u002Fsrc\u002Ftypes\u002FBeforeSwapDelta.sol\";\n\ncontract SecureHook is BaseHook {\n    constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}\n\n    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {\n        return Hooks.Permissions({\n            beforeInitialize: false,\n            afterInitialize: false,\n            beforeAddLiquidity: false,\n            afterAddLiquidity: false,\n            beforeRemoveLiquidity: false,\n            afterRemoveLiquidity: false,\n            beforeSwap: false,           \u002F\u002F Enable only if needed\n            afterSwap: false,            \u002F\u002F Enable only if needed\n            beforeDonate: false,\n            afterDonate: false,\n            beforeSwapReturnDelta: false,      \u002F\u002F DANGER: NoOp attack vector\n            afterSwapReturnDelta: false,       \u002F\u002F DANGER: Can extract value\n            afterAddLiquidityReturnDelta: false,\n            afterRemoveLiquidityReturnDelta: false\n        });\n    }\n\n    \u002F\u002F Implement only the callbacks you enabled above\n}\n```\n\nSee [references\u002Fbase-hook-template.md](references\u002Fbase-hook-template.md) for a complete implementation template.\n\n## Security Checklist\n\nBefore deploying any hook:\n\n| #   | Check                                                 | Status |\n| --- | ----------------------------------------------------- | ------ |\n| 1   | All hook callbacks verify `msg.sender == poolManager` | [ ]    |\n| 2   | Router allowlisting implemented if needed             | [ ]    |\n| 3   | No unbounded loops that can cause OOG                 | [ ]    |\n| 4   | Reentrancy guards on external calls                   | [ ]    |\n| 5   | Delta accounting sums to zero                         | [ ]    |\n| 6   | Fee-on-transfer tokens handled                        | [ ]    |\n| 7   | No hardcoded addresses                                | [ ]    |\n| 8   | Slippage parameters respected                         | [ ]    |\n| 9   | No sensitive data stored on-chain                     | [ ]    |\n| 10  | Upgrade mechanisms secured (if applicable)            | [ ]    |\n| 11  | `beforeSwapReturnDelta` justified if enabled          | [ ]    |\n| 12  | Fuzz testing completed                                | [ ]    |\n| 13  | Invariant testing completed                           | [ ]    |\n\n## Gas Budget Guidelines\n\nHook callbacks execute inside the PoolManager's transaction context. Excessive gas consumption can make swaps revert or become economically unviable.\n\n### Gas Budgets by Callback\n\n| Callback                      | Target Budget | Hard Ceiling | Notes                         |\n| ----------------------------- | ------------- | ------------ | ----------------------------- |\n| `beforeSwap`                  | \u003C 50,000 gas  | 150,000 gas  | Runs on every swap; keep lean |\n| `afterSwap`                   | \u003C 30,000 gas  | 100,000 gas  | Analytics\u002Ftracking only       |\n| `beforeAddLiquidity`          | \u003C 50,000 gas  | 200,000 gas  | May include access control    |\n| `afterAddLiquidity`           | \u003C 30,000 gas  | 100,000 gas  | Reward tracking               |\n| `beforeRemoveLiquidity`       | \u003C 50,000 gas  | 200,000 gas  | Lock validation               |\n| `afterRemoveLiquidity`        | \u003C 30,000 gas  | 100,000 gas  | Tracking\u002Faccounting           |\n| Callbacks with external calls | \u003C 100,000 gas | 300,000 gas  | External DEX routing, oracles |\n\n### Common Gas Pitfalls\n\n1. **Unbounded loops**: Iterating over dynamic arrays (e.g., all active positions) can exceed block gas limits. Cap array sizes or use pagination.\n2. **SSTORE in hot paths**: Each new storage slot costs ~20,000 gas. Prefer transient storage (`tstore`\u002F`tload`) for data that doesn't persist beyond the transaction. Requires Solidity >= 0.8.24 with EVM target set to `cancun` or later.\n3. **External calls**: Each cross-contract call adds ~2,600 gas base cost plus the callee's execution. Batch calls where possible.\n4. **String operations**: Avoid `string` manipulation in callbacks; use `bytes32` for identifiers.\n5. **Redundant reads**: Cache `poolManager` calls — repeated `getSlot0()` or `getLiquidity()` reads cost gas each time.\n\n### Measuring Gas\n\n```bash\n# Profile a specific hook callback with Foundry\nforge test --match-test test_beforeSwapGas --gas-report\n\n# Snapshot gas usage across all tests\nforge snapshot --match-contract MyHookTest\n```\n\n---\n\n## Risk Scoring System\n\nCalculate your hook's risk score (0-33):\n\n| Category              | Points | Criteria                                 |\n| --------------------- | ------ | ---------------------------------------- |\n| **Permissions**       | 0-14   | Sum of enabled permission risk levels    |\n| **External Calls**    | 0-5    | Number and type of external interactions |\n| **State Complexity**  | 0-5    | Amount of mutable state                  |\n| **Upgrade Mechanism** | 0-5    | Proxy, admin functions, etc.             |\n| **Token Handling**    | 0-4    | Non-standard token support               |\n\n### Audit Tier Recommendations\n\n| Score | Risk Level | Recommendation                 |\n| ----- | ---------- | ------------------------------ |\n| 0-5   | Low        | Self-audit + peer review       |\n| 6-12  | Medium     | Professional audit recommended |\n| 13-20 | High       | Professional audit required    |\n| 21-33 | Critical   | Multiple audits required       |\n\n## Absolute Prohibitions\n\n**Never do these things in a hook:**\n\n1. **Never trust `msg.sender` for user identity** - It's always PoolManager\n2. **Never enable `beforeSwapReturnDelta` without understanding NoOp attacks**\n3. **Never store passwords, keys, or PII on-chain**\n4. **Never use `transfer()` for ETH** - Use `call{value:}(\"\")`\n5. **Never assume token decimals** - Always query the token\n6. **Never use `block.timestamp` for randomness**\n7. **Never hardcode gas limits in calls**\n8. **Never ignore return values from external calls**\n9. **Never use `tx.origin` for authorization** - It's a phishing vector; malicious contracts can relay calls with the original user's `tx.origin`\n\n## Pre-Deployment Audit Checklist\n\n| #   | Item                                      | Required For             |\n| --- | ----------------------------------------- | ------------------------ |\n| 1   | Code review by security-focused developer | All hooks                |\n| 2   | Unit tests for all callbacks              | All hooks                |\n| 3   | Fuzz testing with Foundry                 | All hooks                |\n| 4   | Invariant testing                         | Hooks with delta returns |\n| 5   | Fork testing on mainnet                   | All hooks                |\n| 6   | Gas profiling                             | All hooks                |\n| 7   | Formal verification                       | Critical hooks           |\n| 8   | Slither\u002FMythril analysis                  | All hooks                |\n| 9   | External audit                            | Medium+ risk hooks       |\n| 10  | Bug bounty program                        | High+ risk hooks         |\n| 11  | Monitoring\u002Falerting setup                 | All production hooks     |\n\nSee [references\u002Faudit-checklist.md](references\u002Faudit-checklist.md) for detailed audit requirements.\n\n## Production Hook References\n\nLearn from audited, production hooks:\n\n| Project        | Description           | Notable Security Features     |\n| -------------- | --------------------- | ----------------------------- |\n| **Flaunch**    | Token launch platform | Multi-sig admin, timelocks    |\n| **EulerSwap**  | Lending integration   | Isolated risk per market      |\n| **Zaha TWAMM** | Time-weighted AMM     | Gradual execution reduces MEV |\n| **Bunni**      | LP management         | Concentrated liquidity guards |\n\n## External Resources\n\n### Official Documentation\n\n- [v4-core Repository](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fv4-core)\n- [v4-periphery Repository](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fv4-periphery)\n- [Uniswap v4 Docs](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Foverview)\n- [Hook Permissions Guide](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Fconcepts\u002Fhooks)\n\n### Security Resources\n\n- [Trail of Bits Audits](https:\u002F\u002Fgithub.com\u002Ftrailofbits\u002Fpublications)\n- [Certora v4 Analysis](https:\u002F\u002Fwww.certora.com\u002F)\n- [ABDK Consulting](https:\u002F\u002Fabdk.consulting\u002F)\n\n### Community\n\n- [v4-hooks-skill by @igoryuzo](https:\u002F\u002Fgithub.com\u002Figoryuzo\u002FuniswapV4-hooks-skill) - Community skill that inspired this guide\n- [v4hooks.dev](https:\u002F\u002Fwww.v4hooks.dev) - Community hook resources\n\n---\n\n## Additional References\n\n- [Base Hook Template](references\u002Fbase-hook-template.md) - Complete implementation starter\n- [Vulnerabilities Catalog](references\u002Fvulnerabilities-catalog.md) - Common patterns and mitigations\n- [Audit Checklist](references\u002Faudit-checklist.md) - Detailed pre-deployment checklist\n",{"name":5,"model":24,"license":15,"metadata":25,"description":7,"allowed-tools":28},"opus",{"author":26,"version":27},"uniswap","1.1.0","Read, Glob, Grep, WebFetch, Task(subagent_type:Explore)","main","be3de0244dc1a57e323d8160787ebb40fb64930e","skills\u002Fv4-security-foundations","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main","https:\u002F\u002Fskills.x402.wtf","https:\u002F\u002Fgithub.com\u002FSolizardking","https:\u002F\u002Fmusebook.trade","Got a mile high and never came down","2026-10-08 23:20:13",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add Solizardking\u002Fskillhub-main --skill v4-security-foundations",{"tool":44,"command":45},"bunx","bunx skills add Solizardking\u002Fskillhub-main --skill v4-security-foundations",{"tool":47,"command":48},"pnpm","pnpm dlx skills add Solizardking\u002Fskillhub-main --skill v4-security-foundations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fv4-security-foundations\u002FSKILL.md",true,[52,58,62],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"references\u002Faudit-checklist.md","REFERENCE","参考文档",8597,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fv4-security-foundations\u002Freferences\u002Faudit-checklist.md",{"path":59,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":60,"sourceHtmlUrl":61},"references\u002Fbase-hook-template.md",12244,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fv4-security-foundations\u002Freferences\u002Fbase-hook-template.md",{"path":63,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":64,"sourceHtmlUrl":65},"references\u002Fvulnerabilities-catalog.md",10828,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fv4-security-foundations\u002Freferences\u002Fvulnerabilities-catalog.md",[67,74,81,88,95,103],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M78E0TGCAMNPS207BA3G07S7","zkrouter","Self-hosted OpenAI-compatible LLM router — smart tier-based routing, ZK-stamped routing decisions, mode overrides, free OpenRouter at install via the Birth bot. Save 60-80% on inference costs by routing to the cheapest capable model across 12+ OpenRouter models.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzkrouter\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M78E0R1Z8BDT6EDTHY17MTNB","zk","For custom ZK Solana programs and privacy-preserving applications to prevent double spending. Guide to integrate rent-free nullifier PDAs for double-spend prevention.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M78E0P3ZTZ1YWF8MD5MM23QE","zk-omni-messaging","Zero-knowledge omnichain messaging between Robinhood Chain and Solana using CheshireZkOmniMessenger (msgType 4) with nullifier anti-replay and the zk-omni-relayer service.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk-omni-messaging\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M78E0JXZ2PNB1896VXAGDBWD","zerion-wallet-data","Use when the user asks to check a wallet's portfolio, token balances, DeFi positions, PnL, transaction history, or NFTs. Provides interpreted on-chain data across 40+ EVM chains and Solana via x402 pay-per-request or API key — no raw RPC decoding needed.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzerion-wallet-data\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":99,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M78E0G14FH9GRRTQYMKD5E59","youtube-clipper","YouTube 视频智能剪辑工具。下载视频和字幕，AI 分析生成精细章节（几分钟级别）， 用户选择片段后自动剪辑、翻译字幕为中英双语、烧录字幕到视频，并生成总结文案。 使用场景：当用户需要剪辑 YouTube 视频、生成短视频片段、制作双语字幕版本时。 关键词：视频剪辑、YouTube、字幕翻译、双语字幕、视频下载、clip video","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M78E0C2ZYA99CFFDNB7ZMK5S","yield-optimization","Multi-chain yield optimization via yield.xyz (StakeKit). Discover 2,988+ yield opportunities across 75+ blockchains, build deposit\u002Fwithdrawal transactions with shell scripts, and sign them with a MoonPay wallet. Use when the user wants to earn yield, find the best lending or staking rate, enter\u002Fexit a position, or check portfolio balances.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyield-optimization\u002FSKILL.md",[],[]]