DeFi AMM Security Skill

100 0 Updated: 2026-07-15 14:50:53

The DeFi AMM Security Skill is a specialized module within the ECC system, focusing on security analysis and vulnerability detection for Decentralized Finance (DeFi) Automated Market Makers (AMMs). This skill covers core security concepts of AMM protocols, common attack vectors (such as flash loan attacks, price manipulation, slippage attacks), auditing methodologies, and best practices. It is suitable for blockchain security engineers, smart contract auditors, and DeFi developers to identify and mitigate security risks in AMMs, enhancing protocol security.

Install
bunx skills add https://github.com/affaan-m/ECC --skill defi-amm-security
Skill Details readonly

1. Skill Overview

This skill applies to writing or auditing Solidity AMM and liquidity pool contracts, implementing token swap, deposit, withdrawal, mint, and burn workflows that hold token balances. It also audits any contract that relies on token.balanceOf(address(this)) for share or reserve calculation logic. It additionally covers scenarios adding admin controls to DeFi protocols including fee setters, pause toggles, oracle update handlers, and other privileged management functions.
Core Principle: Treat this skill as a combined audit checklist + secure pattern library. Audit every user-facing entrypoint against each security category; prioritize hardened reference implementations instead of handwritten custom variants.

2. Core Capabilities

2.1 Reentrancy Mitigation: Mandatory CEI Execution Order

Vulnerable implementation (transfers state before updating internal accounting, exposed to reentrancy exploits):
solidity
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    token.transfer(msg.sender, amount);
    balances[msg.sender] -= amount;
}
 
Secure implementation: Enforce nonReentrant modifier and strictly follow CEI (Checks-Effects-Interactions) order: validate conditions first, update internal state, then execute external token transfers.
solidity
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);
}
 
Rule: Never implement custom reentrancy guards when audited, battle-tested libraries exist.

2.2 Donation / Inflation Attack Mitigation

Directly using token.balanceOf(address(this)) for share computation allows attackers to manipulate the denominator by transferring tokens to the contract outside official deposit paths.
Vulnerable implementation:
solidity
function deposit(uint256 assets) external returns (uint256 shares) {
    shares = (assets * totalShares) / token.balanceOf(address(this));
}
 
Secure implementation: Maintain internal accounting state and measure actual received token delta:
solidity
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;
}

2.3 Oracle Manipulation Protection

Spot market prices are vulnerable to flash-loan manipulation; TWAP (Time-Weighted Average Price) oracles are enforced as the primary source:
solidity
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);
 

2.4 Slippage Protection

Every swap path must accept user-provided minimum output amount (amountOutMin) and transaction deadline (deadline) parameters:
solidity
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);
}

2.5 Safe Reserve Arithmetic

For large reserve calculations with overflow/underflow risk, avoid raw a * b / c arithmetic; use audited safe math primitives such as mulDiv:
solidity
import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
uint256 result = FullMath.mulDiv(a, b, c);

2.6 Admin Access Control

Two-step explicit acceptance ownership transfer is mandatory; all privileged routes are guarded by access modifiers:
 
 
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";

contract MyAMM is Ownable2Step {
    function setFee(uint256 fee) external onlyOwner { ... }
    function pause() external onlyOwner { ... }
}
 

3. Mandatory Audit Checklist

The skill provides a complete standardized audit checklist:
  1. All user-facing entrypoints exposed to reentrancy use the nonReentrant modifier
  2. Strict CEI (Checks-Effects-Interactions) execution order enforced everywhere
  3. Share calculation logic does not rely on raw balanceOf(address(this)) values
  4. All ERC-20 transfers use SafeERC20 safe transfer wrappers
  5. Deposit logic measures actual received token delta via pre/post balance snapshots
  6. Oracle price feeds use TWAP or other manipulation-resistant sources
  7. All swap functions accept user-defined slippage (amountOutMin) and transaction deadline parameters
  8. Overflow-sensitive reserve math uses audited safe primitives such as mulDiv
  9. All admin management functions are protected by formal access control modifiers
  10. Emergency pause functionality exists and has full test coverage
  11. Static analysis and fuzz testing suites executed pre-production

4. Audit Tooling

Recommended security audit tooling and execution commands:
# Slither static analysis scan
pip install slither-analyzer
slither . --exclude-dependencies

# Echidna property-based fuzz testing
echidna-test . --contract YourAMM --config echidna.yaml

# Foundry native fuzz testing
forge test --fuzz-runs 10000

5. Primary Use Cases

  1. Secure development guidance for AMM contracts
     
    Reference standardized secure patterns when writing new liquidity pool and swap logic to eliminate critical security flaws
  2. Smart contract security audits
     
    Systematically audit existing AMM pool implementations against the full checklist to identify exploitable vulnerabilities
  3. DeFi protocol admin feature code review
     
    Audit security risks introduced when adding fee controllers, circuit break pause logic, and oracle update privileged functions
  4. Engineering team secure coding training
     
    Serve as standardized DeFi secure coding specification documentation for Solidity development teams
  5. Vulnerability remediation reference
     
    Quickly locate hardened reference implementations when fixing reentrancy, oracle manipulation, donation inflation, and other core DeFi exploits

6. Critical Guiding Principles

  1. Leverage audited open-source libraries: Never write custom security guards when battle-tested libraries from OpenZeppelin and Uniswap exist
  2. Internal accounting tracking rule: Share calculation logic must measure actual received token delta instead of relying on raw contract balanceOf values
  3. TWAP oracle priority: Prefer time-weighted average price feeds over volatile spot market prices to mitigate flash-loan manipulation attacks
  4. Mandatory slippage + deadline parameters: All swap entrypoints require user-controlled minimum output and transaction expiry guards
  5. Safe math primitives for reserve calculations: Use mulDiv and equivalent audited arithmetic libraries for overflow-sensitive reserve computations
  6. Two-step ownership transfer: Adopt Ownable2Step to require explicit acceptance from new admin addresses
  7. Pre-production full testing requirement: Run static analysis (Slither) and fuzz testing (Echidna/Foundry) before mainnet deployment
  8. Secure audit command execution: Only run audit tooling inside trusted source checkouts or ephemeral sandboxes; never concatenate untrusted contract paths, names, or user-supplied flags into raw shell command strings

Summary

DeFi AMM Security is a specialized Solidity skill for secure development and formal auditing of automated market maker liquidity pool contracts. It covers six core vulnerability classes: reentrancy attack mitigation, CEI execution ordering, donation/inflation exploit prevention, flash-loan-resistant TWAP oracle design, user-controlled slippage/deadline protection, and overflow-safe reserve arithmetic plus privileged admin access control. It includes side-by-side vulnerable/secure Solidity code examples, a complete audit checklist, and ready-to-use CLI commands for Slither static analysis, Echidna property fuzz testing, and Foundry native fuzz suites. This skill is built for DeFi developers writing new AMM pool contracts, auditors reviewing existing liquidity implementations, and maintainers assessing security risks introduced by admin fee, pause, and oracle management features, acting as a fully actionable security pattern library and audit checklist.