Hello World on the Ethereum Blockchain

Anyone attempting to learn and explore the Ethereum blockchain will quickly come across some difficult hurdles. The first of these is, of course, the difficulty inherent in getting one’s head around the paradigm shift that is blockchain technology. The second is that the software implementation is rather complex and the third is that the documentation is poor and constantly lags behind the latest developments.

This article is designed to help newcomers who wish to dig past the basic concepts, and get their hands dirty by implementing some very simple distributed applications on Ethereum. We have trawled through various tutorials to try and validate which combination of development tools is the best to use in exploring and testing Ethereum distributed applications.

To negotiate the first challenge; wrapping one’s head around the paradigm shift that is the blockchain, we recommend reading this article: http://truffleframework.com/tutorials/ethereum-overview. There are plenty of other articles and lectures out there that will help you get a high level overview of why blockchain tech is a paradigm shift.

Lets get started.

The developer environment

There are essentially two groups of technologies we will need develop a distributed application (or dApp). These are:

  1. An Ethereum node connected to a test network. In the blockchain world, a “node” is an instance of the distributed ledger on your own computer. To get this distributed ledger, you will need to install the necessary software, then perform a ‘sync’ which involves downloading the ledger (likely to be gigabytes big) onto your own machine. In our case, the ledger is a test network ledger, designed to provide a testing environment. This network is called Rinkeby (there are others).
  2. Tools to interact with Ethereum via your node. There are various ways to talk to an Ethereum network, we will use javascript based technologies that are executed through a command line interface (CLI) environment. We will create new accounts, wallets, test sending ether etc. using these tools. We will also write, compile and deploy ‘smart contracts’. Once we can interact with the Ethereum network, we will need to work out how to write, compile, deploy and test a ‘smart contract’. The language we will use is called Solidity, and the framework we will use to compile and deploy Solidity apps to Ethereum is called Truffle. In our struggle to get our heads around writing dApps, Truffle proved to be the missing link: it facilitates the multiple complex steps required to deploy a smart contract to the Ethereum Virtual Machine.

Development tools

Ethereum.org recommends using the Ethereum Wallet; a complete development environment wrapped up in a GUI that, notionally, facilitates the development lifecycle. We found, however, that Ethereum Wallet suffers from a few issues. Its GUI is buggy, and by hiding complexity behind a simple UI a fair amount of understanding is lost. Further, when a part of the process goes wrong, it is very difficult to isolate the issue when so much is hidden behind the GUI.

So we have opted for command line tools. There are, here, multiple challenges. The first of these is that documentation is poor. Another is that there is quite a broad range of frameworks necessary. Below, we break it down into easy steps for you.

NOTE: If you are running Windows, we have found that using an alternative command line interface to Windows’ cmd is preferable. We have used Cygwin and found this to be quite good. You can download and install Cygwin from the Cygwin website.

Step 1: Install an Ethereum Node

Geth is the Go-Ethereum implementation of the Ethereum spec. It provides the software necessary to run a node, and also the command line interface (CLI) necessary to interact with that node.

Once Geth is installed, syncing with the Rinkeby (test) network … i.e. downloading the distributed ledger … may take hours depending on your Internet speeds.

  1. Download and install Geth from here: https://geth.ethereum.org/downloads/
  2. At your terminal (*nix) or cmd (win) initialise Geth to run with the test Ethereum network called Rinkeby. This tutorial offers a quick step-by-step guide on how to get the Rinkeby network up and running. However, we have found that the command line parameters used when launching Geth to connect to the Rinkeby network are best sourced from the Rinkeby web site under the tab “Connect Yourself”. Once Geth is launched, the syncing process (which may take hours) begins.
  3. Create an account (and key). An account exists as an alphanumeric key.  This page offers a good place to start. All that is essentially necessary is to run the following command (and type in a password). Make sure that you save your account key somewhere.
    geth account new
  4. Request ‘monopoly money’ Ethers. This is done by going to the Rinkeby Faucet webpage, and following the instructions there. You will need your account key. Note: the instructions change all the time, so there is no point documenting it further here.

When running the Geth node, please use the below command. This command includes the –rpc variable which will mean that we can connect to Geth from Truffle, to deploy our new contract.

geth --networkid=4 --datadir=$HOME/.rinkeby --cache=512 --ethstats='yournode:Respect my authoritah!@stats.rinkeby.io' --rpc --unlock="0x5bfabbdae534f68f52bd212497575aac4b864985" --bootnodes=enode://a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf@52.169.42.101:30303

Note: The above command will ask you for the password associated to your wallet account key.

Step 2: Install contract development tools

Install NodeJS

NodeJS is … It comes with the NodeJS Package Manager (NPM). The NPM will later be used to download other frameworks.

  1. Install NodeJS from here: https://nodejs.org/en/

Install solc, the Solidy compiler

Now that NodeJS is used, we can install the Solidity compiler simply using NodeJS’ package manager. Type this in the terminal:

npm install -g solc

Install Truffle

Truffle is a framework that takes a lot of the pain out of deploying contracts on Ethereum. Again, type this into the terminal:

npm install -g ethereumjs-testrpc
npm install -g truffle

Writing and deploying a contract

Now, we can get down to business. We will write the contract in Solidity in text file ending in *.sol. It will then be compiled down to bytecode which can be run on the Ethereum Virtual Machine. Doing these steps is quite complex and so we use a framework called Truffle. Truffle makes compiling and deploying a distributed app similar-ish to compiling an application in modern language like, say, Java.

First lets create a folder that will contain the entire project.

$ mkdir hello-world
$ cd hello-world
$ truffle init

You’ll notice that this causes Truffle to write a folder structure into your project folder. It creates:

  • a contracts folder
  • a migrations folder
  • a test folder
  • a truffle.js file

To get Truffle to work with the test network Rinkeby, add the following lines to your truffle.js. Make sure that you change the ‘from’ address to be your own account created on the Rinkeby network.


module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" // Match any network id
    },
    rinkeby: {
      host: "localhost", // Connect to geth on the specified
      port: 8545,
      from: "0x0085f8e72391Ce4BB5ce47541C846d059399fA6c", // default address to use for any transaction Truffle makes during migrations
      network_id: 4,
      gas: 4612388 // Gas limit used for deploys
    }
  }
};

Copy the below contract into your contracts folder. Call it Greeter.sol


pragma solidity ^0.4.0;

contract mortal {
  /* Define variable owner of the type address */
  address owner;

  /* This function is executed at initialization and sets the owner of the contract */
  function mortal() { owner = msg.sender; }

  /* Function to recover the funds on the contract */
   function kill() { if (msg.sender == owner) selfdestruct(owner); }
  }

contract greeter is mortal {
  /* Define variable greeting of the type string */
  string greeting;

  /* This runs when the contract is executed */
  function greeter(string _greeting) public {
    greeting = _greeting;
  }

  /* Main function */
  function greet() constant returns (string) {
    return greeting;
  }
}

Deploy

We use Truffle to deploy the contract. In the Greeter.sol code we are using, a constructor parameter is used. To make sure that Truffle uses a constructor parameter when the contract is deployed, we need to add 2 lines in the 2_deploy_contracts.js file:

var ConvertLib = artifacts.require("./ConvertLib.sol");
var MetaCoin = artifacts.require("./MetaCoin.sol");
var greeter = artifacts.require("./Greeter.sol");

module.exports = function(deployer) {
 deployer.deploy(ConvertLib);
 deployer.link(ConvertLib, MetaCoin);
 deployer.deploy(MetaCoin);
 deployer.deploy(greeter, "Hello World");
};

Deploy the contract to the Rinkeby test net:

truffle migrate --network rinkeby

Go to Ether scan to see if your contract has deployed correctly. You’ll need to replace the wallet key with your own:
https://rinkeby.etherscan.io/address/0x5bfabbdae534f68f52bd212497565aac4b864985
You’ll also notice that the contract deploy will be logged in your Geth node log tail.

Interacting with the contract

To interact with the contract, we need to know the address of the contract, and the ABI of the contract.

Both of these can be found in multiple ways. Perhaps the easiest is to consult the  appropriate JSON file, created by Truffle, in the builds directory.

Here are 3 ways to get the contract address:

  1. Look at the transactions on etherscan: https://rinkeby.etherscan.io/address/0x0cc5c81bc72f012961c12c636f3f0245e1f7f204
  2. Look at the Geth node output log tail
  3. Look at the JSON file in the builds directory

In my case the contract address is: 0x0cC5C81BC72F012901C12c636f3f0245e1f7f204

The ABI is all the available functions that the contract offers (it is like the API of OO programming). When interacting with contracts, the ABI must be supplied. I assume this is because the contracts do not have self-knowledge about what methods/functions/params that they expose.

Getting the ABI is slightly painful, because white space must be stripped out. … AND … it needs to be presented as a Javascript array. Use this webinterface to strip out the white space: https://www.browserling.com/tools/remove-all-whitespace.

My ABI is thus: [{“constant”:false,”inputs”:[],”name”:”kill”,”outputs”:[],”payable”:false,”type”:”function”},{“constant”:true,”inputs”:[],”name”:”greet”,”outputs”:[{“name”:””,”type”:”string”}],”payable”:false,”type”:”function”},{“inputs”:[{“name”:”_greeting”,”type”:”string”}],”payable”:false,”type”:”constructor”}]

Go into Geth (geth attach in command line) and now run the below line. This will parse the ABI code into a Javascript array:

var myABI = JSON.parse('[{"constant":false,"inputs":[],"name":"kill","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"inputs":[{"name":"_greeting","type":"string"}],"payable":false,"type":"constructor"}]');

Now create a javascript object that represents the contract. This javascript object can then be used to access the contract and call methods on it:

var griter = eth.contract(myABI).at("0x0cC5C81BC72F012901C12c636f3f0245e1f7f204");

Now, we can test calling the greet() method:

griter.greet();

If geth prints out “Hello World” then congratulations, you are done!

What is interesting, at this point, is trying to understand if any parts of the Ethereum network has changed as a result of us calling this method. If you look in Etherscan, you’ll see that nothing is changed; that is, no transaction is necessary to retrieve a value from the blockchain. Similarly, no gas is required.

The next step is to require paying a certain amount of Ethers to call the “greet” method. For example, imagine a contract in which the user must pay something in order to see a message, a password, a text passage etc. In such an instance, a transaction would be necessary and calling the ‘greet’ method (which would probably be better called something else) would result in a change to the state of the blockchain, and a change to counts of ether in various accounts.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *