Connecting and interacting via Ethers.js
In this article, we'll cover the installation of Ethers.js, use it to connect to a web3 provider and interact with a smart contract.
Last updated
In this article, we'll cover the installation of Ethers.js, use it to connect to a web3 provider and interact with a smart contract.
Last updated
Ethers.js is an excellent choice for individuals who are fairly new to dApp and blockchain development due to its user-friendly nature. Its ease of use makes it highly accessible, attracting numerous emerging companies and projects. Compared to alternative libraries like web3.js, ethers.js stands out for its exceptional performance capabilities within the browser environment.
This import statement makes the Ethers.js library available for use in your code:
The Contract Application Binary Interface (ABI) is a specification that describes the functions and events of a smart contract. Before interacting with a deployed smart contract, you need to obtain its ABI. Assuming you have the ABI saved in an abi.json
file in your project directory, you can import it as follows:
Make sure to replace './abi.json'
with the correct path to your ABI file.
To connect your dApp with a wallet provider, you have two options: Web3Provider or JsonRpcProvider.
In this code, provider
is created using Web3Provider
and is connected to the injected Web3 provider in the browser, such as MetaMask. The eth_requestAccounts
method prompts the user to connect their wallet and returns a list of the user's accounts.
Using JsonRpcProvider:
The code line below retrieves the current block number from the blockchain:
In Kyoto and other EVM-blockchain networks, blocks are created sequentially and contain a set of transactions. Each block is identified by a unique block number. The block number represents the position of a block in the blockchain's history.
To connect with smart contracts and run view functions use:
To connect with smartcontract and execute functions use:
or
If you want to know more about the getBlockNumber()
function, follow this .
More information you can find here: