301. 發代幣 - ERC20 (ep.17)

閱讀時間約 3 分鐘

1. 介面

  • 宣告一個介面, 定義了需要滿足的函式與事件
  • 介面中的限制:
  1. 所有宣告的函式必須是external, 即使最終在合約使用的是public也一樣
  2. 不能宣告建構子constructor (合約才會出現)
  3. 不能宣告在儲存空間的變數(狀態變數, state variables)
  4. 不能宣告修飾子(modifier)


2. 總發行量函式

  • 回傳代幣的總發行量
  • 使用狀態變數 uint256 _totalSupply來儲存
function totalSupply()external view returns (uint256);


3. 帳戶餘額查詢函式

  • 給定一個帳戶 address, 回傳該帳戶擁有的代幣餘額 uint256
  • 用位址找出餘額 - 映射關係
  • 因為是個 address => uint256的關係, 引此因此會使用 mapping來儲存
  • mapping(address => uint256) _balance;
function balanceOf(address account) external view returns(uint256);


4. 轉帳函式

  • 呼叫的人[msg.sender], 就是轉帳的發起者, 轉移 [ amount ] 數量的代幣給特定帳戶 [ to ]
  • 成功時回傳 true, 反之, 回傳 false
function transfer(address to, uint256 amount) external returns(bool);


5. 轉帳事件

  • 當發生代幣轉移時, 必須觸發此事件, 即使轉移的數量為 [0] 也是
event Transfer(address indexed from, address indexed to , uint256 value);


6. 授權函式

  • 呼叫者授權 [msg.sender], 授權 [ amount ] 數量的代幣給第三方帳戶 [ spender ]使用
  • 成功時回傳true, 反之回傳 false
function approve(address spender, uint256 amount) external returns (bool);


7. 授權事件

  • 當授權函式被使用時, 必須觸發授權事件, 即使授權的數量 value 為0也是
event Approval(address indexed owner, address indexed spender, uint256 value);


8. 授權數量查詢函式

  • 回傳代幣擁有者owner授權給第三方帳戶spender的代幣數量
  • 我們可以觀察到授權的行為是 owner => spender => uint256
  • 因此在儲存授權的資訊時, 會使用
  • mapping (address => mapping (address => uint256))
function allowance(address owner, address spender) external view returns(uint256);


9. 第三方轉帳函式

  • 呼叫者為被授權的第三方帳戶, 從授權者 [from] 轉移 [ amount ] 數量的代幣給接收者to
  • 成功時回傳true, 失敗時回傳false
  • 需檢查互叫者是否有足夠的額度可用
  • 轉帳時檢查持有者是否有足夠的餘額
  • 轉帳時需要同時減去額度
function transferFrom(address from, address to, uint256 amount) external returns(bool);


在 2022 年,我們該如何寫智能合約

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