Interacting Ethereum Smart Contracts with web3.js (part-2)
By: Saikrishna Reddem
Tags: Solidity, Web3j, Smart Contracts, Ethereum, Ganache Cli

Prerequisites:

Basic understanding of smart contracts and creating contracts in Remix(Web based IDE)

Smart Contracts

Smart contracts are self-executing contracts with the terms of the agreement between buyer and seller which is directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. A smart contract enables individuals to exchange data in a trusted, conflict-free manner without relying on a third party like a bank, lawyer or notary. These smart contracts are being stored on the Ethereum Blockchain, hence are needed to be validated or mined like a regular transaction. Ethereum smart contracts are stored as special transactions which can be used to build applications. Contracts written in smart-contract-specific programming languages are compiled into ‘bytecode’,

which a feature called the ‘ethereum virtual machine’ (EVM) can read and execute.

Solidity is the language that you can use to code the actual smart contracts. The syntax is very similar to JavaScript and it’s designed with the Ethereum Virtual Machine in mind. Solidity is statically typed, supports inheritance, libraries and contains complex user-defined types.

The solidiy programs can be executed in local machines or using an online IDE called remix. For this blog post, we will be using the online editor.

You can find the remix ide at

Solidity just similar like to object-oriented programming language

The smart contracts are sort of like API’s. The objective of this blog is to show how the smart contract can interact with a web UI.

Let us create a contract in remix

pragma solidity ^0.4.25;

contract studentDetails{



uint private id;

string private name;

string private college;



function setStudentDetails(uint _id,string _name,string _college){

id = _id;

name = _name;

college = _college;

}

function getStudentDetails() constant public returns(uint,string,string){

return(id,name,college);

}

}

here id,name,college are state variables.

function setStudentDetails is used to set values for variables of id,name,college and function getStudentDetails is used for retrieval of id,name,college.

Make sure you compile with specified version which you have taken in your contract.In my contract I have taken ^0.4.25 and set the environment to JavaScript VM .But while attaching to the WEB-UI make sure you have to take Web3 Provider .

Now we are going to install ganache-cli and web.js to create a simple user-interface that allows to interact with ethereum smart contract.

Installing Ganache CLI and running

Ganache CLI, part of the Truffle suite of Ethereum development tools, is the command line version of Ganache, your personal blockchain for Ethereum development.

Ganache CLI uses ethereumjs to simulate full client behavior and make developing Ethereum applications faster, easier, and safer. It also includes all popular RPC functions and features (like events) and can be run deterministically to make development a breeze.

Looking for TestRPC?

If you came here expecting to find the TestRPC, you’re in the right place! Truffle has taken the TestRPC under its wing and made it part of the Truffle suite of tools. From now on you can expect better support along with tons of new features that help make Ethereum development safer, easier, and more enjoyable. Use ganache-cli just as you would testrpc .

Make sure you have installed latest version of node and npm(node package manager).

->node -v

->npm -v

Using npm:

npm install -g ganache-cli

There are a lot of options for running ganache-cli, which can be referred in their Github page.

This provides you with 10 different accounts and private keys, along with a local server at localhost:8545.

Installing web3.js

web3.js — Ethereum JavaScript API

web3.js is a collection of libraries which allow you to interact with a local or remote ethereum node, using a HTTP or IPC connection.

First you need to get web3.js into your project. This can be done using the following methods:

npm: npm install web3

First Create a Directory.

Type the command npm init to get package.json which consists of installed dependencies.

->npm init

Now install web3.js

->npm install web3

Switch over to the Remix IDE and Click on the Run , In the Environment Drop-Down change it from Javascript VM to Web3 Provider.

A pop-up asks Are you Sure want to connect to Ethereum node?

Make it yes.

Click on Ok.

Interacting Smart Contracts using WEB UI

We will create index.html to take Student id, name , college fields in input fields and retrieve in text field.

web3.min.js has been included in script part.

index.css

All the following code should be present inside the script tag in the index.html



{

web3 = new Web3(web3.currentProvider);

}

else

{

// set the provider you want from Web3.providers

web3 = new Web3(new Web3.providers.HttpProvider(“

} if (typeof web3 !== ‘undefined’)web3 = new Web3(web3.currentProvider);else// set the provider you want from Web3.providersweb3 = new Web3(new Web3.providers.HttpProvider(“ http://localhost:8545 ”));

If the web3 is not undefined, we will be using the current provider. This is applicable in cases when we use chrome extensions like meta-mask or if we are using ethereum browsers like Mist. If it’s undefined, we can manually specify the provider ourselves (that is our ganache-cli/testrpc).

now we have to take default web3 account .

->web3.eth.defaultAccount = web3.eth.accounts[0];

Here we are using the first one of the 10 accounts provided by the ganache-cli.

Next, we need to use the web3.eth.contract() method to initialize (or create) the contract on an address. It accepts one parameter, which is referred to as the ABI (Application Binary Interface).

ABI is the interface between two program modules, one of which is often at the level of machine code. The interface is the de facto method for encoding/decoding data into/out of the machine code. In Ethereum, it’s basically how you can encode Solidity contract calls for the EVM and, backward, how to read the data out of the transaction

ABI can be obtained from remix by clicking on Compile tab and clicking on Details. Scroll down and copy the content of Interface — ABI. This should be passed as the parameter of web3.eth.contract().

var studentdetailsContract = web3.eth.contract(PASTE ABI HERE!);

Now we have created a variable studentdetailsContract, the interface for interacting with our contract.

Next we have to specify the address for the contract to interact.Address found at Run tab .After Deploying the contract in my case studentDetails.

click on the marked icon to copy the address of the contract.

->var studentdetails = studentdetailsContract.at(‘paste the address here’);

You can check in the console as

->studentdetails.setStudentDetails(01,’krishna’,’gmrit’);

->studentdetails.getStudentDetails();

These functions can be used in our web-page by calling them using javascript and jquery.

$(“#button”).click(function() {

studentdetails.setStudentDetails($(“#id”).val(), $(“#name”).val(),$("#college").val());

});

Here we are passing the content of fields, id,name.college to the smart contract using setStudentDetails function.

studentdetails.getStudentDetails(function(error, result){

if(!error){

$(“#student-details”).html(result[0]+result[1]+result[2]);

console.log(result);

}

else

console.error(error);

});

This function call will display the id ,name and college of the student-details, in the text field of the UI by fetching the data from the smart contact using getStudentDetails function.

R.Saikrishna

Application Developer,Interests in Blockchain Development