Communitygithub.com

DeFi AMM 安全性

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

DeFi AMM 安全性 是什麼?

DeFi AMM Security 是一套專為 Solidity 自動做市商 (AMM) 合約、流動性池金庫與交換函數設計的安全檢查清單與實作範例。此技能協助開發者與審計員識別並緩解如重入攻擊、捐贈/通貨膨脹攻擊、預言機操縱、滑點不足、整數溢位以及不安全的管理員控制等常見漏洞。其內容涵蓋 OpenZeppelin 的 ReentrancyGuard、SafeERC20 與 Ownable2Step 等經過實戰考驗的函式庫,並提供使用內部帳務而非原始 balanceOf() 的安全存款邏輯、滑點保護與 deadline 參數、以及基於 TWAP 的價格擷取模式。該技能支援所有 Solidity 相容的平台,並建議在部署前搭配 Slither 與 Echidna 等靜態分析與模糊測試工具。其結構為可操作的檢查清單與程式碼範例,適合在審計或開發工作流程中使用。

相容平台~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.

相關技能