Skip to main content

eth_getBalance

Returns the ETH balance of a given address on Bittensor Blockchain.

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

Parameters​

  1. Address - DATA, 20 bytes

    • The address to check balance for
    • Format: 0x prefixed, 40 hex characters
  2. Block Parameter - QUANTITY|TAG

    • "latest" - Most recent block (default)
    • "earliest" - Genesis block
    • "pending" - Pending state
    • "safe" - Latest safe block
    • "finalized" - Latest finalized block
    • Block number in hex format
{
"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 ETH = 10^18 wei)
  • Format: 0x prefixed

Implementation Examples​

curl -X POST https://api-bittensor-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"latest"
],
"id": 1
}'

Response Example​

Successful Response​

{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1a055690d9db80000"
}

This represents 0x1a055690d9db80000 wei = 1.85 ETH

Error Response​

{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid params: invalid address"
}
}

Common Use Cases​

1. Wallet Balance Display​

Display formatted balance with USD value:

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

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:

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:

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:

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-bittensor-mainnet-archive.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:

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

Error Handling​

Common errors and solutions:

Error CodeDescriptionSolution
-32602Invalid address formatEnsure address is 40 hex chars with 0x prefix
-32602Invalid block parameterUse valid block tag or hex number
-32000Account not foundAddress may not exist on chain
async function safeGetBalance(address) {
try {
// Validate address format
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
throw new Error('Invalid address format');
}

const balance = await provider.getBalance(address);
return { success: true, balance: formatEther(balance) };

} catch (error) {
console.error('Failed to get balance:', error);

// Return zero for non-existent accounts
if (error.code === -32000) {
return { success: true, balance: '0' };
}

return { success: false, error: error.message };
}
}

Need help? Contact our support team or check the Bittensor documentation.