
Lesson 3: Standard Protocols and Composability
Learning goals: understand ERC-20, implement a token contract, and deploy and interact with it using Remix.
Previous lesson
Lesson outline
1. ERC-20
2. Remix
- (TBD) Hands-on assignment: issue your first meme coin
1. ERC-20
ERC-20 is used to issue tokens. It is a protocol.
At the time, there were more and more projects on Ethereum, and anyone could issue a token, but every contract wrote balance queries, transfers, and approvals differently, so wallets, exchanges, and protocols had a hard time integrating them in a uniform way.
So the community proposed ERC-20, specifying a standard interface for fungible tokens, so that different tokens could be recognized and used consistently by the ecosystem.
Interface
Interface definition
The ERC-20 interface definition specifies the minimum set of properties and methods that need to be implemented when you implement ERC-20.
Very simple, right?
Create your own token
openzeppelin-contracts already has a ready-made abstract contract. You only need to inherit it to get a token with a complete set of default features.
Write a complete ERC-20 from scratch
Practice Solidity a bit.
Below, we will write an ERC-20 token contract by hand, step by step.
You can first think of ERC-20 as three parts:
A balance system: who has how many tokens
An allowance system: who allows whom to spend how many tokens
A standard interface: how others interact with this token
I. First write the contract header
First put up the outermost layer of the contract:
What this part does
pragma solidity ^0.8.0;
Specifies the Solidity compiler version
import "../token/ERC20/IERC20.sol";
Imports the ERC-20 interface
contract SimpleERC20 is IERC20
Means this contract is to implement the functions required by the ERC-20 standard
In other words, since it says it is an IERC20, it has to implement all the methods specified in the interface.
II. First define the state variables
The core of an ERC-20 token is “storing data”. First write out the data that need to be saved.
1. _totalSupply
Represents the total number of tokens.
It records how many tokens there are in the whole system.
2. _balances
Represents each address’s balance.
For example:
This means the alice address has 100 tokens.
3. _allowances
Represents allowance relationships.
Its meaning is:
The first-level address: the token owner
The second-level address: the authorized spender
uint256: the allowance
For example:
This means dex may spend at most 500 tokens from alice.
4. _name
Represents the token name.
For example "My Token".
5. _symbol
Represents the token symbol.
For example "MTK".
6. _decimals
Represents the display precision.
ERC-20 tokens are usually set to 18.
III. Write the constructor
The constructor runs when the contract is deployed, and is used to complete initialization.
What the constructor does
1. Set the name
Save the name passed in at deployment.
2. Set the symbol
Save the short name passed in at deployment.
3. Set the decimals
Set the token’s display precision to 18.
4. Set the total supply
The total number of tokens equals the initial issuance.
5. Give the initial tokens to the deployer
The person who deploys the contract receives the entire initial token supply at the start.
6. Emit a Transfer event
In ERC-20, a transfer from the zero address to some address means minting tokens.
IV. Implement totalSupply
Start with the simplest read-only function.
What it does
Returns the current total number of tokens.
V. Implement balanceOf
What it does
Takes an address and returns the number of tokens that address holds.
VI. Implement allowance
What it does
Queries the remaining allowance that owner has authorized for spender.
VII. Implement the metadata functions
These functions are used to return basic information about the token.
1. name
Returns the token name.
2. symbol
Returns the token’s short name.
3. decimals
Returns the token’s precision.
VIII. First write the internal transfer function _transfer
Before writing the external transfer, first write the real transfer logic as an internal function.
What _transfer does
1. Check that the sender address cannot be the zero address
2. Check that the recipient address cannot be the zero address
3. Read the sender’s balance
4. Check whether the balance is sufficient
5. Subtract from the sender’s balance
6. Add to the recipient’s balance
7. Emit a transfer event
IX. Implement transfer
Once you have _transfer, the external transfer function is very simple.
What it does
Means “the caller transfers their own tokens to someone else”.
Here the sender is fixed as msg.sender.
X. First write the internal approve function _approve
As with transfers, first get the internal logic in place.
What _approve does
1. Check that owner cannot be the zero address
2. Check that spender cannot be the zero address
3. Record the allowance
4. Emit an approval event
XI. Implement approve
What it does
Means “the caller authorizes spender to spend at most this many of their tokens”.
Note:
approve does not transfer tokens
It only records an allowance
XII. First write _spendAllowance
Before implementing transferFrom, first split out the logic for “consuming an allowance”.
What _spendAllowance does
1. Read the current allowance
2. Check whether it is an unlimited allowance
If the allowance value is the maximum uint256, that usually means an “unlimited allowance”, and in that case it is not decremented.
3. Check whether the allowance is sufficient
4. Decrement the allowance
XIII. Implement transferFrom
What it does
Means “the caller, based on an allowance, transfers tokens out of the from account to to”.
The execution flow is:
Check and decrement the allowance
Execute the transfer
This is ERC-20’s “authorized transfer” mechanism.
XIV. Implement _mint
What it does
Internally mint tokens.
What _mint does
1. Check that the recipient address cannot be the zero address
2. Increase the total supply
3. Increase the account balance
4. Emit a mint event
A transfer from the zero address to the user address means minting.
XV. Implement _burn
What it does
Internally burn tokens.
What _burn does
1. Check that the address tokens are burned from cannot be the zero address
2. Read the account balance
3. Check whether the balance is sufficient
4. Subtract from the account balance
5. Decrease the total supply
6. Emit a burn event
A transfer to the zero address means burning.
XVI. The complete code
At this point, a simple ERC-20 contract has been written.
XVII. Finally, hold on to this main thread
When you write an ERC-20 by hand, the most important thing is to remember this main thread:
Use _balances to record balances
Use _allowances to record allowances
Use transfer to handle transfers of your own tokens
Use approve + transferFrom to handle authorized transfers
Use the Transfer and Approval events to tell the outside world what happened
ERC-20 may look like it has quite a few functions, but the core is really just two sentences: **How balances are recorded, and how allowances are recorded.
How transfers change the books, and how approvals change the books.**
That is the skeleton of the entire ERC-20.
2. Remix
Remix is a Solidity IDE.
It is not that frontend full-stack framework; they share a name, so do not mix them up.
After you open the web page, you get a browser-based editor.

Create a new file and paste in the MyToken we wrote.

Click this button on the right: Deploy & run transactions.

Under CONTRACT, select the contract we just wrote.

Fill in the constructor parameters in order.

Then click Deploy, and deploy it into the test environment Remix provides.

A Token we just deployed now appears under Deployed Contracts.
On the right, a piece of deployment transaction information is also printed.
After you expand our Token, you can see the methods you can call, and you can read the properties.

Then, on this panel, you can click these buttons to operate this Token contract.

At the top, you can find a list of test Accounts.

- (TBD) Hands-on assignment: issue your first meme coin
The original assignment page is blank; the content is to be added.
Code snippets from the article
The following code comes from code blocks in the original X Article, arranged in the order they appeared.
function decimals() public view returns (uint8) {
return _decimals;
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title SimpleERC20
* @dev A simple ERC20 token contract implementation
*/
contract SimpleERC20 is IERC20 {
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name_, string memory symbol_, uint256 initialSupply) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
_totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
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 value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_spendAllowance(from, msg.sender, value);
_transfer(from, to, value);
return true;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function _transfer(address from, address to, uint256 value) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(fromBalance >= value, "ERC20: transfer amount exceeds balance");
_balances[from] = fromBalance - value;
_balances[to] += value;
emit Transfer(from, to, value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _spendAllowance(address owner, address spender, uint256 value) internal {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= value, "ERC20: insufficient allowance");
_approve(owner, spender, currentAllowance - value);
}
}
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += value;
_balances[account] += value;
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= value, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - value;
_totalSupply -= value;
emit Transfer(account, address(0), value);
}
}
require(owner != address(0), "ERC20: approve from the zero address");
_totalSupply += value;
mapping(address => mapping(address => uint256)) private _allowances;
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += value;
_balances[account] += value;
emit Transfer(address(0), account, value);
}
require(to != address(0), "ERC20: transfer to the zero address");
emit Approval(owner, spender, value);
uint8 private _decimals;
_name = name_;
function _spendAllowance(address owner, address spender, uint256 value) internal {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= value, "ERC20: insufficient allowance");
_approve(owner, spender, currentAllowance - value);
}
}
string private _name;
mapping(address => uint256) private _balances;
emit Transfer(address(0), msg.sender, initialSupply);
require(fromBalance >= value, "ERC20: transfer amount exceeds balance");
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
emit Transfer(from, to, value);
_balances[account] = accountBalance - value;
_allowances[alice][dex] = 500;
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= value, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - value;
_totalSupply -= value;
emit Transfer(account, address(0), value);
}
require(currentAllowance >= value, "ERC20: insufficient allowance");
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
uint256 currentAllowance = allowance(owner, spender);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 accountBalance = _balances[account];
_balances[alice] = 100;
_balances[to] += value;
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_spendAllowance(from, msg.sender, value);
_transfer(from, to, value);
return true;
}
constructor(string memory name_, string memory symbol_, uint256 initialSupply) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
_totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function symbol() public view returns (string memory) {
return _symbol;
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
_allowances[owner][spender] = value;
_balances[from] = fromBalance - value;
require(from != address(0), "ERC20: transfer from the zero address");
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @dev A simple ERC20 token example, inheriting from the abstract contract ERC20
*
* This example shows how to quickly create your own token by inheriting from an abstract contract
*/
contract MyToken is ERC20 {
/**
* @dev Constructor: initialize the token name and symbol, and mint the initial supply
*
* @param name_ Token name, for example "My Token"
* @param symbol_ Token symbol, for example "MTK"
* @param initialSupply Initial supply (18 decimal places will be added automatically)
*/
constructor(string memory name_, string memory symbol_, uint256 initialSupply) ERC20(name_, symbol_) {
// Use the internal function _mint to mint tokens to the deployer
// msg.sender is the address of the contract deployer
_mint(msg.sender, initialSupply * 10**decimals());
}
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
string private _symbol;
_symbol = symbol_;
function _transfer(address from, address to, uint256 value) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(fromBalance >= value, "ERC20: transfer amount exceeds balance");
_balances[from] = fromBalance - value;
_balances[to] += value;
emit Transfer(from, to, value);
}
emit Transfer(account, address(0), value);
_balances[msg.sender] = initialSupply;
require(spender != address(0), "ERC20: approve to the zero address");
_balances[account] += value;
uint256 fromBalance = _balances[from];
function approve(address spender, uint256 value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
_totalSupply -= value;
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
// Specify the Solidity version
pragma solidity >=0.4.16;
/**
* @dev The ERC-20 standard interface defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another account (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}.
* `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the total token supply.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `value` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}.
* This is zero by default.
*
* This value changes when {approve} or {transferFrom} is called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance because of transaction ordering.
* One possible way to mitigate this race condition is to first reduce the spender's allowance to 0
* and then set the desired value:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves `value` tokens from `from` to `to` using the allowance mechanism.
* `value` is then deducted from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
_decimals = 18;
if (currentAllowance != type(uint256).max) {
require(account != address(0), "ERC20: burn from the zero address");
uint256 private _totalSupply;
emit Transfer(address(0), account, value);
_totalSupply = initialSupply;
function name() public view returns (string memory) {
return _name;
}
require(accountBalance >= value, "ERC20: burn amount exceeds balance");
function transfer(address to, uint256 value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract SimpleERC20 is IERC20 {
}
require(account != address(0), "ERC20: mint to the zero address");
_approve(owner, spender, currentAllowance - value);
This article was imported from an X Article. Original: https://x.com/i/status/2110719125500952997