eth_getBalance
Returns the ETH balance of a given address on Polygon PoS.
When to Use This Method​
eth_getBalance
is essential for:
- Wallet Applications - Display user balances
- Transaction Validation - Check if account has sufficient funds
- DeFi Applications - Monitor collateral and liquidity
- Account Monitoring - Track balance changes over time
Parameters​
-
Address -
DATA
, 20 bytes- The address to check balance for
- Format:
0x
prefixed, 40 hex characters
-
Block Parameter -
QUANTITY|TAG
"latest"
- Most recent block (default)"earliest"
- Genesis block"pending"
- Pending state"safe"
- Latest safe block"finalized"
- Latest finalized block- Block number in hex format
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"latest"
],
"id": 1
}
Returns​
QUANTITY
- Integer of the current balance in wei.
- Type: Hexadecimal string
- Unit: Wei (1 ETH = 10^18 wei)
- Format:
0x
prefixed
Implementation Examples​
- cURL
- JavaScript
- Python
- Go
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"latest"
],
"id": 1
}'
// Using ethers.js
import { JsonRpcProvider, formatEther } from 'ethers';
const provider = new JsonRpcProvider('https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY');
async function getBalance(address) {
// Get balance in wei
const balanceWei = await provider.getBalance(address);
// Convert to ETH
const balanceEth = formatEther(balanceWei);
console.log(`Balance: ${balanceEth} ETH`);
return balanceEth;
}
// Check multiple balances
async function getMultipleBalances(addresses) {
const balances = await Promise.all(
addresses.map(async (addr) => {
const balance = await provider.getBalance(addr);
return {
address: addr,
balance: formatEther(balance)
};
})
);
return balances;
}
from web3 import Web3
# Connect to Base
w3 = Web3(Web3.HTTPProvider('https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
def get_balance(address):
# Get balance in wei
balance_wei = w3.eth.get_balance(address)
# Convert to ETH
balance_eth = w3.from_wei(balance_wei, 'ether')
print(f"Balance: {balance_eth} ETH")
return balance_eth
# Get balance at specific block
def get_historical_balance(address, block_number):
balance_wei = w3.eth.get_balance(address, block_identifier=block_number)
return w3.from_wei(balance_wei, 'ether')
# Monitor balance changes
def monitor_balance(address, interval=2):
import time
last_balance = 0
while True:
current_balance = w3.eth.get_balance(address)
if current_balance != last_balance:
change = current_balance - last_balance
print(f"Balance changed: {w3.from_wei(change, 'ether')} ETH")
last_balance = current_balance
time.sleep(interval)
package main
import (
"context"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")
// Get balance at latest block
balance, err := client.BalanceAt(context.Background(), address, nil)
if err != nil {
log.Fatal(err)
}
// Convert wei to ETH
ethValue := new(big.Float).Quo(
new(big.Float).SetInt(balance),
big.NewFloat(1e18),
)
fmt.Printf("Balance: %f ETH\n", ethValue)
}
Response Example​
Successful Response​
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1a055690d9db80000"
}
This represents 0x1a055690d9db80000
wei = 1.85 ETH
Error Response​
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid params: invalid address"
}
}
Common Use Cases​
1. Wallet Balance Display​
Display formatted balance with USD value:
async function displayWalletBalance(address) {
const provider = new JsonRpcProvider('https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY');
// Get ETH balance
const balance = await provider.getBalance(address);
const ethBalance = formatEther(balance);
// Get ETH price (from your price oracle)
const ethPrice = await getEthPrice(); // Implement this
const usdValue = parseFloat(ethBalance) * ethPrice;
return {
eth: ethBalance,
usd: usdValue.toFixed(2),
formatted: `${ethBalance} ETH ($${usdValue.toFixed(2)})`
};
}
2. Transaction Pre-validation​
Check if account has enough balance for transaction:
async function canAffordTransaction(from, to, value, gasLimit, maxFeePerGas) {
const balance = await provider.getBalance(from);
// Calculate total cost
const valueBigInt = BigInt(value);
const gasCost = BigInt(gasLimit) * BigInt(maxFeePerGas);
const totalCost = valueBigInt + gasCost;
if (balance < totalCost) {
const shortage = formatEther(totalCost - balance);
throw new Error(`Insufficient balance. Need ${shortage} more ETH`);
}
return true;
}
3. Balance Change Detection​
Monitor account for balance changes:
class BalanceMonitor {
constructor(provider, address) {
this.provider = provider;
this.address = address;
this.lastBalance = null;
}
async start(callback, interval = 2000) {
setInterval(async () => {
const currentBalance = await this.provider.getBalance(this.address);
if (this.lastBalance && currentBalance !== this.lastBalance) {
const change = currentBalance - this.lastBalance;
callback({
address: this.address,
previousBalance: this.lastBalance,
currentBalance,
change,
changeFormatted: formatEther(change)
});
}
this.lastBalance = currentBalance;
}, interval);
}
}
// Usage
const monitor = new BalanceMonitor(provider, "0x...");
monitor.start((data) => {
console.log(`Balance changed by ${data.changeFormatted} ETH`);
});
4. Historical Balance Query​
Get balance at specific block:
async function getBalanceHistory(address, blocks) {
const history = [];
for (const blockNumber of blocks) {
const balance = await provider.getBalance(address, blockNumber);
const block = await provider.getBlock(blockNumber);
history.push({
block: blockNumber,
timestamp: block.timestamp,
balance: formatEther(balance)
});
}
return history;
}
// Get balance every 1000 blocks
async function getBalanceSnapshots(address, count = 10) {
const currentBlock = await provider.getBlockNumber();
const blocks = [];
for (let i = 0; i < count; i++) {
blocks.push(currentBlock - (i * 1000));
}
return getBalanceHistory(address, blocks);
}
Performance Optimization​
Batch Balance Queries​
Query multiple balances efficiently:
async function batchGetBalances(addresses) {
const batch = addresses.map((addr, i) => ({
jsonrpc: '2.0',
method: 'eth_getBalance',
params: [addr, 'latest'],
id: i
}));
const response = await fetch('https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
const results = await response.json();
return results.map((r, i) => ({
address: addresses[i],
balance: formatEther(BigInt(r.result))
}));
}
Caching Strategy​
Implement smart caching for balance queries:
class BalanceCache {
constructor(ttl = 5000) {
this.cache = new Map();
this.ttl = ttl;
}
getCacheKey(address, block) {
return `${address}-${block}`;
}
async getBalance(provider, address, block = 'latest') {
const key = this.getCacheKey(address, block);
const cached = this.cache.get(key);
// Return cached if block is not 'latest' (immutable)
if (cached && block !== 'latest') {
return cached.balance;
}
// Check TTL for 'latest' block
if (cached && block === 'latest') {
if (Date.now() - cached.timestamp < this.ttl) {
return cached.balance;
}
}
// Fetch fresh balance
const balance = await provider.getBalance(address, block);
this.cache.set(key, {
balance,
timestamp: Date.now()
});
return balance;
}
}
Error Handling​
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
-32602 | Invalid address format | Ensure address is 40 hex chars with 0x prefix |
-32602 | Invalid block parameter | Use valid block tag or hex number |
-32000 | Account not found | Address may not exist on chain |
async function safeGetBalance(address) {
try {
// Validate address format
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
throw new Error('Invalid address format');
}
const balance = await provider.getBalance(address);
return { success: true, balance: formatEther(balance) };
} catch (error) {
console.error('Failed to get balance:', error);
// Return zero for non-existent accounts
if (error.code === -32000) {
return { success: true, balance: '0' };
}
return { success: false, error: error.message };
}
}
Need help? Contact our support team or check the Polygon documentation.