Published on October 24, 2024By DeveloperBreeze

Tutorial: Getting Wallet Balance Using Ethers.js in Node.js

In this tutorial, you will learn how to retrieve the balance of an Ethereum wallet using Ethers.js in a Node.js environment. We will cover two methods:

  1. Using Infura as a provider to access the Ethereum blockchain.
  2. Connecting directly to a public Ethereum node.

By the end of this tutorial, you’ll be able to query the balance of any Ethereum wallet and display it in Ether units.


Prerequisites

To follow along, you’ll need the following:

  • Node.js installed on your machine.
  • Basic understanding of JavaScript.
  • An Ethereum wallet (with private key or mnemonic phrase).
  • (Optional) An Infura account to access the Ethereum network.

Step 1: Install Ethers.js

First, you need to install Ethers.js, a library for interacting with the Ethereum blockchain.

Run the following command in your project folder to install it:

npm install ethers

Step 2: Set Up Infura and Create an API Key

If you plan to use Infura as your Ethereum provider, follow these steps:

  1. Go to [Infura’s website](https://infura.io/).
  2. Sign up or log in to your account.
  3. Create a new project and get your Project ID from the settings.
  4. You’ll use this Project ID as your API key for accessing the Ethereum network.

Step 3: Create the Node.js Script

Now, let's create a script to query the balance of an Ethereum wallet. This script will work with both Infura and public nodes.

  1. Create a file called getBalance.js in your project folder.
  2. Open this file and write the following code:

Using Infura to Query Wallet Balance

const ethers = require('ethers');

// Replace this with your Ethereum wallet's private key or mnemonic phrase
const privateKey = 'YOUR_PRIVATE_KEY_OR_MNEMONIC';

// Replace this with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Create a wallet instance using your private key and connect it to the Infura provider
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Function to get the balance of the wallet
async function getWalletBalance() {
    // Get the wallet's balance in wei
    const balanceInWei = await wallet.getBalance();

    // Convert the balance from wei to Ether for readability
    const balanceInEther = ethers.utils.formatEther(balanceInWei);

    // Log the results
    console.log(`Wallet Address: ${wallet.address}`);
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
}

// Execute the function
getWalletBalance();

Using a Public Node to Query Wallet Balance (Alternative)

If you don't want to use Infura, you can connect to a public Ethereum node:

const ethers = require('ethers');

// Replace this with your Ethereum wallet's private key or mnemonic phrase
const privateKey = 'YOUR_PRIVATE_KEY_OR_MNEMONIC';

// Use a public Ethereum node URL (this is a public node for demonstration purposes)
const publicProvider = new ethers.JsonRpcProvider('https://mainnet.publicnode.com');

// Create a wallet instance using your private key and connect it to the public node provider
const wallet = new ethers.Wallet(privateKey, publicProvider);

// Function to get the balance of the wallet
async function getWalletBalance() {
    // Get the wallet's balance in wei
    const balanceInWei = await wallet.getBalance();

    // Convert the balance from wei to Ether for readability
    const balanceInEther = ethers.utils.formatEther(balanceInWei);

    // Log the results
    console.log(`Wallet Address: ${wallet.address}`);
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
}

// Execute the function
getWalletBalance();

Step 4: Replace Your Private Key and Provider

  • Replace 'YOUR_PRIVATE_KEY_OR_MNEMONIC' with your actual Ethereum wallet's private key or mnemonic phrase.
  • For the Infura method, replace 'YOUR_INFURA_PROJECT_ID' with the Infura Project ID you received when you created your Infura account.

> Important: Keep your private key secure. Never share it publicly or commit it to version control. For better security, consider using environment variables to store sensitive information like private keys.

Step 5: Run the Script

Once your script is set up, run it from the command line:

node getBalance.js

If everything is set up correctly, the script will output the wallet’s Ethereum balance in Ether:

Wallet Address: 0xYourEthereumAddress
Wallet Balance: 2.345 ETH

How It Works

  • Ethers.js: We are using Ethers.js to interact with the Ethereum blockchain. Ethers.js simplifies the process of querying the blockchain and formatting the data for developers.
  • Provider: Whether you use Infura or a public node, the provider allows us to connect to the Ethereum network. Infura is commonly used because of its reliability and scalability, but public nodes can work as well if you're looking for a simple alternative.
  • getBalance(): This function queries the Ethereum network for the balance of the wallet in wei (the smallest unit of ETH). We then use ethers.utils.formatEther() to convert the balance from wei to Ether.

Step 6: Explore More

Once you've successfully retrieved the balance, you can expand your script to add more features. For example:

  • Check the balance of other Ethereum addresses (not just your wallet).
  • Send ETH to other addresses.
  • Interact with smart contracts using Ethers.js.

Conclusion

In this tutorial, you learned how to use Ethers.js to query the balance of an Ethereum wallet in Node.js. You also saw how to use Infura or connect to a public node to access the Ethereum network. This is the foundation for working with Ethereum and interacting with wallets and smart contracts in a programmatic way.

By connecting to the Ethereum network and querying wallet balances, you now have a powerful tool for building decentralized applications (dApps) and automating blockchain-related tasks.

Comments

Please log in to leave a comment.

Continue Reading:

Weather App with Node.js

Published on August 08, 2024

javascript

Installing Solana on Ubuntu

Published on August 09, 2024

bashrust

Creating a Token on Solana

Published on August 09, 2024

bashrust

Fetching Address Details from Solana

Published on August 09, 2024

javascriptjson

Tracking Newly Created Tokens on Ethereum

Published on August 09, 2024

javascriptnodejs

Tracking Newly Created Tokens on Solana

Published on August 09, 2024

javascriptnodejs

Tracking Solana Address for New Trades and Amounts

Published on August 09, 2024

javascriptnodejs

Node.js: How to Create an HTTP Server

Published on August 12, 2024

javascriptnodejs

GraphQL API Server with Node.js and Apollo Server

Published on August 12, 2024

nodejsgraphql

Building a GraphQL API with Node.js and Apollo Server

Published on August 12, 2024

javascriptnodejsgraphql