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

Discover more amazing content handpicked just for you

Tutorial

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

  • Use crypto.randomBytes when:
  • You are building Node.js applications without blockchain-specific functionality.
  • You want to avoid adding external dependencies.
  • Use ethers.randomBytes when:
  • You are developing Ethereum-related applications and already have ethers.js in your project.
  • You want the flexibility of generating random bytes with minimal configuration, defaulting to 32 bytes for Ethereum addresses or private keys.

Oct 24, 2024
Read More
Tutorial

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

Now let’s query the ERC-20 token transfer history for a specific wallet address using the Etherscan API.

const axios = require('axios');

// Replace with your Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

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

// Replace with the ERC-20 token contract address
const contractAddress = '0xTokenContractAddress';

// Etherscan API URL to fetch ERC-20 token transactions
const url = `https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=${contractAddress}&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=${apiKey}`;

async function getTokenTransactions() {
    try {
        // Make the API request to Etherscan
        const response = await axios.get(url);
        const transactions = response.data.result;

        // Log the token transactions
        transactions.forEach(tx => {
            console.log(`
                From: ${tx.from}
                To: ${tx.to}
                Value: ${ethers.utils.formatUnits(tx.value, 18)} Tokens
                Transaction Hash: ${tx.hash}
            `);
        });
    } catch (error) {
        console.error('Error fetching token transactions:', error);
    }
}

// Call the function to get the token transactions
getTokenTransactions();

Oct 24, 2024
Read More
Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

  • Decentralized Applications (dApps): If you’re building an application that needs to interact with Ethereum in real-time, such as sending transactions or calling smart contract functions.
  • Wallets: If you are developing a wallet application that needs to sign and broadcast transactions.
  • Smart Contract Deployment: Use Infura to deploy or interact with smart contracts on the Ethereum blockchain.
  • Rate Limits: Etherscan’s free tier limits the number of API requests per second (usually around 5 per second). This is fine for querying data but can be limiting for large-scale applications that need to process a lot of data quickly.
  • Pricing: Etherscan offers paid tiers that increase the API request limits.

Oct 24, 2024
Read More
Tutorial

Sending Transactions and Interacting with Smart Contracts Using Infura and Ethers.js

In this tutorial, you learned how to use Ethers.js with Infura to send Ether, interact with smart contracts, and deploy contracts on the Ethereum blockchain. This setup allows you to interact with the blockchain in real-time without the need to run your own Ethereum node, making it easier to develop decentralized applications (dApps) and other blockchain-based services.

Using Infura for node access and Ethers.js for transaction management and contract interaction gives you a powerful combination to build on Ethereum.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

Before you begin, you’ll need the following:

  • Node.js installed on your machine.
  • A basic understanding of JavaScript.
  • An Etherscan API key (explained below).

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

  • Decentralized Exchanges (DEXs): Many decentralized exchanges (like Uniswap) require ERC-20 tokens for trading. WETH allows ETH holders to trade ETH just like any other ERC-20 token.
  • DeFi Lending Platforms: Platforms such as Aave or Compound often require collateral in the form of ERC-20 tokens, making WETH essential for ETH holders who want to participate.
  • Token Swaps: WETH allows for seamless token swaps between ETH and other ERC-20 tokens on platforms that support such swaps.

ETH and WETH serve different but complementary roles in the Ethereum ecosystem. While ETH is the native currency used to power the network, WETH enables ETH to interact with the growing number of decentralized applications and DeFi protocols that rely on the ERC-20 standard. By understanding how to wrap and unwrap ETH, you can effectively engage in the broader Ethereum DeFi ecosystem without leaving the native ETH environment.

Oct 24, 2024
Read More
Cheatsheet
solidity

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:
  go get -v github.com/ethereum/go-ethereum

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A block explorer and analytics platform for Ethereum.
  • Key Features:
  • Provides real-time data on Ethereum blocks, transactions, and gas prices.
  • Includes charts and statistics on Ethereum network performance.
  • Offers detailed contract and token information.
  • Integrates with Etherscan and other blockchain services.
  • Website: Etherchain
  • Description: The official documentation for the Ethereum blockchain, covering topics from basics to advanced development.
  • Key Features:
  • Comprehensive guides on setting up development environments.
  • Tutorials on smart contract development and DApp creation.
  • Detailed explanations of Ethereum concepts and protocols.
  • Regularly updated with the latest information.
  • Website: Ethereum Documentation

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

     npm install @openzeppelin/contracts

Now that your environment is set up, you can create the ERC-20 token contract.

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Ownable Pattern: Restricts access to certain functions to the contract owner.

  • Pausable Pattern: Allows the contract to be paused or unpaused.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

5. Avoid Unnecessary Computations

  • Reduce redundant calculations or operations within your smart contract. Precompute values where possible and reuse them.
  • Example: Store the result of a complex computation in a variable rather than recalculating it multiple times.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

To build a DApp, you first need a smart contract that will serve as the backend logic. Let’s create a simple smart contract that allows users to store and retrieve a message on the blockchain.

Example Contract:

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

After writing the smart contract, the next step is to deploy it on a test network to see it in action.

Steps to Deploy:

Aug 22, 2024
Read More
Tutorial
javascript solidity

Creating a Decentralized Application (dApp) with Solidity, Ethereum, and IPFS: From Smart Contracts to Front-End

npm install -g truffle
npm install -g ganache-cli

Initialize a new Truffle project:

Aug 20, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

   def get_balance():
       response = session.get_wallet_balance(coin='BTC')
       if response['ret_code'] == 0:
           balance = response['result']['BTC']['available_balance']
           print(f"Available BTC balance: {balance}")
       else:
           print(f"Error fetching balance: {response['ret_msg']}")
       return balance

   get_balance()

This function retrieves and prints the available balance in your BTC wallet.

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

   export BYBIT_API_KEY='your_api_key'
   export BYBIT_API_SECRET='your_api_secret'

In your Python script, initialize the Pybit HTTP client:

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

In this tutorial, we'll learn how to track a specific Solana address for new trades and notify via console.log with the transaction details, including the amount bought or sold. We will use the Solana Web3.js library to connect to the Solana blockchain, listen for new transactions, and fetch their details.

Prerequisites

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

Step 4: Monitor for New Tokens

You can run this script periodically to monitor for new token creation events. Consider setting up a cron job or a scheduled task to execute the script at regular intervals.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

const axios = require('axios');

// Replace with your Etherscan API key
const ETHERSCAN_API_KEY = 'YOUR_ETHERSCAN_API_KEY';

async function getNewTokens() {
  try {
    const url = `https://api.etherscan.io/api?module=account&action=tokentx&address=0x0&startblock=0&endblock=99999999&sort=asc&apikey=${ETHERSCAN_API_KEY}`;
    const response = await axios.get(url);

    if (response.data.status === '1') {
      const transactions = response.data.result;
      const newTokens = transactions.filter(tx => tx.tokenSymbol && tx.tokenName && tx.from === '0x0000000000000000000000000000000000000000');

      console.log('Newly Created Tokens:');
      newTokens.forEach(token => {
        console.log(`- Token Name: ${token.tokenName}`);
        console.log(`  Token Symbol: ${token.tokenSymbol}`);
        console.log(`  Token Contract Address: ${token.contractAddress}`);
      });
    } else {
      console.error('Error fetching token transactions:', response.data.message);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

getNewTokens();
  • Etherscan API: We use the tokentx action from Etherscan's API to fetch token transfer events. The API returns a list of token transactions, including newly created tokens.
  • Filter for New Tokens: We filter transactions where the from address is 0x0000000000000000000000000000000000000000, indicating a token creation event. This address is used as a placeholder for the "zero address" in token contracts.
  • Display Information: We log the name, symbol, and contract address of each newly created token.

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!