当前位置:   article > 正文

以太坊开发入门-ERC20合约_erc20.totalsupply() + amount

erc20.totalsupply() + amount

在上一章节中完成了一个非常简单的合约,本节中将按照ERC20协议完成一个合约, 本章部分源代码参考于网络开源代码,详细了解:openzeppelin-contracts/contracts/token/ERC20 at master · OpenZeppelin/openzeppelin-contracts · GitHub

开始之前先介绍一下什么是ERC20:

ERC-20指的是以太坊网络的一种代币合约标准。ERC-20是现在最出名的标准,ERC-20标准里无价值的差别,Token之间是能够进行互换的。意思就是在ERC-20标准下,你的100块“钱”和我的100块“钱”相同,没什么区别。ERC-20标准里规定了Token要有它的名字、符号、总供应量以及包含转账、汇款等其他功能。这个标准的优势就是:只要Token符合ERC-20标准,这样的话它就会兼容以太坊钱包。也就是说,就可以太坊钱包里加入这个Token,还能通过钱包把它发给别人。由于ERC-20标准的存在,发行Token就会更加简单。现在以太坊上ERC-20 Token的数量超过了180000种。

ERC2.0是一套接口定义,定义了合约的基本功能,其定义如下:

  1. // SPDX-License-Identifier: MIT
  2. //file IERC20.sol
  3. pragma solidity ^0.8.0;
  4. interface IERC20 {
  5. // 总发行量
  6. function totalSupply() external view returns (uint256);
  7. // 查看地址余额
  8. function balanceOf(address account) external view returns (uint256);
  9. /// 从自己帐户给指定地址转账
  10. function transfer(address account, uint256 amount) external returns (bool);
  11. // 查看被授权人还可以使用的代币余额
  12. function allowance(address owner, address spender) external view returns (uint256);
  13. // 授权指定帐户使用你拥有的代币
  14. function approve(address spender, uint256 amount) external returns (bool);
  15. // 从一个地址转账至另一个地址,该函数只能是通过approver授权的用户可以调用
  16. function transferFrom(
  17. address from,
  18. address to,
  19. uint256 amount
  20. ) external returns (bool);
  21. /// 定义事件,发生代币转移时触发
  22. event Transfer(address indexed from, address indexed to, uint256 value);
  23. /// 定义事件 授权时触发
  24. event Approval(address indexed owner, address indexed spender, uint256 value);
  25. }

详细说明参考代码注释。

  1. // SPDX-License-Identifier: MIT
  2. //file IERC20Metadata.sol
  3. pragma solidity ^0.8.0;
  4. import "./IERC20.sol";
  5. interface IERC20Metadata is IERC20 {
  6. // 代币名称, 如:BitCoin
  7. function name() external view returns (string memory);
  8. // 代币符号或简称, 如:BTC
  9. function symbol() external view returns (string memory);
  10. // 代币支持的小数点后位数,若无特别需求,我们一般默认采用18位。
  11. function decimals() external view returns (uint8);
  12. }

MetaData数据定义,该部分比较简单,定义三个函数,分别对应代币名称,代币简称和代币小数点位数。

具体代码实现:

  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import "./IERC20.sol";
  4. import "./IERC20Metadata.sol";
  5. contract ERC20 is IERC20, IERC20Metadata {
  6. // 地址余额
  7. mapping(address => uint256) private _balances;
  8. // 授权地址余额
  9. mapping(address => mapping(address => uint256)) private _allowances;
  10. uint256 private _totalSupply;
  11. string private _name;
  12. string private _symbol;
  13. // 设定代币名称符号,并初始化铸造了10000000000代币在发布者帐号下。
  14. constructor() {
  15. _name = "HarryToken";
  16. _symbol = "HYT";
  17. _mint(msg.sender, 10000000000);
  18. }
  19. function name() public view virtual override returns (string memory) {
  20. return _name;
  21. }
  22. function symbol() public view virtual override returns (string memory) {
  23. return _symbol;
  24. }
  25. /// 小数点位数一般为 18
  26. function decimals() public view virtual override returns (uint8) {
  27. return 18;
  28. }
  29. // 返回当前流通代币的总量
  30. function totalSupply() public view virtual override returns (uint256) {
  31. return _totalSupply;
  32. }
  33. // 查询指定帐号地址余额
  34. function balanceOf(address account) public view virtual override returns (uint256) {
  35. return _balances[account];
  36. }
  37. // 转帐功能
  38. function transfer(address to, uint256 amount) public virtual override returns (bool) {
  39. address owner = msg.sender;
  40. _transfer(owner, to, amount);
  41. return true;
  42. }
  43. // 获取被授权者可使用授权帐号的可使用余额
  44. function allowance(address owner, address spender) public view virtual override returns (uint256) {
  45. return _allowances[owner][spender];
  46. }
  47. // 授权指定帐事情可使用自己一定额度的帐户余额。
  48. // 授权spender, 可将自己余额。使用可使用的余额的总量为amount
  49. function approve(address spender, uint256 amount) public virtual override returns (bool) {
  50. address owner = msg.sender;
  51. _approve(owner, spender, amount);
  52. return true;
  53. }
  54. //approve函数中的spender调用,将授权人 from 帐户中的代币转入to 帐户中
  55. function transferFrom(
  56. address from,
  57. address to,
  58. uint256 amount
  59. ) public virtual override returns (bool) {
  60. address spender = msg.sender;
  61. _spendAllowance(from, spender, amount);
  62. _transfer(from, to, amount);
  63. return true;
  64. }
  65. function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
  66. address owner = msg.sender;
  67. _approve(owner, spender, _allowances[owner][spender] + addedValue);
  68. return true;
  69. }
  70. function decreaseAllowance(address spender, uint256 substractedValue) public virtual returns (bool) {
  71. address owner = msg.sender;
  72. uint256 currentAllowance = _allowances[owner][spender];
  73. require(currentAllowance >= substractedValue, "ERC20: decreased allowance below zero");
  74. unchecked {
  75. _approve(owner, spender, currentAllowance - substractedValue);
  76. }
  77. return true;
  78. }
  79. function _transfer(
  80. address from,
  81. address to,
  82. uint256 amount
  83. ) internal virtual {
  84. require(from != address(0), "ERC20: transfer from the zero address");
  85. require(to != address(0), "ERC20: transfer to the zero address");
  86. _beforeTokenTransfer(from, to, amount);
  87. uint256 fromBalance = _balances[from];
  88. require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
  89. unchecked {
  90. _balances[from] = fromBalance - amount;
  91. }
  92. _balances[to] += amount;
  93. emit Transfer(from, to, amount);
  94. _afterTokenTransfer(from, to, amount);
  95. }
  96. function _mint(address account, uint256 amount) internal virtual {
  97. require(account != address(0), "ERC20: mint to the zero address");
  98. _beforeTokenTransfer(address(0), account, amount);
  99. _totalSupply += amount;
  100. _balances[account] += amount;
  101. emit Transfer(address(0), account, amount);
  102. _afterTokenTransfer(address(0), account, amount);
  103. }
  104. function _burn(address account, uint256 amount) internal virtual {
  105. require(account != address(0), "ERC20: burn from the zero address");
  106. _beforeTokenTransfer(account, address(0), amount);
  107. uint256 accountBalance = _balances[account];
  108. require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
  109. unchecked {
  110. _balances[account] = accountBalance - amount;
  111. }
  112. _totalSupply -= amount;
  113. emit Transfer(account, address(0), amount);
  114. _afterTokenTransfer(account, address(0), amount);
  115. }
  116. function _approve(
  117. address owner,
  118. address spender,
  119. uint256 amount
  120. ) internal virtual {
  121. require(owner != address(0), "ERC20: approve from the zero address");
  122. require(spender != address(0), "ERC20: approve to the zero address");
  123. _allowances[owner][spender] = amount;
  124. emit Approval(owner, spender, amount);
  125. }
  126. function _spendAllowance(
  127. address owner,
  128. address spender,
  129. uint256 amount
  130. ) internal virtual {
  131. uint256 currentAllowance = allowance(owner, spender);
  132. if (currentAllowance != type(uint256).max) {
  133. require(currentAllowance >= amount, "ERC20: insufficient allowance");
  134. unchecked {
  135. _approve(owner, spender, currentAllowance - amount);
  136. }
  137. }
  138. }
  139. function _beforeTokenTransfer(
  140. address from,
  141. address to,
  142. uint256 amount
  143. ) internal virtual {}
  144. function _afterTokenTransfer(
  145. address from,
  146. address to,
  147. uint256 amount
  148. ) internal virtual {}
  149. }
  1. // 地址余额
  2. mapping(address => uint256) private _balances;
  3. // 授权地址余额
  4. mapping(address => mapping(address => uint256)) private _allowances;
  5. uint256 private _totalSupply;
  6. string private _name;
  7. string private _symbol;

ERC20合约中定义了5个变量:

_balances变量以keyv=>value方式存储帐号和其对应的余额。

_allowances变量是一个两层mapping,数据值以下结构存储:0x123456=>[0x123457=>1000, 0x123458=>2000],代表的意思是0x123456帐号授权0x123457和0x123458两个帐号,分别可以使用0x123456帐号1000和2000余额额度。使用余额的函数为transferFrom。

_totalSupply变量是存储当成代币合约发行的代币总量,一般我们每铸造一个新代币,就在其值上+1。

_name变量是代币的名称,如比特币名称:BitCoin

_symbol变量是代币的简称, 如比特币简称:BTC

  1. // 设定代币名称符号,并初始化铸造了10000000000代币在发布者帐号下。
  2. constructor() {
  3. _name = "HarryToken";
  4. _symbol = "HYT";
  5. _mint(msg.sender, 10000000000);
  6. }

构造函数,指令name和symbol。这里我们调用了一个private的函数_mint,给合约创建者新铸造了10000000000个代币。因为本合约实现的时候并没有public的mint函数可以铸造代币,所以直接初始化入创建者帐户,该合约所有的代币都只能用创建都帐户转出。当前也可以将实现一个public的mint函数,关加上权限控制,让有权限的帐户可以随时调mint铸造新代币。

  1. function name() public view virtual override returns (string memory) {
  2. return _name;
  3. }
  4. function symbol() public view virtual override returns (string memory) {
  5. return _symbol;
  6. }
  7. /// 小数点位数一般为 18
  8. function decimals() public view virtual override returns (uint8) {
  9. return 18;
  10. }

IERC20Metadata 接口的实现方法,主要用于获取代币名称,简称及支持的小数点位数。

  1. function totalSupply() public view virtual override returns (uint256) {
  2. return _totalSupply;
  3. }

totalSupply查询当前代币的发行总量。

  1. function balanceOf(address account) public view virtual override returns (uint256) {
  2. return _balances[account];
  3. }

balanceOf查询指令帐户的代币余额。

  1. // 转帐功能
  2. function transfer(address to, uint256 amount) public virtual override returns (bool) {
  3. address owner = msg.sender;
  4. _transfer(owner, to, amount);
  5. return true;
  6. }
  7. function _transfer(
  8. address from,
  9. address to,
  10. uint256 amount
  11. ) internal virtual {
  12. require(from != address(0), "ERC20: transfer from the zero address");
  13. require(to != address(0), "ERC20: transfer to the zero address");
  14. _beforeTokenTransfer(from, to, amount);
  15. uint256 fromBalance = _balances[from];
  16. require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
  17. unchecked {
  18. _balances[from] = fromBalance - amount;
  19. }
  20. _balances[to] += amount;
  21. emit Transfer(from, to, amount);
  22. _afterTokenTransfer(from, to, amount);
  23. }

transfer转帐函数,一个比较重要的功能,调用者可以将自己的余额转给其它帐户。

_transfer为private的具体实现函数。主要是作了一些必要的检查,然后从发起帐户扣减余额,再将余额加到接收帐户。最后发送了一个转帐事件,方便开发者监听转帐功能。这里的_beforeTokenTransfer和_afterTokenTransfer并没有实现具体功能,开发中可根据实现需要做一些功能实现。

  1. // 获取被授权者可使用授权帐号的可使用余额
  2. function allowance(address owner, address spender) public view virtual override returns (uint256) {
  3. return _allowances[owner][spender];
  4. }
  5. // 授权指定帐事情可使用自己一定额度的帐户余额。
  6. // 授权spender, 可将自己余额。使用可使用的余额的总量为amount
  7. function approve(address spender, uint256 amount) public virtual override returns (bool) {
  8. address owner = msg.sender;
  9. _approve(owner, spender, amount);
  10. return true;
  11. }
  12. function _approve(
  13. address owner,
  14. address spender,
  15. uint256 amount
  16. ) internal virtual {
  17. require(owner != address(0), "ERC20: approve from the zero address");
  18. require(spender != address(0), "ERC20: approve to the zero address");
  19. _allowances[owner][spender] = amount;
  20. emit Approval(owner, spender, amount);
  21. }

allowance、approve主要是实现授权其它帐户可以使用自己的余额,并设定使用上限。相关的授权者存储在_allowances变量中。

  1. function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
  2. address owner = msg.sender;
  3. _approve(owner, spender, _allowances[owner][spender] + addedValue);
  4. return true;
  5. }
  6. function decreaseAllowance(address spender, uint256 substractedValue) public virtual returns (bool) {
  7. address owner = msg.sender;
  8. uint256 currentAllowance = _allowances[owner][spender];
  9. require(currentAllowance >= substractedValue, "ERC20: decreased allowance below zero");
  10. unchecked {
  11. _approve(owner, spender, currentAllowance - substractedValue);
  12. }
  13. return true;
  14. }

increaseAllowance、decreaseAllowance两个函数是对approve函数功能的加强,对授权额度进行增减,这两个函数关不是ERC20协议中的内容。只是作者在参考源码时觉得有用,就加入了这两个函数。

  1. function transferFrom(
  2. address from,
  3. address to,
  4. uint256 amount
  5. ) public virtual override returns (bool) {
  6. address spender = msg.sender;
  7. _spendAllowance(from, spender, amount);
  8. _transfer(from, to, amount);
  9. return true;
  10. }
  11. function _spendAllowance(
  12. address owner,
  13. address spender,
  14. uint256 amount
  15. ) internal virtual {
  16. uint256 currentAllowance = allowance(owner, spender);
  17. if (currentAllowance != type(uint256).max) {
  18. require(currentAllowance >= amount, "ERC20: insufficient allowance");
  19. unchecked {
  20. _approve(owner, spender, currentAllowance - amount);
  21. }
  22. }
  23. }

transferFrom,_spendAllowance是在授权额度下,进行转帐的功能实现。

transferFrom函数的from参数是授权帐户,to是余额接受帐户,amount是转帐余额,该函数的功能是将from帐户的余额转移amount个数据至to用户帐户中,调用者必须是from帐户通过_approve对其进行过授权,并且还有剩余的授权额度。该函数与transfer的区别是,transfer只能转移出调用者自己的帐户余额。

_spendAllowance是在进行授权转帐时首先扣减授权额度,保证被授权都在授权额度范围内使用转帐功能。

  1. function _mint(address account, uint256 amount) internal virtual {
  2. require(account != address(0), "ERC20: mint to the zero address");
  3. _beforeTokenTransfer(address(0), account, amount);
  4. _totalSupply += amount;
  5. _balances[account] += amount;
  6. emit Transfer(address(0), account, amount);
  7. _afterTokenTransfer(address(0), account, amount);
  8. }
  9. function _burn(address account, uint256 amount) internal virtual {
  10. require(account != address(0), "ERC20: burn from the zero address");
  11. _beforeTokenTransfer(account, address(0), amount);
  12. uint256 accountBalance = _balances[account];
  13. require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
  14. unchecked {
  15. _balances[account] = accountBalance - amount;
  16. }
  17. _totalSupply -= amount;
  18. emit Transfer(account, address(0), amount);
  19. _afterTokenTransfer(account, address(0), amount);
  20. }

_mint和_burn是两个相反的功能,一个是新铸造代币,一个是燃烧(销毁)代币。两个方法都是private,关没有对外开放。

完成上述三个源文件的代码就可能编译部署,选中ERC20.sol文件,完成编译。部署时要特别注意在选中Contract中的实现合约ERC20,不要误选了接口合约。

否则会部署后报如下错误,很多刚开始接触合约的读者都遇到该问题了,所以作者提示一下。

部署成功后,就可以查看并调用合约了。

一个比较健全的ERC20代币合约就完成了。下一章节给大家分享在ERC721协议下实现NTF相关的功能。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/369259?site
推荐阅读
相关标签
  

闽ICP备14008679号