cft

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

Building The Smart Contract


user

Vincent T

2 years ago | 6 min read

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

OverviewIn 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: MIT

pragma 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):

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:

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.

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.

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:

The output returned should look like the following:

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.

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.

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.

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

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.

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.

Upvote


user
Created by

Vincent T

Involved in blockchain development and imaging technology.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles