⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

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

  1. Address - DATA, 20 bytes

    • The address to check balance for
    • Format: 0x prefixed, 40 hex characters
    • Example: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
  2. 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

# 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
}'

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 CodeDescriptionSolution
-32602Invalid paramsCheck address format and block parameter
-32603Internal errorRetry with exponential backoff
-32005Rate limit exceededImplement 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.