Section 4 of 4

Build
+15 Shields

Basic 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

  1. User calls swap(tokenIn, amountIn, minAmountOut)
  2. Contract determines direction (token0 → token1 or vice versa)
  3. Contract transfers input tokens from user to pool
  4. Contract calculates output using getAmountOut()
  5. Contract verifies amountOut >= minAmountOut (slippage protection)
  6. Contract transfers output tokens to user
  7. Contract updates reserves
  8. 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
Solidity
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