Skip to main content

Command Palette

Search for a command to run...

Web3 frontend part -2

Published
•2 min read•View as Markdown

Till now we have stored the ABI and the address of the smart contract in a JavaScript file.

Now lets say our smart contract has a particular function that we need to call. For that we need to create an instance or an object of the smart contract. For that we use the ethers.js library.

First of all we install the ethers library using the command:

npm install ethers

The ethers package provides a class named Contract. This class helps in creating an object which makes it easier to use an on-chain Contract as a normal JavaScript object, with the methods mapped to encoding and decoding data for you.(more like the ORM model that is used in databases).

In order to communicate with the Contract on-chain, this class needs to know what methods are available and how to encode and decode the data, which is what the ABI provides.

While an on-chain Contract may have many methods available, you can safely ignore any methods you don't need or use, providing a smaller subset of the ABI to the contract.

Let us now import the class first.

//Firstly we import the class of the ethers.js library
import {Contract} from "ethers";

Now we create functions inside this file so that we can pass in the required parameters and create the instance of the smart contract and return that instance.

export async function createSigninginstance(ABI,contractaddress,providerorSigner)
{
    //In case we are calling read only functions inside the smart contract then we create the instance using the provider
    //If we are changing the state of the smart contract then we create the instance using the signer
    let instance=await new Contract(ABI,contractaddress,providerorSigner);
    return instance;
}

More from this blog

Dhruv's Web development journey

64 posts