Every contract must contain a constructor function that is run only once when the contract is first deployed. In our implementation, the constructor takes the initial supply of tokens as a parameter, which is assigned to the owner of the contract. We also emit a Transfer event, indicating a transfer from address 0 to the contract owner's account. This is considered best practice, but is not required by the standard:
constructor(uint256 _initialSupply) public {
balanceOf[msg.sender] = _initialSupply;
totalSupply = _initialSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
We've now written sufficient code to have a functional token, though there are still things we must add before it adheres completely to the ERC-20 standard. The following code represents our implementation thus far, with our variables defined:
pragma solidity ^0.4.24;
contract PacktToken {
string public name = "Packt ERC20 Token";
string public symbol = "PET";
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed _from,
address indexed _to,
uint256 _value);
constructor(uint256 _initialSupply) public {
balanceOf[msg.sender] = _initialSupply;
totalSupply = _initialSupply;
emit Transfer(address(0), 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;
}
}