0xCODE
Published in

0xCODE

Web3.js

Interacting With Smart Contracts Using Web3.js (Part II)

This is a continuation from Part I.

Recap
In the first part, we built our environment (Node.js, Web3.js and connection to an Ethereum node). The Web3 object was then discussed along with basic commands developers can use from the Node prompt. Examples were given for working with user accounts, querying the blockchain and sending a transaction from a Javascript file. Part II will continue with how to interact with a smart contract on the blockchain.

Overview
In Part II we will go over details about smart contracts, and how to interact with them using the Web3.js library functions. We will specify a Web3 provider using Ganache (install the specific version for your operating system), briefly introduced in Part I. It is also important to understand from the developer’s perspective, so we will build a small application using the Solidity programming language using the Remix IDE.

Building The Smart Contract

From the Remix IDE, we are going to create a simple program using Solidity for the smart contract. We are going to use compiler version 0.8.1 (you can use whichever compiler that is available), but make sure there are no compilation errors. It is important that the code compiles successfully in order for deployment.

//SPDX-License-Identifier: MITpragma solidity ^0.8.1;contract SimpleContract {

uint public myValue = 50;
string public myString = "Hello World!";

function setValue(uint _myValue) public {
myValue = _myValue;
}

function setString(string memory _myString) public {
myString = _myString;
}

}

The smart contract SimpleContract contains two functions. These are “setter” functions, which input a value that causes a change in the state. Two state variables are defined myValue (an integer) and myString (a string) with assigned values (50 and “Hello World”).

Compiling the program translates the high level programming language to machine readable bytecode. This is how the EVM (Ethereum Virtual Machine) component will run the instructions in the smart contract, also called opcodes. In a production environment deployment, the Ethereum network will execute the smart contract on all participating nodes for consensus. This incurs a network fee, which is part of the costs that includes gas (a cost for utilizing computing resources). In the next part we will deploy the smart contract.

Note: Since this example will run on a test network, no costs will be required. If you choose to run it on a production network, you will be responsible for paying the costs for gas on the blockchain.

Deploying To Ganache As Web3 Provider

Before the smart contract can be deployed, there must be an Ethereum node. For this example we are going to use Ganache, though there are other providers available (discussed in Part I). Ganache provides a test environment that mimics the Ethereum blockchain. This allows the developer to run a local blockchain which does not incur the cost of gas when testing applications.

Run Ganache first. The version being used in this example is the GUI-based Truffle version 2.5.4 for the macOS (High Sierra 10.13.6). Ganache provides 10 test accounts with a public address (Ethereum address) and private key. We will be using these accounts for testing. For simplicity, we will use the very first Ganache account as our primary user account.

From the Remix IDE, from the Deploy And Run Transactions tab, under the Environment select Web3 Provider from the drop-down box. Make sure you select an account (by default the first account provided from Ganache) and the contract for deployment under Contract is SimpleContract. When asked about the settings, make sure you indicate (url and port number):

http://127.0.0.1:7545

The default port number used by Ganache is 7545.

Click the Deploy button which will send the code to the Web3 provider’s blockchain. A successful deployment (green circle with a check mark) should return the following output in the Remix IDE:

[block:1 txIndex:0]from: 0x68c…b843Dto: SimpleContract.(constructor)value: 0 weidata: 0x608…50033logs: 0hash: 0x525…82507

Developers can begin testing the smart contract from the Remix IDE. We will now use the Web3.js framework to interact with the smart contract using a Node environment.

Interacting With The Smart Contract

Open Node environment from your console (make sure you have installed Web3.js as discussed in Part I). This takes you to the prompt >.

We begin by requiring the web3 library in order to interact with the smart contract.

> const Web3 = require('web3')

This creates a Web3 object that provides access to the functions that allow for communicating with the blockchain. We will now need an endpoint or provider to connect us to the blockchain.

> const web3 = new Web3('http://127.0.0.1:7545')

Specify the Ganache Web3 provider as ‘http://127.0.0.1:7545’ or ‘http://localhost:7545’. This connects our Node environment to the blockchain running on Ganache. To test this, simply issue a command like:

> web3.eth.getAccounts().then(console.log)

The output returned should look like the following:

> ['0x68cd5E5C54e8EEB0bC416Ac661eAD2cBdF0b843D',
'0xC65CC917B6c58dfD76B7B3Bd95b9207e2A68AfF5',
'0x52574e8Fd7F8F74e8BEb61E6bA49d0D3310Ff4ec',
'0x52aC19Bf8a91f77847351547e2a32e9e905B0553',
'0x46F1561a2f82708F62e04054b98c33029070Fbb6',
'0x8E2BA163CF1AeF2a9DE03B020819bbF3825D5490',
'0x58aCc72B3A4705C5B030AB0f450D7Ac454E2D2BF',
'0x80bb897BB00831442e2904d027D16D5F2120b569',
'0x30C6C5515C3795a08CE356447C8e188246A90b66',
'0x31F9f4a0F472B6fd2111767C1C7353514156FdF2'
]

This returns the available user accounts on the Ganache blockchain. That confirms that we have a connection.

We are now going to create an instance of the smart contract for the Node environment using Web3 functions. Let us define a contract object called contract and instantiate the smart contract.

> let contract = new web3.eth.Contract(<ABI>, <Contract Address>)

Notice that there are two parameters to the function, which are <ABI> and <Contract Address>. The ABI (Application Binary Interface) is the JSON format of the smart contract that contains its functions and methods. This gives a reference of what you can call using the Web3 library. The Contract Address refers to the smart contract’s address that was deployed on the blockchain.

To get the ABI, go back to the Solidity Compiler tab in the Remix IDE. Under the Contract section, there is a tiny icon that reads ABI. Click the icon and this will copy the ABI to the clipboard. Now paste the ABI to the section <ABI> in the function. It will look something like the following:

> let contract = new web3.eth.Contract([
{
"inputs": [
{
"internalType": "string",
"name": "_myString",
"type": "string"
}
],
"name": "setString",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_myValue",
"type": "uint256"
}
],
"name": "setValue",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "myString",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "myValue",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
]

Next, to get the Contract Address go to the Deploy And Run Transactions tab. Under Deployed Contracts you should see the name of the smart contract that was deployed (which is SimpleContract). This contains the smart contract address. Click the copy icon next to the smart contract name to copy the smart contract address.

Paste it after the ABI in our function. (See example below)

Note: These examples are test only. Do not use in a production environment.

... ], "0xf363f0067E127648Ae7AdE34b7f23CDF3AA91f52")

Hit enter after you have added the parameters. You can now interact with the smart contract (provided no errors returned).

We use the contract.methods function to issue calls to the blockchain. For example we can get the values of myValue.

> contract.methods.myValue().call().then(console.log)Promise { <pending> }> 50

We can also issue a call to get the value of myString.

> contract.methods.myString().call().then(console.log)Promise { <pending> }> Hello World!

We can also use the contract.methods function to set values to our variables. This is by using one of the setter functions in the smart contract called setValue(). For example, I can change the value of myValue to 500 using the following command:

> contract.methods.setValue(500).send({ from: "0x68cd5E5C54e8EEB0bC416Ac661eAD2cBdF0b843D" }).then(console.log)Promise { <pending> }> {transactionHash: '0x3c75df5f355ddf8bcaf578001729fb1307ba948be5411a7d8ea9b151a0c83ec3',transactionIndex: 0,blockHash: '0x1704fe4be96ed0a1c2a9cae72671d7612fcf9890bd57ab089d586e23c3ceaa53',blockNumber: 2,from: '0x68cd5e5c54e8eeb0bc416ac661ead2cbdf0b843d',to: '0xf363f0067e127648ae7ade34b7f23cdf3aa91f52',gasUsed: 26658,cumulativeGasUsed: 26658,contractAddress: null,status: true,logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',events: {}}

To confirm the value was changed, we issue a call to get the value in the state.

> contract.methods.myValue().call().then(console.log)Promise { <pending> }> 500

When setting a value, it creates a promise in Javascript. Once the promise is handled, it returns the result. In the example our result is returned via the console.log function to display on the screen.

Synopsis

This wraps up this introduction to interacting with smart contracts using Web3.js. For developers this provides the libraries needed to develop applications that can interact with the blockchain through smart contracts. Developers can use standard JSON format that expose functions they can use to interact with blockchain-based applications. This makes it easier to understand when working between the web and the blockchain.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Tabora

Vincent Tabora

Editor HD-PRO, DevOps Trusterras (Cybersecurity, Blockchain, Software Development, Engineering, Photography, Technology)