18. Challenge 2: Token Vendor
Overview
Section titled “Overview”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.
Key concepts
Section titled “Key concepts”- A vendor contract — holds a supply of an ERC-20 and a price.
buyTokenstakes ETH (apayablefunction) and sends back tokens;sellTokensdoes the reverse. It’s an automated, trustless kiosk. - The approve → transferFrom dance — to sell tokens back, the user first calls
approveon the token contract to authorize the vendor, then the vendor callstransferFromto 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.
Common pitfalls
Section titled “Common pitfalls”- Expecting a one-click sell. Selling needs the
approvetransaction first; skipping it makestransferFromrevert. 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.
Check yourself
Section titled “Check yourself”- Why does selling tokens back to the vendor require two transactions?
- What does
approveactually grant, and to whom? - How is a Token Vendor a simplified version of what a DEX does (Module 5)?
Watch the Video
Section titled “Watch the Video”
Challenge 2: Token Vendor
Video credit: Austin Griffith · Duration: 20 minutes
Course Position
Section titled “Course Position”Module 3 extension and Module 5 capstone support.
