ERC20自创代币实现
区块链实验课作业
一、ERC20标准接口
contract ERC20 {function name() constant returns (string name)function symbol() constant returns (string symbol)function decimals() constant returns (uint8 decimals)function totalSupply() constant returns (uint totalSupply);function balanceOf(address _owner) constant returns (uint balance);function transfer(address _to, uint _value) returns (bool success);function transferFrom(address _from, address _to, uint _value) returns (bool success);function approve(address _spender, uint _value) returns (bool success);function allowance(address _owner, address _spender) constant returns (uint remaining);event Transfer(address indexed _from, address indexed _to, uint _value);event Approval(address indexed _owner, address indexed _spender, uint _value);}
二、准备工作
1、选择新建一个文件夹并进入
mkdir homeworkcd homework
2、初始化
truffle initnpm init
此时会出现这样的目录结构
3、下载标准包openzeppelin-contracts
这里的库会提供标准接口,自己创建合约时候直接import即可
npm install zeppelin-solidity
4、之后开始创建自己的代币mycoin
先在contracts文件目录下创建一个文件 mycoin.sol
pragma solidity ^0.4.24;import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";contract mycoin is StandardToken {string public name = "HamburgerCoin"; string public symbol = "HBC";uint public decimals = 2;uint public INITIAL_SUPPLY = 10000 * (10 ** decimals);function mycoin() public {totalSupply_ = INITIAL_SUPPLY;balances[msg.sender] = INITIAL_SUPPLY;}}
上述合约内容中指定了合约的名称、符号和供应量。在 ERC20 当中,通证的供应量其实是整数,上述合约中通证的实际供应量是 10000 * 100 个,出于显示 2 位小数的需求,你在合约浏览器、钱包软件中看到和操作的 1 个通证,实际上在交易中是以 100 个进行的
5、compile
来编译我们的合约
truffle compile
Compiled successfully
表示编译成功
6、deploy
在migrations文件下创建deploy_1.js文件
var mycoin = artifacts.require("mycoin");module.exports = function(deployer) {deployer.deploy(mycoin);}
7、migrate
truffle migrate
这里可以看到地址,gas等详细信息
8、挂载上ganache测试链
将homework项目的truffle-config.js文件加入到ganache的sever中并且保存
已经挂载成功!