Understanding Web3.eth.getBalance: Querying Ethereum Account Balances

·

Introduction

Web3.eth.getBalance is a JavaScript function designed to query account balances on the Ethereum blockchain. As part of the Web3.js library, it enables developers to interact with Ethereum programmatically. This guide explores its syntax, parameters, return values, and practical applications.


Function Syntax

web3.eth.getBalance(addressHexString[, defaultBlock][, callback])

Parameters

  1. addressHexString (Required):

    • The Ethereum address to query, formatted as a hexadecimal string.
  2. defaultBlock (Optional):

    • Specifies the block number (e.g., 12345) or tag ('latest', 'earliest', 'pending'). Defaults to web3.eth.defaultBlock.
  3. callback (Optional):

    • An asynchronous callback function receiving (error, balance), where balance is a BigNumber instance.

Return Value


How It Works

  1. Data Retrieval:

    • Queries the Ethereum blockchain via a connected node (e.g., local Ganache or Infura).
  2. Unit Handling:

    • Balances are returned in wei for precision; convert to ETH using web3.utils.fromWei().

Practical Example

const Web3 = require('web3');
const web3 = new Web3('http://localhost:8545'); // Local Ganache node

const address = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';

web3.eth.getBalance(address)
  .then(balance => console.log(web3.utils.fromWei(balance, 'ether')))
  .catch(console.error);

Prerequisites:


FAQs

1. How do I convert wei to ETH?

Use web3.utils.fromWei(balance, 'ether').

2. Why is my balance query failing?

Ensure:

3. Can I query historical balances?

Yes, by specifying a block number in defaultBlock.


Key Takeaways

👉 Master Ethereum development with these tools

By mastering web3.eth.getBalance, developers can efficiently integrate Ethereum data into dApps and smart contracts.

👉 Explore advanced Web3.js features here