Ethereum smart contracts – ICO example (part 2)

Gabriel Pineiro
2018-10-02T20:30:04-03:00By |
September 6, 2017

ICO smart contract

ERC20 standard

You can read the part 1 here

In part one of this series, we drafted a very simple ICO smart contract for a “basecoinit” token. I finalized that post saying that in part 2, we would continue with the evolution of the smart contract into something ERC20 compliant, and enhanced security. So here we go.

ERC20 stands for “Ethereum request for comment #20”, and was born in GitHub forums where Ethereum developers and users discussed various proposals and options for a common interfaces for contracts. Why? Because that enables to do cool things like a wallet that can handle any ERC20-compatible token without needing to create a special update to support it, etc.

The ERC20 interface code is fairly simple:

interface IStandardToken {
    function totalSupply() constant returns (uint totalSupply);
    function balanceOf(address _owner) constant returns (uint balance);
    function transfer(address _to, uint _value) returns (bool success);
    function transferFrom(address _from, address _to, uint _value) returns (bool success);
    function approve(address _spender, uint _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint remaining);
    event Transfer(address indexed _from, address indexed _to, uint _value);
    event Approval(address indexed _owner, address indexed _spender, uint _value);

What each of this functions do is self-explanatory, but let do a quick review:

  • totalSupply() returns the fixed supply of our tokens
  • balanceOf() returns the balance for a specific address
  • transfer() transfers from the address of the sender of the transaction to specified address
  • transferFrom() transfers from the specified origin address to the destination address
  • approve() the sender of the transaction approves the specified address, to spend tokens on his behalf
  • allowance() returns how many tokens are approved for an address to handle in behalf of another address

And then comes the Events. Events are basically logs in the Ethereum transaction. As you probably already guessed, Transfer() logs the transfer information, and Approval() logs the approve() information.


We are going to focus on one, of many, aspects of security in a smart contract: math. Ethereum Virtual Machine (EVM) is susceptible to overflows and memory offsets. So poor handled math can lead to an “Integer overflow” attack. To avoid that risk, we are going to implement SafeMath library in our contract.

You can check the result in our GitHub

In the next post, I’m going to merge the first Basecoinit contract with this ERC20 safe one, so you can see how the final result looks.