How to Build a Smart Contract for Ethereum? Guide to Blockchain  Development

blockchain-development
Bitcoin, Ethereum and other cryptocurrencies gained immense popularity in mass media and social networks. But this hype differs from the one in 2014, when Bitcoin grew from $100 to $1000.

The main difference between these hypes is Ethereum. Here at VironIT, we’ve been around cryptotech since 2014 and kept an eye on that (alas we didn’t buy Eth when it was cheap).

This article assumes no basic understanding of Ethereum blockchain technology. If you’re starting from scratch, you will be most comfortable working your way through the article from the beginning.

If you already know what is Ethereum and how it works and what it can be used for, without going deep into the technical abyss, we recommend you to skip the intro and instead go to Business Case: Ethereum-based Solution for Data Sales.

Let’s take a deep dive into Ethereum Development!

 

Contents

 

What is Ethereum?

Based on the Ethereum home page, “Ethereum is a decentralized platform that runs smart contracts.” Simply put, Ethereum can be described as an open-source software platform based on blockchain technology that enables developers to build and deploy decentralized applications.

While the Bitcoin blockchain tends to be used for consumer payment transactions, the Ethereum blockchain technology aims for the business world.

Ethereum Price Chart

screenshot_41

Ethereum technology is specifically intended to support smart contract applications that can automate complex physical and financial supply chain procedures and compliance processes involving multiple parties. It has numerous potential internal end uses such as reconciliation.

 

What is Ether?

Keeping it brief and simple, Ether is the “fuel” the Ethereum network needs to function and is known as crypto-fuel in the cryptocurrency market. Crypto-fuel is a form of payment made by users/clients of Ethereum to the machines executing requested operations. Ethers are incentives to make sure that developers provide quality apps to the network and maintain the ethereum network healthy.

For example, when you make transactions, you are actually sending Ether, NOT Ethereum. The term “transaction” is used in Ethereum to refer to the signed data package that stores a message to be sent from an externally owned account to another account on the blockchain.

 

Ether in Numbers

  • At the moment, there are around 92 million ETH circulating around. Compared to the famous Bitcoin, it’s five times more
  • The market capital of Ethereum is close on 32 billion dollars
  • 5 Ethers are created every block (roughly 15-17 seconds) to the miner of the block
  • 2-3 Ethers are sometimes sent to another miner if they were also able to find a solution but his block wasn’t included
 

What is an Ethereum Smart Contract?

smart-contracts

A smart contract is a piece of software that contains rules and regulations for negotiating the terms of a contract. It automatically verifies the contract and then executes the agreed upon terms.

And when this smart contract’s centralized code is made decentralized for execution purposes on the Ethereum blockchain, it becomes an even smarter contract.

Coding and executing smart contracts on the Ethereum blockchain makes them immutable and independent from centralization.

Sounds complicated? Let’s simplify everything using a well-known example.

 

How Do Ethereum Smart Contracts Work?

Ethereum smart contracts may be compared to a vending machine.

Each smart contract is another “coffee machine”, an application. There is a variety of vending machines for selling still and sparkling water, cigarettes, drugs, eye lenses, pizza, milk, etc. The common trait is a finite functionality. If a machine cooks coffee, then it doesn’t sell pizza and vice versa.

vending

Now, imagine that all these vending machines are interconnected, operate on same network and can order services.

Smart contact is a “vending machine” which does a particular function. That’s it.

If you can read the contract and understand what is written in smart contract – you can “use the menu of vending machine and order some coffee for ETH”. The main difference, that in Ethereum machines operate with money and one tiny mistake can cost a fortune.

Therefore, writing a smart contract requires special skills (which are in high demand at the moment) from each other. The network of machines. This is what Ethereum makes possible due to smart contracts.

 

Smart Contracts Use Cases

smartcontracts

 

Business Case: Ethereum-based Solution for Data Sales

In this chapter we will share our experience of  developing an Ethereum-based service for Data Sales and implementing liability smart contract in blockchain. When we’re done you’ll know exactly how to write some deep-looking smart contract code and ready to dive into the complicated task of actually deploying the contract to a live blockchain.

screenshot_42

 

First Things First: What language did we use?

Currently, of all the languages for smart contract development Solidity, a high-level programming language specifically tailored for this job, is the industry standard. A few other languages should be mentioned as well: Serpent, a Python-like language with “.se” extension, and LLL, a Lisp family language. Serpent was popular a while back but nowadays tides have turned in favor of Solidity, a more well-rounded and robust solution.

 

Project description and environment

Our goal was implementation of smart contract to test human-robot interaction via blockchain.

The project is based at AIRA shared-state-liability module (https://github.com/airalab).

We are offering information (data from radiation dosimeter) by smart contract in Ethereum blockchain. For that, we’re going to use:

  • IPFS — to transfer information and blockchain to receive payment and proof transaction

  • Dosimeter — SMG2, compact, universal, and cost efficient Geiger Counter

  • OS — Ubuntu 16.04 LTS

  • Platform — Etherium 1.6.5 (Homestead)

  • Ethereum browser — Parity 1.7.0 (Beta)

  • Project management software — Docker 17.06.0-ce

 

Workflow for AIRA Installation and Deploying Smart Contracts

 

Step 1: How to get access to Ethereum network?

Our first job would be to setup a tool to interact with the Ethereum network, using Parity or Etherium software wallet. Well, we chose the first.

Parity is a wallet application designed to integrate seamlessly with all standard tokens as well as Ether itself.

It includes various functionality allowing you to:

  • Create and manage your Ethereum accounts
  • Manage your Ether and any Ethereum tokens
  • Create and register your own tokens
  • And much more

Let’s start small, with a Parity browser installation and ETH testing.

 
How do I install Parity?

There are a few ways of proceeding to:

  • Build Parity from the sources https://parity.io/
  • Use bash-installer bash — <(curl https://get.parity,io –Lk)
  • Install Parity from binary releases for Ubuntu, Mac/Homebrew and Windows or, if you’re on an Ubuntu Snappy platform, just use our Snappy App.

On MacOS and Ubuntu you can use the One-Line Binary Installer, to use the script just run:

  bash <(curl https://get.parity.io -Lk)  

This method is way faster than building, however it only works on Ubuntu and Mac with Homebrew installed.

Begin the installation by double-clicking on the Parity installer.

screenshot_45

Once you have installed Parity, you will be redirected to a website on your browser and complete the setup of an Ethereum account.

parity_4

 

How to deploy a new contract?

Well done! Now you can easily deploy a new contract. Fill in fields and save the settings and the Contract will be available for everyone.

Here is the contract code, written in Solidity:

 
[code language="javascript"]
pragma solidity ^0.4.17;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }

contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
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);

// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);

/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}

/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}

/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}

/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}

/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
[/code]
 

You can compile it within the Parity Wallet by using the “Develop” page in the “Contracts” tab. For now we will assume the contract is already deployed: this can be done with Parity Wallet by using the “Deploy” function.

screenshot_46

It’s time to deploy the contract using Parity Wallet. After deploying, you’ll be given an address for where the contract resides on the blockchain. In our case, it’s at 0x00755A8868190511093B8d75E645c1Ba52932D1d and looks like this:

screenshot_48

Now you can add this contract to a watch-list (Contracts -> Watch in Parity), follow tips to fill required fields, synchronize with network and test it as well.

 
How to Start Synchronization?

Parity supports state snapshotting which significantly reduces sync-times and database pruning which reduces disk requirements. Get synced by running:

  $ parity  

By default, when running Parity, Parity Ethereum will connect to the official public Ethereum network.

In order to run a chain different to the official public Ethereum one, Parity has to be ran with the –chain option or with a config file specifying chain = “path” under [parity].

There are a few named chains, for example, Main network, Kovan, Ropsten, etc.

In our project we’ve decided to use Kovan, a new testnet for Ethereum using Parity’s Proof of Authority consensus engine, with benefits over Ropsten:

  • Immune to spam attacks (as Ether supply is controlled by trusted parties)
  • Consistent 4 second block time
If you want to interact with the Kovan chain, then run parity with the correct chain config to:
  • Run Kovan OSX / Linux use parity –chain=kovan
  • Run Kovan on windows, edit the Parity startup shortcut and append –chain kovan.

Right click the shortcut -> Properties -> edit the “Target” field to end with parity.exe” –chain kovan.

For Windows setup you can check up short tutorial

https://www.youtube.com/watch?v=dTjstkfOT8E  
What is Warp Sync?

Warp Sync is an extension to the Ethereum Wire protocol, which involves sending snapshots over the network to get the full state at a given block extremely quickly, and then filling in the blocks between the genesis and the snapshot in the background.

When using Parity 1.4 or 1.5, you can run:

  $ parity –warp    

… to automatically fetch a recent snapshot from the network, restore from it, and continue syncing.

When using Parity 1.6 or 1.7, –warp does nothing as it is enabled by default.

 
How to Prune Database?

If there will be some disk space issues by synchronizing you can run Parity with:

 

$ parity –pruning archive

 

It will help you disable Database storage pruning and keep all state-tree data.

Check out also https://github.com/paritytech/parity/wiki/Getting-Synced

 

screen-2

 
Step 2: Why I Need Testnet Ether?

Firstly, what is a Testnet Ether? Testnet Ether is a coin, that you can use on Ethereum testnet for testing Smart Contracts without spending real money.

It has the same properties as usual Ether. You can

  • Mine it
  • Transfer and receive it
  • Pay for gas with it

As soon as the sync process is completed, you have to open in the browser 127.0.0.1:8180, a default parity port, and to create a new account using a new account wizard.

 

Important!: Please, do not forget your password, or else this Ethereum account (with all the funds and tokens) will be PERMANENTLY lost.

 

Yay! Now your may check up Node Health that show you current synchronization status, amount of connecting peers and other metadata. Let’s click on settings button and choose Contracts checkbox.

Remember, Etherium currency needs to make any transaction in blockchain. As it was mentioned earlier, Testnet Ether is the currency used in test networks.

Kovan Etherium (KETH) may be earned by request. Use this link to access test currency by faucet service:

https://github.com/kovan-testnet/faucet  
Step 3: How to Install and Connect a Dosimeter?

We have used SMG2 Geiger Counter, because it is compact, universal, and cost efficient.

It is designed to measure background radiation and identify radioactive items. The dosimeter allows the user to measure the average radiation dose for a one-hour or 24-hour period, as well as the accumulated dose.

screenshot_50

Follow this link http://www.penguin.cz/~fojtik/SMG2/ (for Linux) to setup a driver for a dosimeter to kickstart your journey to creating smart contracts.

Once you have download an archive, you will unzip and change working directory and execute the “build” file with the command:

  $ ./build    

At SMG.c file you have a bunch of variables:

  1. Change *rrdupdate_PATH to “/[your_folder]/rrdupdate”
  2. *RRD_DATABASE to “/var/rrd/radiation.rrd”
  3. Set path *LOG_FILE to turn on logging

Now it’s time to plug in dosimeter and turn it on. After running “sudo ./SMG2” file you’ll see the following:

screenshot_51

RRD-OK tells you that everything is ok. Now data from dosimeter can be stored to RRD database.

 
Step 4: How do we wire up AIRA?

What is AIRA? AIRA (short for Autonomous Intelligent Robot Agent) is the project that implements the standard of economic interaction between human-robot and robot-robot. AIRA allows to connect a variety of different robots to the market of robot’s liabilities which exist in Ethereum.

Follow this link https://github.com/airalab/aira/blob/master/README.md to install AIRA.

After the stable version is installed, you have to change settings for your database folder in the following file:

[installation_folder]/aira-IoT/docker/share-state-liability/docker-compose.yaml

Navigate to robot -> volumes -> ./state and change it to the destination folder.

As soon as it is done, you are free to start docker using:

  $ docker-compose up    

Pay attention that Parity from your docker project will also need to be synchronized.

screenshot_52

If you wish to handle your cryptocurrency online you are going to need to install a browser extension.

You can manage adding contracts on http://127.0.0.1:8000.

You will be redirected to 127.0.0.1/ HYPERLINK “

 

screenshot_53

 

Summary

We hope this post helped you in getting a very rudimentary understanding of how smart contracts are created.

As we worked our way through the article, we discovered how to set up appropriate environment to work with Ethereum network, tested AIRA platform for distributed applications and acquired an awful lot of tools and skills:

  • A tool to access Ethereum network (Parity, Etherium wallet or other analogue)
  • Test coins to operate in development network
  • An installed and connected dosimeter to share its database
  • Experience with AIRA app
  • Deployment and monitoring of contracts
 

Why Outsource Ethereum Blockchain to VironIT?

Have a Killer Idea?

Let’s Make it a Reality!

VironIT is an innovative and reliable outsourcing software development company that offers the development of blockchain apps and Smart Contracts using Ethereum platform. We cooperate with our clients on a regular basis to provide them with the confidence in making the most complex business decisions by developing reliable Blockchain solutions.

If you have a Etherium software project in mind, just drop us a line at info@vironit.com

 

FAQ

How is Ethereum different than Bitcoin?

Bitcoin was conceived as a “a purely peer-to-peer version of electronic cash”, focusing on payments, and value transfer as its primary applications.

Ethereum extends the ideas Bitcoin is built on in order to provide a more generalized computational platform. This enables the creation of smart contracts, decentralized applications, and even decentralized governance applications.

 

What are Geth, Mist, Ethminer, Mix?

Geth: This is the Go implementation of an Ethereum node, and is the basis for any interactions with the Ethereum blockchain.

Mist: This is the equivalent of a web browser, but for the Ethereum platform. It acts as a GUI to display the accounts and contracts that you interact with. It also allows you to create and interact with contracts in a graphical user interface without ever touching the command line.

Ethminer: A standalone miner. This can be used to mine or benchmark a mining set-up. It is compatible with Eth, Geth, and Pyethereum.

Mix: The integrated development environment for DApp authoring. Quickly prototype and debug decentralised applications on the Ethereum platform.

 

What is a Dapp Ethereum?

Dapp (short for Decentralized Application) is a piece of software consisting of a UI and a decentralized backend; typically making use of a blockchain and smart contracts. Most of the projects listed on this page were built using Ethereum – a popular development platform for creating dapps.

 

What’s the difference between account and “wallet contract”?

An account is your public / private key pair file that serves as your identity on the blockchain. See “account” in the glossary. A “wallet contract” is an Ethereum contract that secures your ether and identity with features such as multisignature signing and programmed deposit/withdrawal limits.

 

How can I mine Ether?

With AlethZero

  • To process transactions Disable “Debug” > “Force Mining” Click “Mine”
  • To force mine (Use sparingly, unless stress testing)Enable “Debug” > “Force Mining” Click “Mine”

With the Eth client

# Only force mine to acquire ether or stress test

$ eth –force-mining –mining on [your options]

Please, estimate my article. I did my best!
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading…