31. SpeedRun Challenge 4: DEX
Overview
Section titled “Overview”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.
Video and Challenge Outline
Section titled “Video and Challenge Outline”1. DEX Architecture
Section titled “1. DEX Architecture”- Contrast an order-book exchange with an automated market maker.
- Identify the two assets in the pool: ETH and the
$BALERC-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.
2. Pool Initialization and Reserves
Section titled “2. Pool Initialization and Reserves”- 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
transferFromrequires token approval before initialization. - Account for the fact that
address(this).balancealready includesmsg.valueduring a payable call.
Key idea: the first liquidity provider establishes both the starting reserves and the initial market price.
3. Constant-Product Pricing
Section titled “3. Constant-Product Pricing”The challenge uses the constant-product invariant:
x * y = kxandyare 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.
4. ETH-to-Token and Token-to-ETH Swaps
Section titled “4. ETH-to-Token and Token-to-ETH Swaps”- Implement
ethToToken()for payable ETH input and ERC-20 output. - Compute the pre-swap ETH reserve by subtracting
msg.valuefrom the current balance. - Implement
tokenToEth(uint256 tokenInput)with balance and allowance checks. - Pull ERC-20 input with
transferFrombefore sending ETH output. - Use a checked low-level
callfor 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.
5. Liquidity Provider Accounting
Section titled “5. Liquidity Provider Accounting”- 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.
6. Frontend Interaction
Section titled “6. Frontend Interaction”- 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.
7. Testing, Deployment, and Verification
Section titled “7. Testing, Deployment, and Verification”- 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.
AMM Concepts to Explain
Section titled “AMM Concepts to Explain”Price Impact
Section titled “Price Impact”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
Section titled “Slippage”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.
Impermanent Loss
Section titled “Impermanent Loss”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.
Security Review
Section titled “Security Review”- 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.
Capstone Application
Section titled “Capstone Application”For the DEX capstone path:
- Implement initialization, pricing, both swap directions, deposit, and withdrawal.
- Add focused tests for the invariant, liquidity shares, approvals, and failure paths.
- Connect the Scaffold-ETH frontend to every core action.
- Add minimum-output and deadline parameters as a security extension.
- Deploy only to a testnet and document the limitations of the educational AMM.
Watch the Video
Section titled “Watch the Video”Video credit: Austin Griffith · Duration: 50 minutes
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.
