Design an AMM smart contract with constant product formula, liquidity provision, fee collection, and flash swap support.
## ROLE You are a DeFi protocol developer who has built AMM systems from scratch. You understand the mathematics of Uniswap V2/V3, Curve, and Balancer and can implement efficient trading mechanics with robust security. ## OBJECTIVE Design an AMM smart contract for [PROTOCOL NAME] implementing [AMM TYPE: constant product, stable swap, concentrated liquidity] for trading [TOKEN PAIRS] on [CHAIN]. ## TASK ### Core AMM Mathematics - Invariant formula: x * y = k (constant product) or StableSwap curve with amplification - Price calculation: how token prices derive from reserve ratios - Slippage: price impact formula based on trade size relative to pool depth - Minimum output: user-specified minimum to prevent sandwich attacks - TWAP oracle: time-weighted average price accumulator for external consumers ### Liquidity Provision - Adding liquidity: proportional deposit matching current pool ratio - Initial liquidity: first depositor sets the price, minimum liquidity locked permanently - LP tokens: ERC-20 tokens representing share of pool (mint on deposit, burn on withdrawal) - Imbalanced deposits: single-sided liquidity with automatic rebalancing and penalty/bonus - Withdrawal: burn LP tokens to receive proportional share of both pool tokens ### Fee System - Swap fee: configurable fee (e.g., 0.3%) deducted from input amount - Fee distribution: fees accumulate in the pool, increasing LP token value - Protocol fee: optional protocol-level fee (e.g., 1/6 of swap fee) sent to treasury - Dynamic fees: optional volatility-based fee adjustment for impermanent loss mitigation - Fee accounting: precise tracking to avoid rounding errors over millions of swaps ### Flash Swaps - Mechanism: borrow tokens from the pool, execute arbitrary logic, repay in same transaction - Callback pattern: IFlashSwapCallback interface for borrower contracts - Fee: flash swap fee equal to or greater than standard swap fee - Validation: verify repayment satisfies invariant after callback completion - Use cases: arbitrage, liquidations, collateral swaps ### Router Contract - Multi-hop swaps: route through multiple pools for pairs without direct liquidity - Path finding: optimal route calculation considering gas and price impact - Deadline parameter: transaction expiry to prevent stale trades - ETH wrapping: automatic WETH wrapping/unwrapping for native token trades - Permit support: gasless token approvals via EIP-2612 ### Security Architecture - Reentrancy locks: critical on swap and liquidity functions - Price manipulation resistance: TWAP oracle with sufficient observation window - Minimum liquidity: permanent lock of initial LP tokens to prevent pool draining - Access control: factory pattern with permissioned pool creation (or permissionless with safeguards) - Circuit breakers: maximum single-block volume to detect and limit attacks ## OUTPUT FORMAT Complete AMM contract suite with Pool, Factory, Router contracts, mathematical proofs, and integration guide. ## CONSTRAINTS - Swap gas cost must be under 150K gas for simple token-to-token swaps - All math must use fixed-point arithmetic with no precision loss exceeding 1 wei - Must handle fee-on-transfer tokens and rebasing tokens gracefully - Pool creation must be deterministic (CREATE2) for address prediction - Include comprehensive integration tests with realistic trading scenarios
Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[PROTOCOL NAME][TOKEN PAIRS][CHAIN]