Communitygithub.com

DeFi AMM セキュリティ

Solidity AMM コントラクト、流動性プール、スワップフローのためのセキュリティチェックリスト。リエントランシー、CEI順序、ドネーション/インフレーション攻撃、オラクル操作、スリッページ、管理制御、整数計算をカバー。Solidity AMM、流動性プール、スワップコードの監査や作成時に使用。

DeFi AMM セキュリティ とは?

このスキルは、Solidity で実装された AMM(自動マーケットメーカー)コントラクト、LP ボールト、スワップ関数に特化したセキュリティチェックリストおよび堅牢な実装パターンを提供します。リエントランシー攻撃、CEI(Checks-Effects-Interactions)順序違反、ドネーション/インフレーション攻撃、オラクル操作、スリッページ保護、管理制御、整数計算のオーバーフローなど、DeFi プロトコルで頻繁に発生する脆弱性パターンを網羅しています。各パターンに対して、脆弱なコード例と OpenZeppelin や Uniswap v3 コアライブラリなどの実績あるライブラリを活用した安全な実装例を提示します。Claude Code、Cursor、Codex などの AI エージェントや開発者が、AMM や流動性プールのコードを監査・作成する際に、チェックリストとして活用できます。静的解析ツール(Slither)やファジングツール(Echidna、Foundry)の実行コマンドも含まれており、実践的なセキュリティレビューを支援します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

DeFi AMM セキュリティ は何をしますか?

Solidity AMM コントラクト、LP ボールト、スワップ関数における重要な脆弱性パターンと堅牢な実装。

使用する場面

  • Solidity AMM または流動性プールコントラクトの作成または監査
  • トークン残高を保持するスワップ、デポジット、引き出し、ミント、バーンフローの実装
  • シェア計算や準備金計算で token.balanceOf(address(this)) を使用するコントラクトのレビュー
  • DeFi プロトコルへの手数料設定者、一時停止機能、オラクル更新、その他の管理機能の追加

仕組み

このスキルをチェックリスト兼パターンライブラリとして使用します。すべてのユーザーエントリポイントを以下のカテゴリに対して確認し、手作りのバリアントよりも堅牢な例を優先します。

実行上の安全

このスキル内のシェルコマンドはローカル監査の例です。信頼できるチェックアウトまたは使い捨てサンドボックスでのみ実行し、信頼できないコントラクト名、パス、RPC URL、秘密鍵、ユーザー指定のフラグをシェルコマンドに組み込まないでください。ツールのインストールや、ローカルリソースや有料リソースを大量に消費する可能性のある長時間のファジング/静的解析ジョブの実行前に確認を求めてください。

コマンド例、ログ、レポートに秘密鍵、シードフレーズ、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/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.

関連スキル