DeFi AMM Security

VerifiedSafe

Security checklist for Solidity AMM contracts, liquidity pools, and swap flows. Covers reentrancy, donation attacks, oracle manipulation, slippage, and integer math.

Sby Skills Guide Bot
SecurityAdvanced
8/29/2026
Claude CodeCursorCodex
#solidity#defi#amm#reentrancy#smart-contracts

Recommended for

Automated summary

A security checklist and hardened Solidity pattern library for auditing or writing AMM, liquidity-pool, and swap contracts.

Strengths

  • Pairs each vulnerability class with vulnerable and then hardened Solidity snippets
  • Covers reentrancy and CEI ordering, donation/inflation attacks, TWAP oracles, slippage, admin controls, and integer math
  • Recommends OpenZeppelin primitives and internal accounting instead of balanceOf for share math
  • Includes execution-safety guidance on secrets and sandboxed audits

Limitations

  • It is a checklist, not a complete audit methodology or automated tooling
  • Snippets are illustrative and not production-ready as written
  • Solidity/EVM-specific and does not cover formal verification
When to use it

Use when writing or reviewing Solidity AMM, LP vault, or swap code and you need concrete hardening patterns.

When not to use it

Not for non-EVM chains, general smart-contract auditing outside AMM/LP scope, or as a replacement for a professional audit.

Security analysis

Safe
Quality score90/100

The skill is an educational Solidity security checklist with defensive examples. It includes only local audit commands (slither, echidna, forge) and explicitly warns against injecting untrusted input or handling secrets. No destructive, exfiltration, obfuscation, or safety-disabling behavior is present.

No concerns found

How this analysis is made

Examples

Audit a swap function
Review this Solidity swap function for reentrancy, slippage, and oracle-manipulation risks, then show me the hardened version.
Harden deposit share math
My AMM vault computes shares from token.balanceOf(address(this)). Show me a donation/inflation-safe deposit function using internal accounting.
Replace spot price with TWAP
Replace the spot price in my AMM with a Uniswap V3 30-minute TWAP, and add a deadline plus amountOutMin check to the swap.

name: defi-amm-security description: 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. metadata: version: "1.0.0" origin: ECC direct-port adaptation

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
  • Deposits measure actual tokens received
  • Oracle reads use TWAP or another manipulation-resistant source
  • Swaps require amountOutMin and deadline
  • Overflow-sensitive reserve math uses safe primitives like mulDiv
  • Admin functions are access-controlled
  • Emergency pause exists and is tested
  • Static analysis and fuzzing are run before production

Audit Tools

pip install slither-analyzer
slither . --exclude-dependencies

echidna-test . --contract YourAMM --config echidna.yaml

forge test --fuzz-runs 10000

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/defi-amm-security-mte1lkn8/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/defi-amm-security-mte1lkn8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/defi-amm-security-mte1lkn8/download' --output '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md.part' && mv '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md.part' '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && test -s '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/defi-amm-security' && cp -R '.skill-downloads/defi-amm-security-mte1lkn8' '.claude/skills/defi-amm-security'

Cursor
test -f '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && test -s '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/defi-amm-security' && cp -R '.skill-downloads/defi-amm-security-mte1lkn8' '.cursor/skills/defi-amm-security'

Codex
test -f '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && test -s '.skill-downloads/defi-amm-security-mte1lkn8/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/defi-amm-security' && cp -R '.skill-downloads/defi-amm-security-mte1lkn8' '.agents/skills/defi-amm-security'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/defi-amm-security-mte1lkn8'

openskills read 'defi-amm-security-mte1lkn8'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/defi-amm-security-mte1lkn8/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills