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

When developing cryptographic applications in JavaScript, one common requirement is the generation of cryptographically secure random bytes. Two popular methods for doing this are crypto.randomBytes from Node.js's built-in crypto module, and ethers.randomBytes from the ethers.js library, which is often used for Ethereum-related operations. Both functions serve the same purpose, but they have some key differences. Let’s explore these two methods in detail.

  • crypto.randomBytes:
  • Library: crypto.randomBytes is part of Node.js’s built-in crypto module. It requires no additional dependencies and is readily available in any Node.js environment.
  • Usage: The function takes a single argument specifying the number of bytes to generate and returns a Buffer object containing the random bytes.
  • Example:

Oct 24, 2024
Read More
Tutorial

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

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

  • Node.js installed on your machine.
  • A basic understanding of JavaScript.
  • An Etherscan API key (explained below).
  • Familiarity with Ethers.js for blockchain interaction.

Oct 24, 2024
Read More
Tutorial

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

In some cases, you might want to use both Etherscan and Infura. For example, you might use Etherscan to query transaction histories or token transfers, and Infura to send transactions or deploy contracts.

  • Etherscan: Use to fetch transaction history and display it in your dApp.
  • Infura: Use to allow users to send transactions or interact with smart contracts.

Oct 24, 2024
Read More
Tutorial

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

  • Contract Address: Replace '0xTokenContractAddress' with the ERC-20 token contract’s address (for example, USDT, DAI, etc.).
  • Wallet Address: Replace '0xYourWalletAddress' with the wallet address whose balance you want to query.
  • ABI (Application Binary Interface): The ABI specifies the functions and data structures used in the smart contract. In this case, we’re using a simple balanceOf function to query the balance.
node contractInteraction.js

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

const axios = require('axios');

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

// Replace this with the transaction hash you want to query
const transactionHash = '0xYourTransactionHash';

// Etherscan API URL to fetch transaction details
const url = `https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=${transactionHash}&apikey=${apiKey}`;

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

    // Log the transaction details
    console.log('Transaction Details:', transactionDetails);
  } catch (error) {
    console.error('Error fetching transaction details:', error);
  }
}

// Call the function to get the transaction details
getTransactionDetails();
  • Replace 'YOUR_ETHERSCAN_API_KEY' with your actual Etherscan API key.
  • Replace '0xYourTransactionHash' with the transaction hash you want to query.
  • This script uses the eth_getTransactionByHash endpoint to fetch transaction details, such as gas price, block number, and sender/receiver addresses.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

For example, in token burn events, project developers often send tokens to this address to signal to the community that those tokens are now out of circulation. This is usually followed by a public announcement, detailing the number of tokens burned and the reasons behind the burn.

Token burns are typically done to increase scarcity, and scarcity can lead to a higher token value if demand remains the same or increases. The basic principle of supply and demand comes into play: when the supply of an asset is reduced, it becomes more valuable (assuming demand holds steady).

Oct 24, 2024
Read More
Tutorial

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

  • Users deposit ETH into a smart contract.
  • The smart contract issues an equivalent amount of WETH.
  • WETH can then be used within DeFi platforms and decentralized applications.
  • To retrieve the original ETH, users can exchange their WETH back through the smart contract.
  • The contract will burn the WETH and return the original ETH to the user.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

This cheatsheet focuses exclusively on essential blockchain libraries that can be integrated into various development projects. These libraries provide functionality for interacting with blockchains, handling data, and implementing security, making them crucial for any blockchain-based application.

  • Description: A JavaScript library that enables developers to interact with the Ethereum blockchain using HTTP, WebSocket, or IPC.
  • Use Cases:
  • Interact with smart contracts.
  • Send transactions and interact with the Ethereum network.
  • Handle accounts, wallets, and keys.
  • Monitor events emitted by smart contracts.
  • Key Features:
  • Supports all major Ethereum network interactions.
  • Comprehensive set of utilities for Ethereum development.
  • Wide adoption with extensive documentation.
  • Installation:

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

with development tools like Hardhat and Truffle.

Aug 23, 2024
Read More
Tutorial
solidity

Writing an ERC-20 Token Contract with OpenZeppelin

Before you begin, make sure you have the following:

  • Node.js and npm: Node.js is required to run the development environment, and npm is used to manage packages.
  • Truffle or Hardhat: These are development frameworks for Ethereum. You can use either one, but for this tutorial, we will use Hardhat.
  • MetaMask: A browser extension wallet to interact with your smart contract.
  • OpenZeppelin Contracts: A library of secure smart contract components.

Aug 22, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

function setMyUint(uint _value) public {
    myUint = _value;
}

function getMyUint() public view returns (uint) {
    return myUint;
}

function add(uint a, uint b) public pure returns (uint) {
    return a + b;
}

function deposit() public payable {
    // Function to receive Ether
}

Modifiers are used to change the behavior of functions.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Examples of Gas Costs:

  • Arithmetic Operations: Adding, subtracting, or multiplying integers consumes minimal gas (e.g., 3-5 gas units).
  • Storage Operations: Writing data to the blockchain (e.g., updating a state variable) is expensive (e.g., 20,000 gas units).
  • Function Calls: Calling a function, especially one that interacts with another contract, can significantly increase gas consumption.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Decentralized applications (DApps) represent the future of software, leveraging blockchain technology to create applications that are transparent, secure, and free from centralized control. By combining smart contracts with a user interface, DApps offer a new way to interact with blockchain technology. In this tutorial, we will guide you through the process of building a DApp on the Ethereum blockchain. You’ll learn how to create a simple DApp, connect it to a smart contract, and deploy it on a test network.

A decentralized application (DApp) is an application that runs on a peer-to-peer network, like a blockchain, rather than relying on a single centralized server. DApps are open-source, operate autonomously, and the data is stored on the blockchain, making them transparent and resistant to censorship.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Example Contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 public storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

Create a React application in the project directory:

npx create-react-app client
cd client
npm install web3

Aug 20, 2024
Read More
Tutorial
python

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

You can set a stop-loss order when opening a position or on an existing position:

   def place_stop_loss(symbol, side, qty, stop_price):
       response = session.place_active_order(
           symbol=symbol,
           side=side,
           order_type='Market',
           qty=qty,
           stop_loss=stop_price,
           time_in_force='GoodTillCancel'
       )
       if response['ret_code'] == 0:
           print(f"Stop-loss set at {stop_price} for {symbol}")
       else:
           print(f"Error setting stop-loss: {response['ret_msg']}")
       return response

   place_stop_loss('BTCUSD', 'Buy', 0.01, 29000)  # Buy 0.01 BTC with stop-loss at $29,000

Aug 14, 2024
Read More
Tutorial
python

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

   api_key = os.getenv('BYBIT_API_KEY')
   api_secret = os.getenv('BYBIT_API_SECRET')

   session = HTTP(
       endpoint='https://api.bybit.com',
       api_key=api_key,
       api_secret=api_secret
   )

This creates a session that you can use to interact with the Bybit API.

Aug 14, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

Conclusion

In this tutorial, we explored how to track a specific Solana address for new trades using the Solana Web3.js library. By monitoring transactions and parsing their instructions, we can log details of each new trade to the console. This approach can be extended to trigger notifications or other actions when new trades occur.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

In this tutorial, we'll learn how to track newly created tokens on the Solana blockchain. Solana uses the SPL Token Program for its token operations, which allows developers to create, transfer, and manage tokens efficiently. We will explore how to interact with Solana's RPC API and the Solana Web3.js library to monitor new token creation events.

Prerequisites

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!