v4-security-foundations
БесплатноБез исполняемых скриптовНе проверенSecurity-first Uniswap v4 hook development. Use when user mentions "v4 hooks", "hook security", "PoolManager", "beforeSwap", "afterSwap", or asks about V4…
от Uniswap★ 236 звёзд на GitHubОб этом скилле
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:
| Threat Area | Description | Mitigation |
|---|---|---|
| Caller Verification | Only PoolManager should invoke hook functions |
Verify msg.sender == address(poolManager) |
| Sender Identity | msg.sender always equals PoolManager, never the end user |
Use sender parameter for user identity |
| Router Context | The sender parameter identifies the router, not the user |
Implement router allowlisting |
| State Exposure | Hook state is readable during mid-transaction execution | Avoid storing sensitive data on-chain |
| Reentrancy Surface | External calls from hooks can enable reentrancy | Use reentrancy guards; minimize external calls |
Permission Flags Risk Matrix
All 14 hook permissions with associated risk levels:
| Permission Flag | Risk Level | Description | Security Notes |
|---|---|---|---|
beforeInitialize |
LOW | Called before pool creation | Validate pool parameters |
afterInitialize |
LOW | Called after pool creation | Safe for state initialization |
beforeAddLiquidity |
MEDIUM | Before LP deposits | Can block legitimate LPs |
afterAddLiquidity |
LOW | After LP deposits | Safe for tracking/rewards |
beforeRemoveLiquidity |
HIGH | Before LP withdrawals | Can trap user funds |
afterRemoveLiquidity |
LOW | After LP withdrawals | Safe for tracking |
beforeSwap |
HIGH | Before swap execution | Can manipulate prices |
afterSwap |
MEDIUM | After swap execution | Can observe final state |
beforeDonate |
LOW | Before donations | Access control only |
afterDonate |
LOW | After donations | Safe for tracking |
beforeSwapReturnDelta |
CRITICAL | Returns custom swap amounts | NoOp attack vector |
afterSwapReturnDelta |
HIGH | Modifies post-swap amounts | Can extract value |
afterAddLiquidityReturnDelta |
HIGH | Modifies LP token amounts | Can shortchange LPs |
afterRemoveLiquidityReturnDelta |
HIGH | Modifies withdrawal amounts | Can steal funds |
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 3) 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
// MALICIOUS - DO NOT USE
function beforeSwap(
address,
PoolKey calldata,
IPoolManager.SwapParams calldata params,
bytes calldata
) external override returns (bytes4, BeforeSwapDelta, uint24) {
// Claim to handle the swap but steal tokens
int128 amountSpecified = int128(params.amountSpecified);
BeforeSwapDelta delta = toBeforeSwapDelta(amountSpecified, 0);
return (BaseHook.beforeSwap.selector, delta, 0);
}
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
For every transaction: sum(deltas) == 0
The PoolManager tracks what each address owes or is owed. At transaction end, all debts must be settled.
Key Functions
| Function | Pu
Установить v4-security-foundations в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGlobGrepWebFetchTask(subagent_type:Explore)Вложенные файлы
FAQ
Что делает скилл v4-security-foundations?
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.
Как установить скилл v4-security-foundations?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл v4-security-foundations запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic