在昨天講完 interface 之後,今天就來看看裡面需要怎麼實作就能做出自己的 ERC20 token 吧!
本日合約:
pragma solidity ^0.4.25;
import "browser/SafeMath.sol";
import "browser/IERC20.sol";
contract ERC20 is IERC20 {
using SafeMath for uint256;
uint256 private _totalSupply;
mapping(address => uint256) _balances;
// 所有存在的 Token 數量
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
// 讀取 tokenOwner 這個 address 所持有的 Token 數量
// address => uint256
function balanceOf(address tokenOwner) external view returns (uint256 balance) {
return _balances[tokenOwner];
}
// 從 msg.sender 轉 tokens 個 Token 給 to 這個 address
// msg.sender ---tokens---> to
function transfer(address to, uint256 tokens) external returns (bool success) {
_balances[msg.sender] = _balances[msg.sender].sub(tokens);
_balances[to] = _balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// 得到 tokenOwner 授權給 spender 使用的 Token 剩餘數量
function allowance(address tokenOwner, address spender) external view returns (uint256 remaining) {
// TODO
}
// tokenOwner -> spender -> tokens
// address => address => uint256
// msg.sender 授權給 spender 可使用自己的 tokens 個 Token
function approve(address spender, uint256 tokens) external returns (bool success) {
// TODO
}
// 將 tokens 個 Token 從 from 轉到 to
function transferFrom(address from, address to, uint256 tokens) external returns (bool success) {
// TODO
}
}
本日影片:
https://youtu.be/ee_RaOSuvOk
Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF