Blockchain and Web3 course Β· Module 8: ERC-20 & Token Creation

ERC-20 Tokens - Gold of the Crypt

3 min read Β·
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)                   β”‚
β”‚                                                                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
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. 1. ERC-20 is:

  2. 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):

  1. QuestionQuiz: ERC-20
  2. QuestionQuiz: transfer()
  3. QuestionQuiz: approve()
  4. QuestionQuiz: transferFrom()
  5. QuestionQuiz: decimals
  6. QuestionQuiz: USDT decimals
  7. QuestionQuiz: allowance()
  8. Put in orderSorting: Approve + transferFrom flow
  9. Coding taskGap: Reading token data
  10. Coding taskGap: Token transfer
  11. Put in orderHorizontal sorting: transfer syntax
  12. Click in orderSorting: Building the Transfer event
  13. Coding taskGap: Approve flow
  14. Put in orderSorting: Vesting schedule
  15. Click in orderSorting: Building the ERC-20 interface
  16. Coding taskGap: Checking the balance
  17. Put in orderHorizontal sorting: approve syntax
  18. QuestionQuiz: totalSupply()
  19. QuestionQuiz: permit()
  20. QuestionQuiz: EIP-2612 deadline
  21. QuestionQuiz: mint vs transfer
  22. QuestionQuiz: cap - maximum supply
  23. QuestionQuiz: snapshots
  24. QuestionQuiz: wrapped tokens
  25. QuestionQuiz: fee on transfer
  26. Coding taskGap: The mint function
  27. Coding taskGap: The burn function
  28. Put in orderSorting: Full permit flow
  29. Put in orderHorizontal sorting: permit call
  30. Click in orderSorting: Building the Approval event
  31. Coding taskGap: Checking the allowance
  32. Put in orderSorting: Staking deposit
  33. Coding taskGap: Implementing the cap
  34. Put in orderHorizontal sorting: mint function
  35. Click in orderSorting: balanceOf + transfer
  36. Coding taskGap: Pausable toggle
  37. Put in orderSorting: Token vesting release
  38. Coding taskGap: Snapshot mechanism
  39. Put in orderHorizontal sorting: Approval event
  40. Put in orderSorting: Burning process
  41. Project to submitSend your project to the mentor
  42. ConversationEnd of Module 8