Communitygithub.com

Seguridad en DeFi AMM

Lista de verificación de seguridad para contratos AMM en Solidity, pools de liquidez y flujos de intercambio. Cubre reentrancy, orden CEI, ataques de donación o inflación, manipulación de oráculos, slippage, controles de administración y matemáticas enteras. Útil al auditar o escribir código AMM, pools de liquidez o swaps en Solidity.

¿Qué es Seguridad en DeFi AMM?

Esta habilidad proporciona una lista de verificación de seguridad exhaustiva y ejemplos de implementaciones robustas para contratos AMM en Solidity, vaults de liquidez y funciones de swap. Está diseñada para desarrolladores y auditores que trabajan con protocolos DeFi y necesitan evitar vulnerabilidades críticas como reentrancy, ataques de donación/inflación basados en saldos de tokens, manipulación de oráculos y desbordamientos matemáticos. La guía incluye fragmentos de código comparativos (vulnerable vs. seguro) que demuestran cómo aplicar el orden CEI, usar ReentrancyGuard de OpenZeppelin, SafeERC20, y medidas antimanipulación como TWAP. También cubre controles de acceso con Ownable2Step, protección contra slippage mediante parámetros de cantidad mínima y fecha límite, y el uso de bibliotecas matemáticas seguras como FullMath de Uniswap. La habilidad recomienda herramientas de auditoría como Slither, Echidna y pruebas de fuzzing con Forge, y es aplicable a cualquier contrato que mantenga saldos de tokens, implemente swaps, depósitos o retiros. Es un recurso práctico para integrar seguridad desde el diseño y durante las revisiones de código.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace Seguridad en DeFi AMM?

Patrones críticos de vulnerabilidad e implementaciones robustas para contratos AMM en Solidity, vaults de LP y funciones de swap.

Cuándo usarlo

  • Escribir o auditar un contrato AMM o pool de liquidez en Solidity
  • Implementar flujos de swap, depósito, retiro, mint o burn que manejen saldos de tokens
  • Revisar cualquier contrato que use token.balanceOf(address(this)) en cálculos de participaciones o reservas
  • Agregar configuradores de tarifas, pausadores, actualizaciones de oráculos u otras funciones administrativas a un protocolo DeFi

Cómo funciona

Utilícelo como una biblioteca de patrones más lista de verificación. Revise cada punto de entrada de usuario según las categorías a continuación y prefiera los ejemplos robustos sobre variantes hechas a mano.

Seguridad de ejecución

Los comandos de shell en esta habilidad son ejemplos locales de auditoría. Ejecútelos solo en un checkout de confianza o en un entorno aislado desechable, y no inserte nombres de contratos, rutas, URLs RPC, claves privadas o indicadores suministrados por el usuario no confiables en los comandos de shell. Pregunte antes de instalar herramientas o ejecutar trabajos largos de fuzzing/análisis estático que puedan consumir recursos locales o pagos significativos.

Nunca incluya secretos, claves privadas, frases semilla, tokens API o credenciales de firma de mainnet en ejemplos de comandos, registros o informes.

Ejemplos

Reentrancy: aplicar orden CEI

Vulnerable:

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

Seguro:

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, "Insuficiente");
    balances[msg.sender] -= amount;
    token.safeTransfer(msg.sender, amount);
}

No escriba su propio guardia cuando exista una biblioteca robusta.

Ataques de donación o inflación

Usar token.balanceOf(address(this)) directamente para cálculos de participaciones permite que un atacante manipule el denominador enviando tokens al contrato fuera de la ruta prevista.

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

Realice un seguimiento contable interno y mida los tokens realmente recibidos.

Manipulación de oráculos

Los precios spot son manipulables con préstamos flash. Prefiera 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);

Protección contra slippage

Cada ruta de swap necesita slippage proporcionado por el llamador y una fecha límite.

function swap(
    uint256 amountIn,
    uint256 amountOutMin,
    uint256 deadline
) external returns (uint256 amountOut) {
    require(block.timestamp <= deadline, "Expirado");
    amountOut = _calculateOut(amountIn);
    require(amountOut >= amountOutMin, "Slippage excedido");
    _executeSwap(amountIn, amountOut);
}

Matemáticas de reserva seguras

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

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

Para cálculos grandes de reservas, evite el naive a * b / c cuando exista riesgo de desbordamiento.

Controles administrativos

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

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

Prefiera la aceptación explícita para la transferencia de propiedad y restrinja cada ruta privilegiada.

Lista de verificación de seguridad

  • Los puntos de entrada expuestos a reentrancy usan nonReentrant
  • Se respeta el orden CEI
  • El cálculo de participaciones no depende de balanceOf(address(this)) sin procesar
  • Las transferencias ERC-20 usan SafeERC20
  • Los depósitos miden los tokens realmente recibidos
  • Las lecturas de oráculos usan TWAP u otra fuente resistente a manipulación
  • Los swaps requieren amountOutMin y deadline
  • Los cálculos de reservas sensibles a desbordamiento usan primitivas seguras como mulDiv
  • Las funciones administrativas tienen control de acceso
  • Existe una pausa de emergencia y está probada
  • Se ejecutan análisis estático y fuzzing antes de producción

Herramientas de auditoría

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.

Skills relacionados