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

  • 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.

Once you’ve added the code, run the script:

Oct 24, 2024
Read More
Tutorial

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

  • Rate Limits: Infura’s free tier provides a generous number of requests (e.g., 100,000 requests per day) and supports more requests as you scale. This makes it more suitable for real-time dApps.
  • Pricing: Infura’s paid plans offer higher limits and additional features like access to Layer 2 networks.
  • Use Etherscan if:
  • You only need to read blockchain data.
  • You want to build tools for analytics or explorers.
  • You don’t need to send transactions or interact directly with smart contracts.
  • Use Infura if:
  • You need to interact with the Ethereum blockchain in real-time.
  • You’re building dApps, wallets, or tools that require transactions.
  • You need to write data to the blockchain, such as sending Ether or deploying contracts.

Oct 24, 2024
Read More
Tutorial

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

To follow along with this tutorial, you’ll need:

  • Node.js installed on your machine.
  • A basic understanding of JavaScript and blockchain concepts.
  • An Ethereum wallet with some test ETH (using testnets like Goerli or Ropsten is recommended for testing).
  • An Infura Project ID to access the Ethereum network.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=0xYourTransactionHash&apikey=YOUR_ETHERSCAN_API_KEY

You can also query ERC-20 token balances for a given address using the Etherscan API.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

The "0x000000000000000000000000000000000000dead" address plays a vital role in the cryptocurrency ecosystem, acting as a black hole for tokens that need to be permanently removed from circulation. Token burns, when done responsibly, can reduce supply, increase scarcity, and potentially drive up the value of a cryptocurrency. However, it’s important to understand the potential risks and long-term impacts of token burns before making investment decisions based on burn events.

Oct 24, 2024
Read More
Tutorial

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

WETH is simply ETH wrapped in a smart contract to make it compatible with the ERC-20 token standard. Wrapping ETH into WETH enables users to interact with decentralized applications (dApps), decentralized exchanges (DEXs), and DeFi platforms that require ERC-20 tokens.

  • ETH: The native asset of Ethereum, does not conform to any token standard.
  • WETH: An ERC-20 token, designed to work seamlessly with Ethereum-based DeFi applications and smart contracts.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  <dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.8.7</version>
  </dependency>

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A development framework for Ethereum that provides a suite of tools for writing, testing, and deploying smart contracts.
  • Key Features:
  • Built-in smart contract compilation, linking, deployment, and binary management.
  • Scriptable deployment & migrations framework.
  • Network management for deploying to different networks.
  • Interactive console for direct contract interaction.
  • Testing framework using Mocha and Chai.
  • Website: Truffle
  • Description: A flexible and extensible development environment for Ethereum, designed to manage and automate tasks like contract compilation and deployment.
  • Key Features:
  • Local Ethereum network for testing (Hardhat Network).
  • Easy integration with popular tools like Ethers.js and Waffle.
  • Plugins for Solidity coverage, gas reporting, and more.
  • Error messages and stack traces specific to Solidity.
  • Highly customizable and scriptable.
  • Website: Hardhat

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

     async function main() {
         const [deployer] = await ethers.getSigners();

         console.log("Deploying contracts with the account:", deployer.address);

         const MyToken = await ethers.getContractFactory("MyToken");
         const myToken = await MyToken.deploy("MyToken", "MTK", ethers.utils.parseUnits("1000000", 18));

         console.log("MyToken deployed to:", myToken.address);
     }

     main()
         .then(() => process.exit(0))
         .catch((error) => {
             console.error(error);
             process.exit(1);
         });
  • getSigners: Retrieves the list of accounts provided by the Ethereum node, with the first account used as the deployer.
  • getContractFactory: Gets the contract to deploy.
  • deploy: Deploys the contract with the specified parameters (name, symbol, and initial supply).
  • parseUnits: Converts the initial supply to the correct units, considering the token’s decimals.

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Value Types:

- bool: true or false

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Choose data structures that minimize gas consumption. For example, mappings are generally more gas-efficient than arrays for storing large datasets.
  • Example: Use a mapping instead of an array for storing user balances.

5. Avoid Unnecessary Computations

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

  • Run truffle compile to compile the smart contract. This will generate the necessary ABI (Application Binary Interface) and bytecode.
  • Start Ganache and configure Truffle to use it by editing the truffle-config.js file.
  • Run truffle migrate to deploy the smart contract to the local blockchain provided by Ganache.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Once deployed, the contract will appear in the "Deployed Contracts" section.
  • You can now call the set and get functions to interact with your contract.

After deployment, you can test your contract by interacting with its functions:

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

You can host your front-end on a decentralized platform like Fleek or Netlify for broader access.

In this tutorial, we built a decentralized application (dApp) using Solidity, Ethereum, and IPFS. We covered the entire process from writing and deploying a smart contract, interacting with the contract through a React-based front-end, to integrating decentralized file storage using IPFS. This dApp architecture provides a foundation for developing more complex decentralized applications, offering users increased security, transparency, and control over their data.

Aug 20, 2024
Read More
Tutorial
python

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

Monitoring open positions is essential for active traders to manage their portfolio and respond to market changes.

The following function fetches open positions for a specific trading pair:

Aug 14, 2024
Read More
Tutorial
python

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

This code defines a function get_latest_price that fetches the last traded price of the specified symbol.

You can also retrieve the order book to see current buy and sell orders:

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

Introduction

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.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

Conclusion

In this tutorial, we explored how to track newly created tokens on the Solana blockchain using the Solana Web3.js library. By monitoring transactions involving the SPL Token Program, we can identify new token minting events. This approach provides a powerful way to stay updated with new token launches on Solana.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

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

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!