๐ฉ Challenge: ๐ต Token Vendor ๐ค

Build a custom token on the ERC20 standard
Learn how to perform secure contract-to-contract token transfers
Design and build a token vending machine that can buy and sell custom tokens
See how to confirm token balances onchain and offchain
๐ค Smart contracts are kind of like "always on" vending machines that anyone can access. Let's make a decentralized, digital currency. Then, let's build an unstoppable vending machine that will buy and sell the currency. We'll learn about the "approve" pattern for ERC20s and how contract to contract interactions work.
๐ต Create YourToken.sol smart contract that inherits the ERC20 token standard from OpenZeppelin. Set your token to _mint() 1000 (* 10 ** 18) tokens to the msg.sender. Then create a Vendor.sol contract that sells your token using a payable buyTokens() function.
๐ Edit the frontend that invites the user to input an amount of tokens they want to buy. We'll display a preview of the amount of ETH it will cost with a confirm button.
๐ It will be important to verify your token's source code in the block explorer after you deploy. Supporters will want to be sure that it has a fixed supply and you can't just mint more.
๐ The final deliverable is an app that lets users purchase your ERC20 token, transfer it, and sell it back to the vendor. Deploy your contracts on your public chain of choice and then yarn vercel your app to a public web server. Submit the url on SpeedRunEthereum.com!
๐ฌ Meet other builders working on this challenge and get help in the Challenge Telegram!
Checkpoint 0: ๐ฆ Environment ๐
Before you begin, you need to install the following tools:
- Node (>= v20.18.3)
- Yarn (v1 or v2+)
- Git
Then download the challenge to your computer and install dependencies by running:
npx create-eth@1.0.2 -e challenge-token-vendor challenge-token-vendor
cd challenge-token-vendor
in the same terminal, start your local network (a blockchain emulator in your computer):
yarn chain
in a second terminal window, ๐ฐ deploy your contract (locally):
cd challenge-token-vendor
yarn deploy
in a third terminal window, start your ๐ฑ frontend:
cd challenge-token-vendor
yarn start
๐ฑ Open http://localhost:3000 to see the app.
๐ฉโ๐ป Rerun
yarn deploy --resetwhenever you want to deploy new contracts to the frontend, update your current contracts with changes, or re-deploy it to get a fresh contract address.
โ ๏ธ We have disabled AI in Cursor and VSCode and highly suggest that you do not enable it so you can focus on the challenge, do everything by yourself, and hence better understand and remember things. If you are using another IDE, please disable AI yourself.
๐ง If you are a vibe-coder and don't care about understanding the syntax of the code used and just want to understand the general takeaways, you can re-enable AI by:
- Cursor: remove
*from.cursorignorefile - VSCode: set
chat.disableAIFeaturestofalsein.vscode/settings.jsonfile
Checkpoint 1: ๐ตYour Token ๐ต
๐ฉโ๐ป Edit
YourToken.solto inherit the ERC20 token standard from OpenZeppelin.
Mint 1000 (* 10 ** 18) to your frontend address using the
constructor().
(Your frontend address is the address in the top right of http://localhost:3000)
You can
yarn deploy --resetto deploy your contract until you get it right.
๐ฅ Goals
- Can you check the
balanceOf()your frontend address in theDebug Contractstab? (YourToken contract) - Can you
transfer()your token to another account and check that account'sbalanceOf?
๐ฌ Hint: Use an incognito window to create a new address and try sending to that new address. Can use the
transfer()function in theDebug Contractstab.
Checkpoint 2: โ๏ธ Vendor ๐ค
๐ฉโ๐ป Edit the
Vendor.solcontract with a payablebuyTokens()function
Use a price variable named tokensPerEth set to 100:
uint256 public constant tokensPerEth = 100;
๐ The
buyTokens()function inVendor.solshould usemsg.valueandtokensPerEthto calculate an amount of tokens toyourToken.transfer()tomsg.sender.
๐ Emit event
BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens)when tokens are purchased.
Edit packages/hardhat/deploy/01_deploy_vendor.ts to deploy the Vendor (uncomment Vendor deploy lines).
Uncomment the Buy Tokens sections in packages/nextjs/app/token-vendor/page.tsx to show the UI to buy tokens on the Token Vendor tab.
๐ฅ Goals
- When you try to buy tokens from the vendor, you should get an error: 'ERC20InsufficientBalance'
โ ๏ธ This is because the Vendor contract doesn't have any YourTokens yet!
โ๏ธ Side Quest: send tokens from your frontend address to the Vendor contract address and then try to buy them.
โ๏ธ We can't hard code the vendor address like we did above when deploying to the network because we won't know the vendor address at the time we create the token contract.
โ๏ธ So instead, edit
YourToken.solto mint the tokens to themsg.sender(deployer) in the constructor().
โ๏ธ Then, edit
deploy/01_deploy_vendor.tsto transfer 1000 tokens to vendor address.
await yourToken.transfer(vendorAddress, hre.ethers.parseEther("1000"));
๐ Look in
packages/nextjs/app/token-vendor/page.tsxfor code to uncomment to display the Vendor ETH and Token balances.
You can
yarn deploy --resetto deploy your contract until you get it right.
๐ฅ Goals
- Does the
Vendoraddress start with abalanceOf1000 inYourTokenon theDebug Contractstab? - Can you buy 10 tokens for 0.1 ETH?
- Can you transfer tokens to a different account?
โ ๏ธ Uncomment the import of Ownable.sol contract!
๐ Edit
Vendor.solto inherit Ownable.
contract Vendor is Ownable {
๐ Change constructor of
Vendor.solto:
constructor(address tokenAddress) Ownable(msg.sender) {
In deploy/01_deploy_vendor.ts you will need to call transferOwnership() on the Vendor to make your frontend address the owner:
await vendor.transferOwnership("**YOUR FRONTEND ADDRESS**");
๐ฅ Goals
- Is your frontend address the
ownerof theVendor?
๐ Finally, add a
withdraw()function inVendor.solthat lets the owner withdraw all the ETH from the vendor contract.
๐ฅ Goals
- Can only the
ownerwithdraw the ETH from theVendor?
โ๏ธ Side Quests
- What if you minted 2000 and only sent 1000 to the
Vendor?
Checkpoint 3: ๐ค Vendor Buyback ๐คฏ
๐ฉโ๐ซ The hardest part of this challenge is to build your Vendor to buy the tokens back.
๐ง The reason why this is hard is the approve() pattern in ERC20s.
๐ First, the user has to call approve() on the YourToken contract, approving the Vendor contract address to take some amount of tokens.
๐คจ Then, the user makes a second transaction to the Vendor contract to sellTokens(uint256 amount).
๐ค The Vendor should call yourToken.transferFrom(msg.sender, address(this), theAmount) and if the user has approved the Vendor correctly, tokens should transfer to the Vendor and ETH should be sent to the user.
๐ Edit
Vendor.soland add asellTokens(uint256 amount)function!
โ ๏ธ You will need extra UI for calling approve() before calling sellTokens(uint256 amount).
๐จ Use the Debug Contracts tab to call the approve and sellTokens() at first but then...
๐ Look in the packages/nextjs/app/token-vendor/page.tsx for the extra approve/sell UI to uncomment!
๐ฅ Goal
- Can you sell tokens back to the vendor?
- Do you receive the right amount of ETH for the tokens?
โ๏ธ Side Quests
-
Should we disable the
ownerwithdraw to keep liquidity in theVendor? -
It would be a good idea to display Sell Token Events. Create an event
SellTokens(address seller, uint256 amountOfTokens, uint256 amountOfETH)andemitit in yourVendor.soland uncommentSellTokens Eventssection in yourpackages/nextjs/app/events/page.tsxto update your frontend.
โ ๏ธ Test it!
- Now is a good time to run
yarn testto run the automated testing function. It will test that you hit the core checkpoints. You are looking for all green checkmarks and passing tests!
Checkpoint 4: ๐พ Deploy your contracts! ๐ฐ
๐ก Edit the defaultNetwork to your choice of public EVM networks in packages/hardhat/hardhat.config.ts
๐ You will need to generate a deployer address using yarn generate This creates a mnemonic and saves it locally.
๐ฉโ๐ Use yarn account to view your deployer account balances.
โฝ๏ธ You will need to send ETH to your deployer address with your wallet, or get it from a public faucet of your chosen network.
๐ Run yarn deploy to deploy your smart contract to a public network (selected in hardhat.config.ts)
๐ฌ Hint: You can set the
defaultNetworkinhardhat.config.tstosepoliaoroptimismSepoliaOR you canyarn deploy --network sepoliaoryarn deploy --network optimismSepolia.
Checkpoint 5: ๐ข Ship your frontend! ๐
โ๏ธ Edit your frontend config in packages/nextjs/scaffold.config.ts to change the targetNetwork to chains.sepolia (or chains.optimismSepolia if you deployed to OP Sepolia)
๐ป View your frontend at http://localhost:3000 and verify you see the correct network.
๐ก When you are ready to ship the frontend app...
๐ฆ Run yarn vercel to package up your frontend and deploy.
You might need to log in to Vercel first by running
yarn vercel:login. Once you log in (email, GitHub, etc), the default options should work.
If you want to redeploy to the same production URL you can run
yarn vercel --prod. If you omit the--prodflag it will deploy it to a preview/test URL.
Follow the steps to deploy to Vercel. It'll give you a public URL.
๐ฆ Since we have deployed to a public testnet, you will now need to connect using a wallet you own or use a burner wallet. By default ๐ฅ
burner walletsare only available onhardhat. You can enable them on every chain by settingonlyLocalBurnerWallet: falsein your frontend config (scaffold.config.tsinpackages/nextjs/)
Configuration of Third-Party Services for Production-Grade Apps.
By default, ๐ Scaffold-ETH 2 provides predefined API keys for popular services such as Alchemy and Etherscan. This allows you to begin developing and testing your applications more easily, avoiding the need to register for these services. This is great to complete your SpeedRunEthereum.
For production-grade applications, it's recommended to obtain your own API keys (to prevent rate limiting issues). You can configure these at:
-
๐ท
ALCHEMY_API_KEYvariable inpackages/hardhat/.envandpackages/nextjs/.env.local. You can create API keys from the Alchemy dashboard. -
๐
ETHERSCAN_API_KEYvariable inpackages/hardhat/.envwith your generated API key. You can get your key here.
๐ฌ Hint: It's recommended to store env's for nextjs in Vercel/system env config for live apps and use .env.local for local testing.
Checkpoint 6: ๐ Contract Verification
Run the yarn verify --network your_network command to verify your contracts on etherscan ๐ฐ
๐ You may see an address for both YourToken and Vendor. You will want the Vendor address.
๐ Search this address on Sepolia Etherscan (or Optimism Sepolia Etherscan if you deployed to OP Sepolia) to get the URL you submit to ๐โโ๏ธSpeedRunEthereum.com.
๐ Head to your next challenge here.
๐ฌ Problems, questions, comments on the stack? Post them to the ๐ scaffold-eth developers chat
You're viewing this challenge as a guest. Want to start building your onchain portfolio?
Connect your wallet and register to unlock the full Speedrun Ethereum experience.