Communitygithub.com

DeFi AMM セキュリティ

Solidity AMMコントラクト、流動性プール、スワップフローのためのセキュリティチェックリストです。リエントランシー、CEI順序、ドネーション/インフレーション攻撃、オラクル操作、スリッページ、管理者コントロール、整数演算などに対応します。AMM、流動性プール、スワップコードの監査や実装時に使用します。

DeFi AMM セキュリティ とは?

このスキルは、Solidityで書かれたAMM(自動マーケットメーカー)コントラクト、流動性プール(LP)ボールト、スワップ機能のための包括的なセキュリティチュートリアル兼チェックリストです。開発者や監査担当者が、リエントランシー攻撃、ドネーション/インフレーション操作、オラクル操作、整数オーバーフローなどの一般的な脆弱性パターンを理解し、それらに対処するための堅牢な実装例を学べるように設計されています。すべての章で「脆弱な実装」と「安全な実装」を対比し、OpenZeppelinやUniswap v3コアなど実績のあるライブラリを活用したベストプラクティスを示します。さらに、実際の監査で使用するチェックリストや静的解析ツール(Slither、Echidna、Foundry fuzzテスト)の実行例も含まれているため、実務での品質保証に直接役立ちます。Claude Code、Cursor、Codexなど、任意のAIエージェントプラットフォームで動作するように設計されており、Markdown形式で提供されるため、プロンプトやナレッジベースに組み込みやすいのが特徴です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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/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.

関連スキル