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

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

The main difference between the hypes is Ethereum. Here at VironIT, we have been around and monitored cryptotech since 2014 (alas, we did not buy Eth when it was cheap).

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

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

Let’s take a deep dive into Ethereum Development!

 

Contents

 

What is Ethereum?

According to 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 to be used in 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 many potential internal end uses like reconciliation.

 

What is Ether?

Briefly and simply, Ether is the “fuel” the Ethereum network needs to function; it is known as crypto-fuel in the cryptocurrency market. Crypto-fuel is a type of payment made by users/clients of Ethereum to the machines that execute the requested operations. Ethers are incentives to make sure that developers provide quality apps for the network and maintain a healthy Ethereum network.

For example, when you make transactions, you are actually sending Ether, NOT Ethereum. The term “transaction” is used by 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

  • Currently, there are around 92 million ETH circulating. This is five times more than the famous Bitcoin
  • The market capital of Ethereum is almost 32 billion dollars
  • Five Ethers are created every block (roughly 15–17 seconds) for the miner of the block
  • Two to three Ethers are sometimes sent to another miner if he or she was also able to find a solution but his or her block was not 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.

When this smart contract’s centralized code is 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.

Sound complicated? Let’s simplify things using a well-known example.

 

How Do Ethereum Smart Contracts Work?

Ethereum smart contracts can be compared to a vending machine.

Each smart contract is another application. There are many vending machines that sell still and sparkling water, cigarettes, drugs, lenses, pizza, milk, etc. The common trait is finite functionality. If a machine makes coffee, then it does not sell pizza and vice versa.

vending

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

A smart contact is a “vending machine” that performs a particular function. That’s it.

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

Therefore, writing a smart contract requires special skills (which are currently in high demand) from each other. The network of machines is what makes Ethereum possible because of smart contracts.

 

Smart Contracts Use Cases

smartcontracts

 

Business Case: Ethereum-based Solution for Data Sales

In this chapter, we share our experience of developing an Ethereum-based service for data sales and implementing a liability smart contract in the blockchain. When we’re done, you will know exactly how to write some deep-looking smart contract code and be 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 the job, is the industry standard. A few other languages should be mentioned as well: Serpent is a Python-like language with an “.se” extension, and LLL is a Lisp-family language. Serpent was popular, but tides have turned in favor of Solidity, a more well-rounded and robust solution.

 

Project description and environment

Our goal was to implement a 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 a radiation dosimeter) by smart contract in the 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 task would be to set up a tool to interact with the Ethereum network, using the Parity or Ethereum software wallet; we chose the first.

Parity is a wallet application designed to integrate seamlessly with all standard tokens and with 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:

  • 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 much 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 the 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 in 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 will 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 complete required fields, synchronize with the network, and test it.

 
How to Start Synchronization?

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

  $ parity  

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

To run a chain different from the official public Ethereum chain, Parity must be run 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 this project, we have 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:
  • 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 of 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 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

 

This 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?

First, what is Testnet Ether? Testnet Ether is a coin that you can use on Ethereum testnet to test Smart Contracts without spending real money.

It has the same properties as 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 this Ethereum account (with all the funds and tokens) will be PERMANENTLY lost.

 

Now you may check Node Health, which shows your current synchronization status, number of connecting peers, and other metadata. Click on the settings button and choose the Contracts checkbox.

Remember, Ethereum currency is needed to make any transaction in the blockchain. As mentioned earlier, Testnet Ether is the currency used in test networks.

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

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

We used the 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 set up a driver for a dosimeter to kickstart your journey to creating smart contracts.

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

  $ ./build    

At SMG.c file you have many 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 the dosimeter and turn it on. After running thesudo ./SMG2” file, you will see the following:

screenshot_51

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

 
Step 4: How do we wire up AIRA?

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

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

After the stable version is installed, change the 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 this is done, you are free to start using the docker:

  $ docker-compose up    

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

screenshot_52

If you wish to handle your cryptocurrency online, you will 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 gave you a very rudimentary understanding of how smart contracts are created.

As we went through the article, we discovered how to set up an appropriate environment to work with the Ethereum network, tested the AIRA platform for distributed applications, and acquired many tools and skills:

  • A tool to access the Ethereum network (Parity, Ethereum wallet, or other analogues)
  • Test coins to use in a development network
  • An installed and connected dosimeter to share its database
  • Experience with the 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 the Ethereum platform. We work with our clients on a regular basis to provide them with the confidence to make the most complex business decisions by developing reliable Blockchain solutions.

If you have an Ethereum software project in mind, send us an email: info@vironit.com

FAQ

How is Ethereum different than Bitcoin?

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

Ethereum extends the ideas on which Bitcoin is built 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 with which you interact. It also allows you to create and interact with contracts in a graphical user interface without ever touching the command line.

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

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

 

What is a Dapp Ethereum?

Dapp (short for Decentralized Application) is software consisting of a UI and a decentralized backend, typically using 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 an account and “wallet contract”?

An account is a 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?

Use 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…
Share
Share