前言 通过以太坊提供的EIP-20协议,创建自己的加密货币(加密代币、Token)
下载依赖
1 npm install openzeppelin-solidity
创建智能合约 contracts/DemoToken.sol 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.16 <0.9.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; contract DemoToken { using SafeMath for uint256; // 定义代币名称 string public name = "DemoToken"; // 定义代币符号 string public symbol = "DMT"; // 定义代币单位相对于`wei`的位数 uint256 public decimals = 18; // 定义代币发行总量 uint256 public totalSupply; // 指定用户的余额 mapping(address => uint256) public balanceOf; constructor() public { totalSupply = 1000000 * (10 ** decimals); // 初始化创始人的余额为代币发行总量 balanceOf[msg.sender] = totalSupply; } // 转账 function _transfer(address _from, address _to, uint256 _value) internal { // 转出用户余额必须大于转账金额 require(balanceOf[_from] >= _value); // 转出用户余额减少 balanceOf[_from] = balanceOf[_from].sub(_value); // 接收用户余额增加 balanceOf[_to] = balanceOf[_to].add(_value); // 完成转账后触发事件 emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { // 目标用户地址必须有效 require(_to != address(0)); // 发起转账 _transfer(msg.sender, _to, _value); return true; } // 事件,当事件被触发时会将日志写入到区块链中,如果有前端订阅了这个事件将会回调 event Transfer(address indexed _from, address indexed _to, uint256 _value); }
测试智能合约
在测试环境中,没办法直接获取msg.sender的值,所以需要手动通过{from:""}传递msg.sender的值
<first_account_public_key>:智能合约部署者的公钥,测试链的第一个账号<other_account_public_key>:接收转账用户的公钥100:转账金额
scripts/test.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const DemoToken = artifacts.require ("DemoToken.sol" );module .exports = async function (callback ) { const demoToken = await DemoToken .deployed (); console .log ("创始人账户余额" , web3.utils .fromWei (await demoToken.balanceOf ("<first_account_public_key>" ), "ether" )); await demoToken.transfer ( "<other_account_public_key>" , web3.utils .toWei ("100" , "ether" ), { from : "<first_account_public_key>" } ); console .log ("创始人账户余额" , web3.utils .fromWei (await demoToken.balanceOf ("<first_account_public_key>" ), "ether" )); console .log ("接收转账人账户余额" , web3.utils .fromWei (await demoToken.balanceOf ("<other_account_public_key>" ), "ether" )); callback (); }
完成 参考文献 哔哩哔哩——千锋教育