Your First Ethereum Smart Contract

, we are going to delve deeper into Smart contracts, the backbone of the Ethereum platform and, later you will be building your own Smart contract, just so you can get an idea of what to do and how they work. You will need to know how to use your command line for this and you should also have a basic understanding of computer programming. If you haven’t already got it, you will need to download geth.

The Smart contract is an account that holds objects on the blockchain. Each one contains functions written in code and they can interact with one or more other Smart contracts. They can also make decisions, they can store data and they can send ETH to other users. A contract is defined solely by its creator but the execution of the contract and the services that it offers is done by the Ethereum network. The contract will exist and will be executable for as long as the entire network is in existence and will only go if it is programmed with a self-destruct command.

So, what you can do with these contracts? The better question would be what do you want to do with these contracts? Smart contracts can be used for all sorts of things, from a simple “I will pay you this much on this date” contract, right up to something much more complicated. To give you a better idea, we are going to build a very simple contract, the “Hello World” contract, and then we will build a crypto token that you can send on to whomever you want. Once you have the hang of that, you will move on to raising funds through crowdfunding and, if that is successful, it will supply a democratic and radically transparent organization that will only do the bidding of its own citizens, will never go against its own constitution and has no way of being censored or even closed. And you are going to do all that in 300 lines of code or less.

Let’s begin.

Your very first citizen is going to be ‘the greeter’. This is an automatic companion that will talk to you and greet you whenever you are feeling a little lonely because, let’s face it, the Frontier is a lonely place! ‘The Greeter’ is a digital entity, a very intelligent one that lives on the Ethereum blockchain. He can have a conversation with anyone who

interacts, based on the input and while he may not be able to physically talk, he is a fantastic listener. To get started, open your command line and then input the following code at the command prompt:

contract mortal {

/* Define the variable owner of the type address*/ address owner;

 

/* this function will be executed at initialization and will set the owner of the contract */

function mortal() { owner = msg.sender; }

 

 

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

}

 

 

contract greeter is mortal {

/* define the variable greeting of the type string */ string greeting;

 

/* this will run when the contract is executed */ function greeter(string _greeting) public { greeting = _greeting;

}

 

 

/* main function */

function greet() constant returns (string) { return greeting;

}

}

Did you notice, while you were typing away, that we have two separate contracts here? One is “mortal” and one “greeter”. The reason for this is the high-level language, Solidity, that we use is a language that accepts inheritance. What that means is that a contract may inherit one or more characteristics from another contract. This is incredibly useful and helps us to simplify the code as we won’t need to rewrite any characteristics that are common between the contracts. And that leads

to smaller, better written and easier to read contracts. So, when we declare that ‘the greeter’ is ‘mortal’ we are inheriting the traits from the ‘mortal’ contract, keeping our code much simpler.

The characteristic of ‘mortal’ that is inherited means nothing more than that the ‘greeter’ contract may be killed off by the owner. This would be done as a way of cleaning the blockchain up and recovering any funds that may be locked into it when the contract is finished and isn’t needed any further. By default, Ethereum contracts are immortal and do not have owners, which means that once they have been deployed, the author or owner has no privileges any longer – be aware of this before you deploy your contract!

The Solc Compiler

Now, before you can deploy these contracts, you need two things – the code that has been compiled and the ABI – Application Binary Interface. This is a JavaScript Object that defines the interaction with the contract. The first part, the compiled code, requires a compiler and, on your geth console, you should already have Solidity compiler. To test, type in this command:

eth.getCompilers()

If it is installed you should see something along these lines:

[‘Solidity’ ]

If you don’t, you either need to install it or move on to the section below about using the online compiler.

Compiling the Contract

The next step is to reformat the contract and we do this by getting rid of all the line breaks in it so that it can all fit into a string variable. It should look like this when you have finished:

var greeterSource = ‘contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public

{ greeting = _greeting; } function greet() constant returns (string) { return greeting; }

}’

 

var greeterCompiled = web3.eth.compile.solidity(greeterSource)

Your code is now compiled so we need to get it ready to deploy. To do this, we will need to set up a few variables, for example, the greeting that you want to be used. We will now edit the first line, written below,

to something a tad more interesting and then execute the commands:

var _greeting = “Hello World!”

var                                                                greeterContract         = web3.eth.contract(greeterCompiled.greeter.info.abiDefinition);

 

 

var  greeter  =  greeterContract.  New(_greeting,{from:web3.eth.accounts[0],  data: greeterCompiled.greeter.code, gas: 300000}, function(e, contract){

if(!e) {

 

if(!contract.address) {

console.log(“Contract            transaction          send:                                                          TransactionHash:                 ” + contract.transactionHash + ” waiting to be mined…”);

 

} else {

console.log(“Contract mined! Address: ” + contract.address); console.log(contract);

}

 

 

}

})

Using the Online Compiler

If solC compiler is not installed you can make use of the online compiler. Simply open the online Solidity compiler and copy the code above into it and you will see the compiled code in the left pane. Look for the box called ‘Web3 deploy” and copy the code for ‘themortalcontract’ and ‘thegreetercontract’ into one text file and then, in that text file, change the first line to your chosen greeting:

var _greeting = “Hello World!”

Now copy the text that results into your geth console window or, if you want, you can import the file using the command:

loadScript(‘name of your file.js’)

Wait for around 30 seconds and you should see something like this on your screen:

Contract mined! address: 0xdaa24d02bad7e9d6a80106db164bad9399a0423e

The gas costs of deploying the contract must be paid so you might have

to unlock the account that will send the transaction. To do this, you will use the password that you chose when you set up geth.

This particular contract will need at least 180,000 gas for deployment and, at the time of writing this, the price stood at around 0.00000002 ETH per gas unit. This cost will not be paid to the developers on Ethereum; it is given to the miners as their rewards for finding new blocks and keeping the entire network secure. The gas price will fluctuate and is set by supply and demand of the computations. If the price goes too high, you can consider becoming an Ethereum miner and lower the asking price.

Back to the contract; in under 60 seconds, you should see a log that has the contract address in it. This confirms that the contract has been deployed successfully and the code can be verified with the following command:

eth.getCode(greeter.address)

If you see 0x on your screen, you have not been successful; anything else will confirm that your ‘greeter’ is now live. If you create the contract again, using the command eth.sendTransaction, it gets published to another address, not the same one.

Run Your Greeter

To call the ‘greeter’, simply type in this command in the terminal:

greeter.greet();

This call does not change anything in the blockchain so the return will be instant and it will not have any cost in gas associated with it. You should see the following:

‘Hello, World!’

Getting Others to Interact

If other people are to run this contract, they will need the address of the contract location and the ABI a kind of user manual that describes the function names and how they are to be called in the JavaScript console. To get them to run these commands:

greeterCompiled.greeter.info.abiDefinition; greeter.address;

If you used the online browser-based compiler the ABI can be got from the fields labeled “Interface” in ‘thegreetercontract’ and ‘themortalcontract’. You can then instantiate a new JS object which

may be used by any machine on the network to call the contract. To create the contract object in JS, we need to replace the array (the ABI) and the address (a string):

var greeter = eth.contract(ABI).at(Address);

To instantiate this example, you would call the following:

var greeter2 = eth.contract([{constant:false,inputs:[],name:‘kill’,outputs: [],type:‘function’},{constant:true,inputs:[],name:‘greet’,outputs:

[{name:”,type:‘string’}],type:‘function’},{inputs:

[{name:‘_greeting’,type:‘string’}],type:‘constructor’}]).at(‘greeterAddress’);

Make sure that ‘greeterAddress’ is replaced with your own contract address.

Cleaning Up

So, your very first contract has gone live! Sadly, the excitement that comes with this can easily wear off, especially when contract owners write more contracts and leave the old and abandoned ones lying around on the network. There is a chance that a blockchain rent may be introduced  sometime in the future to  help increase blockchain scalability but for now, it’s down to you to remove your abandoned contracts by implementing the self-destruct button.

To do this, you need to send a transaction to the network and you will need to pay a small fee because you are making a change to the blockchain after the code below has been run. Self-destruct is subsidized by the blockchain network at the moment so it won’t cost anywhere near as much as a normal transaction. Input this code:

greeter.kill.sendTransaction({from:eth.accounts[0]})

Only the contract owner can send the transaction necessary to trigger this and, to verify that it was successful, you can input the following code – if it was successful, you should see the output ‘0’:

eth.getCode(greeter.address)

Every contract must implement their own ‘kill’ clause and, in this example, it must be done by the account that created it.

That, my friends, is your very first Smart Contract!

Next, we are going to look into the future of the Ethereum blockchain and the code of tomorrow.

Related Articles

Leave a Reply