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
addressHexString(Required):- The Ethereum address to query, formatted as a hexadecimal string.
defaultBlock(Optional):- Specifies the block number (e.g.,
12345) or tag ('latest','earliest','pending'). Defaults toweb3.eth.defaultBlock.
- Specifies the block number (e.g.,
callback(Optional):- An asynchronous callback function receiving
(error, balance), wherebalanceis aBigNumberinstance.
- An asynchronous callback function receiving
Return Value
- Returns a
BigNumberrepresenting the balance in wei (1 ETH = 10¹⁸ wei).
How It Works
Data Retrieval:
- Queries the Ethereum blockchain via a connected node (e.g., local Ganache or Infura).
Unit Handling:
- Balances are returned in wei for precision; convert to ETH using
web3.utils.fromWei().
- Balances are returned in wei for precision; convert to ETH using
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:
- Install Web3.js (
npm install web3). - Run an Ethereum node (e.g., Ganache).
FAQs
1. How do I convert wei to ETH?
Use web3.utils.fromWei(balance, 'ether').
2. Why is my balance query failing?
Ensure:
- The address is valid.
- The node connection is active.
3. Can I query historical balances?
Yes, by specifying a block number in defaultBlock.
Key Takeaways
👉 Master Ethereum development with these tools
- Precision Matters: Balances are in wei; convert for user-friendly displays.
- Async Support: Use callbacks or Promises for non-blocking operations.
By mastering web3.eth.getBalance, developers can efficiently integrate Ethereum data into dApps and smart contracts.