Blog

17/05/2019

How to ICO TOKEN erc20 ERC20 Tokens and ICO Smart Contracts



Lately, I have seen a lot of articles on the web giving basic examples of how to launch your own ERC20 tokens or how to set up your very own ICO (Initial Coin Offering). These are always high level, rushed overviews that leave out a lot of details, which in turn can lead to a lot of mistakes, wasted money, and headaches.

Don’t get me wrong, these people mean well. But as a professional blockchain developer, it irks me to see this. People are reading your article to learn, and just showing them how to do something while skipping basic steps be the most helpful thing. So, I decided to make this tutorial in a way that anyone can follow along no matter what your experience level.

This will be a 6 step process.

  • Setting up a Coinbase account
  • Setting up MyEtherWallet
  • Buying and sending Ethereum to your new wallet
  • Setting up the smart contract
  • Deploying your contract to the Ethereum Blockchain
  • Verifying your code on Etherescan and adding it to MyEtherWallet

Now when I say 6 steps, I mean 6 major steps. There is still a lot to each step. I say this is the easy way because you don’t need to lean anything new for the most part as long as you know how to follow directs and use a web browser, you can follow this tutorial and launch your very own ERC20 token, and when I said in depth, well its quite long. Just a fair warning.

What you will need for this tutorial

  • A working cell phone
  • A government issued ID or passport for verifying yourself
  • A computer with access to the internet
  • A bank account, credit card, or debit card with about $60–$100 USD to spare
  • An ability to follow through a very lengthy tutorial (I did say in depth)

The only thing you will need to pay for in this tutorial is a little bit of Ethereum (ETH) in order to deploy your brand new token and start your very own ICO. Everything else is free to use software open to the public! You can always follow along without buying anything if you just want to know the process. In that case, it’s free knowledge!!!

This tutorial is designed in such a way that even if you are not a programmer, and have very little to no technical knowledge, you to can launch your very own ICO in just a few minutes! As such, I will not go in depth in explaining the code, just to process to get your token/ICO live on the Ethereum blockchain.

Step 1. Setting up a Coinbase account and buying some ETH

The first thing you will need to do is set up a Coinbase account if you don’t already have one. Go to https://www.coinbase.com/ and click the signup button. It should look like this at the time of this writing:

Coinbase sign up

Fill in your details and click on the create account button. You will then be prompted to fill in a phone number. Once you do that, you will get a verification code to input via text message.

Once you have gone through that process you will need to do the Identity Verification. It should look something like this:

Coinbase Identity Verifications form

And set up a payment method. It should look something like this:

Coinbase set up a payment method

Now I do apologize that I am not able to 100% take you through this step by step. I tried to set up a new Coinbase account which I already have linked to all of my computers and Cell phones. When I tried to make the new one for this tutorial, Coinbase saw that as a security threat, prevented me from making the new account and locked out my account. They sent me an email about the potential security threat and asked me to either verify myself or take no action for 48 hours at which time my account became unlocked. So, I am happy to see that Coinbase is taking security very very seriously.

But, once you are all verified and your payment method has been linked, you can finally buy a bit of Ethereum and get this process started. To do this, click on the tab that says Buy/Sell, click on the Ethereum Icon and either type in the amount of money you plan to spend, or the amount of Ethereum you want to buy. It should look something like this:

Buying Ethereum form Coinbase

Now that you have a bought a bit of Ethereum and paid Coinbases outrageous fee (something close to 10% but we don’t really have many other options especially in the USA), we need to transfer the Ethereum out of Coinbase and into an ERC20 compatible wallet. So, let’s go set that up and come back to this.

Step 2. Setting up MyEtherWallet

Before we get started, I just want to say that I highly recommend using this link for the Ledger Nano S Cryptocurrency Hardware Wallet to keep your account and funds secure. It will normally run you around $100 USD, But this tutorial is all about using free software, so I am not going to cover that here.

The First step is going to https://www.myetherwallet.com/ Where you will be greeted with a big scary warning that looks like this:

MyEtherWallet site

Also why I recommend getting a Ledger Nano S, but I digress. Click on the “MyEtherWallet is not a Bank” button and you will be greeted with this page:

Create a new Wallet

Enter a new password and make sure to write it down as you will not be able to access your wallet ever again if you lose it.

After that, you will be taken to a page your you can download your keystore, print your paper wallet and see your private key. I recommend you store your private key in a safe place, print your paper wallet and download your keystore.

If you lose your password, you will not be able to use your keystore in MyEtherWallet. Your private Key is just that, PRIVATE. DO NOT GIVE IT TO ANYONE. It is used to digitally sign your transactions and your wallet is all but worthless without it. Your public key is used in creating the address that will be used to send and receive transactions. For the most part, it doesn’t really have a piratical use for the average user so there is no need too worry to much about it.

For the purposes of this tutorial, all the screenshots where the private key is visible are using a dummy account and will not be the actual wallet to send ETH to or to deploy the contract.

Download Keystore

After you click on download keystore and click the “I Understand Continue” button, you will be taken to this page:

Private Key page

Copy your private Key and save it in a safe location. If you click on the “Print Paper Wallet” button you will see something like this:

Paper Wallet

I usually keep this with me in my wallet. Keep it safe and secure location, as this gives direct access to your account and anyone else who has access to it.

Returning to the previous page click on the “Save your address” button and you will be taken to a page that looks like this:

MyEtherWallet Selector

Here, click on the “Keystore / JSON File” radio button, Click the “Select your wallet file” button and browse to your newly downloaded keystore file. Upload it and you will be prompted for your password.

As I said before, keep your password safe and handy. I forgot the password for the demo wallet I was using for this tutorial so I had to make another one. If I had had any Ether in that wallet, it would be gone forever to me. So now we have a new wallet with a new address to continue the tutorial with.

Once logged in, you will be able to see your wallet address. You’re going to want to copy that address, then we can continue to step 3! Where your address is will be highlighted in red in the image below.

MyEtherWallet Details

Copy that address and now we head back to your newly created Coinbase Account.

Step 3. Sending Ether to your new wallet

Comming base to Coinbase, after you log in click onto the Accounts tab and scroll down to the Ethereum section. There we will click on the send button highlighted below. It should look something like this:

Coinbase Accounts

Once you click on the button, a popup will appear. Paste your new wallet address into the receiver text box and fill out the amount of Ether you wish to send. Please note, that because of the cost of gas, you will not be able to send 100% of your Ether without lots of time-consuming calculations. I usually just leave a few bucks in the account and always make sure to buy a little more than I am going to need. The send screen should look something like this:

Send ETH from Coinbase

Once you have sent the Ethereum, you need to wait until enough miners have confirmed the transaction. This can be easily figured out by clicking on the transaction that just appeared in your list. This will pull up another popup that should look something like this:

Verifying a transaction from Coinbase

If you click onto the “View Transaction” link, it will take you to Etherscan.io where you can view the transaction hash in real time and see how many conformations it has or if it’s completed or not. That should look something like this:

Etherscan View Transaction

Once the transaction has the Green success for the “TxReceipt Status:” it’s time to start setting up the smart contract!

Step 4. Setting up the smart contract

A lot of ICO’s like to make their ERC20 tokens and ICO smart contract as two separate smart contracts deployed onto the Ethereum blockchain. We are not going to do that. Like the title says the easy way. So, what we are going to do is make one contract where the ICO is added as an extra feature of the token, and once the ICO is done and over with, we flip a switch and the ICO functions will just revert the transactions. Now, let’s get started!

First, we need to go to the remix compiler. At the time of this writing it should look something like this:

Remix compiler

Don’t worry too much about what is already in there. Remix just adds that as a default. Now, first things first. Go ahead and delete everything and start off with a nice empty page. Then, we can add the following code to the very first line:

pragma solidity ^0.4.23;

This is telling the compiler that we are going to be using solidity version 0.4.23.

Next, we need to add out Safe Math library and ownable modifier. If you don’t know what that means, don’t worry too much about it. It programmer speak and you do not need to understand it for this tutorial. Just copy and paste the following code below.

/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
    /**
     * @dev Multiplies two numbers, throws on overflow.
     **/
    function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
        if (a == 0) {
            return 0;
        }
        c = a * b;
        assert(c / a == b);
        return c;
    }
    
    /**
     * @dev Integer division of two numbers, truncating the quotient.
     **/
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // assert(b > 0); // Solidity automatically throws when dividing by 0
        // uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        return a / b;
    }
    
    /**
     * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
     **/
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }
    
    /**
     * @dev Adds two numbers, throws on overflow.
     **/
    function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a + b;
        assert(c >= a);
        return c;
    }
}
/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 **/
 
contract Ownable {
    address public owner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
     **/
   constructor() public {
      owner = msg.sender;
    }
    
    /**
     * @dev Throws if called by any account other than the owner.
     **/
    modifier onlyOwner() {
      require(msg.sender == owner);
      _;
    }
    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     **/
    function transferOwnership(address newOwner) public onlyOwner {
      require(newOwner != address(0));
      emit OwnershipTransferred(owner, newOwner);
      owner = newOwner;
    }
}

The Safe Math library will add functionality to the uint256 data type and allow us to perform some safe calculations and prevent overflow errors. If you don’t know about or would like to know more overflow errors the Wikipedia on it can be found here: Integer_overflow.

The Ownable modifier will allow the contract to be owned by an address and will grant us some special permissions to help prevent some malicious attacks.

Next, we need to add the ERC20 and ERC20Basic interfaces. They just set the groundwork to let the token do its job later.

/**
 * @title ERC20Basic interface
 * @dev Basic ERC20 interface
 **/
contract ERC20Basic {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 **/
contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

After that, we add the basic token and the standard token contracts.

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 **/
contract BasicToken is ERC20Basic {
    using SafeMath for uint256;
    mapping(address => uint256) balances;
    uint256 totalSupply_;
    
    /**
     * @dev total number of tokens in existence
     **/
    function totalSupply() public view returns (uint256) {
        return totalSupply_;
    }
    
    /**
     * @dev transfer token for a specified address
     * @param _to The address to transfer to.
     * @param _value The amount to be transferred.
     **/
    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balances[msg.sender]);
        
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        emit Transfer(msg.sender, _to, _value);
        return true;
    }
    
    /**
     * @dev Gets the balance of the specified address.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     **/
    function balanceOf(address _owner) public view returns (uint256) {
        return balances[_owner];
    }
}
contract StandardToken is ERC20, BasicToken {
    mapping (address => mapping (address => uint256)) internal allowed;
    /**
     * @dev Transfer tokens from one address to another
     * @param _from address The address which you want to send tokens from
     * @param _to address The address which you want to transfer to
     * @param _value uint256 the amount of tokens to be transferred
     **/
    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balances[_from]);
        require(_value <= allowed[_from][msg.sender]);
    
        balances[_from] = balances[_from].sub(_value);
        balances[_to] = balances[_to].add(_value);
        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
        
        emit Transfer(_from, _to, _value);
        return true;
    }
    
    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     **/
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
        return true;
    }
    
    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     **/
    function allowance(address _owner, address _spender) public view returns (uint256) {
        return allowed[_owner][_spender];
    }
    
    /**
     * @dev Increase the amount of tokens that an owner allowed to a spender.
     *
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     * @param _spender The address which will spend the funds.
     * @param _addedValue The amount of tokens to increase the allowance by.
     **/
    function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
    
    /**
     * @dev Decrease the amount of tokens that an owner allowed to a spender.
     *
     * approve should be called when allowed[_spender] == 0. To decrement
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     * @param _spender The address which will spend the funds.
     * @param _subtractedValue The amount of tokens to decrease the allowance by.
     **/
    function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}

All right, now we have our base token that meets ERC20 Standards. It can transfer, be held in an address, and does some other pretty basic stuff. But we still don’t have any tokens yet. Just a skeleton to build on top of. Since we are building an ICO into the token, let’s add the crowdsale part of the token next.

To do this we need to add the Configurable contract to keep track of some of our variables and the CrowdsaleToken to handle our ICO functionality. This part I will go a little more in depth with, as this is the important part. The rest of the code above has been copied and pasted from thousands of GitHub repositories around the world, so the information about it is pretty much everywhere.

First, the Configurable Contract.

/**
 * @title Configurable
 * @dev Configurable varriables of the contract
 **/
contract Configurable {
    uint256 public constant cap = 1000000*10**18;
    uint256 public constant basePrice = 100*10**18; // tokens per 1 ether
    uint256 public tokensSold = 0;
    
    uint256 public constant tokenReserve = 1000000*10**18;
    uint256 public remainingTokens = 0;
}

Short sweet simple and to the point. Essentially this is just a contract to hold most of our ICO variables. It’s not technically needed and we could just add these variables to the CrowdsaleToken, but this way is cleaner and easier to manage and maintain.

So, I bet your curious about what these variables do, so I will explain.

cap is the number of tokens that we want to sale.

basePrice is the number of tokens that will be sold per 1 Ether (1 Ethereum)

tokensSold is… well, the number of tokens that have been sold.

tokenReserve is the number of tokens that you want to keep for yourself or company.

remainingTokens is the number of tokens remaining that can be sold.

Pretty self-explanatory for the most part. and the weird looking 100*10**18is saying that we want 100 to the power of 18. This is needed because solidity cannot handle decimal numbers for the most part and everything on the Ethereum blockchain is handled in the smallest denomination of Ethereum called Wei. 1 Wei is equal to 0.000000000000000001 Ethereum. And writing out something like 100*10**18 is a whole lot easier to look at, read and modify later then 100000000000000000000. So it really is just a short hand things for “to the power of”.

Now, on to the CrowdsaleToken! If you don’t want to know or care about what these functions are doing, feel free to skip to the end of this section where all the code will be in one place.

First, we have our contract header.

contract CrowdsaleToken is StandardToken, Configurable, Ownable

Here we are saying that CrowdsaleToken is also a StandardToken, and that it is also Configurable and it is Ownable. Meaning that all the functionality of the StandardToken, Configurable, and the Ownable contracts are now available to the CrowdsaleToken.

Next, we have

enum Stages {
        none,
        icoStart, 
        icoEnd
    }
    
    Stages currentStage;

This current state will be used to let store the state of the ICO. none if not started, icoStart for ICO is Currently in process, and icoEnd for, you guessed it, the ICO is over.

Next, we have the constructor. When the contract is created, this function is called automatically.

constructor() public {
        currentStage = Stages.none;
        balances[owner] = balances[owner].add(tokenReserve);
        totalSupply_ = totalSupply_.add(tokenReserve);
        remainingTokens = cap;
        emit Transfer(address(this), owner, tokenReserve);
    }

Because we already defined the owner variable in the Ownable contract, and solidity must create each previously inherited contract before this constructor can be called, it’s automatically available to us and automatically assigns it to our address! Cool right?

So, from there we set the current stage to none, transfer the reserve tokens to our wallet address, add the reserve to the totalSupply_, then log the Event onto the Ethereum blockchain. Pretty cool stuff.

Next, we have the function without a name. The most important function of all. What this function is doing is taking the Ether that is sent to the contract address, calculating the number of tokens that should be issued back to the sender, making sure that we do not over-issue any tokens, and making sure that is more ether was sent then we have tokens for sale, that the remaining amount of ether is returned to the sender. All the valid ether is then sent to the contract owners wallet address.

/**
     * @dev fallback function to send ether to for Crowd sale
     **/
    function () public payable {
        require(currentStage == Stages.icoStart);
        require(msg.value > 0);
        require(remainingTokens > 0);
        
        uint256 weiAmount = msg.value; // Calculate tokens to sell
        uint256 tokens = weiAmount.mul(basePrice).div(1 ether);
        uint256 returnWei = 0;
        
        if(tokensSold.add(tokens) > cap){
            uint256 newTokens = cap.sub(tokensSold);
            uint256 newWei = newTokens.div(basePrice).mul(1 ether);
            returnWei = weiAmount.sub(newWei);
            weiAmount = newWei;
            tokens = newTokens;
        }
        
        tokensSold = tokensSold.add(tokens); // Increment raised amount
        remainingTokens = cap.sub(tokensSold);
        if(returnWei > 0){
            msg.sender.transfer(returnWei);
            emit Transfer(address(this), msg.sender, returnWei);
        }
        
        balances[msg.sender] = balances[msg.sender].add(tokens);
        emit Transfer(address(this), msg.sender, tokens);
        totalSupply_ = totalSupply_.add(tokens);
        owner.transfer(weiAmount);// Send money to owner
    }

That’s a lot of stuff for a function without a name. But there is a very important reason that it does not have a name.

This is called a fallback function. What a fallback function essentially is for is if someone sends either to the contract address without calling one of the functions of the contract, this function is called automatically. This allows us to ensure that all the Ether sent to the contract is handled appropriately. The payable keyword is required if the function is going to handle Ether at all.

Finally, we have the last 3 functions.

/**
     * @dev startIco starts the public ICO
     **/
    function startIco() public onlyOwner {
        require(currentStage != Stages.icoEnd);
        currentStage = Stages.icoStart;
    }
/**
     * @dev endIco closes down the ICO 
     **/
    function endIco() internal {
        currentStage = Stages.icoEnd;
        // Transfer any remaining tokens
        if(remainingTokens > 0)
            balances[owner] = balances[owner].add(remainingTokens);
        // transfer any remaining ETH balance in the contract to the owner
        owner.transfer(address(this).balance); 
    }
/**
     * @dev finalizeIco closes down the ICO and sets needed varriables
     **/
    function finalizeIco() public onlyOwner {
        require(currentStage != Stages.icoEnd);
        endIco(); 
    }

In order to begin receiving Ether for our ICO, the owner of the contract has to call the startICO() function. It’s pretty self-explanatory. It requires that the ICO has not ended yet, and then sets the contracts Current stage to icoStart. pretty simple.

The endICO() function has another new keyword called internal. What this means is that is cannot be called from outside of the contract, and what this function does is send any remaining unsold tokens and any remaining ether left in the contract to the owner’s address. It sets the state to let the contract know that the ICO is now over forever, and that’s about it.

The final function is the finalizeIco() function, which again, can only be called by the owner of the contract. All this function does is ensure that the ICO has not already been finalized, and then call the endICO() function. Pretty simple.

Be warned though. Once you call this function, there is no going back. If you call this function before you start your ICO, you will not be able to ever start it and will have to deploy a brand new contract. Everything that happens on the blockchain is permanent and forever. Once the code is up or a function called, it can never be changed.

Now for the final piece! The Actual Token!!!

All we need to do now is give it a name, give it an abbreviation like Ethereum is abbreviated to ETH for short, Bitcoin has BTC etc. etc. And lastly, tell it how many decimal places we are supposed to have.

/**
 * @title LavevelToken 
 * @dev Contract to create the Lavevel Token
 **/
contract LavevelToken is CrowdsaleToken {
    string public constant name = "Lavavel";
    string public constant symbol = "LVL";
    uint32 public constant decimals = 18;
}

That is about it for the code. We now have our very own Cryptocurrency with an ICO already built into it. Well… Almost. We still need to deploy it. Just for completeness, I’m going to post the entire source code all in one down below.

pragma solidity ^0.4.23;
/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
library SafeMath {
    /**
     * @dev Multiplies two numbers, throws on overflow.
     **/
    function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
        if (a == 0) {
            return 0;
        }
        c = a * b;
        assert(c / a == b);
        return c;
    }
    
    /**
     * @dev Integer division of two numbers, truncating the quotient.
     **/
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // assert(b > 0); // Solidity automatically throws when dividing by 0
        // uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
        return a / b;
    }
    
    /**
     * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
     **/
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }
    
    /**
     * @dev Adds two numbers, throws on overflow.
     **/
    function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
        c = a + b;
        assert(c >= a);
        return c;
    }
}
/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 **/
 
contract Ownable {
    address public owner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
     **/
   constructor() public {
      owner = msg.sender;
    }
    
    /**
     * @dev Throws if called by any account other than the owner.
     **/
    modifier onlyOwner() {
      require(msg.sender == owner);
      _;
    }
    
    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     **/
    function transferOwnership(address newOwner) public onlyOwner {
      require(newOwner != address(0));
      emit OwnershipTransferred(owner, newOwner);
      owner = newOwner;
    }
}
/**
 * @title ERC20Basic interface
 * @dev Basic ERC20 interface
 **/
contract ERC20Basic {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 **/
contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 **/
contract BasicToken is ERC20Basic {
    using SafeMath for uint256;
    mapping(address => uint256) balances;
    uint256 totalSupply_;
    
    /**
     * @dev total number of tokens in existence
     **/
    function totalSupply() public view returns (uint256) {
        return totalSupply_;
    }
    
    /**
     * @dev transfer token for a specified address
     * @param _to The address to transfer to.
     * @param _value The amount to be transferred.
     **/
    function transfer(address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balances[msg.sender]);
        
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        emit Transfer(msg.sender, _to, _value);
        return true;
    }
    
    /**
     * @dev Gets the balance of the specified address.
     * @param _owner The address to query the the balance of.
     * @return An uint256 representing the amount owned by the passed address.
     **/
    function balanceOf(address _owner) public view returns (uint256) {
        return balances[_owner];
    }
}
contract StandardToken is ERC20, BasicToken {
    mapping (address => mapping (address => uint256)) internal allowed;
    /**
     * @dev Transfer tokens from one address to another
     * @param _from address The address which you want to send tokens from
     * @param _to address The address which you want to transfer to
     * @param _value uint256 the amount of tokens to be transferred
     **/
    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(0));
        require(_value <= balances[_from]);
        require(_value <= allowed[_from][msg.sender]);
    
        balances[_from] = balances[_from].sub(_value);
        balances[_to] = balances[_to].add(_value);
        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
        
        emit Transfer(_from, _to, _value);
        return true;
    }
    
    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     *
     * Beware that changing an allowance with this method brings the risk that someone may use both the old
     * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
     * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     **/
    function approve(address _spender, uint256 _value) public returns (bool) {
        allowed[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
        return true;
    }
    
    /**
     * @dev Function to check the amount of tokens that an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return A uint256 specifying the amount of tokens still available for the spender.
     **/
    function allowance(address _owner, address _spender) public view returns (uint256) {
        return allowed[_owner][_spender];
    }
    
    /**
     * @dev Increase the amount of tokens that an owner allowed to a spender.
     *
     * approve should be called when allowed[_spender] == 0. To increment
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     * @param _spender The address which will spend the funds.
     * @param _addedValue The amount of tokens to increase the allowance by.
     **/
    function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
        allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
    
    /**
     * @dev Decrease the amount of tokens that an owner allowed to a spender.
     *
     * approve should be called when allowed[_spender] == 0. To decrement
     * allowed value is better to use this function to avoid 2 calls (and wait until
     * the first transaction is mined)
     * From MonolithDAO Token.sol
     * @param _spender The address which will spend the funds.
     * @param _subtractedValue The amount of tokens to decrease the allowance by.
     **/
    function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
        uint oldValue = allowed[msg.sender][_spender];
        if (_subtractedValue > oldValue) {
            allowed[msg.sender][_spender] = 0;
        } else {
            allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
        }
        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
        return true;
    }
}
/**
 * @title Configurable
 * @dev Configurable varriables of the contract
 **/
contract Configurable {
    uint256 public constant cap = 1000000*10**18;
    uint256 public constant basePrice = 100*10**18; // tokens per 1 ether
    uint256 public tokensSold = 0;
    
    uint256 public constant tokenReserve = 1000000*10**18;
    uint256 public remainingTokens = 0;
}
/**
 * @title CrowdsaleToken 
 * @dev Contract to preform crowd sale with token
 **/
contract CrowdsaleToken is StandardToken, Configurable, Ownable {
    /**
     * @dev enum of current crowd sale state
     **/
     enum Stages {
        none,
        icoStart, 
        icoEnd
    }
    
    Stages currentStage;
  
    /**
     * @dev constructor of CrowdsaleToken
     **/
    constructor() public {
        currentStage = Stages.none;
        balances[owner] = balances[owner].add(tokenReserve);
        totalSupply_ = totalSupply_.add(tokenReserve);
        remainingTokens = cap;
        emit Transfer(address(this), owner, tokenReserve);
    }
    
    /**
     * @dev fallback function to send ether to for Crowd sale
     **/
    function () public payable {
        require(currentStage == Stages.icoStart);
        require(msg.value > 0);
        require(remainingTokens > 0);
        
        
        uint256 weiAmount = msg.value; // Calculate tokens to sell
        uint256 tokens = weiAmount.mul(basePrice).div(1 ether);
        uint256 returnWei = 0;
        
        if(tokensSold.add(tokens) > cap){
            uint256 newTokens = cap.sub(tokensSold);
            uint256 newWei = newTokens.div(basePrice).mul(1 ether);
            returnWei = weiAmount.sub(newWei);
            weiAmount = newWei;
            tokens = newTokens;
        }
        
        tokensSold = tokensSold.add(tokens); // Increment raised amount
        remainingTokens = cap.sub(tokensSold);
        if(returnWei > 0){
            msg.sender.transfer(returnWei);
            emit Transfer(address(this), msg.sender, returnWei);
        }
        
        balances[msg.sender] = balances[msg.sender].add(tokens);
        emit Transfer(address(this), msg.sender, tokens);
        totalSupply_ = totalSupply_.add(tokens);
        owner.transfer(weiAmount);// Send money to owner
    }
/**
     * @dev startIco starts the public ICO
     **/
    function startIco() public onlyOwner {
        require(currentStage != Stages.icoEnd);
        currentStage = Stages.icoStart;
    }
/**
     * @dev endIco closes down the ICO 
     **/
    function endIco() internal {
        currentStage = Stages.icoEnd;
        // Transfer any remaining tokens
        if(remainingTokens > 0)
            balances[owner] = balances[owner].add(remainingTokens);
        // transfer any remaining ETH balance in the contract to the owner
        owner.transfer(address(this).balance); 
    }
/**
     * @dev finalizeIco closes down the ICO and sets needed varriables
     **/
    function finalizeIco() public onlyOwner {
        require(currentStage != Stages.icoEnd);
        endIco();
    }
    
}
/**
 * @title LavevelToken 
 * @dev Contract to create the Kimera Token
 **/
contract LavevelToken is CrowdsaleToken {
    string public constant name = "Lavavel";
    string public constant symbol = "LVL";
    uint32 public constant decimals = 18;
}

Also, you can find the source code here and everything else you will need for this tutorial. Except a cell phone, computer and a bit of money. Those are on you.

If you are curious about adding or exploring other possible features that you can add to ERC20 Tokens, feel free to check out my other GitHub repository. It’s not complete, and probably never will be, but at the time of this writing there are about 9 (I think) different kinds of ERC20 tokens and a few different modifiers, with more planned to be developed but i just haven’t gotten around to it yet. . I add to this repository from time to time when I’m bored and not working on another project. So, every now and again I’ll have something new up there. Start it and follow it if you want to get the updates when I add new stuff.

Or you can also try the OpenZeppelin repository. They have a lot more than just ERC20 tokens and have tons of solidity code written and available, and are always a great source for new code or just inspiration. Their project is based off in NPM and Node.js if I remember right. If I am wrong, I am probably to lazy to edit this latter.

Now, let’s deploy this contract!

Step 5. Deploying your contract to the Ethereum Blockchain

First, you need to copy the source code from the example above or from the GitHub repository if you don’t already have it up in the Remix Compiler. Once you have the solidity source code in the remix compiler, you need to hit the Start Compile button.

Once that finishes, use the drop-down arrow next to the details button to select the LavevelToken (Or whatever you have renamed the contract to) and hit the details button. These are labeled 1 and 2 in the image below. There are several contracts in this one contract so it is very important that you make sure to select the LevevelToken (Or whatever you have renamed it to). Selecting a different contract will give you different byte code and the deployment will not be successful.

Remix compiler

Once the details pane opens, scroll down to the BYTECODE section. There you need to copy the extremely long string of characters in the Object section. Make sure to only copy the numbers and letters and not the quote marks. This can usually be done by simply double-clicking on it and using Ctrl+C on Windows and Command+C on mac. It should look something like this:

Remix compiler bytecode

When you have copied the byte code, head back over to MyEtherWallet. Chances are pretty good that you will have to log in again as it logs you out a lot for security reasons, but by now, you should be familiar with the process. If not, you will be soon.

Once you are back into your wallet, in the menu list at the top you are going to want to click on the Contracts tab. Then you are going to want to click onto the Deploy Contract link. This should look like this before you click on the Deploy link:

MyEtherWallet Contracts tab

Once you click on the Deploy Contract link you can paste the byte code into the Byte Code box and MyEtherWallet will make you log into your wallet again once you want to deploy it. Don’t worry about the Gas Limit, just leave that alone. It should look something like this:

MyEtherWallet Deploy a contract

Once you have logged in, you should see a button pop up like this:

MyEtherWallet sign a contract

When you go to sign the transaction, you will need to confirm that you do indeed want to so this, because accidents happy and the blockchain is forever. it will look something like this:

Confirm signing a contract

Simply click the “Yes, I am sure! Make transaction.” button and then the “Deploy Contract” button to sign the transaction.

Once the transaction has been signed, a little green box will show up for a few seconds on the bottom of the screen that will have a link to the transaction hash in Etherscan. it will look something like this:

Successful contract deployment

If you miss the popup you can always copy your wallet address, head over the Etherscan.io and paste it into this box to view your history:

Etherscan.io

Once in your history, there should be an out transaction. if you click on it, it will take you to your newly deployed contract! Or if it is grayed out, click on the TxHash link and wait for the Green success to appear. If you do not see the transaction at all. just wait about a minute or two and it should pop up.

Transaction history

Congratulations, you have just deployed your very own ERC20 token to the Ethereum blockchain!! You are almost ready to start your very own ICO! Just one more step to go!

Step 6. Verifying you’re the code on Etherscan and adding it to MyEtherWallet and starting the ICO

Once the transaction is processed, we now need to verify the contracts code on Etherscan so that people who wish to interact with the contract can have access to the ABI (application binary interface). The ABI is needed in order for MyEtherWallet and other programs to know how to interact with the contract. So, let’s get that started by clicking on the Contract creation link. Once on the contracts address page, you should see something like this:

Contract Address Page

Here you want to click on the Code tab to start the verification process. Click on the link shown below to start the process.

Code Section

Once you click the link it should take you to the page in the image below. The contracts address should auto-populate. If not, you can always paste it in. First, make sure to turn the Optimization drop down to NO. This contract is not optimized and it will cause errors if you leave it as yes.

Verify Code

Open the remix compiler again and copy and paste the code into “Enter Solidity Contract Code Below” text box. Enter the Contracts name, In the case of this tutorial it would be LavevelToken. If you changed the name enter it exactly. For the Compiler version, in the remix compiler click on the settings tab and you will see this:

Compiler Version

Make sure in the drop down you match the current version number and commit hash, that is all the digits after the word commit. Make sure that optimized is set to no and you are ready to verify.

If you did everything correctly you should see this screen:

Verify Contract Code

If it has the green thumbs up message up at the top then it’s done, if you get a big red block up top, you have something messed up and need to repeat the above steps starting from when you clicked on the verify code link.

If everything was successful, you can now access your ABI code in Etherscan. Now to add the token to our wallet.


Heading back to MyEtherWallet go ahead and login to your wallet and just below on the right hand side you should see this:

ERC20 Tokens

I have already added the token in this image. But just follow the steps below because you will need to do this for every ERC20 token you have in your wallet. Click on the “Add Custom Token” Button and fill in the contract address which can be easily copied from Etherscan on the contracts page here:

Contract Address Copy Button

And enter in the Details like in the image below using whatever token abbreviation you chose and how ever many decimals you picked if you changed it at all and hit the Save button:

Adding Custom Token

Once successful, the new token should pop up in your list just like in the first image above. Now it’s time to start the ICO and make our first transfer to verify that everything works!


First, we need to go back to Etherscan to our contract page and click on the code tab. Now that the contract code has been verified, it will look a lot different. It will now have an ABI section that we will need to copy along with the contracts address. Leave the Etherscan tab open and open MyEtherWallet to the contracts tab to begin. Here we will paste the contract address and ABI code into the two text boxes provided. Once you do that a drop down should appear. In the drop down select the startICO function from the list. Having everything set up, it should look something like this:

Starting the ICO

Remember, Only the wallet address that deployed the contract can call this function successfully. Once you click the Write button a popup will appear with a generate transaction button. Click the generate transaction button and it will ask you to sign into your wallet again. Once you do you, the popup will change slightly and you should see something like this:

Confirm calling of start ICO function

Leave the Gas limit alone and click the “Yes I am sure! Make transaction.” button. The by now familiar green popup will appear once again at the bottom of the screen. If you click on it, it will again take you to Etherscan and if you see something like this:

Transaction not confirmed

Do not panic or worry, all that means is that the transaction has not been picked up yet. Just wait a little bit and hit refresh if the page does not refresh its self and you should see something like this:

Pending transaction

Once the (Pending) turns into a green success for the “TxReceipt Status:” your ICO is up and running!! Congrats!

Now to test it to make sure everything worked correctly.


Copy the contracts address one more time and head back to MyEtherWallet, login, and click on the Send Ether & tokens tab. There you want to do a small test. I’m going to buy 3 of my brand new tokens just as a test. Fill in the details like the image below:

Buying tokens

Once you click on Generate Transaction you should see something like this:

Confirm you want to send Ether

Click on the “Yes, I’m sure! make transaction.” button and the by now familiar green pop up at the bottom of the screen will popup again. If you haven’t figured it out by now, the green popup happens whenever you successfully submit a transaction to the Ethereum blockchain. If something went wrong, it will normally be red. This green popup does not mean that the transaction will be successful, just that it was submitted successfully. Clicking on it will take you back to Etherscan.io to see the transaction:

Transaction hash for buying tokens

Once it is successful, Looking back at your wallet. You should see that the Ether has returned to your wallet, minus the transaction cost, and you should have a few new shiny tokens just like below:

Token purchase and return of Ether success

Now your ICO and ERC20 token is live and ready to go. I wish you all the best and success in your project. I hope you enjoyed the painfully long, but informative tutorial.

Wrapping up

Just for a quick reference, at the time of this writing 1 ETH (Ethereum) is at $404.26 USD. To deploy this token onto the blockchain (I ended up deploying two because I forgot to take pictures of the process on the first one) cost $40 USD and $36 USD for the cost of GAS. I put in $100 out of my pocket which Coinbase takes about a $10 fee, then had to transfer the remaining ETH into my ERC20 compatible wallet to deploy the contract from there. Leaving roughly $5 of ETH in my Coinbase wallet and about $17 of ETH left over in my new account created with MyEtherWallet.

For the purposes of completion, I went through the step by step creation of a new wallet where I took pictures of both the public and private keys. that wallet is a dummy account made only for this tutorial and not the address used to create the ERC20 tokens or the one I sent the ETH to.

The Contract address used in this tutorial is 0x9922D178DFEeD0c19618A2A9bac8810E37F02909 which you can view live on Etherscan to verify this tutorial.

The testing process to verify this code lasted about all of 5 minutes, so it has a very high potential for bugs and I do not recommend using it for an actual ICO, just for educational purposes.

Just a quick Disclaimer, while this is a live ICO and ERC20 contract on the Ethereum Blockchain, this is not a real ICO. I have no product, company or vision attached to this and this contract and it was made for the solely for this tutorial. If you send Ethereum to this address you will NOT get it back and it will be considered a donation.

If you would like to know how to list your token on an exchange for free, please refer to my article How to Get Your ERC20 Token onto an Exchange For Free

I hope you enjoyed this tutorial and that you found it informative. If you have further questions, feel free to contact me on my LinkedIn or Twitter. I’m always happy to help. I spent many long days making this tutorial and I hope you enjoyed it and found it useful.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...