302. 轉帳篇 - ERC20 (ep.18)

閱讀時間約 4 分鐘

1. 總發行量函式 totalSupply() returns (uint256)

  • 回傳代幣的總發行量
  • 使用狀態變數 uint256 _totalSupply來儲存

2. 帳戶餘額查詢函式 balanceOf(address) returns (uint256)

  • 給定一個帳戶(address), 回傳該帳戶擁有的代幣餘額(uint256)
  • 使用mapping來儲存 mapping(address => uint256) _balance;

3. 轉帳函式 transfer(address, uint256) returns (bool);

  • 呼叫者[msg.sender], 轉移 amount數量的代幣給特定帳戶 to
  • 成功時回傳 true, 反之回傳 false
  • 檢查需要做: amount 是否超過餘額? 是否轉移給 address 0x0 代表銷毀的意思

4. 轉帳事件

當代幣轉移時, 必須觸發此事件, 即使轉移的數量為0也是


5. 轉帳實作

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

interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);

function totalSupply() external view returns (uint256);

function balanceOf(address account) external view returns (uint256);

function transfer(address to, uint256 amount) external returns(bool);
}

contract ERC20 is IERC20 {
uint256 _totalSupply;
mapping(address => uint256) _balance;

constructor(){
_balance[msg.sender] = 10000;
_totalSupply = 10000;
}

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

function balanceOf(address account) public view returns (uint256) {
return _balance[account];
}
function transfer(address to, uint256 amount) public returns (bool){
uint256 myBalance = _balance[msg.sender];
require(myBalance >= amount, "No money to transfer");
require(to !=address(0), "Transfer to address 0");

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


在 2022 年,我們該如何寫智能合約 - 18 - ERC20 實作 轉帳篇


尋大神腳印, 亦步亦趨。
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容