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:
- All user-facing entrypoints exposed to reentrancy use the
nonReentrantmodifier - Strict CEI (Checks-Effects-Interactions) execution order enforced everywhere
- Share calculation logic does not rely on raw
balanceOf(address(this))values - All ERC-20 transfers use
SafeERC20safe transfer wrappers - Deposit logic measures actual received token delta via pre/post balance snapshots
- Oracle price feeds use TWAP or other manipulation-resistant sources
- All swap functions accept user-defined slippage (
amountOutMin) and transaction deadline parameters - Overflow-sensitive reserve math uses audited safe primitives such as
mulDiv - All admin management functions are protected by formal access control modifiers
- Emergency pause functionality exists and has full test coverage
- 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
- Secure development guidance for AMM contracts
Reference standardized secure patterns when writing new liquidity pool and swap logic to eliminate critical security flaws
- Smart contract security audits
Systematically audit existing AMM pool implementations against the full checklist to identify exploitable vulnerabilities
- DeFi protocol admin feature code review
Audit security risks introduced when adding fee controllers, circuit break pause logic, and oracle update privileged functions
- Engineering team secure coding training
Serve as standardized DeFi secure coding specification documentation for Solidity development teams
- Vulnerability remediation reference
Quickly locate hardened reference implementations when fixing reentrancy, oracle manipulation, donation inflation, and other core DeFi exploits
6. Critical Guiding Principles
- Leverage audited open-source libraries: Never write custom security guards when battle-tested libraries from OpenZeppelin and Uniswap exist
- Internal accounting tracking rule: Share calculation logic must measure actual received token delta instead of relying on raw contract
balanceOfvalues - TWAP oracle priority: Prefer time-weighted average price feeds over volatile spot market prices to mitigate flash-loan manipulation attacks
- Mandatory slippage + deadline parameters: All swap entrypoints require user-controlled minimum output and transaction expiry guards
- Safe math primitives for reserve calculations: Use
mulDivand equivalent audited arithmetic libraries for overflow-sensitive reserve computations - Two-step ownership transfer: Adopt
Ownable2Stepto require explicit acceptance from new admin addresses - Pre-production full testing requirement: Run static analysis (Slither) and fuzz testing (Echidna/Foundry) before mainnet deployment
- 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.