Communitygithub.com

DeFi AMM 安全审计清单

针对 Solidity AMM 合约、流动性池和交换流程的安全检查清单。涵盖重入攻击、CEI 顺序、捐赠或通胀攻击、预言机操纵、滑点、管理员控制和整数运算。适用于审计或编写 Solidity AMM、流动性池或交换代码。

DeFi AMM 安全审计清单 是什么?

这是一份全面的安全审计清单和模式库,专门用于 Solidity 的自动化做市商 (AMM) 合约、流动性池和交换功能。该技能旨在帮助开发者和审计员识别并防范 DeFi 协议中的关键漏洞,例如重入攻击、捐赠/通胀攻击、预言机操纵和滑点滥用。它支持所有基于智能合约的 DeFi 平台,包括使用 OpenZeppelin 和 Uniswap 等常用库的项目。技能以检查清单加模式库的形式工作,针对每个用户入口点进行审查,并优先使用经过验证的安全实现模式(如 ReentrancyGuard、TWAP 预言机和 SafeERC20),而不是手写的简化版本。同时,它还强调了安全开发实践,比如使用 CEI 顺序、跟踪内部会计、要求滑点保护和截止日期,以及实施拥有两步转移权限的管理员控制。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/defi-amm-security

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

DeFi AMM 安全审计清单 是做什么的?

针对 Solidity AMM 合约、LP 金库和交换函数的关键漏洞模式及强化实现。

使用场景

  • 编写或审计 Solidity AMM 或流动性池合约
  • 实现持有代币余额的 swap、deposit、withdraw、mint 或 burn 流程
  • 审查任何在份额或储备计算中使用 token.balanceOf(address(this)) 的合约
  • 为 DeFi 协议添加费用设置者、暂停者、预言机更新或其他管理员功能

工作原理

将其用作检查清单加模式库。根据以下分类审查每个用户入口点,并优先使用强化示例,而不是手写的变体。

执行安全

本技能中的 shell 命令是本地审计示例。仅在受信任的检出目录或一次性沙箱中运行它们,不要将不受信任的合约名称、路径、RPC URL、私钥或用户提供的标志拼接到 shell 命令中。在安装工具或运行可能消耗大量本地或付费资源的长时间模糊测试/静态分析任务之前,请先询问用户。

切勿在命令示例、日志或报告中包含机密信息、私钥、助记词、API 令牌或主网签名凭证。

示例

重入攻击:强制 CEI 顺序

有漏洞的写法:

function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    token.transfer(msg.sender, amount);
    balances[msg.sender] -= amount;
}

安全的写法:

import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

using SafeERC20 for IERC20;

function withdraw(uint256 amount) external nonReentrant {
    require(balances[msg.sender] >= amount, "余额不足");
    balances[msg.sender] -= amount;
    token.safeTransfer(msg.sender, amount);
}

当存在经过验证的库时,不要自己编写守卫。

捐赠或通胀攻击

直接使用 token.balanceOf(address(this)) 进行份额计算会让攻击者通过向合约发送代币(绕过预期路径)来操纵分母。

// 有漏洞的写法
function deposit(uint256 assets) external returns (uint256 shares) {
    shares = (assets * totalShares) / token.balanceOf(address(this));
}
// 安全的写法
uint256 private _totalAssets;

function deposit(uint256 assets) external nonReentrant returns (uint256 shares) {
    uint256 balBefore = token.balanceOf(address(this));
    token.safeTransferFrom(msg.sender, address(this), assets);
    uint256 received = token.balanceOf(address(this)) - balBefore;

    shares = totalShares == 0 ? received : (received * totalShares) / _totalAssets;
    _totalAssets += received;
    totalShares += shares;
}

跟踪内部会计,并衡量实际收到的代币数量。

预言机操纵

现货价格容易受到闪电贷操纵。建议使用 TWAP。

uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = 1800;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos);
int24 twapTick = int24(
    (tickCumulatives[1] - tickCumulatives[0]) / int56(uint56(30 minutes))
);
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(twapTick);

滑点保护

每个交换路径都需要调用者提供的滑点参数和截止时间。

function swap(
    uint256 amountIn,
    uint256 amountOutMin,
    uint256 deadline
) external returns (uint256 amountOut) {
    require(block.timestamp <= deadline, "已过期");
    amountOut = _calculateOut(amountIn);
    require(amountOut >= amountOutMin, "滑点超出限制");
    _executeSwap(amountIn, amountOut);
}

安全的储备数学运算

import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";

uint256 result = FullMath.mulDiv(a, b, c);

对于大型储备数学运算,当存在溢出风险时,避免使用简单的 a * b / c。

管理员控制

import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";

contract MyAMM is Ownable2Step {
    function setFee(uint256 fee) external onlyOwner { ... }
    function pause() external onlyOwner { ... }
}

对于所有权转移,建议使用显式接受,并对每个特权路径设置门禁。

安全检查清单

  • 暴露重入风险的入口点使用 nonReentrant
  • 尊重 CEI 顺序
  • 份额计算不依赖于原始的 balanceOf(address(this))
  • ERC-20 转账使用 SafeERC20
  • 存款操作衡量实际收到的代币数量
  • 预言机读取使用 TWAP 或其他抗操纵源
  • 交换要求提供 amountOutMin 和 deadline
  • 对溢出敏感的储备数学运算使用安全的原语,如 mulDiv
  • 管理员函数受访问控制
  • 存在紧急暂停功能并经过测试
  • 在生产前运行静态分析和模糊测试

审计工具

pip install slither-analyzer
slither . --exclude-dependencies

echidna-test . --contract YourAMM --config echidna.yaml

forge test --fuzz-runs 10000

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能