Communitygithub.com

DeFi AMM 安全

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

DeFi AMM 安全 是什么?

此技能提供了一份全面的安全清单和加固实现模式,专为Solidity AMM合约、LP金库和兑换函数设计。它系统地涵盖了常见攻击向量的防御措施,包括通过OpenZeppelin的ReentrancyGuard强制执行CEI顺序以防止重入攻击、通过跟踪内部会计指标而非直接依赖token.balanceOf(address(this))来防御捐赠/通胀攻击、使用TWAP而非现货价格来防止预言机操纵、强制实施调用者提供的滑点保护与截止时间、以及使用SafeERC20和FullMath.mulDiv等安全数学原语。该技能适用于Slither、Echidna和Foundry等平台的审计和开发工作流程,直接作为可粘贴的Solidity代码示例及操作检查清单使用,确保生产中部署的合约具备防弹能力。

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

在你喜欢的 AI 中提问

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

文档

DeFi AMM 安全 是做什么的?

针对Solidity AMM合约、LP金库和swap函数的关键漏洞模式与加固实现。

何时使用

  • 编写或审计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);

滑点保护

每个 swap 路径都需要调用者提供滑点和截止时间。

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 或其他抗操纵来源
  • Swap 要求提供 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相关技能