编写ERC20智能合约
时间: 2024-04-21 22:27:52 浏览: 191
好的,以下是一个简单的ERC20智能合约示例:
```solidity
pragma solidity ^0.8.0;
contract ERC20Token {
string public name;
string public symbol;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor(string memory _name, string memory _symbol, uint256 _totalSupply) {
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
balanceOf[msg.sender] = _totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value, "Insufficient balance");
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value, "Insufficient balance");
require(allowance[_from][msg.sender] >= _value, "Insufficient allowance");
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
```
该合约包括以下功能:
- `name`:代币名称
- `symbol`:代币符号
- `totalSupply`:代币总量
- `balanceOf`:每个地址的代币余额
- `allowance`:允许其他地址花费的代币数量
该合约实现了ERC20标准中的以下函数:
- `transfer`:从调用者的地址向另一个地址发送代币
- `approve`:允许另一个地址花费指定数量的代币
- `transferFrom`:从一个地址向另一个地址发送代币,前提是已经获得了允许
该合约还定义了两个事件:
- `Transfer`:代币发送时触发
- `Approval`:允许花费代币时触发
要部署这个合约,你需要使用Solidity编译器将其编译为字节码,然后将字节码发送到以太坊网络上。你可以使用Remix或Truffle等工具来编译和部署智能合约。
阅读全文