Checking and polling Ethereum balance using Electrum CLI and RPC
The Ethereum decentralized platform provides a robust API for interacting with the network, allowing developers to programmatically check and query an address’s balance in a variety of ways. In this article, we’ll explore how to use the Electrum CLI and Remote Procedure Call (RPC) APIs to accomplish this task.
Prerequisites
Before getting started, make sure you have:
- An Ethereum wallet configured and associated with a compatible cryptocurrency account.
ethers.js
library installed:npm install ethers
oryarn add ethers
- Electrum CLI installed: [Install Electrum CLI](
Method 1: Using Electrum CLI
You can use Electrum CLI to query the balance of an Ethereum address directly from your terminal. Here are the steps:
- Get the wallet’s private key: Make sure you have access to a private key for the account you want to check.
- Set up Electrum CLI:
npx @openethereum cli init --name eth-cli --default-wallet private_key
Replace private_key
with the actual private key of your wallet.
- List all addresses – Run the following command to see a list of all addresses in your wallet:
eth account list
- Poll an address’s balance – Choose the address you want to check and run the following command:
eth balance --address
-count 1
Replace
Method 2: Using Electrum RPC
The Electrum RPC API provides a more convenient way to interact with an Ethereum wallet, allowing you to poll balances without having to set up multiple connections. To use RPC, first install the ethers.js
library and import it into your application:
const { ethers } = require('ethers');
Then, create a new Electrum API client instance:
const api = new ethers.Wallet(privateKey);
Here is an example of how to query the balance of an address via RPC:
- Get the wallet’s private key: Make sure you have access to a private key for the account you want to check.
- Create a new Electrum API client instance:
const api = new ethers.Wallet(privateKey);
- List all addresses: Run the following command to see a list of all addresses in your wallet:
eth account list
- Poll an address balance: Choose the address you want to check and run the following code:
async function getBalance(address) {
try {
const balance = await api.getBalance(address);
console.log(Address: ${address}, Balance: ${balance}
);
} catch (error) {
console.error(error);
}
}
Replace address
with the desired Ethereum address.
Use Case Examples
- Transaction Automation: You can use this method to automate transactions by querying an address balance and then using it as input into a script or application.
- Monitoring Wallet Balances: This technique allows you to monitor your wallet balances in real time, ensuring that accounts are being updated correctly.
By following these steps and examples, you can easily query Ethereum address balances using the Electrum CLI and RPC API, making it easy to manage and interact with your digital assets programmatically.