Deploy Your First Ethereum Smart Contract on a Blockchain!

Understanding the concepts behind a blockchain is not as hard as one could imagine.
Of course some specific concepts of a blockchain environment are harder to understand (e.g. mining) but I will try first to give you a simple introduction to the most important concept of blockchain.
Then we will write a first smart contract inside a blockchain.
That will be the first step before trying to build a decentralized web application implementing smart contracts!

Basically a blockchain is a chain of block, more precisely a linked chain of blocks.

A block is one element of a blockchain and each block has a common structure.
The security of a blockchain is assured by its decentralized nature.
Unlike a classic database, a copy of the blockchain is stored in each node of its peer-to-peer network.
In the case where the local version of a blockchain in a networks node were corrupted, all the other nodes of the P2P network would still be able to agree on the actual value of the blockchain: thats the consensus.
In order to add a fraudulous transaction to a blockchain, one should be able to hack half of the user of the network.
Furthermore, it is also very hard to alter even only a local version of a blockchain because of a block structure.

Block structure

What is interesting in the concept of blockchain is that we can store any kind of data with very high security. Data is stored inside a block that contains several elements:

  • A hash
  • The hash of the previous block
  • An index (number of the block in the chain)
  • A nonce (an integer that will be used during the mining process)
  • A timestamp
  • The data
  • A hash representing the data

If you are not familiar with the concept of hash, the important things to know are:

  • From a very large departure set (typically infinite and very diverse), a hash function gives back a string of fixed length
  • The hash of a block is easy to calculate
  • Given a hash, it is impossible to build a message with this hash value
  • If you modify the message (even very slightly), you totally change the hash
  • It is almost impossible to find two messages with equal hash

The hash of a block is calculated by taking as argument the hash of the previous block, the index, the nonce, the timestamp, and a hash representing the data of the current block.
Among these inputs, the nonce will vary during the process of mining but of course the others stay fixed.
Because of the properties of a block, if you try to change the transactions/data inside a block, its hash will not be consistent with the data anymore (neither will be the previous hash of the next block).

Mining a block

When a block is created, nodes of the network will try to mine it, which means to insert it into the blockchain.
The miner who succeeds will get a reward.

Proof of work

In order to mine a block, you have to find a valid hash for this block, but as you may remember a hash is quite easy to calculate.
Thats why you need to add a condition on the desired hash, typically a fixed number of zeros the hash must start with.
The proof-of-work enhances blockchain’s security because of the considerable amount of calculation needed to modify a single block.
To conclude, a miner has to solve a time consuming mathematical problem to mine a block.

The nonce

A nonce is an integer which will be incremented during the mining process.

Without a nonce, the data of a block is constant, and thus the hash function always returns the same result.
If your hash consists of hexadecimal characters, and you want to have a hash starting with 5 zeros you will have a probability of 1/1048576 to produce a hash verifying this condition with a random nonce.

Each time you fail to get a hash verifying the condition, you can update the nonce and try again.
This assures that the miners of the network will have to work to add a block to the blockchain and thats why this algorithm is called proof of work.

Smart Contracts

Smart contracts have been introduced in the ethereum blockchain.
This is some code written inside the block of a blockchain that is able to execute a transaction if some conditions are fulfilled.
It is useful when the execution of a contract depends on some difficult conditions, or when you usually use a third-party to ensure the execution of the contract.

Initializing the project

In this part we will write a smart contract using Solidity, the programming language used in the ethereum blockchain and Truffle; a development environment for Ethereum.
We will use Ganache (you can download it here which will give us access to a personal ethereum blockchain in order to test our smart-contracts and deploy them in a blockchain.
First, lets install Truffle and initialize our project by running the following commands:

[code language=”bash”]
npm install -g truffle
mkdir my-first-smart-contracts
cd my-first-smart-contracts
truffle init

The truffle init command will provide the basic folders and files of your project:

  • contracts/
  • migrations/
  • test/
  • build/
  • truffle.js
  • truffle-config.js

You can now open Ganache.
You will see 10 fake accounts that we can use and a local blockchain with only one initial block.
You can also see the port where your local blockchain runs. It should be by default HTTP://

Let’s open your truffle.js file and modify it to connect it with the blockchain.

[code language=”javascript”]
module.exports = {
networks: {
development: {
host: ‘localhost’,
port: 7545,
network_id: ‘*’

Our first smart contract

In our contracts folder, we will create a basic smart contract Message.sol.
It will only enable us to write a message in the blockchain but it will be a good start to understand the way solidity works.

[code language=”javascript”]
pragma solidity ^0.4.17;

contract Message {

bytes32 public message;

function setMessage(bytes32 newMessage) public {
message = newMessage;

function getMessage() public constant returns (bytes32) {
return message;

As you can see, a contract looks like a regular class in another language.

However, unlike a typical class, there is no this to access instance variables.
The state variables, like message here, can be read or written directly.
Solidity is a typed language, you have to declare the types of the variables you create and specify the types of function arguments (like in setMessage) and returned values (like in getMessage)

A call to setMessage will add a transaction to the blockchain and thus cost you gas because it modifies the state of the contract.
Gas is the amount you have to pay for running a transaction.
The miner can decide to increase or decrease the amount of gas according to its need.

However you want to be able to access the value in the blockchain without spending gas, that’s why we precise constant in getMessage declaration.

You may wonder why we used the type bytes32 and not string which exists in solidity.
The main reason is that writing to the ethereum blockchain costs ether.
The type string, being dynamically sized, is more expensive to use when writing data in the blockchain than the type bytes32.

Deploying to the test blockchain

Our contract being written, we now want to deploy it on the network.

In order to do this we have to write a migration file in javascript.
In the folder migrations/ let’s create a new migration file called 2_message_migration.js.
It is important to write the ‘2’ because Truffle will execute the migrations in the order of the prefix.

[code language=”javascript”]
var Message = artifacts.require(‘./Message.sol’);
module.exports = function(deployer) {

The artifacts.require method is similar to the require of node and will tell Truffle which contracts you want to interact with.
The name of the variable must match the name of your contract.
The deployer object gives you access to the deployment function.
Our example is the easiest one.

Back to the shell, we can now deploy our contract to the blockchain:

[code language=”bash”]
truffle compile
truffle migrate

In ganache you can now see new blocks automatically mined and corresponding to the deployment of your contract in your blockchain!

Interacting with the contract

The contract being deployed on our local blockchain, we can now write our first transactions and see what happens.

To interact with the contract we can use directly the truffle console and write javascript in it or write a script and run it.
In this example we will interact directly in the console.

[code language=”bash”]
truffle console
var message;
Message.deployed().then(function(instance){message = instance;})
message.setMessage(web3.fromAscii(‘Premier message !’));

If you go back to Ganache, you will see that a new block has been added to the blockchain, that’s because setMessage is a transaction and modifies the state of our contract.

[code language=”bash”]

Functions from contract are promisified, that’s why we use then to access the data. Moreover, as we used the type bytes32 to write our message, we have to add web3.fromAscii and web3.toAscii to write and read our message.

This last command should return the value of your message but if you look at your blocks in Ganache, you will not see any new blocks as this getter function did not modify the state of your contract.

Testing a contract

Truffle easily enables you to create tests for your contracts. It comes with its own assertion library which provides you classic test hooks beforeEach, afterEach, beforeAll, afterAll, and assertions equal, notEqual, isEmpty

[code language=”javascript”]
import ‘truffle/Assert.sol’;
import ‘truffle/DeployedAddresses.sol;
import ‘../contracts/Message.sol’;

contract TestMessage {
function testSetMessage() {
Message messageContract = Message(DeployedAddresses.Message());
messageContract.setMessage(‘Hello World!’);
bytes32 expected = bytes32(‘Hello World!’);
Assert.equal(messageContract.getMessage(), expected, ‘The message should be set’);

The contracts you deployed on the blockchain are available through the DeployedAddresses.sol library.
It is mandatory that your test contract and your test file start with ‘Test’, followed by the name of the contract.

The test being written you can now run it in the console:

[code language=”bash”]
truffle test
Using network ‘development’.

Compiling ./contracts/Message.sol…
Compiling ./test/TestMessage.sol…
Compiling truffle/Assert.sol…
Compiling truffle/DeployedAddresses.sol…
✓ testSetMessage (55ms)

1 passing (402ms)

Next steps

We learnt how blockchain works and what a smart contract is but most importantly how to develop using the truffle environment thanks to a simple example.
The next step is to write one or more sophisticated contracts and build a web app to interact with them!