In this tutorial, we’ll show you how to create your own cryptocurrency with Ethereum.

Now we’re at the moment of truth. In this lesson we’ll put all that we have learned into action. We’ll analyze and study one of the example codes on the official Ethereum website. This code is an example on how to create your own crypto currency, and by now we should be able to read and understand this code and almost any other smart contract code.

Read the official Ethereum.org source code for creating your own cryptocurrency.

contract tokenRecipient { 

    function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData);

}

contract MyToken {

    /* Public variables of the token */

    string public standard = 'Token 0.1';

    string public name;

    string public symbol;

    uint8 public decimals;

    uint256 public totalSupply;

    /* This creates an array with all balances */

    mapping (address => uint256) public balanceOf;

    mapping (address => mapping (address => uint256)) public allowance;

    /* This generates a public event on the blockchain that will notify clients */

    event Transfer(address indexed from, address indexed to, uint256 value);

    /* Initializes contract with initial supply tokens to the creator of the contract */

    function MyToken(

        uint256 initialSupply,

        string tokenName,

        uint8 decimalUnits,

        string tokenSymbol

    ) {

    balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens

    totalSupply = initialSupply; // Update total supply

    name = tokenName; // Set the name for display purposes

    symbol = tokenSymbol; // Set the symbol for display purposes

    decimals = decimalUnits; // Amount of decimals for display purposes

    }

    /* Send coins */

    function transfer(address _to, uint256 _value) {

    if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough

    if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows

    balanceOf[msg.sender] -= _value; // Subtract from the sender

    balanceOf[_to] += _value; // Add the same to the recipient

    Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place

    }

    /* Allow another contract to spend some tokens in your behalf */

    function approveAndCall(address _spender, uint256 _value, bytes _extraData)

    returns (bool success) {

        allowance[msg.sender][_spender] = _value;

        tokenRecipient spender = tokenRecipient(_spender);

        spender.receiveApproval(msg.sender, _value, this, _extraData);

        return true;

    }

    /* A contract attempts to get the coins */

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {

    if (balanceOf[_from] < _value) throw; // Check if the sender has enough

    if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance

    balanceOf[_from] -= _value; // Subtract from the sender

    balanceOf[_to] += _value; // Add the same to the recipient

    allowance[_from][msg.sender] -= _value;

    Transfer(_from, _to, _value);

    return true;

    }

    /* This unnamed function is called whenever someone tries to send ether to it */

    function () {

        throw; // Prevents accidental sending of ether

    }

}

The first thing you might’ve noticed is the style of the code. It varies, both from most of the code that we’ve created in the previous lessons, and even within this code itself there are some inconsistencies between one line and the other. Relax, It’s only an aesthetic matter. Just like literature writers – each with its own individual style of writing, so is each coder writes his or her code slightly different from its peers. But remember, In most cases it’s only a matter of style preferences, it will hardly have any effect on the way the code will be executed.

The code begins with the declaration of two contracts tokenRecipient and myToken. We can see that there’s no heredity relation between the two. (The contract myToken IS NOT tokenRecipient). From this we can dictate two things.

The contract myToken will not inherit any attributes from the contract tokenRecipient.
The contract tokenRecipient is probably mentioned in this code because the myToken contract will have some sort of interaction with this type of contract

Because the contract myToken dosen’t inherate any attributes from the contract tokenRecipient , we’re not obliged to begin our reading of the code by first reading the contract tokenRecipient. We can begin by reading the contract myToken, and that’s excatly what we’re going to do now.

Deploying the contract myToken

So let’s focus on the main contract – the myToken contract. We can see that this contract has a constructor function (Reminder constructor functions have the same name of the contract. Every contract can have only one constrictor function).

contract MyToken {

    /* Initializes contract with initial supply tokens to the creator of the contract */

    function MyToken(

        uint256 initialSupply,

        string tokenName,

        uint8 decimalUnits,

        string tokenSymbol

    ) {

        balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens

        totalSupply = initialSupply; // Update total supply

        name = tokenName; // Set the name for display purposes

        symbol = tokenSymbol; // Set the symbol for display purposes

        decimals = decimalUnits; // Amount of decimals for display purposes

    }

}

The constructor function myToken takes 4 arguments from the user, but before we’re going through them, let’s have a look at the complete list of the variable that are defined in this contract.

contract MyToken {

    string public standard = 'Token 0.1';

    string public name;

    string public symbol;

    uint8 public decimals;

    uint256 public totalSupply;

    /* This creates an array with all balances */

    mapping (address => uint256) public balanceOf;

    mapping (address => mapping (address => uint256)) public allowance;

}

The first variable standard is a public string that is hard coded to contain the following message “Token 0.1”. This message has no real meaning. The one who wrote this code probably assumed that he’ll make more codes for other crypto currencies and he just wanted to make sure that anyone who uses a crypto currency that was created with this code, will be notified that the coin which he or she is using was created with this specific code.

The second and third variables name and symbol will hold the name of our token and the token symbol (for example, Diginomics Coin as a coin name, and DGC as its symbol). Now we’re getting to the real part, the next variable decimals will specify the amount of decimal places our currency can be divided to. Remember that in Ethereum, one Ether can also be displayed as 1. followed by 18 zeros? Can one DGC be splinted to cents? how about 0.9999999? will this represent a usable denomination? We can even leave this field as zero, that way our coin won’t be dividable and we can associate it with real life object.

One coin might be worth one cup of coffee, or one ticket to a concert. The decimals variable is where we’ll define our sub denominations. totalSupply will represent the finite amount of tokens which we’re about to mint using this code. We can mint only few hundreds or as many as millions.

After we’ve declared variables for the coin name, code, decimal units and total supply. The next thing that our contract needs is a type of an account book which will keep the balance of each user (address). And to do so, an array was declared. This array is called balanceOf and it uses address to map to each individual cell. Each cell will contain a uint256 variable. The number in this variable will represent the current amount of tokens that the user who own this address can use. Pay attention that unlike many other cryptocurrencies, our coin doesn’t necessarily maintain a public ledger or blockchain, instead it relays on the Ethereum blockchain to keep its own variables secure and accurate.

allowance is the last variable. Let’s leave it for now. We’ll get back to it soon enough, but right now we have all that we need in order to run our constructor function, so let’s see what this function is all about.

contract MyToken {

    /* Initializes contract with initial supply tokens to the creator of the contract */

    function MyToken(

        uint256 initialSupply,

        string tokenName,

        uint8 decimalUnits,

        string tokenSymbol

    ) {

        balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens

        totalSupply = initialSupply; // Update total supply

        name = tokenName; // Set the name for display purposes

        symbol = tokenSymbol; // Set the symbol for display purposes

        decimals = decimalUnits; // Amount of decimals for display purposes

    }

}

Well, the constructor functions ask the user to insert four arguments. It will ask the user to insert these four arguments only once, and that is at the time of deployment. These four arguments are: initialSupply, tokenName, decimalUnits and tokenSymbol. Then, our constructor function will assign each of these values to the proper variable. It is easy to guess that tokenSymbol will be given to Symbol, decimalUnits to decimals, tokenName to name and initialSupply to totalSupply. But why we’re also assigning the balance of the creator of the contract with the initial supply? well, our contract is quite simple actually, it will provide ALL of the initial amount of tokens to a single balance, the balance of the creator. This is of course only the way that this smart contract works, we can write smart contract with more sophisticate rules and mechanism to dispense your coin in a fairer manner. It’s only up to you!.

Transfer

In the previous section we’ve declared the variables of the contract myToken and we’ve populated them, using the constructor function (The only variable we haven’t populated using the constructor function is the string standard. This string is hard coded).

Now we can see that our code contains three more named function transfer, callAndAprove and transferFrom. One event called Transfer (pay attention that the event Transfer begins with a capital T, while the function transfer begins with a lower case t). And one more unnamed function. We’ll begin by looking at the three named function.

The first function is transfer:

function transfer(address _to, uint256 _value) {

    if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough

    if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows

    balanceOf[msg.sender] -= _value; // Subtract from the sender

    balanceOf[_to] += _value; // Add the same to the recipient

    Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place

}

The transfer function is used to transfer (send) tokens from one address to another. This function asks the user to supply two arguments: the address of the receiver (_to) and the amount of tokens that the user wishes to send _value. Once the user inserted this arguments, the function will run two If statements. The first If statement will make sure that the balance of the sender (The one who called the function transfer has enough token at his or her disposal at balanceOf[msg.sender]. If he or she doesn’t have enough the execution of the function will be stopped (thrown). Once we’ve passed the first If statement, there’s another test we need to pass. In this test, we’re making sure that, no matter what, the balance of the receiver plus the new value will not be lower than the original balance of the receiver. (We’re basically making sure that the variable _value will not contain any negative number that might accidently drain the balance of the receiver). If we’ve passed both of the tests above, we’re free to perform our transfer, and transfer basically means to remove the _value from the balanceOf the sender (msg.sender), and add it to the balanceOF the receiver (_value). And last, we’ll use the event Transfer (with a capital T) to let anyone who’s following our contract that the transfer was completed by providing the address of the sender, the address of the receiver and the amount of tokens that were sent.

approveAndCall

The second function is approveAndCall:

function approveAndCall(address _spender, uint256 _value, bytes _extraData)

returns (bool success) {

    allowance[msg.sender][_spender] = _value;

    tokenRecipient spender = tokenRecipient(_spender);

    spender.receiveApproval(msg.sender, _value, this, _extraData);

    return true;

}

Over here we’re defining the child contract (tokenRecipient). Each tokenRecipient will be allowed to use a fixed amount of tokens, as defined in the array allowance. This function will take the following arguments: The address of the one who is allowed to spend the token (_spender), The amount of tokens he or she is allowed to spend (_value), and string of bytes that will contain some extra data (_extraData – for the purpose of this tutorial we’ll leave this field empty). The function will also return a Boolean variable called success which will be used in order to indicate that the function was indeed sacksful. The first step that this function will do is quite straight forward. It will look inside the array allowance for the cell with the same index as the msg.sender, then it will look inside this cell for the array with the address of the _spender and it will populate this cell with the amount of tokens (_value) this spender is allowed to use.

The next two lines will look for the contract of the token recipient and will notify it by calling the function receiveApproval. So now seems like a good time to look into the first contract.

contract tokenRecipient { 

    function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); 

}

This contract will be used by all those who are allowed to spend tokens. You might ask yourself “Why do we need another special contract for that, didn’t the transfer function already allows us to send tokens to any address?”, and you’ll be right. In most cases the transfer function will be enough, but in this case, the creator of the contract wanted to add another functionality into the contract – the allowance functionality. And as a part of this decision, the creator also decided that whenever we authorized a contract to use some of the tokens (remember, everything in Ethereum is a contract, even a simple user wallet), this contract will also be notified, and it will also be requested to approve our call. To do so, we need to add the functionality we believe the recipient of the token contract will support. Pay attention, we aren’t necessarily going to deploy a contract like tokenRecipient, we’re just telling the compiler that we’re believing such a contract exist, and if it does exist, it can be used as defined (in our case, if such a contract exist, it will have the function receiveApproval, which will take the arguments: _from, _value, _token and _extraData).

Now that we know that a contract like tokenRecipient will include the function receiveApproval, and we know how to use this function, we can go back to our approveAndCall function in our token contract and tell the Ethereum Virtual Machine what its next septs should be. First, it should declare a new object which will represent the recipient. This object will be declared like any other object by first declaring its type tokenRecipient and then its name _spender. But because this object should also represent a real contract, we also need to tell the Ethereum Virtual Machine, where it can find this contract by providing the address of that contract (_spender). Once our object _spender was defined, we can use it by calling its function receiveApproval. It this function goes through, we’ll get to the finale step of our function – returning true value to the Boolean success

transferFrom

The third function is transferFrom:

function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {

    if (balanceOf[_from] < _value) throw; // Check if the sender has enough

    if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance

    balanceOf[_from] -= _value; // Subtract from the sender

    balanceOf[_to] += _value; // Add the same to the recipient

    allowance[_from][msg.sender] -= _value;

    Transfer(_from, _to, _value);

    return true;

}

This function is very similar to our transfer function, with four differences.

This function will take one more argument from the user – The _from address, which will represent the address of the parent contract.

Another If statement is used to make sure that the msg.sender is allowed by the parent contract (which is under the_from address), to send the required amount of tokens. This is done by checking the allowance array.

After the transfer was completed, The allowance array will be updated to subtract the amount of tokens the msg.sender spent.
the value true will be returned to the user.

unnamed functions

The last function is the unnamed function:

function (){

    throw;

}

That’s one of our security mechanism. If the contract is requested to perform a function that wasn’t predefined, just throw the call.

The Ethereum Virtual Machine cannot, at this stage, support which sizes which are not pre-defined – like strings. The bytes variable type allows us to bypass this restriction by sending the data in the form of a bytes string.

You need to be logged in to see your course progress.