Study notesWeek 7: Tokens: ERC-20, ERC-721, ERC-1155
Week 7 / Blockchain from zero

Tokens

Week 7 · Blockchain

What You Can Do By The End

Where we left off

Recap Of Week 6

Week 7 · Blockchain

A Token Is A Record In A Contract

mapping(address => uint256) public balanceOf;

// balanceOf[alice] == 50
// means: alice owns 50 units
Week 7 · Blockchain

Why Standards Exist

Fungible tokens

ERC-20 At A Glance

Week 7 · Blockchain

Decimals And Integers

05101520181886ETHDAIWBTCUSDC
// 1.5 tokens with 18 decimals
uint256 amount = 15 * 10**17;
// stored as 1500000000000000000
Week 7 · Blockchain

A Minimal ERC-20, Part One

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract MiniToken {
    string public name = "Mini";
    uint8 public constant decimals = 18;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    event Transfer(address indexed from, address indexed to, uint256 value);
    constructor() { totalSupply = 1000 * 10**18; balanceOf[msg.sender] = totalSupply; }
}
Week 7 · Blockchain

A Minimal ERC-20, Part Two

function transfer(address to, uint256 value) external returns (bool) {
    require(balanceOf[msg.sender] >= value, "balance too low");
    balanceOf[msg.sender] -= value;
    balanceOf[to] += value;
    emit Transfer(msg.sender, to, value);
    return true;
}
Week 7 · Blockchain

Approve And transferFrom

// 1. you:     token.approve(market, 100)
// 2. market:  token.transferFrom(you, shop, 100)
// allowance[you][market] goes 100 -> 0
Non-fungible

ERC-721: Unique Tokens

Week 7 · Blockchain

ERC-1155: Many Types, One Contract

// id 1: gold coin   (supply 1,000,000)
// id 2: sword       (supply 500)
// id 3: royal crown (supply 1)
Week 7 · Blockchain

Choosing A Standard

NeedStandard
Interchangeable unitsERC-20
One of a kind itemsERC-721
Many types in one contractERC-1155
Design

Token Design Questions

Week 7 · Blockchain

Build It Safely With OpenZeppelin

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract ClassToken is ERC20 {
    constructor(uint256 initial) ERC20("ClassToken", "CLS") {
        _mint(msg.sender, initial * 10**decimals());
    }
}
Week 7 · Blockchain

Recap

Week 7 · Blockchain

Next Week: DeFi

Week 7 · Blockchain

Questions And Exercise