1 min read

🧰 Web3 [Serie Part 4/10] - Call A Smart Contract

🧰 Web3 [Serie Part 4/10] - Call A Smart Contract

Introduction

In this chapter, we are going to interact with our Smart Contract.

First, we will use the Call API. This API will allow us to retrieve data from the Smart Contract.

2 APIs

Call API

We will start from the index.js script we developed in the past lecture.

const Web3 = require('web3');
const MyContract = require('./build/contracts/MyContract.json');

const main = async() => {
    const web3 = new Web3('http://127.0.0.1:7545');
    const id = await web3.eth.net.getId();
    const contract = new web3.eth.Contract(
        MyContract.abi,
        MyContract.networks[id].address
    );    
}

main();
Initial index.js

Now, let's add a 'call' to our Smart Contract, using the 'methods.myMethod.call' methods from Web3. As we can see in the Web3 doc, we can add several parameters to this methods. For this first Call, we will keep things simple, and leave it blank.

Here is the code, and comments are following.

const Web3 = require('web3');
const MyContract = require('./build/contracts/MyContract.json');

const main = async() => {
    const web3 = new Web3('http://127.0.0.1:7545');

    const id = await web3.eth.net.getId();
    const contract = new web3.eth.Contract(
        MyContract.abi,
        MyContract.networks[id].address
    );

    const data = await contract.methods.get().call();
    console.log(data);
}

main();
index.js
  • We use the contract.methods.get().call() to call the 'get' method we defined in our Smart Contract.
  • Then, we console.log the result stored in data.

We can see the following result in the terminal:

0

Since, we didn't initialize our Smart Contract uint variable, this is empty, and our get function is thus returning 0.

🎉 🥳 👯‍♂️ 🎈 Congratulations! We successfully call our method get in our Smart Contract, directly from our index.js script. In the next lecture, we will send transaction !