← coderrocketfuel.com

Get the Ether Balance For An Ethereum Address With Web3.js

In this article, we'll walk through how to get the Ether balance for an Ethereum address using Node.js and Web3.js.

To get the balance of an Ethereum address, we'll need a way to connect to an Ethereum blockchain node. To make this easy, we'll use Infura. Their API gives you instant access to the Ethereum networks.

Before moving on, make sure you have an Infura account created and a Public ID API key. We'll use that api key to access Infura's API.

Table Of Contents

Install Web3.js NPM Package

Before we install Web3.js, make sure you have Node.js installed and an application directory setup to store our code.

If needed, we wrote a guide on installing Node.js.

You can install the Web3.js NPM package with one of these commands:

NPM:

npm install web3 --save

Yarn:

yarn add web3

When that's done installing, Web3.js is ready to be used and we can start writing some code.

Get Eth Balance of an Ethereum Address

Let's get the balance for an Ethereum address!

Open up your favorite text editor and add this code to your application's index.js or app.js file (make sure you replace YOUR_PROJECT_ID with your unique Project ID):

const Web3 = require("web3")

const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID"))

web3.eth.getBalance("0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5", function(err, result) {
  if (err) {
    console.log(err)
  } else {
    console.log(web3.utils.fromWei(result, "ether") + " ETH")
  }
})

A couple of different things are happening in the code here, so let's go through each part:

  1. First, we require the web3 NPM package and store it in the uppercase Web3 variable.
  2. Then, we create a web3 instance and set its provider (the method in which web3 gets access to an Ethereum node). We use the HttpProvider() function and pass our Infura api endpoint. This api endpoint is for the Mainnet network (you can replace this with any of the other networks, i.e. Ropsten) and has the ID for our project appended to the end of the url.
  3. Now that the web3 instance is ready to use, we use the web3.eth.getBalance() function to get the balance of an Ethereum address. We pass an Ethereum address as a parameter and the function returns a callback with an error and the balance for the address.
  4. Inside the callback, we do some error handling by logging any errors that occur.
  5. Then, we log the result from the callback function. We use the web3.utils.fromWei() function to log it in a human readable-format.

When you run the code, you should get an output similar to this:

2519.67405 ETH

If you're looking for more things to do with Web3.js, check out the documentation.