generate the code for an ERC-20
- User
generate the code for an ERC-20
- Assistant
token using Solidity:
code
generate the code for an ERC-20
token using Solidity:
pragma solidity ^0.8.0;
contract MyToken {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceOf[msg.sender] = _totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
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(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
This contract defines an ERC-20 token with the standard functions transfer, approve, and transferFrom. The constructor sets the initial values for the token's name, symbol, decimals, and totalSupply, and sets the entire initial supply to the contract creator's address.
The balanceOf mapping stores the token balance of each address, and the allowance mapping stores the approved spending limits for each user.
The transfer function allows a user to send tokens to another address. The approve function allows a user to approve another address to spend a certain amount of their tokens, while the transferFrom function allows the approved address to actually spend those tokens.
The emit keyword is used to trigger events when token transfers or approvals occur, allowing external systems to track these events.