Bird
Raised Fist0
Blockchain / Solidityprogramming~10 mins

ERC-20 implementation in Blockchain / Solidity

Choose your learning style10 modes available
Introduction

ERC-20 is a standard way to create tokens on the Ethereum blockchain. It helps different tokens work well together.

When you want to create your own digital currency or token.
When you want your token to be compatible with wallets and exchanges.
When you want to manage token balances and transfers easily.
When you want to allow others to spend tokens on your behalf.
When you want to build decentralized apps that use tokens.
Syntax
Blockchain / Solidity
pragma solidity ^0.8.0;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract MyToken is IERC20 {
    string public name = "MyToken";
    string public symbol = "MTK";
    uint8 public decimals = 18;
    uint256 private _totalSupply;

    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;

    constructor(uint256 initialSupply) {
        _totalSupply = initialSupply * 10 ** decimals;
        _balances[msg.sender] = _totalSupply;
        emit Transfer(address(0), msg.sender, _totalSupply);
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    function transfer(address to, uint256 amount) public override returns (bool) {
        require(to != address(0), "Transfer to zero address");
        require(_balances[msg.sender] >= amount, "Not enough balance");

        _balances[msg.sender] -= amount;
        _balances[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        require(spender != address(0), "Approve to zero address");

        _allowances[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        require(to != address(0), "Transfer to zero address");
        require(_balances[from] >= amount, "Not enough balance");
        require(_allowances[from][msg.sender] >= amount, "Allowance exceeded");

        _balances[from] -= amount;
        _balances[to] += amount;
        _allowances[from][msg.sender] -= amount;

        emit Transfer(from, to, amount);
        return true;
    }
}

This code uses Solidity version 0.8.0 or higher for safety features.

The contract implements the IERC20 interface to follow the ERC-20 standard.

Examples
This shows a minimal contract that promises to follow ERC-20 but needs full code.
Blockchain / Solidity
contract SimpleToken is IERC20 {
    // minimal implementation
}
This function returns how many tokens an address owns.
Blockchain / Solidity
function balanceOf(address account) public view override returns (uint256) {
    return _balances[account];
}
This function moves tokens from the sender to another address.
Blockchain / Solidity
function transfer(address to, uint256 amount) public override returns (bool) {
    require(_balances[msg.sender] >= amount, "Not enough balance");
    _balances[msg.sender] -= amount;
    _balances[to] += amount;
    emit Transfer(msg.sender, to, amount);
    return true;
}
Sample Program

This complete contract creates a token named MyToken with symbol MTK. The creator gets all tokens at the start. It supports checking balances, transferring tokens, approving others to spend tokens, and transferring tokens on behalf of others.

Blockchain / Solidity
pragma solidity ^0.8.0;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract MyToken is IERC20 {
    string public name = "MyToken";
    string public symbol = "MTK";
    uint8 public decimals = 18;
    uint256 private _totalSupply;

    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;

    constructor(uint256 initialSupply) {
        _totalSupply = initialSupply * 10 ** decimals;
        _balances[msg.sender] = _totalSupply;
        emit Transfer(address(0), msg.sender, _totalSupply);
    }

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    function transfer(address to, uint256 amount) public override returns (bool) {
        require(to != address(0), "Transfer to zero address");
        require(_balances[msg.sender] >= amount, "Not enough balance");

        _balances[msg.sender] -= amount;
        _balances[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public override returns (bool) {
        require(spender != address(0), "Approve to zero address");

        _allowances[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        require(to != address(0), "Transfer to zero address");
        require(_balances[from] >= amount, "Not enough balance");
        require(_allowances[from][msg.sender] >= amount, "Allowance exceeded");

        _balances[from] -= amount;
        _balances[to] += amount;
        _allowances[from][msg.sender] -= amount;

        emit Transfer(from, to, amount);
        return true;
    }
}
OutputSuccess
Important Notes

Always check for zero address to avoid sending tokens to nowhere.

Events like Transfer and Approval help wallets and apps track token movements.

Decimals define how divisible your token is; 18 is common like Ether.

Summary

ERC-20 is a standard for tokens on Ethereum.

It defines functions to check balances, transfer tokens, and approve spending.

Following ERC-20 makes your token work with many wallets and exchanges.

Practice

(1/5)
1. What is the main purpose of the balanceOf function in an ERC-20 token contract?
easy
A. To approve another address to spend tokens
B. To transfer tokens from one address to another
C. To check the token balance of a specific address
D. To mint new tokens to an address

Solution

  1. Step 1: Understand the role of balanceOf

    The balanceOf function returns how many tokens a given address owns.
  2. Step 2: Compare with other functions

    Functions like transfer move tokens, approve allows spending, and minting creates tokens. These are different from checking balance.
  3. Final Answer:

    To check the token balance of a specific address -> Option C
  4. Quick Check:

    balanceOf = check balance [OK]
Hint: balanceOf always returns token count for an address [OK]
Common Mistakes:
  • Confusing balanceOf with transfer function
  • Thinking approve checks balances
  • Mixing minting with balance checking
2. Which of the following is the correct Solidity function signature for transferring tokens in an ERC-20 contract?
easy
A. function transfer(address to, uint256 amount) public returns (bool);
B. function transfer(uint256 amount, address to) public returns (bool);
C. function transfer(address to) public returns (uint256);
D. function transfer(address from, address to, uint256 amount) public;

Solution

  1. Step 1: Recall ERC-20 transfer signature

    The standard transfer function takes the recipient address first, then the amount, and returns a boolean.
  2. Step 2: Check each option

    function transfer(address to, uint256 amount) public returns (bool); matches the standard: transfer(address to, uint256 amount) public returns (bool). Others have wrong parameter order, missing return, or extra parameters.
  3. Final Answer:

    function transfer(address to, uint256 amount) public returns (bool); -> Option A
  4. Quick Check:

    transfer(to, amount) returns bool [OK]
Hint: transfer always has (address to, uint256 amount) and returns bool [OK]
Common Mistakes:
  • Swapping parameter order
  • Omitting return type
  • Adding extra parameters not in standard
3. Given this snippet from an ERC-20 contract:
mapping(address => uint256) balances;

function transfer(address to, uint256 amount) public returns (bool) {
    if (balances[msg.sender] >= amount) {
        balances[msg.sender] -= amount;
        balances[to] += amount;
        return true;
    }
    return false;
}

What will transfer return if msg.sender has 50 tokens and tries to send 60 tokens?
medium
A. true
B. Returns the remaining balance
C. Throws an error
D. false

Solution

  1. Step 1: Check balance condition

    The function checks if balances[msg.sender] is at least amount. Here, 50 < 60, so condition fails.
  2. Step 2: Determine function return

    Since condition fails, the function skips token transfer and returns false.
  3. Final Answer:

    false -> Option D
  4. Quick Check:

    Insufficient balance returns false [OK]
Hint: Transfer returns false if sender lacks enough tokens [OK]
Common Mistakes:
  • Assuming transfer throws error on insufficient balance
  • Thinking it returns true anyway
  • Confusing return value with balance amount
4. Identify the bug in this ERC-20 approve function snippet:
mapping(address => mapping(address => uint256)) allowances;

function approve(address spender, uint256 amount) public returns (bool) {
    allowances[msg.sender][spender] = amount;
    return true;
}
medium
A. No bug, function is correct
B. Should emit an Approval event after setting allowance
C. Should check if amount is less than balance
D. Should decrease allowance instead of setting it

Solution

  1. Step 1: Review ERC-20 approve requirements

    The standard requires emitting an Approval event after changing allowance for transparency.
  2. Step 2: Check function code

    The function sets allowance but does not emit the Approval event, missing a key part of the standard.
  3. Final Answer:

    Should emit an Approval event after setting allowance -> Option B
  4. Quick Check:

    approve must emit Approval event [OK]
Hint: approve must emit Approval event to follow standard [OK]
Common Mistakes:
  • Ignoring event emission
  • Checking balance in approve (not required)
  • Decreasing allowance instead of setting
5. You want to add a feature to your ERC-20 token that prevents transfers when the contract is paused. Which is the best way to implement this without breaking the ERC-20 standard?
hard
A. Add a paused boolean and require it false in transfer and transferFrom functions
B. Remove the transfer function and replace it with a new function that checks pause
C. Add a new function pauseTransfer that users must call before transferring
D. Modify the balanceOf function to return zero when paused

Solution

  1. Step 1: Understand pause feature integration

    To pause transfers, the contract needs a state variable like paused and checks in transfer functions.
  2. Step 2: Check ERC-20 compliance

    Removing or renaming transfer breaks the standard. Changing balanceOf output breaks expected behavior. Adding a separate function for pause is not standard.
  3. Final Answer:

    Add a paused boolean and require it false in transfer and transferFrom functions -> Option A
  4. Quick Check:

    Pause by require(!paused) in transfer functions [OK]
Hint: Use a paused flag and require it false in transfer methods [OK]
Common Mistakes:
  • Removing or renaming standard functions
  • Changing balanceOf behavior
  • Adding extra steps users must call
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard