JavaScript to retrieve Ethereum blockchain data

JavaScript to retrieve Ethereum blockchain data

This post is for you if you are making your way to Web3 as a JavaScript developer and are searching for a starting point. As such, let's dive into the ethers.js library with this tutorial. You'll learn how to find out how much ETH is in different Ethereum wallets.

What is Ethereum blockchain?

Ethereum is a public, decentralized platform for developers to deploy and execute computer code in the form of "contracts." Both the code and the data generated by running it are stored on the blockchain, a distributed database. Like every Ethereum user, every contract has a wallet address. The book "Mastering Ethereum" contains additional information if you want to learn more about it.

Retrieving CryptoPunks contract's balance

CryptoPunks is a famous collection of 10,000 unique 8-bit characters stored on the Ethereum blockchain as NFTs. The contract acts as a middleman between the seller and the buyer, protecting both sides. You may examine this contract and related transactions by using tools like Etherscan: etherscan.io/contractdiffchecker?a1=0x16f5a..

To get a contract's balance, you should first install the ethers package with npm.

npm install --save ethers

In your preferred IDE, create a file called getbalance.js. Add some code to the top of the file to use ethers.

const ethers = require("ethers");

Next step is to get a provider, which is an abstraction of a connection to the Ethereum platform.

const ethers = require("ethers");

const provider = ethers.getDefaultProvider();

Add a constant CRYPTO_PUNKS with a contract's address. Because data in a blockchain is never changed, you can safely copy and paste it from this article.

const ethers = require("ethers");

const provider = ethers.getDefaultProvider();

CRYPTO_PUNKS = "0x16F5A35647D6F03D5D3da7b35409D65ba03aF3B2"

You're almost there! Create an async function called getBalance to acquire the current balance of a wallet by its address.

async function getBalance(address) {
  const balanceBigNumber = await provider.getBalance(address);
}

Ethereum's default currency is Wei, which is quite small in comparison to ETH. To make the output more readable, use the ethers.utils.formatEther function to convert the value and print the result to the console in "ETH" currency.

async function getBalance(address) {
  const balanceBigNumber = await provider.getBalance(address);
  console.log(ethers.utils.formatEther(balanceBigNumber), "ETH");
}

The final step is to add getBalance(CRYPTO_PUNKS); to the end of the file and check the results. Your getbalance.js file should look something like this by now:

const ethers = require("ethers");

const provider = ethers.getDefaultProvider();

const CRYPTO_PUNKS = "0x16F5A35647D6F03D5D3da7b35409D65ba03aF3B2";

async function getBalance(address) {
  const balanceBigNumber = await provider.getBalance(address);
  console.log(ethers.utils.formatEther(balanceBigNumber), "ETH");
} 

getBalance(CRYPTO_PUNKS);

Run your code to see the current balance of the CryptoPunks NFT contract.

node getbalance.js

You'll most likely get the same result as seen below:

0.0 ETH

If the contract's balance is zero, it means that no one is trading NFTs through it. This is a regular occurrence for collections as rare as CryptoPunks, so don't worry, we'll discover another wallet with some ETH on it.

Retrieve a person's wallet balance

You may also get the balance of any person's wallet because it is public information. To see the current balance of one of Ethereum's oldest wallets, add the following code to the end of getbalance.js.

getBalance("0x87885AaEEdED51C7e3858a782644F5d89759f245");

This wallet was created by Vitalik Buterin, who was the first to describe the Ethereum concept in a document known as the Yellow Paper.

At the time of this writing, the following results of code execution were obtained:

40.039662359041694731 ETH

Exceeding Request-Rate

You will likely see this notice regarding excessive code executions. This is nothing more than a reminder to create an API key you can use with getDefaultProvider function. This step can be ignored if you wait a minute or so to run your code again.

========= NOTICE =========
Request-Rate Exceeded  (this message will not be repeated)

The default API keys for each service are provided as a highly-throttled,
community resource for low-traffic projects and early prototyping.

While your application will continue to function, we highly recommended
signing up for your own API keys to improve performance, increase your
request rate/limit and enable other perks, such as metrics and advanced APIs.

For more details: https://docs.ethers.io/api-keys/
==========================

Summary

You've learned how to use ethers.js to read Ethereum blockchain data to retrieve any wallet's balance. As a more advanced usage, you can also execute contracts and change data with it. Read the official documentation for more details and code examples docs.ethers.io/v5

If you're a ReactJS developer who wants to use Ethereum as a backend and build a frontend for your app, you'll probably like to check out wagmi: React Hooks for Ethereum built on top of ethers.js.

Ethers.js is not the only node package to read data from Ethereum. As an alternative, you can use web3.js a collection of Ethereum libraries, or essentila-eth, which has a significantly smaller size. And finally, you can avoid using any middleware and send HTTP requests directly to Ethereum JSON RPC API.

All of the tools above are in a constant development state, so don't hesitate to send your feedback to the authors. Whatever way you choose, it's easier to build web3 together with the intention of helping each other.