Skip to content

31. SpeedRun Challenge 4: DEX

This is the most substantial build in the course and the flagship option for the capstone. A DEX (decentralized exchange) built as an automated market maker replaces the human order book with a contract that holds reserves and prices trades by formula. You’ll implement pool initialization, the constant-product pricing curve, swaps in both directions, and liquidity-provider accounting — then connect a frontend and deploy to a testnet. Everything below is a standalone build guide; read it end to end before you start, and treat the live SpeedRun challenge as the authoritative checkpoint list. Budget several hours, not one sitting.

  • Contrast an order-book exchange with an automated market maker.
  • Identify the two assets in the pool: ETH and the $BAL ERC-20 token.
  • Locate the contracts and frontend in the Scaffold-ETH project.
  • Trace how the frontend reads reserves and calls unfinished contract functions.
  • Treat the smart contract as both the exchange and the custody layer for pool reserves.

Key idea: users trade against shared reserves held by the contract rather than matching directly with another trader.

  • Track total liquidity and each provider’s share.
  • Seed the pool once with init(uint256 tokens).
  • Pair the incoming ETH with ERC-20 tokens at an initial ratio.
  • Understand why transferFrom requires token approval before initialization.
  • Account for the fact that address(this).balance already includes msg.value during a payable call.

Key idea: the first liquidity provider establishes both the starting reserves and the initial market price.

The challenge uses the constant-product invariant:

x * y = k
  • x and y are the two pool reserves.
  • A trade adds to one reserve and removes from the other.
  • The output amount must preserve the invariant after accounting for fees.
  • Larger trades move the reserve ratio further and therefore experience greater price impact.
  • The challenge’s price function applies a 0.3% fee before calculating output.

Key idea: the AMM does not fetch a market price from an API. It derives a price from the current reserve ratio and the invariant.

  • Implement ethToToken() for payable ETH input and ERC-20 output.
  • Compute the pre-swap ETH reserve by subtracting msg.value from the current balance.
  • Implement tokenToEth(uint256 tokenInput) with balance and allowance checks.
  • Pull ERC-20 input with transferFrom before sending ETH output.
  • Use a checked low-level call for ETH transfers.
  • Emit events for both swap directions.

Key idea: reserve snapshots must represent the pool before the input is applied, or the pricing calculation will be wrong.

  • Implement deposit() to accept ETH and the proportional token amount.
  • Mint an internal liquidity share based on the provider’s contribution.
  • Implement withdraw(uint256 amount) to burn a share and return both assets.
  • Keep deposits proportional so they do not unexpectedly move the pool price.
  • Understand why Solidity integer division may require conservative rounding.
  • Emit liquidity-added and liquidity-removed events for frontend indexing.

Key idea: liquidity shares represent a proportional claim on both reserves, not a fixed amount of ETH or tokens.

  • Display ETH and token reserves.
  • Preview swap output before sending a transaction.
  • Surface wallet balance and ERC-20 allowance state.
  • Require approval before token-input swaps or liquidity deposits.
  • Refresh UI state from contract reads and emitted events after each transaction.
  • Show the effect of trade size on the pricing curve.

Key idea: a usable DEX frontend must explain approvals, expected output, reserve changes, and transaction state before asking the user to sign.

  • Run the checkpoint tests after reserves, pricing, swaps, and liquidity are implemented.
  • Test zero inputs, insufficient balances, insufficient allowances, and failed transfers.
  • Deploy contracts to the selected public testnet.
  • Point Scaffold-ETH at the same network and confirm contract addresses.
  • Deploy the frontend and verify the contract source where supported.

SpeedRun estimates 3–10 hours for the complete challenge. The 50-minute video is an overview and walkthrough, not a replacement for implementing and testing each checkpoint.

A trade changes the reserve ratio. A larger trade relative to pool depth causes a larger movement along the constant-product curve and receives a worse average execution price.

Slippage is the difference between the expected and executed result. A production DEX should let the user define a minimum acceptable output and a deadline. The educational challenge is intentionally smaller and should not be treated as production-ready trading code.

The pricing function retains a small portion of the input in the pool. Fees increase pool value for liquidity providers, but fee logic must be included consistently in previews and contract calculations.

When the external market price changes, arbitrage moves the pool ratio. A liquidity provider may end up with a lower value than simply holding the two assets, even after earning fees.

  • Add minimum-output protection before treating the contract as more than a learning exercise.
  • Follow checks-effects-interactions around external token and ETH transfers.
  • Check every ERC-20 transfer result or use a safe transfer library.
  • Protect initialization from being captured by an unintended caller.
  • Test rounding behavior for very small deposits and withdrawals.
  • Consider reentrancy around ETH withdrawal and token callbacks.
  • Do not use spot reserve ratios as a manipulation-resistant oracle.
  • Expect front-running and sandwich attacks when trades are visible in the public mempool.

For the DEX capstone path:

  1. Implement initialization, pricing, both swap directions, deposit, and withdrawal.
  2. Add focused tests for the invariant, liquidity shares, approvals, and failure paths.
  3. Connect the Scaffold-ETH frontend to every core action.
  4. Add minimum-output and deadline parameters as a security extension.
  5. Deploy only to a testnet and document the limitations of the educational AMM.

Open the current SpeedRun Ethereum DEX challenge

The video also touches on multisig and SVG NFT topics. For this course, focus on the DEX walkthrough and use the current SpeedRun challenge as the implementation source of truth. The video does not publish chapter markers, so the outline above follows the conceptual build sequence rather than exact timestamps.

Module 5: Capstone.