Home Crypto How to Interact with Blockchain using Ethers.js

How to Interact with Blockchain using Ethers.js

0
How to Interact with Blockchain using Ethers.js

[ad_1]

BLOCKCHAIN SERIES

Utilizing ethers, read data and send transactions on the blockchain

Ethers.js

Ethers.js is a library that allows us to connect with the Ethereum Blockchain and its ecosystem. We can use ethers to connect to Ethereum nodes through JSON-RPC, Infura, Alchemy, Cloudflare, or Metamask.

Installation

npm install ethers

Authentication

Crypto wallets like Metamask, Coinbase, TrustWallet, and Phantom are used to connect to the blockchain. They provide an entry point to every decentralized application. We can install crypto wallets as add-ons or plugins to our browsers.

When we add crypto wallets as an extension to our browsers, they automatically inject themselves into the browser window object. For example, If we add the Metamask extension, it injects an ethereum object into the browser window.

Establish Provider Connection

Ethers.js library makes it easy to connect to any node in a blockchain. We can either use the default provider given by the browser extension or third-party RPC providers like Alchemy, Infura, and Moralis.

Credits: Author

Fetch Wallet Balance

After initializing the provider, we can invoke the provider method, getBalance() to fetch the balance of an ethereum account.

Credits: Author

Handling BigNumber

In Ethereum, many operations are performed on numbers that are outside the range of values in javascript, called BigNumbers. Ethers.js helps us to convert BigNumbers into numbers that are in human readable format.

Credits: Author

Create Signer

A signer is an abstraction of a blockchain account that is used to sign messages and send transactions on the blockchain. After initializing the provider, we can create a signer from it.

Credits: Author

Send Transactions

We can use the signer to send the transaction. A transaction object might contain from and to addresses, the token value to be sent, the gas price, and the gas limit.

Credits: Author

Interaction with Smart Contract

We can connect to a smart contract and invoke the methods specified in contract ABI using the signer. ABIs are written in JSON format. It contains details on smart contracts, such as what functions are available, how to use them, and how to retrieve data from them.

For example, if your ABI contains a balanceOf() function, we can invoke the method as follows:

Credits: Author

[ad_2]

Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here