Share your feedback on Twitter and claim 5M Free GetBlock Requests

banner image

How to Connect to Ethereum via Ether.js?

Vance Wood

Vance Wood

March 14, 2024

7 min read

article cover

In our exploration of Ethereum development tools, we already covered essential web3 libraries. Now, we set our sights on a comprehensive Ether.js tutorial.

Ethers guide: Highlights

Ethers.js, a JavaScript library designed for Ethereum, simplifies the connections with decentralized infrastructure.

  • Its primary functionality is enabling developers to write JavaScript and TypeScript codes to “talk” to Ethereum and Ethereum-like blockchains;
  • The tool allows accessing blockchain data and smart contracts functionality, as well as managing transactions;
  • This feature set is comparable to other Web3 libraries such as web3.js, which serve similar purposes in the ecosystem;
  • Despite its wide range of functionality, the library is designed to be lightweight, ensuring that it doesn't add unnecessary bulk to applications that use it.

Before delving into the detailed guide on utilizing Ethers.js, let's explore its significance in Ethereum dApp development.

What is Ether.js?

Ethers.js provides functionalities that enable JavaScript applications to establish connection to Ethereum via a set of APIs that encapsulate the logic for formatting requests, sending them to ETH nodes, and processing the responses received.

Created and maintained by a cryptography specialist Richard Moore, better known as RicMoo on X and GitHub, the library was introduced in 2016 as a more convenient alternative for web3.js.

Its smaller minified package size (142kB) and more concise, intuitive API are preferred by developers.

N.B.: Explore our guide on Web3 Libraries to discover further Web3.js vs Ethers.js distinctions.

Using the library, developers can also interact with test networks and Ethereum Virtual Machine (EVM) compatible protocols, such as BNB Smart Chain (BSC), Arbitrum, or Polygon.

Prerequisites for Connecting to Ethereum via Ether.js

Before integrating Ethers.js, there are a few essential setups to address.

  • Node.js;
  • npm: typically comes bundled with Node.js but yarn is also an option;
  • Access to either a local ETH node or a remote node exposing RPC API.

In the following tutorial, in order to connect to Ethereum we’ll use endpoints provided by GetBlock – a Web3 infrastructure service with access to over 55 blockchain protocols.

Finally, we can install the library:

npm install ethers --save 

This will add the latest version of the library as a dependency and download it into the node_modules directory. Now, the project is ready for Ethereum blockchain interactions and establishing reliable connection to Ethereum.

Connecting to Ethereum Network

Managing providers in ethers involves choosing the method of communication with Ethereum nodes.

Please note that the tutorial utilizes version 6.11.1 of the library, which introduced some changes to the Provider class.

Connecting_to_Ethereum_with_Ethers.js

Step 1: Importing Ethers

The first step is importing the necessary modules into the JavaScript code:

const { ethers } = require("ethers";

This will open access to all the objects and functions provided by the library.

Context Banner

Step 2: Obtaining node URL

The library exposes a JsonRpcProvider class, which allows developers to connect to ETH infrastructure using RPC API.

To access ETH API, GetBlock users simply can sign up for an account and obtain a free endpoint. Clients receive 40,000 free requests sufficient for testing the service and following this tutorial.

GetBlock_ETH_API

Step 3: Initializing Ethers.js Provider

After acquiring the endpoint, instantiate a provider object, passing the URL as an argument:

const provider = new ethers.providers.JsonRpcProvider(“https://go.getblock.io/”;

This URL specifies the RPC node endpoint, where the application will send requests to connect to the Ethereum network.

Interacting with the Ethereum Network via Ether.js

Once a connection to the Ethereum network is established, developers can use the methods exposed by the Provider class to send various requests to the node .

The tutorials below guide through the main types of interactions with Ethereum. Connect to other EVM blockchains can be established via similar procedures.

.

Retrieving Account Information

Let’s start with querying the ETH holdings of the random address "0xdA98bC69e4De00ac54C94fb4fE29E8CEBe7CfB40".

Inside the main function, the code calls the getBalance method:

Account_balance_request_with_Ethers.js

The library’s formatEther function helps automatically convert the balance in ETH instead of default wei.

Finally, it outputs the balance in a user-friendly format.

getBalance_response

Sending Transactions

Start by defining the sender and recipient. The library internally derives the sender’s account associated with the private key provided:

const privateKey_sender = 'SENDER_PRIVATE_KEY';
const receiverAddress = '0x…';
  1. To allow the sender to sign transactions, initialize the wallet from the private key;
const wallet = new ethers.Wallet(privateKey_sender, provider)
  1. Within the sendTransaction() method, specify the recipient (to) and the amount (value). ethers.parseEther() function will allow passing the amounts in ETH;
const main = async () => {
  const tx = await wallet.sendTransaction({
       to: receiverAddress,
       value: ethers.parseEther("0.05")
   })
  1. Finally, the wait() method ensures that the receipt is printed only after the operation is confirmed.
 await tx.wait()
   console.log(tx)
}

The complete code is provided below:

sending_ETH_transactions_with_Ethers.js

When the transaction is included in the block, the receipt logs to the console:

sendTransaction_response

Interacting with Smart Contracts

Knowing the contract address and its ABI, the library can create an abstraction – an object representing the contract in JavaScript.

Let’s create a script to call the mint function on a contract we created within our NFT tutorial:

contract_interaction_within_ethers.js

To unwarp:

  • Once an instance of the contract abstraction is created, users can call its functions directly from the code using standard function call syntax;
  • Parameters must match the function's definition in the contract;
  • These types of interactions also require a Signer, which in this case is created by instantiating a Wallet with a private key and a provider.

In essence, this is how this web3 library helps developers in building dApps that utilize the features of Solidity contracts and connection to Ethereum via API endpoints.

Wrapping up

Ether.js API is instrumental in enabling blockchain functionality of various applications, including those in DeFi, NFTs, or any other category. Ether.js integration is exactly what helps make these apps blockchain-based and efficiently process user requests, while the library handles the ETH connection under the hood, simplifying developers' mission.

Ready to experience top-notch connectivity? Sign up for a GetBlock account now to access high-quality connections to BSC, Ethereum, or popular Layer 2 networks such as Arbitrum, Optimism, Polygon, and Base.

Frequently Asked Questions (FAQs)

Can I use a hosted node with ethers instead of setting up one?

Yes, it might be easier to obtain access to a remote Ethereum node by registering an account with a node hosting service like GetBlock and obtaining an API endpoint. This allows connecting to the network without running a local node.

How do I connect to Ethereum via Ether.js?

Start by installing the library into the Node.js environment using ‘npm i ethers’. To connect to the ETH blockchain, import the module into the code and instantiate a JSON RPC provider using the URL obtained from a node service.

How can I check my Ethereum account balance using Ether.js?

To fetch any account balance, pass the address as an argument to the getBalance method. The balance can further be converted to ETH using utility functions if needed.

Can I interact with smart contracts with Ether.js?

Yes, users and apps can construct transactions to invoke smart contract functions by utilizing the Provider and Signer classes within the library.

Vance Wood

Vance Wood

March 14, 2024

7 min read

twittertwittertelegramtelegramLinkedinLinkedin