Blockchain and Web3 course Β· Module 8: ERC-20 & Token Creation
ERC-20 Tokens - Gold of the Crypt
In this lesson7
Welcome to the Mint! Atlas here. Today you'll learn about ERC-20 - the standard for creating fungible tokens, the "underground gold" of the Crypt.
What is ERC-20?
ERC-20 is a standard defining the interface for fungible tokens on Ethereum. Every ERC-20 token has identical functions, making integration with wallets and exchanges easy.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ERC-20 STANDARD β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β REQUIRED FUNCTIONS: β
β βββ totalSupply() - total supply β
β βββ balanceOf(address) - address balance β
β βββ transfer(to, amount) - token transfer β
β βββ allowance(owner, spender) - approved for spending β
β βββ approve(spender, amount) - approve spending β
β βββ transferFrom(from, to, amount) - transfer on behalf β
β β
β REQUIRED EVENTS: β
β βββ Transfer(from, to, amount) β
β βββ Approval(owner, spender, amount) β
β β
β OPTIONAL: β
β βββ name() - token name (e.g. "Tether USD") β
β βββ symbol() - symbol (e.g. "USDT") β
β βββ decimals() - decimal places (usually 18) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββPopular ERC-20 Tokens
Token β Symbol β Decimals β Use
ββββββββββββΌβββββββββΌβββββββββββΌββββββββββββββββββ
USDT β USDT β 6 β Stablecoin (USD)
USDC β USDC β 6 β Stablecoin (USD)
DAI β DAI β 18 β Stablecoin (decentralized)
WETH β WETH β 18 β Wrapped Ether
UNI β UNI β 18 β Governance (Uniswap)
LINK β LINK β 18 β Oracle (Chainlink)Interacting with an ERC-20 Token
import { ethers } from "ethers";
const ERC20_ABI = [
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
"function totalSupply() view returns (uint256)",
"function balanceOf(address) view returns (uint256)",
"function transfer(address to, uint256 amount) returns (bool)",
"function approve(address spender, uint256 amount) returns (bool)",
"function allowance(address owner, address spender) view returns (uint256)",
"function transferFrom(address from, address to, uint256 amount) returns (bool)",
"event Transfer(address indexed from, address indexed to, uint256 amount)",
"event Approval(address indexed owner, address indexed spender, uint256 amount)"
];
const provider = new ethers.JsonRpcProvider("https://...");
const usdtAddress = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
const token = new ethers.Contract(usdtAddress, ERC20_ABI, provider);
// Read data
const name = await token.name();
const symbol = await token.symbol();
const decimals = await token.decimals();
const balance = await token.balanceOf("0x...");
console.log(`${name} (${symbol})`);
console.log(`Balance: ${ethers.formatUnits(balance, decimals)}`);Token Transfer
const wallet = new ethers.Wallet(privateKey, provider);
const tokenWithSigner = token.connect(wallet);
// Transfer
const tx = await tokenWithSigner.transfer(
"0x...", // recipient
ethers.parseUnits("100", decimals) // amount
);
await tx.wait();Approve and TransferFrom
// 1. Owner approves (approve)
const approveTx = await tokenWithSigner.approve(
spenderAddress,
ethers.parseUnits("1000", decimals)
);
await approveTx.wait();
// 2. Spender can now use transferFrom
const transferTx = await tokenAsSpender.transferFrom(
ownerAddress,
recipientAddress,
ethers.parseUnits("100", decimals)
);
await transferTx.wait();Creating Your Own Token
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract KryptaCoin is ERC20 {
constructor(uint256 initialSupply) ERC20("Krypta Coin", "KRYPTA") {
_mint(msg.sender, initialSupply * 10**decimals());
}
}Summary
- ERC-20 - fungible token standard
- Functions: transfer, approve, transferFrom
- Interaction with ethers.js
- Decimals and formatting
- Creating your own token
Code for this lesson: index.js
// ERC-20 Standard - basics
class ERC20Token {
constructor(name, symbol, decimals, initialSupply, owner) {
// Token metadata
this._name = name;
this._symbol = symbol;
this._decimals = decimals;
// State
this._totalSupply = BigInt(initialSupply) * BigInt(10 ** decimals);
this._balances = new Map();
this._allowances = new Map();
// Initial mint to owner
this._balances.set(owner, this._totalSupply);
console.log(`Deployed ${name} (${symbol})`);
console.log(` Total Supply: ${this.formatAmount(this._totalSupply)} ${symbol}`);
console.log(` Owner: ${owner}\n`);
}
// === ERC-20 Required Functions ===
name() { return this._name; }
symbol() { return this._symbol; }
decimals() { return this._decimals; }
totalSupply() { return this._totalSupply; }
balanceOf(account) {
return this._balances.get(account) || BigInt(0);
}
transfer(from, to, amount) {
const amountBN = BigInt(amount);
const fromBalance = this.balanceOf(from);
if (fromBalance < amountBN) {
throw new Error("ERC20: transfer amount exceeds balance");
}
this._balances.set(from, fromBalance - amountBN);
this._balances.set(to, this.balanceOf(to) + amountBN);
console.log(`Transfer: ${from.slice(0,8)}... -> ${to.slice(0,8)}...`);
console.log(` Amount: ${this.formatAmount(amountBN)} ${this._symbol}`);
return true;
}
approve(owner, spender, amount) {
if (!this._allowances.has(owner)) {
this._allowances.set(owner, new Map());
}
this._allowances.get(owner).set(spender, BigInt(amount));
console.log(`Approval: ${owner.slice(0,8)}... -> ${spender.slice(0,8)}...`);
console.log(` Amount: ${this.formatAmount(BigInt(amount))} ${this._symbol}`);
return true;
}
allowance(owner, spender) {
return this._allowances.get(owner)?.get(spender) || BigInt(0);
}
transferFrom(spender, from, to, amount) {
const amountBN = BigInt(amount);
const currentAllowance = this.allowance(from, spender);
if (currentAllowance < amountBN) {
throw new Error("ERC20: insufficient allowance");
}
// Decrease allowance
this._allowances.get(from).set(spender, currentAllowance - amountBN);
// Transfer
return this.transfer(from, to, amount);
}
// Helper
formatAmount(amount) {
return (Number(amount) / (10 ** this._decimals)).toLocaleString();
}
}
console.log("=== ERC-20 TOKEN STANDARD ===\n");
// Deploy token
const token = new ERC20Token(
"Atlas Coin",
"ATLAS",
18,
1000000, // 1M tokens
"0xOwner123"
);
// Check balances
console.log("--- Balances ---");
console.log(`Owner: ${token.formatAmount(token.balanceOf("0xOwner123"))} ATLAS`);
console.log(`Alice: ${token.formatAmount(token.balanceOf("0xAlice456"))} ATLAS\n`);
// Transfer
console.log("--- Transfer ---");
token.transfer("0xOwner123", "0xAlice456", "100000000000000000000000"); // 100k
// Approve & TransferFrom (typical flow for DEX)
console.log("\n--- Approve for DEX ---");
token.approve("0xAlice456", "0xUniswapRouter", "50000000000000000000000"); // 50k
console.log("\n--- DEX executes transferFrom ---");
token.transferFrom(
"0xUniswapRouter",
"0xAlice456",
"0xLiquidityPool",
"50000000000000000000000"
);
console.log("\n--- Final Balances ---");
console.log(`Owner: ${token.formatAmount(token.balanceOf("0xOwner123"))} ATLAS`);
console.log(`Alice: ${token.formatAmount(token.balanceOf("0xAlice456"))} ATLAS`);
console.log(`Pool: ${token.formatAmount(token.balanceOf("0xLiquidityPool"))} ATLAS`);
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. ERC-20 is:
2. The transfer(to, amount) function in ERC-20:
These are 2 of 15 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for using approve/transferFrom:
- Code editor
Complete the code for reading token data
- Code editor
Complete the transfer code
- Horizontal ordering
What does the transfer function call look like?
- Click in order
Click the buttons in the correct order to build the Transfer event
- Code editor
Complete the approve code
- Vertical ordering
Arrange the stages of a vesting schedule (token release schedule):
- Click in order
Click the buttons in the correct order to build the balanceOf declaration
- Code editor
Complete the code for checking the balance
- Horizontal ordering
What does the approve function call look like?
- Code editor
Complete the code for the mint function
- Code editor
Complete the code for the burn function
- Vertical ordering
Arrange the steps of the full permit flow:
- Horizontal ordering
What does the permit function call look like?
- Click in order
Click the buttons in the correct order to build the Approval event
- Code editor
Complete the code for checking the allowance
- Vertical ordering
Arrange the steps for staking ERC-20 tokens:
- Code editor
Complete the code for checking the maximum supply
- Horizontal ordering
What does the mint function declaration look like in Solidity?
- Click in order
Click the buttons in the correct order to check the contract's balance
- Code editor
Complete the pausable code
- Vertical ordering
Arrange the process of releasing tokens in vesting:
- Code editor
Complete the snapshot code
- Horizontal ordering
What does emitting the Approval event look like?
- Vertical ordering
Arrange the steps for burning tokens (burn):
Tasks after this lesson
- QuestionQuiz: ERC-20
- QuestionQuiz: transfer()
- QuestionQuiz: approve()
- QuestionQuiz: transferFrom()
- QuestionQuiz: decimals
- QuestionQuiz: USDT decimals
- QuestionQuiz: allowance()
- Put in orderSorting: Approve + transferFrom flow
- Coding taskGap: Reading token data
- Coding taskGap: Token transfer
- Put in orderHorizontal sorting: transfer syntax
- Click in orderSorting: Building the Transfer event
- Coding taskGap: Approve flow
- Put in orderSorting: Vesting schedule
- Click in orderSorting: Building the ERC-20 interface
- Coding taskGap: Checking the balance
- Put in orderHorizontal sorting: approve syntax
- QuestionQuiz: totalSupply()
- QuestionQuiz: permit()
- QuestionQuiz: EIP-2612 deadline
- QuestionQuiz: mint vs transfer
- QuestionQuiz: cap - maximum supply
- QuestionQuiz: snapshots
- QuestionQuiz: wrapped tokens
- QuestionQuiz: fee on transfer
- Coding taskGap: The mint function
- Coding taskGap: The burn function
- Put in orderSorting: Full permit flow
- Put in orderHorizontal sorting: permit call
- Click in orderSorting: Building the Approval event
- Coding taskGap: Checking the allowance
- Put in orderSorting: Staking deposit
- Coding taskGap: Implementing the cap
- Put in orderHorizontal sorting: mint function
- Click in orderSorting: balanceOf + transfer
- Coding taskGap: Pausable toggle
- Put in orderSorting: Token vesting release
- Coding taskGap: Snapshot mechanism
- Put in orderHorizontal sorting: Approval event
- Put in orderSorting: Burning process
- Project to submitSend your project to the mentor
- ConversationEnd of Module 8