Query and understand Ethereum account balances.
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).
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:
Wei is the smallest denomination of Ethereum. Just like cents to dollars, wei to ETH.
Common conversions:
// 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)); // 500000000000000000The second parameter specifies which block to query. This lets you get historical balances.
// 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
});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);