以太坊开发入门-ERC20发行代币

  • Harry.H
  • 更新于 2022-09-05 14:58
  • 阅读 5062

一个相对完整的ERC20代币合约

在上一章节中完成了一个非常简单的代币合约,本节中将按照ERC20协议完成一个代币合约, 本章部分源代码参考于网络开源代码,详细了解:https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC20。 开始之前先介绍一下什么是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是一套接口定义,定义了代币合约的基本功能,其定义如下:

// SPDX-License-Identifier: MIT
//file IERC20.sol
pragma solidity ^0.8.0;

interface IERC20 {
    // 总发行量
    function totalSupply() external view returns (uint256);
    // 查看地址余额
    function balanceOf(address account) external view returns (uint256);
    /// 从自己帐户给指定地址转账
    function transfer(address account, uint256 amount) external returns (bool);
    // 查看被授权人还可以使用的代币余额
    function allowance(address owner, address spender) external view returns (uint256);
    // 授权指定帐户使用你拥有的代币
    function approve(address spender, uint256 amount) external returns (bool);
    // 从一个地址转账至另一个地址,该函数只能是通过approver授权的用户可以调用
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    /// 定义事件,发生代币转移时触发
    event Transfer(address indexed from, address indexed to, uint256 value);
    /// 定义事件 授权时触发
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

详细说明参考代码注释。

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

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

具体代码实现:

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

import "./IERC20.sol";
import "./IERC20Metadata.sol";
contract ERC20 is IERC20, IERC20Metadata {
    // 地址余额
    mapping(address => uint256) private _balances;
    // 授权地址余额
    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /// 小数点位数一般为 18
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    // 返回当前流通代币的总量
    function totalSupply() public view virtual  override returns (uint256) {
        return _totalSupply;
    }

    // 查询指定帐号地址余额
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    // 转帐功能
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _transfer(owner, to, amount);
        return true;
    }

    // 获取被授权者可使用授权帐号的可使用余额
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    // 授权指定帐事情可使用自己一定额度的帐户余额。
    // 授权spender, 可将自己余额。使用可使用的余额的总量为amount
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _approve(owner, spender, amount);
        return true;
    }

    //approve函数中的spender调用,将授权人 from 帐户中的代币转入to 帐户中
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = msg.sender;
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = msg.sender;
        _approve(owner, spender, _allowances[owner][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 substractedValue) public virtual returns (bool) {
        address owner = msg.sender;
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= substractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - substractedValue);
        }
        return true;
    }

    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;
        emit Transfer(account, address(0), amount);
        _afterTokenTransfer(account, address(0), amount);
    }

    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve  to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}
    // 地址余额
    mapping(address => uint256) private _balances;
    // 授权地址余额
    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    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

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

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

  function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /// 小数点位数一般为 18
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

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

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

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

function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }
balanceOf查询指令帐户的代币余额。
    // 转帐功能
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _transfer(owner, to, amount);
        return true;
    }
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

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

    // 获取被授权者可使用授权帐号的可使用余额
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    // 授权指定帐事情可使用自己一定额度的帐户余额。
    // 授权spender, 可将自己余额。使用可使用的余额的总量为amount
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = msg.sender;
        _approve(owner, spender, amount);
        return true;
    }
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve  to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

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

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = msg.sender;
        _approve(owner, spender, _allowances[owner][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 substractedValue) public virtual returns (bool) {
        address owner = msg.sender;
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= substractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - substractedValue);
        }
        return true;
    }

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

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = msg.sender;
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

   function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

transferFrom,_spendAllowance是在授权额度下,进行转帐的功能实现。 transferFrom函数的from参数是授权帐户,to是余额接受帐户,amount是转帐余额,该函数的功能是将from帐户的余额转移amount个数据至to用户帐户中,调用者必须是from帐户通过_approve对其进行过授权,并且还有剩余的授权额度。该函数与transfer的区别是,transfer只能转移出调用者自己的帐户余额。 _spendAllowance是在进行授权转帐时首先扣减授权额度,保证被授权都在授权额度范围内使用转帐功能。

function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;
        emit Transfer(account, address(0), amount);
        _afterTokenTransfer(account, address(0), amount);
    }

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

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

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

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

image.png

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

点赞 0
收藏 3
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Harry.H
Harry.H
web3世界的一粒量子