cryptocurrency nodejs blockchain ethereum ethersjs infura private-key wallet-balance public-node query-wallet
Tutorial: Getting Wallet Balance Using Ethers.js in Node.js
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:
- Using Infura as a provider to access the Ethereum blockchain.
- 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:
- Go to [Infura’s website](https://infura.io/).
- Sign up or log in to your account.
- Create a new project and get your Project ID from the settings.
- 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.
- Create a file called
getBalance.js
in your project folder. - 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.
Comments
Please log in to leave a comment.