Solidity using web3.js

Interacting with Smart Contracts using Solidity & Web3

Anurag Srivastava
Zeonlab & Blockchain Semantics Blog
5 min readDec 14, 2017

--

Everything we do on the Ethereum Blockchain happens at the level of geth, which is a command line level interface on geth console. We do not expect an end user to be typing commands on some terminal for every small thing that he does on Ethereum. So there needs to be a way by which we can interact with the command line level interface using codes running on browsers. How do we make sure that a simple click by the user is interpreted as a command on the black-box terminal geth is running on? The answer to all these questions is web3.js.

web3.js is a collection of libraries which allows us to interact with a local or remote ethereum node, using a HTTP or IPC connection. Simply speaking, it provides us with JavaScript APIs to communicate with geth. It uses JSON-RPC internally to communicate with geth, which is a light-weight remote procedure call (RPC) protocol.

Ethereum Node Setup:

Before we proceed any further, it’s necessary to have a mining node of Ethereum running locally. In an earlier post, we have discussed on how to set up an Ethereum node. If you landed on this page without following along from the previous lessons, just copy and paste the following command in the terminal:

geth — datadir <path to your testnet directory> — networkid 12345 — rpc — rpcaddr “localhost” — rpcport 8545 — rpccorsdomain “*” — rpcapi “eth,net,web3,personal,admin,mine” — mine — minerthreads 1 — nodiscover — maxpeers 0 miner

Sample Smart Contract:

In the following section, an example will be presented that will make use of web3.js to allow interaction with the contracts via a web page served over a simple HTTP web server. This can be achieved by following these steps:

pragma solidity ^0.4.11;
contract sample {
string public name = “ZeonLab”;
function set(string _name) {
name = _name;
}

function get() constant returns (string) {
return name;
}
}

Creating UI for smart contract functions

Open up your preferred code editor and create an index.html in the project folder.

We’re not going to create anything too fancy rather the UI would just have 2 buttons; One for the set() function and other for the get() function.

To get started, paste the following contents into the empty index.html file:

<html>
<head>
<title>Web3 — Simple Demo</title>
</head>
<body class=”container”>
<h3>Web3 — Usage Example</h3>
<div class=”tab-content”>
<div role=”tabpanel” class=”tab-pane active” id=”blockchain”>
<h3> 1. Set the value in the blockchain</h3>
<div class=”form-group form-inline”>
<input type=”text” class=”text form-control” value=”Siri”>
<button class=”set btn btn-primary”>Set Value</button>
<p>Once you set the value, an event will be created which will be used to identify the status of the transaction.</p>
</div>
<h3> 2. Get the current value</h3>
<div class=”form-group”>
<div>
current value is <span class=”value”></span>
</div>
<button class=”get btn btn-primary”>Get Value</button>
<p>Click the button to get the current value. The initial value of the variable name is “ZeonLab”.</p>
</div>
<h3> 3. Contract Calls </h3>
<p>Javascript calls being made: </p>
</div>
</div>
</body>
<script></script>
</html>

Using Web3.js to Interact with the Smart Contract

Having the HTML code ready, we need to import web3 module to interact with smart contract from HTML.

If you do not have web3.js already, download it from the following link:

https://github.com/ethereum/web3.js

Once downloaded, web3 module can be imported into Javascript using the script tag as:

<script src=”web3.js-develop/dist/web3.js”></script>

Once the file is successfully referred in JS, web3 needs to be initialized by an HTTP endpoint. This HTTP endpoint is exposed by the Geth client on which a node was setup.

Web3 provider can be set by adding the following lines of code between the script tags:

var Web3 = require(‘web3’);
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(“http://localhost:8545"));

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).

This ABI allows you to call functions and receive data from your smart contract.

To retrieve the ABI of the contract, copy the contract code and paste it in Remix IDE(http://remix.ethereum.org). Next click on the ‘Details’ button in ‘Compile’ tab. Scroll down to see the contract ABI. Copy the ABI by clicking on the icon shown below:

Once done paste the ABI code into script against the variable sampleContractABI. Your code should look something like this:

var sampleContractABI = [{“constant”:true,”inputs”:[],”name”:”name”,”outputs”:[{“name”:””,”type”:”string”}],”payable”:false,”stateMutability”:”view”,”type”:”function”},{“constant”:false,”inputs”:[{“name”:”_name”,”type”:”string”}],”name”:”set”,”outputs”:[],”payable”:false,”stateMutability”:”nonpayable”,”type”:”function”},{“constant”:true,”inputs”:[],”name”:”get”,”outputs”:[{“name”:””,”type”:”string”}],”payable”:false,”stateMutability”:”view”,”type”:”function”},{“anonymous”:false,”inputs”:[{“indexed”:false,”name”:”name”,”type”:”string”}],”name”:”LogSet”,”type”:”event”}];

Next initialize the smart contract with web3.eth.contract method as follows:

var sampleContract = web3.eth.contract(sampleContractABI);

Now that we have the interface for interacting with our contract through the sampleContract variable, the last thing to do is to define the actual contract address.

Go back to Remix and click the Run tab, and click on the copy icon next to the contract that we created earlier on the right column. Then add the following lines of code to the script.

var sampleContractInstance = sampleContract.at(<contract address>);

Great! Now let’s attach simple JQuery functions to the get and set buttons in the HTML.

$(“#blockchain button.set”).click(function() {
var value = $(“#blockchain input.text”).val();
var params = {
gas: 40000,
from:
};
SimpleStorage.sendTransaction.set(value, params);
});
$(“#blockchain button.get”).click(function() {
var value = SimpleStorage.get.call();
$(“#blockchain .value”).html(value);
});

In the set(), we’re simply sending a transaction to the ‘SampleContract’ with the params specified. Whereas in the get(), we’re simply making a call and the result is set to an element with the class name ‘value’.

If you did everything correctly, you can now view index.html in the browser, with get and set buttons.

This is all about using TestRPC with Web3.js to interact with smart contracts through a browser. If you are still facing troubles write to us at hello@blockchainsemantics.com .

--

--