Token导航 LogoToken导航TokenDH.com
前端设计只读github未标认证来源可访问许可证需确认审计提醒

v4-security-foundationsv4 安全基础

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

11,640

周安装

462

GitHub Stars

203

下载量

4,080
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:v4-security-foundations(v4 安全基础)
来源仓库:https://github.com/uniswap/uniswap-ai
仓库路径:skills/v4-security-foundations
安装命令:
npx skills add https://github.com/uniswap/uniswap-ai --skill v4-security-foundations
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/uniswap/uniswap-ai --skill v4-security-foundations

简介

用于辅助安全审计和权限检查。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

  • 适合梳理敏感配置和分析鉴权逻辑。
  • 使用时不能把工具输出直接当最终结论。
  • 涉及密钥或生产系统时应确认最小权限和操作边界。
  • v4-security-foundations 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

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 AreaDescriptionMitigation
Caller VerificationOnly PoolManager should invoke hook functionsVerify msg.sender == address(poolManager)
Sender Identitymsg.sender always equals PoolManager, never the end userUse sender parameter for user identity
Router ContextThe sender parameter identifies the router, not the userImplement router allowlisting
State ExposureHook state is readable during mid-transaction executionAvoid storing sensitive data on-chain
Reentrancy SurfaceExternal calls from hooks can enable reentrancyUse reentrancy guards; minimize external calls

Permission Flags Risk Matrix

All 14 hook permissions with associated risk levels:

Permission FlagRisk LevelDescriptionSecurity Notes
beforeInitializeLOWCalled before pool creationValidate pool parameters
afterInitializeLOWCalled after pool creationSafe for state initialization
beforeAddLiquidityMEDIUMBefore LP depositsCan block legitimate LPs
afterAddLiquidityLOWAfter LP depositsSafe for tracking/rewards
beforeRemoveLiquidityHIGHBefore LP withdrawalsCan trap user funds
afterRemoveLiquidityLOWAfter LP withdrawalsSafe for tracking
beforeSwapHIGHBefore swap executionCan manipulate prices
afterSwapMEDIUMAfter swap executionCan observe final state
beforeDonateLOWBefore donationsAccess control only
afterDonateLOWAfter donationsSafe for tracking
beforeSwapReturnDeltaCRITICALReturns custom swap amountsNoOp attack vector
afterSwapReturnDeltaHIGHModifies post-swap amountsCan extract value
afterAddLiquidityReturnDeltaHIGHModifies LP token amountsCan shortchange LPs
afterRemoveLiquidityReturnDeltaHIGHModifies withdrawal amountsCan 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 10) is the most dangerous hook permission. A malicious hook can:

  1. Return a delta claiming it handled the entire swap
  2. PoolManager accepts this and settles the trade
  3. Hook keeps all input tokens without providing output
  4. 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:

  1. Audit the hook code - Verify legitimate use case
  2. Check ownership - Is it upgradeable? By whom?
  3. Verify track record - Has it been audited by reputable firms?
  4. 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

FunctionPurposeDirection
take(currency, to, amount)Withdraw tokens from PoolManagerYou receive tokens
settle(currency)Pay tokens to PoolManagerYou send tokens
sync(currency)Update PoolManager balance trackingPreparation for settle

Settlement Pattern

// Correct pattern: sync before settle
poolManager.sync(currency);
currency.transfer(address(poolManager), amount);
poolManager.settle(currency);

Common Mistakes

  1. Forgetting sync: Settlement fails without sync
  2. Wrong order: Must sync → transfer → settle
  3. Partial settlement: Leaves transaction in invalid state
  4. Double settlement: Causes accounting errors

Access Control Patterns

PoolManager Verification

Every hook callback MUST verify the caller:

modifier onlyPoolManager() {
    require(msg.sender == address(poolManager), "Not PoolManager");
    _;
}

function beforeSwap(
    address sender,
    PoolKey calldata key,
    IPoolManager.SwapParams calldata params,
    bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
    // Safe to proceed
}

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

mapping(address => bool) public allowedRouters;

function beforeSwap(
    address sender,  // This is the router
    PoolKey calldata key,
    IPoolManager.SwapParams calldata params,
    bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
    require(allowedRouters[sender], "Router not allowed");
    // Proceed with swap
}

User Identity via hookData

function beforeSwap(
    address sender,
    PoolKey calldata key,
    IPoolManager.SwapParams calldata params,
    bytes calldata hookData
) external override onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
    // Decode user address from hookData (router must include it)
    address user = abi.decode(hookData, (address));
    // CAUTION: Router must be trusted to provide accurate user
}

msg.sender Trap

// WRONG - msg.sender is always PoolManager in hooks
function beforeSwap(...) external {
    require(msg.sender == someUser); // Always fails or wrong
}

// CORRECT - Use sender parameter
function beforeSwap(address sender, ...) external {
    require(allowedRouters[sender], "Invalid router");
}

Token Handling Hazards

Not all tokens behave like standard ERC-20s:

Token TypeHazardMitigation
Fee-on-transferReceived amount < sent amountMeasure actual balance changes
RebasingBalance changes without transfersAvoid storing raw balances
ERC-777Transfer callbacks enable reentrancyUse reentrancy guards
PausableTransfers can be blockedHandle transfer failures gracefully
BlocklistSpecific addresses blockedTest with production addresses
Low decimalsPrecision loss in calculationsUse appropriate scaling

Safe Balance Check Pattern

function safeTransferIn(
    IERC20 token,
    address from,
    uint256 amount
) internal returns (uint256 received) {
    uint256 balanceBefore = token.balanceOf(address(this));
    token.safeTransferFrom(from, address(this), amount);
    received = token.balanceOf(address(this)) - balanceBefore;
}

Base Hook Template

Start with all permissions disabled. Enable only what you need:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {BaseHook} from "v4-periphery/src/base/hooks/BaseHook.sol";
import {Hooks} from "v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/src/types/BeforeSwapDelta.sol";

contract SecureHook is BaseHook {
    constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}

    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: false,
            afterInitialize: false,
            beforeAddLiquidity: false,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: false,
            afterRemoveLiquidity: false,
            beforeSwap: false,           // Enable only if needed
            afterSwap: false,            // Enable only if needed
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: false,      // DANGER: NoOp attack vector
            afterSwapReturnDelta: false,       // DANGER: Can extract value
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    // Implement only the callbacks you enabled above
}

See references/base-hook-template.md for a complete implementation template.

Security Checklist

Before deploying any hook:

#CheckStatus
1All hook callbacks verify msg.sender == poolManager[]
2Router allowlisting implemented if needed[]
3No unbounded loops that can cause OOG[]
4Reentrancy guards on external calls[]
5Delta accounting sums to zero[]
6Fee-on-transfer tokens handled[]
7No hardcoded addresses[]
8Slippage parameters respected[]
9No sensitive data stored on-chain[]
10Upgrade mechanisms secured (if applicable)[]
11beforeSwapReturnDelta justified if enabled[]
12Fuzz testing completed[]
13Invariant testing completed[]

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

CallbackTarget BudgetHard CeilingNotes
beforeSwap< 50,000 gas150,000 gasRuns on every swap; keep lean
afterSwap< 30,000 gas100,000 gasAnalytics/tracking only
beforeAddLiquidity< 50,000 gas200,000 gasMay include access control
afterAddLiquidity< 30,000 gas100,000 gasReward tracking
beforeRemoveLiquidity< 50,000 gas200,000 gasLock validation
afterRemoveLiquidity< 30,000 gas100,000 gasTracking/accounting
Callbacks with external calls< 100,000 gas300,000 gasExternal DEX routing, oracles

Common Gas Pitfalls

  1. Unbounded loops: Iterating over dynamic arrays (e.g., all active positions) can exceed block gas limits. Cap array sizes or use pagination.
  2. 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 to cancun or later.
  3. External calls: Each cross-contract call adds ~2,600 gas base cost plus the callee's execution. Batch calls where possible.
  4. String operations: Avoid string manipulation in callbacks; use bytes32 for identifiers.
  5. Redundant reads: Cache poolManager calls — repeated getSlot0() or getLiquidity() reads cost gas each time.

Measuring Gas

# Profile a specific hook callback with Foundry
forge test --match-test test_beforeSwapGas --gas-report

# Snapshot gas usage across all tests
forge snapshot --match-contract MyHookTest

Risk Scoring System

Calculate your hook's risk score (0-33):

CategoryPointsCriteria
Permissions0-14Sum of enabled permission risk levels
External Calls0-5Number and type of external interactions
State Complexity0-5Amount of mutable state
Upgrade Mechanism0-5Proxy, admin functions, etc.
Token Handling0-4Non-standard token support

Audit Tier Recommendations

ScoreRisk LevelRecommendation
0-5LowSelf-audit + peer review
6-12MediumProfessional audit recommended
13-20HighProfessional audit required
21-33CriticalMultiple audits required

Absolute Prohibitions

Never do these things in a hook:

  1. Never trust msg.sender for user identity - It's always PoolManager
  2. Never enable beforeSwapReturnDelta without understanding NoOp attacks
  3. Never store passwords, keys, or PII on-chain
  4. Never use transfer() for ETH - Use call{value:}("")
  5. Never assume token decimals - Always query the token
  6. Never use block.timestamp for randomness
  7. Never hardcode gas limits in calls
  8. Never ignore return values from external calls
  9. Never use tx.origin for authorization - It's a phishing vector; malicious contracts can relay calls with the original user's tx.origin

Pre-Deployment Audit Checklist

#ItemRequired For
1Code review by security-focused developerAll hooks
2Unit tests for all callbacksAll hooks
3Fuzz testing with FoundryAll hooks
4Invariant testingHooks with delta returns
5Fork testing on mainnetAll hooks
6Gas profilingAll hooks
7Formal verificationCritical hooks
8Slither/Mythril analysisAll hooks
9External auditMedium+ risk hooks
10Bug bounty programHigh+ risk hooks
11Monitoring/alerting setupAll production hooks

See references/audit-checklist.md for detailed audit requirements.

Production Hook References

Learn from audited, production hooks:

ProjectDescriptionNotable Security Features
FlaunchToken launch platformMulti-sig admin, timelocks
EulerSwapLending integrationIsolated risk per market
Zaha TWAMMTime-weighted AMMGradual execution reduces MEV
BunniLP managementConcentrated liquidity guards

External Resources

Official Documentation

Security Resources

Community


Additional References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.4%
按下载量换算1,444

Claude

29%
按下载量换算1,183

Cursor

16.78%
按下载量换算685

Gemini CLI

9.62%
按下载量换算392

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills