1---2name: defi-protocol3description: Design and implement DeFi protocols — AMMs, lending markets, yield aggregators, and stablecoin mechanisms4allowed-tools: [Read, Write, Bash, Grep]5effort: high6metadata:7 source: https://skillmd.com/skills/uitbreidenos/defi-protocol8---910## When to activate1112- Building automated market makers (AMMs) or DEXes13- Implementing lending/borrowing protocols14- Designing yield farming or liquidity mining strategies15- Creating stablecoin mechanisms or synthetic assets16- Building liquid staking derivatives1718## When NOT to use1920- For simple token transfers or payments21- For centralized exchange backends22- For traditional financial applications2324## Instructions25261. **Define protocol type.** AMM (Uniswap-style), Lending (Aave-style), Yield (Yearn-style), Stablecoin (Maker-style).272. **Model economics.** Constant product formula (x*y=k), interest rate model (utilization-based), yield source identification.283. **Implement core contracts.** Pool, Router, Token, Oracle. Use OpenZeppelin for standard components.294. **Design incentive structure.** LP rewards, governance tokens, fee distribution, impermanent loss mitigation.305. **Security hardening.** Oracle selection (Chainlink vs TWAP), flash loan protection, slippage controls, circuit breakers.316. **Testing.** Fork mainnet tests with Foundry. Simulate flash loan attacks, oracle manipulation, edge cases.327. **Deployment.** Deterministic deployment (CREATE2), multi-sig ownership, timelock for parameter changes.3334## Example3536```solidity37// Simplified AMM Pool (constant product)38contract SimplePool {39 uint256 public reserveA;40 uint256 public reserveB;41 42 function swap(address tokenIn, uint256 amountIn) external returns (uint256 amountOut) {43 // 0.3% fee44 uint256 amountInWithFee = amountIn * 997;45 46 if (tokenIn == tokenA) {47 amountOut = (reserveB * amountInWithFee) / (reserveA * 1000 + amountInWithFee);48 reserveA += amountIn;49 reserveB -= amountOut;50 } else {51 amountOut = (reserveA * amountInWithFee) / (reserveB * 1000 + amountInWithFee);52 reserveB += amountIn;53 reserveA -= amountOut;54 }55 }56}57```