eth_getBalance
Returns the BERA balance of a given address on Berachain.
When to Use This Method
eth_getBalance
is essential for:
- Wallet Applications - Display user BERA balances
- Transaction Validation - Check if account has sufficient funds before sending
- DeFi Applications - Monitor collateral and liquidity positions
- Account Monitoring - Track balance changes over time
Parameters
-
Address -
DATA
, 20 bytes- The address to check balance for
- Format:
0x
prefixed, 40 hex characters - Example:
0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
-
Block Parameter -
QUANTITY|TAG
(optional, defaults to "latest")"latest"
- Most recent block (default)"earliest"
- Genesis block"pending"
- Pending state"safe"
- Latest safe block"finalized"
- Latest finalized block- Block number in hex format (e.g.,
"0x1b4"
)
{
"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 BERA = 10^18 wei)
- Format:
0x
prefixed - Example:
"0x1bc16d674ec80000"
(2 BERA in decimal)
Implementation Examples
- cURL
- JavaScript
- Python
- Go
# Get balance for specific address
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"latest"
],
"id": 1
}'
# Get historical balance at specific block
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"0x1b4"
],
"id": 1
}'
// Using ethers.js
import { JsonRpcProvider, formatEther } from 'ethers';
const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY');
async function getBalance(address) {
// Get balance in wei
const balanceWei = await provider.getBalance(address);
// Convert to BERA
const balanceBera = formatEther(balanceWei);
console.log(`Balance: ${balanceBera} BERA`);
return balanceBera;
}
// Check multiple balances efficiently
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),
balanceWei: balance.toString()
};
})
);
return balances;
}
// Using fetch API
const getBalanceRaw = async (address, blockTag = 'latest') => {
const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getBalance',
params: [address, blockTag],
id: 1
})
});
const data = await response.json();
const balanceWei = BigInt(data.result);
const balanceBera = Number(balanceWei) / 1e18;
return { balanceWei, balanceBera };
};
import requests
import json
from web3 import Web3
def get_balance(address, block='latest'):
url = 'https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'
payload = {
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [address, block],
"id": 1
}
response = requests.post(url, json=payload)
data = response.json()
# Convert wei to BERA
balance_wei = int(data['result'], 16)
balance_bera = balance_wei / 10**18
print(f"Balance: {balance_bera:.6f} BERA")
return balance_bera
# Using web3.py
def get_balance_web3(address):
w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'))
balance_wei = w3.eth.get_balance(address)
balance_bera = w3.from_wei(balance_wei, 'ether')
print(f"Address: {address}")
print(f"Balance: {balance_bera} BERA")
return balance_bera
# Check multiple addresses
def get_multiple_balances(addresses):
w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'))
balances = []
for address in addresses:
balance_wei = w3.eth.get_balance(address)
balance_bera = w3.from_wei(balance_wei, 'ether')
balances.append({
'address': address,
'balance_bera': float(balance_bera),
'balance_wei': balance_wei
})
return balances
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-berachain-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
// Get balance for specific address
address := common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")
balance, err := client.BalanceAt(context.Background(), address, nil)
if err != nil {
log.Fatal(err)
}
// Convert wei to BERA
balanceInBera := new(big.Float)
balanceInBera.SetString(balance.String())
balanceInBera = balanceInBera.Quo(balanceInBera, big.NewFloat(1e18))
fmt.Printf("Address: %s\n", address.Hex())
fmt.Printf("Balance: %f BERA\n", balanceInBera)
}
// Function to check multiple balances
func getMultipleBalances(client *ethclient.Client, addresses []string) error {
for _, addr := range addresses {
address := common.HexToAddress(addr)
balance, err := client.BalanceAt(context.Background(), address, nil)
if err != nil {
return err
}
balanceInBera := new(big.Float)
balanceInBera.SetString(balance.String())
balanceInBera = balanceInBera.Quo(balanceInBera, big.NewFloat(1e18))
fmt.Printf("%s: %f BERA\n", addr, balanceInBera)
}
return nil
}
Response Example
Successful Response
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1bc16d674ec80000"
}
Note: Result 0x1bc16d674ec80000
equals 2,000,000,000,000,000,000 wei (2 BERA).
Error Response
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid params"
}
}
Common Use Cases
1. Wallet Balance Display
Display formatted BERA balance in wallet UI:
async function displayWalletBalance(address) {
try {
const balanceWei = await provider.getBalance(address);
const balanceBera = formatEther(balanceWei);
// Format for display
const formattedBalance = parseFloat(balanceBera).toFixed(4);
console.log(`${address}: ${formattedBalance} BERA`);
return formattedBalance;
} catch (error) {
console.error('Failed to get balance:', error);
return '0.0000';
}
}
2. Transaction Validation
Check sufficient funds before sending transaction:
async function validateTransaction(from, to, amount) {
const balance = await provider.getBalance(from);
const gasPrice = await provider.getGasPrice();
const gasLimit = 21000n; // Basic transfer
const totalCost = parseEther(amount) + (gasPrice * gasLimit);
if (balance < totalCost) {
throw new Error(`Insufficient balance. Need ${formatEther(totalCost)} BERA, have ${formatEther(balance)} BERA`);
}
return true;
}
3. DeFi Position Monitoring
Monitor account balances for DeFi applications:
async function monitorPositions(accounts, threshold = '0.1') {
const thresholdWei = parseEther(threshold);
const lowBalanceAccounts = [];
for (const account of accounts) {
const balance = await provider.getBalance(account);
if (balance < thresholdWei) {
lowBalanceAccounts.push({
address: account,
balance: formatEther(balance),
needsFunding: true
});
}
}
return lowBalanceAccounts;
}
4. Historical Balance Tracking
Track balance changes over time:
async function getBalanceHistory(address, blocks) {
const history = [];
for (const blockNumber of blocks) {
try {
const balance = await provider.getBalance(address, blockNumber);
const block = await provider.getBlock(blockNumber);
history.push({
blockNumber,
timestamp: block.timestamp,
balance: formatEther(balance),
balanceWei: balance.toString()
});
} catch (error) {
console.warn(`Failed to get balance at block ${blockNumber}:`, error);
}
}
return history.sort((a, b) => a.blockNumber - b.blockNumber);
}
Performance Optimization
Batch Balance Queries
Query multiple balances efficiently:
async function getBatchBalances(addresses) {
const batch = addresses.map((addr, index) => ({
jsonrpc: '2.0',
method: 'eth_getBalance',
params: [addr, 'latest'],
id: index + 1
}));
const response = await fetch('https://api-berachain-mainnet.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((result, index) => ({
address: addresses[index],
balance: result.error ? '0' : formatEther(BigInt(result.result))
}));
}
Caching Strategy
Cache balances with smart invalidation:
class BalanceCache {
constructor(ttl = 10000) { // 10 second cache
this.cache = new Map();
this.ttl = ttl;
}
async getBalance(address, provider) {
const key = address.toLowerCase();
const cached = this.cache.get(key);
if (cached && (Date.now() - cached.timestamp) < this.ttl) {
return cached.balance;
}
const balance = await provider.getBalance(address);
this.cache.set(key, {
balance,
timestamp: Date.now()
});
return balance;
}
invalidate(address = null) {
if (address) {
this.cache.delete(address.toLowerCase());
} else {
this.cache.clear();
}
}
}
const balanceCache = new BalanceCache();
Error Handling
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
-32602 | Invalid params | Check address format and block parameter |
-32603 | Internal error | Retry with exponential backoff |
-32005 | Rate limit exceeded | Implement rate limiting client-side |
async function safeGetBalance(address, blockTag = 'latest', maxRetries = 3) {
// Validate address format
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
throw new Error('Invalid address format');
}
for (let i = 0; i < maxRetries; i++) {
try {
return await provider.getBalance(address, blockTag);
} catch (error) {
if (error.code === -32005) {
// Rate limited, wait exponentially
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.code === -32602) {
throw new Error(`Invalid parameters: ${error.message}`);
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
Balance Formatting Utilities
Wei Conversion Helpers
// Convert wei to BERA
function weiToBera(weiAmount) {
return Number(weiAmount) / 1e18;
}
// Convert BERA to wei
function beraToWei(beraAmount) {
return BigInt(Math.floor(beraAmount * 1e18));
}
// Format balance for display
function formatBalance(balanceWei, decimals = 4) {
const balance = weiToBera(balanceWei);
if (balance === 0) return '0';
if (balance < 0.0001) return '< 0.0001';
if (balance > 1000000) return `${(balance / 1000000).toFixed(2)}M`;
if (balance > 1000) return `${(balance / 1000).toFixed(2)}K`;
return balance.toFixed(decimals);
}
Need help? Contact our support team or check the Berachain documentation.