defi-amm-security
하는 일
이 가이드는 암호화폐 교환(AMM)과 유동성 풀을 다루는 탈중앙화 금융(DeFi) 스마트 컨트랙트를 보호하도록 돕습니다. 금전 손실로 이어질 수 있는 흔한 문제를 점검합니다.
사용하는 경우
- ✓새 암호화폐 교환 계약을 작성할 때.
- ✓기존 계약에 보안 결함이 있는지 검토할 때.
- ✓DeFi 프로토콜에 새로운 관리 기능을 추가할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/skills/defi-amm-security/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“이 유동성 풀 계약이 재진입 공격이나 가격 조작에 취약하지 않은지 확인해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
체크리스트처럼 작동합니다. 코드를 안전한 예시와 권장 패턴과 비교해, 알려진 취약점을 피할 수 있도록 합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
DeFi AMM Security
Critical vulnerability patterns and hardened implementations for Solidity AMM contracts, LP vaults, and swap functions.
When to Use
- Writing or auditing a Solidity AMM or liquidity-pool contract
- Implementing swap, deposit, withdraw, mint, or burn flows that hold token balances
- Reviewing any contract that uses
token.balanceOf(address(this))in share or reserve math - Adding fee setters, pausers, oracle updates, or other admin functions to a DeFi protocol
How It Works
Use this as a checklist-plus-pattern library. Review every user entrypoint against the categories below and prefer the hardened examples over hand-rolled variants.
Execution Safety
The shell commands in this skill are local audit examples. Run them only in a trusted checkout or disposable sandbox, and do not splice untrusted contract names, paths, RPC URLs, private keys, or user-supplied flags into shell commands. Ask before installing tools or running long fuzzing/static-analysis jobs that may consume significant local or paid resources.
Never include secrets, private keys, seed phrases, API tokens, or mainnet signing credentials in command examples, logs, or reports.
Examples
Reentrancy: enforce CEI order
Vulnerable:
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount);
token.transfer(msg.sender, amount);
balances[msg.sender] -= amount;
}
Safe:
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);
}
Do not write your own guard when a hardened library exists.
Donation or inflation attacks
Using token.balanceOf(address(this)) directly for share math lets attackers manipulate the denominator by sending tokens to the contract outside the intended path.
// Vulnerable
function deposit(uint256 assets) external returns (uint256 shares) {
shares = (assets * totalShares) / token.balanceOf(address(this));
}
// Safe
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;
}
Track internal accounting and measure actual tokens received.
Oracle manipulation
Spot prices are flash-loan manipulable. Prefer 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 protection
Every swap path needs caller-provided slippage and a deadline.
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);
}
Safe reserve math
import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
uint256 result = FullMath.mulDiv(a, b, c);
For large reserve math, avoid naive a * b / c when overflow risk exists.
Admin controls
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
contract MyAMM is Ownable2Step {
function setFee(uint256 fee) external onlyOwner { ... }
function pause() external onlyOwner { ... }
}
Prefer explicit acceptance for ownership transfer and gate every privileged path.
Security Checklist
- Reentrancy-exposed entrypoints use
nonReentrant - CEI ordering is respected
- Share math does not depend on raw
balanceOf(address(this)) - ERC-20 transfers use
SafeERC20
…
자주 묻는 질문
‘재진입(reentrancy)’이란 무엇인가요?
한 계약이 다른 계약을 호출하고, 그 계약이 처음 호출이 끝나기 전에 다시 첫 번째 계약을 호출해 자금을 빼앗을 수 있는 공격 유형입니다.
‘슬리피지 조작’이란 무엇인가요?
거래를 시작한 시점과 완료된 시점 사이에 거래 가격이 예상치 않게 변해서, 받는 금액이 예상보다 적어지는 것입니다.
‘AMM 스마트 컨트랙트’란 무엇인가요?
중개자 없이 암호화폐 거래를 자동으로 진행하는 블록체인 위 프로그램입니다. Uniswap이나 PancakeSwap 같은 것이 있습니다.
상세 정보
작성자의 원본 설명
Security checklist for Solidity AMM contracts, liquidity pools, and swap flows. Covers reentrancy, CEI ordering, donation or inflation attacks, oracle manipulation, slippage, admin controls, and integer math. Use when auditing or writing Solidity AMM, liquidity pool, or swap code.
repo: affaan-m/ECC
인기도
- GitHub 스타
- 280k
- 순위
- #299
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.