Skip to content

18. Challenge 2: Token Vendor

Challenge 2 builds a Token Vendor: a contract that sells an ERC-20 token for ETH and buys it back. It’s the clearest hands-on lesson in the approve / transferFrom pattern from Module 2, and it’s one of the two suggested shapes for the Module 5 capstone — so it’s worth doing even though it’s listed as extension practice.

  • A vendor contract — holds a supply of an ERC-20 and a price. buyTokens takes ETH (a payable function) and sends back tokens; sellTokens does the reverse. It’s an automated, trustless kiosk.
  • The approve → transferFrom dance — to sell tokens back, the user first calls approve on the token contract to authorize the vendor, then the vendor calls transferFrom to pull the tokens. Two transactions, two contracts — this two-step is the single most important ERC-20 interaction to internalize, because every DEX uses it.
  • Why approval is separate — a contract can’t take your tokens without permission; the allowance you grant is that permission. Understanding this also explains a whole class of wallet-drain scams (over-broad approvals).
  • Pricing and ETH handling — the vendor computes token amounts from the ETH sent and must handle payments and payouts carefully — again foreshadowing Module 4 security.
  • Composing two contracts — the vendor and the token are separate contracts that call each other, the real-world version of the composition idea from lesson 12.
  • Expecting a one-click sell. Selling needs the approve transaction first; skipping it makes transferFrom revert. This confuses almost everyone the first time.
  • Granting an unlimited allowance without thinking. It’s convenient but is exactly the pattern attackers abuse — a good habit to question now.
  • Getting the buy/sell price math or units (wei vs. token decimals) wrong, so amounts come out off by orders of magnitude.
  • Why does selling tokens back to the vendor require two transactions?
  • What does approve actually grant, and to whom?
  • How is a Token Vendor a simplified version of what a DEX does (Module 5)?

Module 3 extension and Module 5 capstone support.