# defi-amm-security

> A Claude Code skill from Affaan M's everything-claude-code repo with a security checklist for Solidity AMM contracts and LP vaults — reentrancy + CEI, donation / inflation attacks, oracle manipulation (TWAP over spot), slippage + deadline enforcement, SafeERC20, Ownable2Step admin controls, and hardened share math with internal accounting instead of raw balanceOf.

**Use case**: Review or harden a Solidity AMM / LP / swap contract against the recurring vulnerability patterns

**Canonical URL**: https://agentcookbooks.com/skills/defi-amm-security/

**Topics**: claude-code, skills, crypto, security

**Trigger phrases**: "audit my AMM contract", "donation attack on my LP vault", "Solidity reentrancy + CEI checklist"

**Source**: [Affaan M](https://github.com/affaan-m/everything-claude-code/tree/main/skills/defi-amm-security)

**License**: MIT

---

## What it does

`defi-amm-security` is the Solidity-AMM review skill in [Affaan M's everything-claude-code](https://github.com/affaan-m/everything-claude-code) — see [skills/defi-amm-security](https://github.com/affaan-m/everything-claude-code/tree/main/skills/defi-amm-security). It's a checklist-plus-pattern library for reviewing AMM, LP vault, and swap-flow contracts — frame the contract through the categories below and prefer the hardened patterns over hand-rolled variants. The skill positions itself as defensive: review and harden, not exploit construction.

The categories covered: reentrancy and CEI ordering (use `ReentrancyGuard` from OpenZeppelin, never hand-rolled), donation / inflation attacks (don't depend on raw `token.balanceOf(address(this))` in share math — track internal `_totalAssets` accounting, measure actual tokens received), oracle manipulation (TWAP via Uniswap V3 `observe` rather than spot prices that are flash-loan manipulable), slippage and deadline (every swap path requires caller-provided `amountOutMin` and `deadline`), safe reserve math (use `FullMath.mulDiv` for overflow-sensitive paths), admin controls (`Ownable2Step` for explicit two-step ownership transfer, every privileged path gated).

The execution-safety note is non-negotiable: shell commands in the skill are local audit examples only — run in a trusted checkout or sandbox, never splice untrusted contract names / RPC URLs / private keys into shell, never include secrets in command output or logs. The checklist at the bottom is the gate before production: nonReentrant on exposed entrypoints, CEI ordered, internal accounting for share math, SafeERC20 on transfers, deposits measure received tokens, oracle uses TWAP, swaps require slippage + deadline, overflow-sensitive math uses safe primitives, admin functions access-controlled, emergency pause exists and is tested, static analysis + fuzzing run.

## When to use it

- Writing or auditing a Solidity AMM, liquidity-pool, or LP-vault contract
- Implementing swap / deposit / withdraw / mint / burn flows that hold token balances
- Reviewing any contract that uses `token.balanceOf(address(this))` in share or reserve math — the donation-attack lens
- Adding fee setters, pausers, oracle updates, or other admin functions to a DeFi protocol
- Pre-deploy gate for any contract that handles user funds — the checklist is the final review

When *not* to reach for it:

- Off-chain trading bots or LLM trading agents — that's `llm-trading-agent-security`
- Non-DeFi Solidity (NFT contracts, on-chain registries, identity) — different threat model
- Other EVM languages (Vyper, Huff) — the patterns are Solidity-shaped
- Exploit construction or offensive security — the skill is defensive review only

## Install

From [affaan-m/everything-claude-code](https://github.com/affaan-m/everything-claude-code) at `skills/defi-amm-security/`. Drop the folder into `~/.claude/skills/defi-amm-security/`. The skill is markdown patterns + checklist. Runtime tooling the patterns reference: OpenZeppelin contracts (`ReentrancyGuard`, `SafeERC20`, `Ownable2Step`), Uniswap V3 core (`FullMath`, `TickMath`), Slither (`pip install slither-analyzer`), Echidna for fuzzing, Foundry's `forge test --fuzz-runs`. Run any audit command inside a trusted local checkout — the skill is explicit about not splicing untrusted input into shell.

## What a session looks like

1. **Read the contract.** Walk through every user entrypoint — swap, deposit, withdraw, mint, burn — and every admin path.
2. **Check the reentrancy lane.** Every exposed entrypoint uses `nonReentrant` from OpenZeppelin. Hand-rolled guards get replaced.
3. **CEI ordering.** Effects before interactions. State writes before external calls. The withdraw example in the skill (transfer-before-state-write) is the canonical fail; rewrite to state-write-then-`safeTransfer`.
4. **Audit share math for donation attacks.** Any path that uses `token.balanceOf(address(this))` as a denominator gets rewritten to track internal `_totalAssets` and measure received tokens via `balBefore` / `balAfter` deltas.
5. **Replace spot oracle reads with TWAP.** Uniswap V3 `observe` with a 30-minute window is the default; spot prices are flash-loan manipulable.
6. **Slippage + deadline on every swap.** `amountOutMin` and `deadline` caller-provided, checked before the swap executes.
7. **Admin path review.** `Ownable2Step` for ownership transfer, every privileged function gated, emergency pause exists, fee changes have sane bounds.
8. **Run the tools.** Slither for static analysis, Echidna for fuzzing, Foundry `forge test --fuzz-runs 10000` against invariants.

The discipline that makes it work: prefer hardened libraries over hand-rolled. The skill is explicit that reentrancy guards, ERC-20 transfers, and ownership transfers all have battle-tested OpenZeppelin implementations — writing your own variant is how subtle bugs ship.

## Receipts

_TODO — to be filled in from a real session. Once the checklist has been applied to a real Solidity AMM, this section will capture: which category turned up the most findings (reentrancy / donation / oracle / slippage / admin / math), whether the contract was actually using raw `balanceOf` in share math (the most common AMM bug), the Slither + Echidna run output on a real codebase and how many findings each surfaced, and any pattern the upstream checklist missed for the specific AMM variant being reviewed._

## Source and attribution

From [Affaan M's everything-claude-code](https://github.com/affaan-m/everything-claude-code/tree/main/skills/defi-amm-security) — an MIT-licensed skill collection covering harness construction, agent ops, video, payments, and platform-specific patterns.

License: MIT.

Quoting the no-hand-rolled rule verbatim: *"Do not write your own guard when a hardened library exists."* That's the wedge — most AMM exploits in production traced to a "we simplified the OpenZeppelin pattern" decision; the skill flips the default to using the library and justifying any deviation explicitly.