DeveloperBreeze

In this tutorial, you will learn how to retrieve the balance of an Ethereum wallet using Ethers.js in a Node.js environment. We will cover two methods:

  1. Using Infura as a provider to access the Ethereum blockchain.
  2. Connecting directly to a public Ethereum node.

By the end of this tutorial, you’ll be able to query the balance of any Ethereum wallet and display it in Ether units.


Prerequisites

To follow along, you’ll need the following:

  • Node.js installed on your machine.
  • Basic understanding of JavaScript.
  • An Ethereum wallet (with private key or mnemonic phrase).
  • (Optional) An Infura account to access the Ethereum network.

Step 1: Install Ethers.js

First, you need to install Ethers.js, a library for interacting with the Ethereum blockchain.

Run the following command in your project folder to install it:

npm install ethers

Step 2: Set Up Infura and Create an API Key

If you plan to use Infura as your Ethereum provider, follow these steps:

  1. Go to Infura’s website.
  2. Sign up or log in to your account.
  3. Create a new project and get your Project ID from the settings.
  4. You’ll use this Project ID as your API key for accessing the Ethereum network.

Step 3: Create the Node.js Script

Now, let's create a script to query the balance of an Ethereum wallet. This script will work with both Infura and public nodes.

  1. Create a file called getBalance.js in your project folder.
  2. Open this file and write the following code:

Using Infura to Query Wallet Balance

const ethers = require('ethers');

// Replace this with your Ethereum wallet's private key or mnemonic phrase
const privateKey = 'YOUR_PRIVATE_KEY_OR_MNEMONIC';

// Replace this with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Create a wallet instance using your private key and connect it to the Infura provider
const wallet = new ethers.Wallet(privateKey, infuraProvider);

// Function to get the balance of the wallet
async function getWalletBalance() {
    // Get the wallet's balance in wei
    const balanceInWei = await wallet.getBalance();

    // Convert the balance from wei to Ether for readability
    const balanceInEther = ethers.utils.formatEther(balanceInWei);

    // Log the results
    console.log(`Wallet Address: ${wallet.address}`);
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
}

// Execute the function
getWalletBalance();

Using a Public Node to Query Wallet Balance (Alternative)

If you don't want to use Infura, you can connect to a public Ethereum node:

const ethers = require('ethers');

// Replace this with your Ethereum wallet's private key or mnemonic phrase
const privateKey = 'YOUR_PRIVATE_KEY_OR_MNEMONIC';

// Use a public Ethereum node URL (this is a public node for demonstration purposes)
const publicProvider = new ethers.JsonRpcProvider('https://mainnet.publicnode.com');

// Create a wallet instance using your private key and connect it to the public node provider
const wallet = new ethers.Wallet(privateKey, publicProvider);

// Function to get the balance of the wallet
async function getWalletBalance() {
    // Get the wallet's balance in wei
    const balanceInWei = await wallet.getBalance();

    // Convert the balance from wei to Ether for readability
    const balanceInEther = ethers.utils.formatEther(balanceInWei);

    // Log the results
    console.log(`Wallet Address: ${wallet.address}`);
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
}

// Execute the function
getWalletBalance();

Step 4: Replace Your Private Key and Provider

  • Replace 'YOUR_PRIVATE_KEY_OR_MNEMONIC' with your actual Ethereum wallet's private key or mnemonic phrase.
  • For the Infura method, replace 'YOUR_INFURA_PROJECT_ID' with the Infura Project ID you received when you created your Infura account.

> Important: Keep your private key secure. Never share it publicly or commit it to version control. For better security, consider using environment variables to store sensitive information like private keys.

Step 5: Run the Script

Once your script is set up, run it from the command line:

node getBalance.js

If everything is set up correctly, the script will output the wallet’s Ethereum balance in Ether:

Wallet Address: 0xYourEthereumAddress
Wallet Balance: 2.345 ETH

How It Works

  • Ethers.js: We are using Ethers.js to interact with the Ethereum blockchain. Ethers.js simplifies the process of querying the blockchain and formatting the data for developers.
  • Provider: Whether you use Infura or a public node, the provider allows us to connect to the Ethereum network. Infura is commonly used because of its reliability and scalability, but public nodes can work as well if you're looking for a simple alternative.
  • getBalance(): This function queries the Ethereum network for the balance of the wallet in wei (the smallest unit of ETH). We then use ethers.utils.formatEther() to convert the balance from wei to Ether.

Step 6: Explore More

Once you've successfully retrieved the balance, you can expand your script to add more features. For example:

  • Check the balance of other Ethereum addresses (not just your wallet).
  • Send ETH to other addresses.
  • Interact with smart contracts using Ethers.js.

Conclusion

In this tutorial, you learned how to use Ethers.js to query the balance of an Ethereum wallet in Node.js. You also saw how to use Infura or connect to a public node to access the Ethereum network. This is the foundation for working with Ethereum and interacting with wallets and smart contracts in a programmatic way.

By connecting to the Ethereum network and querying wallet balances, you now have a powerful tool for building decentralized applications (dApps) and automating blockchain-related tasks.

Continue Reading

Handpicked posts just for you — based on your current read.

How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API

const ethers = require('ethers');

// Replace with your Infura or other Ethereum node provider URL
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with the ERC-20 token contract address (e.g., USDT, DAI)
const contractAddress = '0xTokenContractAddress';

// Replace with the wallet address you want to query
const walletAddress = '0xYourEthereumAddress';

// ERC-20 token ABI (just the balanceOf function)
const abi = [
    'function balanceOf(address owner) view returns (uint256)'
];

// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, provider);

async function getTokenBalance() {
    try {
        // Query the balance
        const balance = await contract.balanceOf(walletAddress);

        // Convert balance to a human-readable format (tokens usually have 18 decimals)
        const formattedBalance = ethers.utils.formatUnits(balance, 18);

        console.log(`Token Balance: ${formattedBalance}`);
    } catch (error) {
        console.error('Error fetching token balance:', error);
    }
}

// Call the function to get the token balance
getTokenBalance();
  • Contract Address: Replace '0xTokenContractAddress' with the address of the ERC-20 token (e.g., USDT, DAI, or any other ERC-20 token).
  • Wallet Address: Replace '0xYourEthereumAddress' with the wallet address whose token balance you want to query.
  • ABI: We are using a minimal ABI with just the balanceOf function, which is all that’s required to query the token balance.

Oct 24, 2024 Tutorial

Blockchain Libraries Cheatsheet

  • Description: The official Go implementation of the Ethereum protocol, used to run full Ethereum nodes and interact with the network.
  • Use Cases:
  • Run a full Ethereum node to participate in the network.
  • Develop Ethereum-based applications with Go.
  • Use as a backend for DApps requiring direct blockchain interaction.
  • Key Features:
  • Full support for Ethereum protocol and consensus algorithms.
  • Provides JSON-RPC API for interacting with the Ethereum network.
  • Includes tools for mining, managing accounts, and more.
  • Installation:

Aug 23, 2024 Cheatsheet

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A blockchain-based storage solution for permanent, low-cost data storage.
  • Key Features:
  • Stores data permanently with a one-time fee.
  • Uses a unique consensus mechanism called Proof of Access.
  • Integrates with Ethereum for storing DApp data, NFTs, and more.
  • Scalable and reliable for long-term data storage.
  • Website: Arweave

Aug 23, 2024 Cheatsheet

Tracking Solana Address for New Trades and Amounts

async function trackAddress(address) {
  try {
    const publicKey = new solanaWeb3.PublicKey(address);

    console.log(`Tracking address: ${publicKey.toBase58()}`);

    let lastSignature = '';

    // Fetch initial transactions
    const signatures = await connection.getSignaturesForAddress(publicKey, { limit: 1 });
    if (signatures.length > 0) {
      lastSignature = signatures[0].signature;
    }

    // Monitor for new transactions
    setInterval(async () => {
      const signatures = await connection.getSignaturesForAddress(publicKey, {
        limit: 10,
      });

      for (const signatureInfo of signatures) {
        if (signatureInfo.signature !== lastSignature) {
          const transaction = await connection.getConfirmedTransaction(signatureInfo.signature);

          if (transaction) {
            const { meta, transaction: tx } = transaction;

            const instructions = tx.message.instructions;
            const postBalances = meta.postBalances;
            const preBalances = meta.preBalances;

            // Check if the transaction involves token transfers
            instructions.forEach((instruction, index) => {
              const programId = instruction.programId.toBase58();

              // Solana's SPL Token Program ID
              if (programId === solanaWeb3.TOKEN_PROGRAM_ID.toBase58()) {
                const data = Buffer.from(instruction.data);
                const command = data.readUInt8(0);

                // 3 represents the Token Transfer instruction
                if (command === 3) {
                  const amount = data.readUInt64LE(1);
                  const fromAccount = instruction.keys[0].pubkey.toBase58();
                  const toAccount = instruction.keys[1].pubkey.toBase58();

                  const balanceChange = (preBalances[index] - postBalances[index]) / solanaWeb3.LAMPORTS_PER_SOL;

                  console.log(`New Trade Detected!`);
                  console.log(`- Signature: ${signatureInfo.signature}`);
                  console.log(`- From: ${fromAccount}`);
                  console.log(`- To: ${toAccount}`);
                  console.log(`- Amount: ${balanceChange} SOL`);
                }
              }
            });
          }

          lastSignature = signatureInfo.signature;
        }
      }
    }, 10000); // Check every 10 seconds
  } catch (error) {
    console.error('Error tracking address:', error);
  }
}

// Replace with the Solana address you want to track
const addressToTrack = 'YourSolanaAddressHere';
trackAddress(addressToTrack);
  • Fetch Transactions: We fetch the transaction signatures for the specified address and track them using getSignaturesForAddress.
  • Monitor New Transactions: Using setInterval, we periodically fetch new transactions and check for token transfer instructions.
  • Parse Transactions: We parse each transaction's instructions to identify token transfers and log the details to the console.
  • Token Program ID: We check if the program ID matches Solana's SPL Token Program to identify relevant instructions.

Aug 09, 2024 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!