Communitygithub.com

DeFi AMM 安全性

Solidity AMM 合約、流動性池及交換流程的安全性檢查清單。涵蓋重入攻擊、CEI 順序、捐贈或通貨膨脹攻擊、預言機操縱、滑點、管理員控制及整數運算。適用於審計或撰寫 Solidity AMM、流動性池或交換程式碼時使用。

DeFi AMM 安全性 是什麼?

DeFi AMM 安全性技能提供了一份詳盡的安全性檢查清單和強化實作模式,專門針對 Solidity 撰寫的自動做市商(AMM)合約、流動性資金池(LP Vault)及交換(Swap)函數。此技能的核心目標是協助開發者與審計人員在撰寫或審查 DeFi 協定時,避免常見但嚴重的漏洞,例如重入攻擊、CEI(Checks-Effects-Interactions)順序錯誤、捐贈或通貨膨脹攻擊(透過操縱代幣餘額來影響份額計算)、預言機價格操縱(推薦使用 TWAP)、滑點保護不足、管理員控制缺失以及整數溢位問題。該技能涵蓋了業界認可的最佳實務,例如使用 OpenZeppelin 的 `ReentrancyGuard` 和 `SafeERC20`、採用內部記帳方式追蹤資產而非直接依賴 `balanceOf`、在交換時要求提供 `amountOutMin` 與 `deadline`、使用 `FullMath.mulDiv` 進行安全的數學運算,以及透過 `Ownable2Step` 實現安全的權限管理。它還整合了 `slither` 和 `echidna-test` 等常見審計工具的 CLI 指令,方便進行靜態分析與模糊測試。此技能適用於任何使用 Solidity 開發或審計 AMM、流動性池或相關 DeFi 協定的場景,支援用於 Cursor、Claude Code 等 AI 代理平台,作為互動式安全性參考。

相容平台~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 金庫及交換函數的關鍵漏洞模式與強化實作範例。

使用時機

  • 撰寫或審計 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, "Insufficient");
    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, "Expired");
    amountOut = _calculateOut(amountIn);
    require(amountOut >= amountOutMin, "Slippage exceeded");
    _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/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.

相關技能