How to Write an ERC20 Token
ERC-20 introduced the standard for Fungible Tokens by making each Token in a set exactly the same (in type and value) as the other Tokens in that set. For example, just as all CORE functions the same and is worth the same, ERC-20 Tokens in a set all have the same functions and value.
Example functionalities ERC-20 provides:
- Transfer tokens from one account to another
- Get the current token balance of an account
- Get the total supply of the token available on the network
- Approve whether an amount of tokens from an account can be spent by a third-party account
An ERC-20 compatible token must implement the following methods and events.
function name() public view returns (string)
function symbol() public view returns (string)
function decimals() public view returns (uint8)
function totalSupply() public view returns (uint256)
function balanceOf(address _owner) public view returns (uint256 balance)
function transfer(address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
function allowance(address _owner, address _spender) public view returns (uint256 remaining)
event Transfer(address indexed _from, address indexed _to, uint256 _value)
event Approval(address indexed _owner, address indexed _spender, uint256 _value)
ERC-20 is a simple protocol. However, there could be great security issues if we do not implement the smart contract carefully. There has been a number of exploits of ERC20 contracts since the protocol was introduced.
We recommend using the OpenZeppelin ERC-20 implementation for your project. The source code can be found at ERC20.sol.
1. Install OpenZeppelin smart contracts in your project
npm install @openzeppelin/contracts
2. Once installed, you can use the contracts in the library by importing them
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract GLDToken is ERC20 {
constructor(uint256 initialSupply) ERC20("Gold", "GLD") {
_mint(msg.sender, initialSupply);
}
}