Scholarpeak

Balance Methods

Query and understand Ethereum account balances.

eth_getBalance

Get the ETH balance of an account

Returns the balance of an account in Wei (the smallest unit of ETH). You need to convert this to ETH by dividing by 1,000,000,000,000,000,000 (1 followed by 18 zeros).

typescript
async function getBalance(address) {
  const balanceWei = await window.ethereum.request({
    method: 'eth_getBalance',
    params: [address, 'latest']
  });
  
  // Convert from Wei to ETH
  const balanceETH = Number(BigInt(balanceWei)) / 1e18;
  
  return balanceETH;
}

Test it:

Understanding Wei

Wei is the smallest denomination of Ethereum. Just like cents to dollars, wei to ETH.

Common conversions:

1 ETH = 1,000,000,000,000,000,000 Wei (1e18)
1 GWei = 1,000,000,000 Wei (1e9)
1 Wei = 1 Wei (smallest unit)
typescript
// Convert Wei to ETH
function weiToEth(wei) {
  return Number(BigInt(wei)) / 1e18;
}

// Convert ETH to Wei
function ethToWei(eth) {
  return BigInt(Math.round(eth * 1e18)).toString();
}

// Examples
console.log(weiToEth('1000000000000000000')); // 1.0
console.log(ethToWei(0.5)); // 500000000000000000

The Block Parameter

The second parameter specifies which block to query. This lets you get historical balances.

"latest"Most recent block (default)
"pending"Pending transactions in the mempool
0x1234Specific block by number (hex format)
typescript
// Always use 'latest' in most cases
const balance = await window.ethereum.request({
  method: 'eth_getBalance',
  params: ['0x1234...', 'latest']  // Current balance
});

// Occasionally useful for historical data
const oldBalance = await window.ethereum.request({
  method: 'eth_getBalance',
  params: ['0x1234...', '0xABCD']  // Balance at specific block
});

Complete Example

typescript
async function showUserBalance() {
  try {
    // Get connected account
    const accounts = await window.ethereum.request({
      method: 'eth_requestAccounts'
    });
    
    const address = accounts[0];
    
    // Get balance
    const balanceWei = await window.ethereum.request({
      method: 'eth_getBalance',
      params: [address, 'latest']
    });
    
    // Convert to ETH
    const balanceETH = (Number(BigInt(balanceWei)) / 1e18).toFixed(2);
    
    console.log(`Balance: ${balanceETH} ETH`);
    
    // Display to user
    document.getElementById('balance').textContent = balanceETH;
    
  } catch (error) {
    console.error('Error:', error);
  }
}

// Call on button click
document.getElementById('balanceBtn').addEventListener('click', showUserBalance);

Key Takeaways

  • ✓ Balances are returned in Wei, not ETH
  • ✓ Divide by 1e18 to convert Wei to ETH
  • ✓ Always use "latest" unless you need historical data
  • ✓ Hex strings returned by Ethereum methods need to be converted with BigInt()
  • ✓ Use toFixed() to format balance display for users