Docs
Neuroweb

eth_getBalance - Query Account Balance

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

Returns the ETH balance of a given address on Neuroweb 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

Request Parameters

Request

This method accepts no parameters.

Response Body

Response
resultOBJECT

**Type**: Hexadecimal string **Unit**: Wei (1 ETH = 10^18 wei) **Format**: `0x` prefixed

Error Responses

Errors
Error 1-32602

Invalid address format

Error 2-32602

Invalid block parameter

Error 3-32000

Account not found

Implementation Examples

Bash
curl -X POST https://api-neuroweb.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_getBalance",
    "params": [
      "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
      "latest"
    ],
    "id": 1
  }'
JavaScript
// Using ethers.js
import { JsonRpcProvider, formatEther } from 'ethers';

const provider = new JsonRpcProvider('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY');

async function getBalance(address) {
  // Get balance in wei
  const balanceWei = await provider.getBalance(address);
  
  // Convert to ETH
  const balanceEth = formatEther(balanceWei);
  
  console.log(`Balance: ${balanceEth} ETH`);
  return balanceEth;
}

// Check multiple balances
async function getMultipleBalances(addresses) {
  const balances = await Promise.all(
    addresses.map(async (addr) => {
      const balance = await provider.getBalance(addr);
      return {
        address: addr,
        balance: formatEther(balance)
      };
    })
  );
  return balances;
}
Python
from web3 import Web3

# Connect to Ethereum
w3 = Web3(Web3.HTTPProvider('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY'))

def get_balance(address):
    # Get balance in wei
    balance_wei = w3.eth.get_balance(address)
    
    # Convert to ETH
    balance_eth = w3.from_wei(balance_wei, 'ether')
    
    print(f"Balance: {balance_eth} ETH")
    return balance_eth

# Get balance at specific block
def get_historical_balance(address, block_number):
    balance_wei = w3.eth.get_balance(address, block_identifier=block_number)
    return w3.from_wei(balance_wei, 'ether')

# Monitor balance changes
def monitor_balance(address, interval=2):
    import time
    last_balance = 0
    
    while True:
        current_balance = w3.eth.get_balance(address)
        if current_balance != last_balance:
            change = current_balance - last_balance
            print(f"Balance changed: {w3.from_wei(change, 'ether')} ETH")
            last_balance = current_balance
        time.sleep(interval)
Go
package main

import (
    "context"
    "fmt"
    "log"
    "math/big"
    
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://api-neuroweb.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }
    
    address := common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")
    
    // Get balance at latest block
    balance, err := client.BalanceAt(context.Background(), address, nil)
    if err != nil {
        log.Fatal(err)
    }
    
    // Convert wei to ETH
    ethValue := new(big.Float).Quo(
        new(big.Float).SetInt(balance),
        big.NewFloat(1e18),
    )
    
    fmt.Printf("Balance: %f ETH\n", ethValue)
}

Common Use Cases

1. Wallet Balance Display

Display formatted balance with USD value:

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