eth_getBalance
Returns the balance of the account at the given address in wei.
Parameters
-
Address -
DATA, 20 Bytes
- The address to check for balance
-
Block Parameter -
QUANTITY|TAG
"latest"
- Most recent block"earliest"
- Genesis block"pending"
- Pending state- Block number in hex
Returns
QUANTITY
- Integer of the current balance in wei.
Request Example
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
"latest"
],
"id": 1
}
Response Example
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1a055690d9db80000"
}
Implementation Examples
- JavaScript
- Python
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get ETH balance
async function getETHBalance(address) {
const balance = await provider.getBalance(address);
// Convert to human-readable format
const balanceInEth = ethers.formatEther(balance);
return {
wei: balance.toString(),
eth: balanceInEth
};
}
// Get historical balance
async function getBalanceAtBlock(address, blockNumber) {
const balance = await provider.getBalance(address, blockNumber);
return balance;
}
// Monitor balance changes
async function watchBalance(address) {
let lastBalance = await provider.getBalance(address);
provider.on('block', async () => {
const currentBalance = await provider.getBalance(address);
if (!currentBalance.eq(lastBalance)) {
console.log(`Balance changed: ${ethers.formatEther(currentBalance)} ETH`);
lastBalance = currentBalance;
}
});
}
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
def get_balance(address):
"""Get ETH balance for an address"""
# Get balance in wei
balance_wei = w3.eth.get_balance(address)
# Convert to ether
balance_eth = w3.from_wei(balance_wei, 'ether')
return {
'wei': balance_wei,
'eth': balance_eth
}
def get_balance_at_block(address, block_number):
"""Get historical balance at specific block"""
balance = w3.eth.get_balance(address, block_identifier=block_number)
return balance
def monitor_balance_changes(address):
"""Monitor balance changes for an address"""
last_balance = w3.eth.get_balance(address)
# Create filter for new blocks
block_filter = w3.eth.filter('latest')
while True:
for block_hash in block_filter.get_new_entries():
current_balance = w3.eth.get_balance(address)
if current_balance != last_balance:
print(f"Balance changed: {w3.from_wei(current_balance, 'ether')} ETH")
last_balance = current_balance
Common Use Cases
1. Wallet Balance Display
// Display user wallet balance
async function displayWalletInfo(address) {
const [balance, txCount, code] = await Promise.all([
provider.getBalance(address),
provider.getTransactionCount(address),
provider.getCode(address)
]);
const isContract = code !== '0x';
return {
address: address,
balance: ethers.formatEther(balance),
transactionCount: txCount,
type: isContract ? 'Contract' : 'EOA',
isEmpty: balance.eq(0)
};
}
2. Balance Requirements Check
// Check if user has enough balance for transaction
async function checkSufficientBalance(address, requiredAmount, gasLimit) {
const balance = await provider.getBalance(address);
const gasPrice = await provider.getGasPrice();
const gasCost = gasPrice * gasLimit;
const totalRequired = BigInt(requiredAmount) + gasCost;
if (balance < totalRequired) {
const shortage = ethers.formatEther(totalRequired - balance);
throw new Error(`Insufficient balance. Need ${shortage} more ETH`);
}
return true;
}
3. Multi-Address Balance Query
// Get balances for multiple addresses efficiently
async function getMultipleBalances(addresses) {
const balancePromises = addresses.map(addr =>
provider.getBalance(addr)
.then(balance => ({
address: addr,
balance: ethers.formatEther(balance)
}))
.catch(error => ({
address: addr,
error: error.message
}))
);
const balances = await Promise.all(balancePromises);
// Sort by balance descending
return balances.sort((a, b) =>
parseFloat(b.balance || 0) - parseFloat(a.balance || 0)
);
}
zkEVM Considerations
On Linea's zkEVM, balance queries are highly optimized:
// Efficient balance tracking on zkEVM
async function trackBalanceChanges(addresses) {
// zkEVM state is updated in batches
// Query at zkProof boundaries for consistency
const balances = new Map();
// Initial balances
for (const addr of addresses) {
balances.set(addr, await provider.getBalance(addr));
}
// Monitor changes efficiently
provider.on('block', async (blockNumber) => {
// Check every 10 blocks for zkEVM efficiency
if (blockNumber % 10 === 0) {
for (const addr of addresses) {
const newBalance = await provider.getBalance(addr);
const oldBalance = balances.get(addr);
if (!newBalance.eq(oldBalance)) {
console.log(`${addr}: ${ethers.formatEther(newBalance)} ETH`);
balances.set(addr, newBalance);
}
}
}
});
}
Error Handling
async function safeGetBalance(address) {
try {
// Validate address format
if (!ethers.isAddress(address)) {
throw new Error('Invalid address format');
}
const balance = await provider.getBalance(address);
return balance;
} catch (error) {
if (error.code === 'INVALID_ARGUMENT') {
console.error('Invalid address provided');
} else if (error.code === 'NETWORK_ERROR') {
console.error('Network connection issue');
} else {
console.error('Failed to get balance:', error);
}
throw error;
}
}
Need help? Contact our support team or check the Linea documentation.