Section 8 of 10
Build
+15 LynxFactory and Router
Factory and Router
What You Are Building
Your AMM handles one pair. A real DEX needs a Factory to create pairs on demand and a Router to make swaps user-friendly.
Factory responsibilities:
- Deploy new Pair contracts using CREATE2
- Register pairs in a mapping for lookup
- Ensure only one pair exists per token combination
- Order tokens canonically (token0 < token1)
Router responsibilities:
- Calculate optimal liquidity amounts (slippage protection)
- Execute multi-hop swaps (ETH → USDC → DAI in one transaction)
- Enforce deadlines (prevent stale transactions from executing)
- Handle WETH wrapping/unwrapping
CREATE2 Deterministic Deployment
The Factory uses CREATE2 to deploy pairs. The salt is keccak256(abi.encodePacked(token0, token1)). This means:
- Pair addresses are deterministic: you can calculate them without querying the blockchain
- The Router never needs to call the Factory to find a pair address
- This saves gas on every swap
Multi-hop Swaps
The Router supports swap paths. To swap ETH for DAI when no ETH/DAI pair exists:
path = [WETH, USDC, DAI]
The Router calculates amounts through each pair:
- WETH → USDC (pair 1)
- USDC → DAI (pair 2)
Each intermediate swap sends tokens directly to the next pair, minimizing transfers.
Your Task
Build a SimpleFactory and a SimpleRouter. The Factory creates pairs. The Router handles addLiquidity with slippage protection and multi-hop swaps with deadlines.
Your Code
Solution.sol
Loading editor...
Requirements
Factory validates token addresses
Factory orders tokens canonically
Factory uses CREATE2
Factory registers pair both directions
Router has deadline protection
Router enforces slippage on swaps