Communitygithub.com

defi-amm-security

솔리디티 AMM(자동화 마켓 메이커) 컨트랙트, 유동성 풀 및 스왑 흐름을 위한 보안 체크리스트입니다. 재진입, CEI 순서, 기부 또는 인플레이션 공격, 오라클 조작, 슬리피지, 관리자 제어 및 정수 연산을 다룹니다. 솔리디티 AMM, 유동성 풀 또는 스왑 코드를 감사하거나 작성할 때 사용하세요.

defi-amm-security란 무엇인가요?

이 스킬은 솔리디티 기반 DeFi AMM(자동화 마켓 메이커) 스마트 컨트랙트, 유동성 풀 볼트 및 스왑 함수의 보안 취약점 패턴과 강화된 구현을 체계적으로 제공합니다. 주요 취약점으로 재진입 공격, CEI 순서 위반, 기부/인플레이션 공격, 오라클 조작, 슬리피지 부재, 안전하지 않은 정수 연산 및 부적절한 관리자 제어를 다루며, 각각에 대한 취약한 코드 예제와 OpenZeppelin, Uniswap V3 Core 라이브러리 등을 활용한 안전한 구현 예제를 함께 제시합니다. 개발자는 이 스킬을 체크리스트 겸 패턴 라이브러리로 활용하여 모든 사용자 진입점을 검토하고, 수동 구현보다 검증된 라이브러리 사용을 권장합니다. 또한 슬리더(Slither), 에키드나(Echidna) 및 파운드리(Forge) 퍼징과 같은 감사 도구 실행 명령어를 포함하여 실제 배포 전 정적 분석 및 퍼징을 수행하도록 안내합니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

DeFi AMM 보안

솔리디티 AMM 컨트랙트, LP 볼트 및 스왑 함수를 위한 주요 취약점 패턴 및 강화된 구현입니다.

사용 시기

  • 솔리디티 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.

관련 스킬