Section 4 of 4
Build
+15 ShieldsBasic Swap Function
Basic Swap Function
What You Are Building
The swap function is the core of any DEX. A user deposits one token and receives the other. The contract calculates the output amount using the constant product formula, applies fees, and transfers tokens.
In this section, you will implement:
getAmountOut(): calculates output tokens for a given input (with 0.3% fee)swap(): executes the trade with slippage protection- Invariant verification (k should only increase due to fees)
- Reserve updates after each swap
The Swap Flow
- User calls
swap(tokenIn, amountIn, minAmountOut) - Contract determines direction (token0 → token1 or vice versa)
- Contract transfers input tokens from user to pool
- Contract calculates output using
getAmountOut() - Contract verifies
amountOut >= minAmountOut(slippage protection) - Contract transfers output tokens to user
- Contract updates reserves
- Contract verifies k has not decreased
Security: Checks-Effects-Interactions
The order of operations matters. Update state (reserves) before making external calls (token transfers). This prevents reentrancy attacks where a malicious token's transfer callback could re-enter the swap function with stale reserves.
Your Task
Complete the swap implementation in the editor. The TODO comments show each step.
Your Code
Solution.sol
Loading editor...
Requirements
getAmountOut validates inputs
Fee calculation uses 997/1000
swap validates tokenIn
swap enforces slippage protection
swap uses reentrancy guard
swap verifies K invariant
Choose Your Architecture
You have built the core. Now decide which protocol type to build. Each path uses a real, audited protocol as its reference. You can come back and build another later.