Communitygithub.com

DeFi AMM Sicherheit

Sicherheitscheckliste für Solidity AMM-Verträge, Liquiditätspools und Swap-Flows. Deckt Reentrancy, CEI-Reihenfolge, Spenden- oder Inflationsangriffe, Oracle-Manipulation, Slippage, Admin-Kontrollen und Ganzzahlarithmetik ab. Verwenden Sie diese bei der Überprüfung oder beim Schreiben von Solidity AMM-, Liquiditätspool- oder Swap-Code.

Was ist DeFi AMM Sicherheit?

Dieses Skill dokumentiert kritische Schwachstellenmuster und gehärtete Implementierungen für Solidity AMM-Verträge, LP-Vaults und Swap-Funktionen. Es dient als kombinierte Checkliste und Mustersammlung. Entwickler und Prüfer können jeden Benutzer-Einstiegspunkt gegen die untenstehenden Kategorien prüfen und die gehärteten Beispiele bevorzugen. Das Skill behandelt Reentrancy (mit nonReentrant und CEI-Reihenfolge), Spenden- oder Inflationsangriffe (durch Verfolgung interner Buchhaltung statt rohem balanceOf), Oracle-Manipulation (durch Verwendung von TWAP statt Spotpreisen), Slippage-Schutz (mit amountOutMin und Deadline), sichere Reserve-Mathematik (mit mulDiv), Admin-Kontrollen (mit Ownable2Step) und Notfall-Pause-Funktionen. Es enthält eine detaillierte Sicherheitscheckliste und empfiehlt die Verwendung von Tools wie Slither und Echidna für statische Analyse und Fuzzing vor der Produktion. Das Skill unterstützt Plattformen wie Ethereum, Arbitrum, Polygon und andere EVM-kompatible Chains, die Solidity AMM-Verträge einsetzen.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/defi-amm-security

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht DeFi AMM Sicherheit?

Kritische Schwachstellenmuster und gehärtete Implementierungen für Solidity AMM-Verträge, LP-Vaults und Swap-Funktionen.

Wann zu verwenden

  • Beim Schreiben oder Prüfen eines Solidity AMM- oder Liquiditätspool-Vertrags
  • Bei der Implementierung von Swap-, Einzahlungs-, Auszahlungs-, Mint- oder Burn-Flows, die Token-Bestände halten
  • Beim Überprüfen eines Vertrags, der token.balanceOf(address(this)) in Share- oder Reserve-Mathematik verwendet
  • Beim Hinzufügen von Gebühreneinstellern, Pausierern, Oracle-Updates oder anderen Admin-Funktionen zu einem DeFi-Protokoll

Wie es funktioniert

Verwenden Sie dies als Checkliste-plus-Musterbibliothek. Überprüfen Sie jeden Benutzer-Einstiegspunkt gegen die untenstehenden Kategorien und bevorzugen Sie die gehärteten Beispiele gegenüber handgerollten Varianten.

Ausführungssicherheit

Die Shell-Befehle in diesem Skill sind lokale Prüfbeispiele. Führen Sie sie nur in einem vertrauenswürdigen Checkout oder einer Wegwerf-Sandbox aus und fügen Sie keine nicht vertrauenswürdigen Vertragsnamen, Pfade, RPC-URLs, privaten Schlüssel oder vom Benutzer bereitgestellte Flags in Shell-Befehle ein. Fragen Sie, bevor Sie Tools installieren oder lange Fuzzing-/Static-Analysis-Jobs ausführen, die möglicherweise erhebliche lokale oder kostenpflichtige Ressourcen verbrauchen.

Fügen Sie niemals Geheimnisse, private Schlüssel, Seed-Phrasen, API-Token oder Anmeldeinformationen für das Mainnet in Befehlsbeispiele, Protokolle oder Berichte ein.

Beispiele

Reentrancy: CEI-Reihenfolge erzwingen

Verwundbar:

function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    token.transfer(msg.sender, amount);
    balances[msg.sender] -= amount;
}

Sicher:

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);
}

Schreiben Sie keinen eigenen Guard, wenn eine gehärtete Bibliothek existiert.

Spenden- oder Inflationsangriffe

Die direkte Verwendung von token.balanceOf(address(this)) für die Share-Mathematik ermöglicht es Angreifern, den Nenner zu manipulieren, indem sie Token außerhalb des vorgesehenen Pfades an den Vertrag senden.

// Verwundbar
function deposit(uint256 assets) external returns (uint256 shares) {
    shares = (assets * totalShares) / token.balanceOf(address(this));
}
// Sicher
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;
}

Verfolgen Sie die interne Buchhaltung und messen Sie die tatsächlich erhaltenen Token.

Oracle-Manipulation

Spotpreise sind durch Flash-Darlehen manipulierbar. Bevorzugen Sie 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);

Slippage-Schutz

Jeder Swap-Pfad benötigt vom Aufrufer bereitgestellten Slippage und eine Frist.

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);
}

Sichere Reserve-Mathematik

import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";

uint256 result = FullMath.mulDiv(a, b, c);

Bei großer Reserve-Mathematik vermeiden Sie naive a * b / c, wenn Überlaufrisiko besteht.

Admin-Kontrollen

import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";

contract MyAMM is Ownable2Step {
    function setFee(uint256 fee) external onlyOwner { ... }
    function pause() external onlyOwner { ... }
}

Bevorzugen Sie explizite Annahme für die Eigentümerübertragung und gaten Sie jeden privilegierten Pfad.

Sicherheitscheckliste

  • Reentrancy-exponierte Einstiegspunkte verwenden nonReentrant
  • CEI-Reihenfolge wird eingehalten
  • Share-Mathematik hängt nicht von rohem balanceOf(address(this)) ab
  • ERC-20-Transfers verwenden SafeERC20
  • Einzahlungen messen tatsächlich erhaltene Token
  • Oracle-Lesevorgänge verwenden TWAP oder eine andere manipulationsresistente Quelle
  • Swaps erfordern amountOutMin und deadline
  • Überlauf-empfindliche Reserve-Mathematik verwendet sichere Primitive wie mulDiv
  • Admin-Funktionen sind zugriffsgesteuert
  • Notfall-Pause existiert und ist getestet
  • Statische Analyse und Fuzzing werden vor der Produktion durchgeführt

Prüfwerkzeuge

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.

Verwandte Skills