Catalog
affaan-m/defi-amm-security

affaan-m

defi-amm-security

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.

NewUpdated Sep 9, 2026

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
Files1
1 files · 1.0 KB

Select a file to preview

Overall Score

84/100

Grade

B

Good

Grades are signals, not a certification. Always review a skill yourself before use.

Safety

88

Quality

85

Clarity

88

Completeness

78

Summary

This skill provides a security checklist and hardened code patterns for Solidity AMM contracts, covering reentrancy, CEI ordering, donation attacks, oracle manipulation, slippage, and admin controls. It serves as an educational reference guide and audit checklist, offering side-by-side vulnerable vs. safe implementations with explanations and tool recommendations.

Detected Capabilities

code pattern referencestatic analysis tool invocation (slither, echidna, forge)local shell command execution for auditingeducational documentation and checklist

Trigger Keywords

Phrases that agents use to match this skill to user intent.

audit solidity ammliquidity pool securityswap reentrancy checkdefi contract reviewuniswap security patternsslither static analysisoracle manipulationdonation attack

Risk Signals

INFO

Shell commands for audit tool invocation (slither, echidna, forge)

Audit Tools section, lines ~106–112
INFO

Instruction to ask before running long fuzzing/analysis jobs that consume resources

Execution Safety section, line ~38
INFO

Explicit warning against including secrets or private keys in examples/logs

Execution Safety section, line ~40

Use Cases

  • Audit Solidity AMM or liquidity pool contracts before deployment
  • Implement secure swap, deposit, or withdraw functions following battle-tested patterns
  • Review existing DeFi contracts for common vulnerability classes
  • Learn proper oracle integration, slippage protection, and access control patterns
  • Set up and run static analysis and fuzzing tools on a local contract codebase

Quality Notes

  • ✓ Clear scope boundaries: when to use, what not to do
  • ✓ Comprehensive vulnerability coverage with side-by-side vulnerable/safe examples
  • ✓ Direct link to OpenZeppelin and Uniswap battle-tested libraries
  • ✓ Execution safety section explicitly warns against secrets, resource consumption, and untrusted input
  • ✓ Practical checklist at the end covers all major categories
  • ✓ Tool recommendations (slither, echidna, forge) are standard industry practice
  • ✓ Well-organized with clear sections and actionable patterns
  • ✓ TWAP oracle pattern with specific Uniswap V3 implementation
  • ⚠ No example of how to run tools end-to-end on a real project (though checklist mentions it)
  • ⚠ No guidance on how to interpret slither/echidna output or handle false positives
Model: claude-haiku-4-5-20251001Analyzed: Sep 9, 2026

Reviews

Add this skill to your library to leave a review.

No reviews yet

Be the first to share your experience.

Version History

  1. v2.0

    Contract changed: description

    ✦ AIClarifies activation scope: skill now explicitly targets auditing or writing AMM code rather than implicit use.

    triggering2026-09-09

    LATEST
  2. v1.2

    Content updated

    ✦ AIAdds execution safety guidance for shell commands and secrets handling.

    2026-07-14

    View This Version
  3. v1.1

    Content updated

    ✦ AIAdds LICENSE file.

    2026-04-20

    View This Version
  4. v1.0

    2026-04-12

    View This VersionInitial version

Use affaan-m/defi-amm-security in your dev environment

Command Palette

Search for a command to run...