其它标准见 eips.ethereum.org/etc ERC-20标准详解
ERC-20为一套接口,实现了这套接口,即为实现这套标准
pragma solidity^0.6.1;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity^0.6.1;
import "./IERC20.sol";
contract test_erc20 is IERC20{
string private _name; //指定名称
uint256 private _totalSupply;//存储总的发行量
address private admin;//定义管理员,用于发布发行量,由于ERC20标准没有规定如何发行,因此需要自己设置发行机制
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256))private _allowance;
constructor(string memory name) public{
_name=name;
_totalSupply=0;
admin=msg.sender;
}
function name() external view returns(string memory){
return _name;
}
//挖矿函数
function mint(address to ,uint256 value) external{
require(admin==msg.sender,"only admin can do");
require(address(0)!=to,"to must is an address");
_balances[to]+=value;
_totalSupply+=value;
emit Transfer(address(0),to,value);
}
//总的发行量
function totalSupply() external override view returns (uint256){
return _totalSupply;
}
//账户的余额
function balanceOf(address who) external override view returns (uint256){
return _balances[who];
}
//查看授权的余额
function allowance(address owner, address spender) override
external view returns (uint256){
return _allowance[owner][spender];
}
//转账接口 A-->B 200 A-200 B+200
function transfer(address to, uint256 value) override external returns (bool){
require(value>0,"value must >0");
require(_balances[msg.sender]>=value,"balance must enough!");
require(address(0)!=to,"to must is an address");
_balances[msg.sender]-=value;
_balances[to]+=value;
//调用事件函数
emit Transfer(msg.sender,to,value);
}
//授权
function approve(address spender, uint256 value)override
external returns (bool){
require(_balances[msg.sender]>=value,"balance must enough!");
require(address(0)!=spender,"to must is an address");
_allowance[msg.sender][spender]=value;
//调用事件
emit Approval(msg.sender,spender,value);
}
//授权转账
function transferFrom(address from, address to, uint256 value)override
external returns (bool){
require(address(0)!=to,"to must is an address");
require(value>0,"value must >0");
require(_allowance[from][to]>=value,"allowance's value must enough");
_allowance[from][to]-=value;
_balances[from]-=value;
_balances[to]+=value;
//调用事件
emit Transfer(from,to,value);
}
}
函数测试
1. 部署合约 2. 模拟挖矿,赋予参与方金额选择第一个账户为管理员,负责部署合约
注意:只有管理员拥有挖矿权限,即调用挖矿函数
4.进行转账这里是引用
5.进行授权第三账户—>第二个账户
转账的三要素:谁转账,转给谁,转多少
6.授权转账授权第三方进行转账
注意:这一步是在上一步骤的基础上进行的,转账的三要素要匹配,否则会出现错误
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)