How to create a token/coin on Ethereum
A couple of days ago I was trying to create a token for my Dapp (Decentralized App). However, I found the current tutorial on the Ethereum website not clear and missing references. My goal here is to show how to create a token on Ethereum using Solidity, Truffle and MetaMask — if you don’t know what these are, just click on them.
The Token
The name of our token will be Friendship, and represents how much another person is your friend.
Let’s start by creating a project with Truffle:
$ mkdir Friendship # Project folder$ cd Friendship # Accessing…$ truffle init # Scaffolding the project
If you check the generated contracts, you will see Metacoin.sol
and Convertlib.sol
, just ignore, we’re not going to use them.
Create a new file called Friendship.sol
under contracts folder. The token is a smart contract:
Now, declare the properties that by convention represents tokens and create the initializer method that will have an initial supply as a parameter.
These properties will also make MetaMask recognize our contract as a token.
Generating and Interacting
In order to generate and manipulate the tokens, we need deploy the contract into the network, let’s use testrpc to simulate an Ethereum client with two accounts previously created by MetaMask.
$ testrpc --account="0xf3a..., 7000000000000000000" --account="0xacb...,80000000000000000000000" # Starting the client passing two private keys from two accounts generated by MetaMask and an amount of ether.
And require Friendship.sol
into 2_deploy_contracts.js
Migrate
truffle migrate --reset # Deploying the contract into the network
After migrating, you can see that Bar has all the tokens, because truffle will grab the first account and make it the default — the first private key passed to testrpc is from Bar.
Interacting / Transfer
Access truffle console:
$ truffle console
On the console:
var friendship = Friendship.deployed() // Note: the owner of the contract will be the first user on testrpc.
Transferring
With the console open we call the function transfer
and pass an address
friendship.then(frn => frn.transfer('0xAA6a7242E2F0976f2402DAD991be5b43A189234B', 20000000)) // Foo address
And now we can check the balance for 0xAA6a7..
:
You can check the complete project on Github
Warning: Here we create a toy token, if you’re planning to create a token /coin for the main Ethereum network, make sure you write plenty of tests!
Conclusion
To create and deploy a token on Ethereum, it is about creating a smart contract with some specific properties. In this tutorial our token is not doing much, but as you grow you can add more features like allowing another contract spend tokens on your behalf, check a full example on Ethereum’s website .