ERC20代币想必大家不陌生了,在以太坊上有数以千计的ERC20代币!本着学以致用的目的,自己也发个币装一把。
先上代码:
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| pragma solidity >=0.4.22 <0.7.0;
abstract contract ERC20Interface { string public name; string public symbol; uint8 public decimals; uint public totalSupply;
function transfer(address _to, uint256 _value) public virtual returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success); function approve(address _spender, uint256 _value) public virtual returns (bool success); function allowance(address _owner, address _spender) public virtual view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ERC20 is ERC20Interface { mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) allowed; constructor() public { name = "Lemool"; symbol = "LEM"; decimals = 0; totalSupply = 10000000; balanceOf[msg.sender] = totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[ _to] + _value >= balanceOf[ _to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf[_from] >= _value); require(balanceOf[ _to] + _value >= balanceOf[ _to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public override view returns (uint256 remaining) { return allowed[_owner][_spender]; }
}
|
ERC20是有标准接口的,其实都很简单,就是几个参数和几个转帐的方法!想当年很多项目就是靠着这几行代码卷钱无数,现在想来会不会有点后悔呢。
在上面转帐的方法还是自己实现了一下,其实还有一种更简单和安全的方法:OpenZeppelin。只有少数几行代码就可以实现ERC20代币合约!
用前先安装一下:npm install @openzeppelin/contracts
1 2 3 4 5 6 7 8 9 10
| pragma solidity >=0.4.22 <0.7.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract TutorialToken is ERC20, ERC20Detailed { constructor() ERC20Detailed("Lemool", "LEM", 0) public { _mint(msg.sender, 10000000); } }
|
短短五六行代码就全搞定了,想想是不是很牛啊!感兴趣的朋友可以一试!
This page is synchronized from the post: ‘ERC20代币合约 / 学习智能合约#5’