Docs

eth_getBalance - Query Account Balance

Get the ETH balance of any address on Centrifuge Mainnet. Essential for wallet applications and balance checking.

Returns the ETH balance of a given address on Centrifuge Mainnet.

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

Implementation Examples

Common Use Cases

1. Wallet Balance Display

Display formatted balance with USD value:

JavaScript
async function displayWalletBalance(address) {
  const provider = new JsonRpcProvider('https://api-centrifuge.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:

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
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-centrifuge.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:

JavaScript
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;
  }
}