DEV Community

Cover image for Exploring the Ethereum Network: Fetching Account Balance with ethers.js
yashdewasthale
yashdewasthale

Posted on

Exploring the Ethereum Network: Fetching Account Balance with ethers.js

In the rapidly evolving landscape of blockchain technology, Ethereum has emerged as a leading platform for decentralized applications(dApps) and smart contracts. As a web3 developer, your expertise in building decentralized application on Ethereum is in high demand. So in this article, we will dive deep into the process of fetching the balance of a specific Ethereum account using the powerful ether.js library and the Infura service. By understanding the code snippets presented here, you will gain valuable insight into working with the Ethereum network and mastering the art of web3 development.

Why Ethereum?

Image description

Ethereum stands out as a prominent blockchain platform due to its robustness flexibility, and extensive developer community. It provides a decentralized virtual machine, known as the Ethereum Virtual Machine(EVM), where smart contracts are executed. This unique feature allows developers to build decentralized applications that can interact with each other and leverage the security and transparency offered by the blockchain.


Prerequisites:

Before diving into web3 development with Ehter.js and Infura, it is essential to have a basic understanding of the following concepts:

  1. JavaScript: Familiarity with JavaScript programming language is necessary as Ehter.js is a JavaScript library. Understanding core JavaScript concepts like variables, functions, objects, and asynchronous programming(Promises, async/await) will greatly assist in working with Ether.js.

  2. Ethereum Basics: A fundamental understanding of Ethereum and its key components is essential. This includes knowledge of Ethereum accounts (address, private keys, and public keys), transactions, gas fees, smart contracts, and the Ethereum Virtual Machine(EVM).

    To know more about Ethereum Virtual Machine(EVM) check out this blog here.

  3. Solidity (Optional): Solidity is the programming language used for developing smart contracts on the Ethereum platform. Although not mandatory, having a basic understanding of Solidity can help in interacting with and deploying smart contracts using Ethers.js.

    To learn Solidity basics check this out here.

  4. JSON-RPC: Understanding the basics of the JSON-RPC protocol will be helpful in grasping how Ether.js communicates with the Ethereum network through Infura. JSON-RPC is a remote procedure call protocol encoded in JSON, which allows clients to interact with Ethereum nodes.

    To know more about JSON-RPC check out this blog here.

  5. Infura Project ID:
    To use Infura, you will need to sign up for an account on the Infura platform and obtain a Project ID. This Project ID is essential for connecting to the Ethereum network through Infura's JSON-RPC API.

    To know more about Infura check out this blog here.


The Significance of Ether.js and Infura in Ethereum Development

In the realm of Ethereum development, two key components play a crucial role in facilitating seamless interaction with the Ethereum network: Ether.js and Infura. These tools serve as instrumental elements for developers, empowering them to build robust decentralized applications while streamlining the development process.

Image description

Ether.js stands out as a highly popular JavaScript library that acts as a vital bridge, connecting developers' applications with the Ethereum network. By providing a user-friendly and intuitive interface, Ether.js simplifies the complex task of working with Ethereum accounts, contracts, and various blockchain operations. This powerful library empowers developers by granting access to the full spectrum of Ethereum functionalities, thus enabling them to create sophisticated decentralized applications efficiently.

Image description

To effectively connect with the Ethereum network, developers typically rely on service providers known as node providers. Infura, in particular, emerges as a leading player in this domain, offering developers a convenient gateway to the Ethereum network through its reliable and scalable infrastructure. By leveraging Infura, developers can effortlessly interact with the Ethereum network without the need to set up and maintain their own Ethereum node. This not only saves valuable time and resources but also allows developers to focus on their core application logic and development tasks.

By combining the capabilities of Ether.js and Infura, developers can harness the full potential of Ethereum, capitalizing on its decentralized features while minimizing the complexities associated with infrastructure management. As a result, developers can concentrate on creating innovative and groundbreaking decentralized applications, propelling the advancement of the Ethereum ecosystem.

Fetching Account Balance:

Now lets dive right into the code explanation part which demonstrate how to fetch the balance of an Ethereum account using ether.js and Infura:

Image description


const { ethers } = require("ethers");

const INFURA_ID = 'YOUR_INFURA_PROJECT_ID';
const provider = new ethers.providers.JsonRpcProvider(`https://mainnet.infura.io/v3/${INFURA_ID}`);
const address = '0x5c6f90e52284726a7276d6a20a3df94a4532a8fa';

const main = async () => {
  const balance = await provider.getBalance(address);
  console.log(`ETH Balance of ${address}: ${ethers.utils.formatEther(balance)} ETH`);
}

main();


Enter fullscreen mode Exit fullscreen mode

Understanding the Code:

Let's break down the code snippet step by step to gain a comprehensive understanding of each component and its significance.

  1. Importing the Required Modules:
    The code begins by importing the ethers object from the ethers library. This library acts as a bridge between your application and the Ethereum network, providing a high-level interface to interact with accounts, contracts, and various Ethereum functionalities.

  2. Setting the Infura Project ID:
    To connect to the Ethereum network, we require an endpoint. In this case, we utilize the popular Infura service, which acts as a gateway to the Ethereum network. The INFURA_ID constant stores your unique Infura project ID, ensuring secure and authenticated access to the network.

  3. Creating a Provider:
    The provider object is crucial for establishing a connection to the Ethereum network. Here, we initialize an instance of the JsonRpcProvider class from the ethers.providers module. It allows us to communicate with the Ethereum network by specifying the Infura endpoint URL, along with the INFURA_ID for authentication.

  4. Defining the Ethereum Address:
    The address constant represents the Ethereum account address for which we want to retrieve the balance. It is essential to replace this placeholder with the actual Ethereum address of interest. This flexibility allows you to fetch the balance of any Ethereum account as per your requirements.

  5. The main Function:
    The main function serves as the entry point of our code. It is marked as asynchronous, enabling the use of the await keyword for handling asynchronous operations. Within this function, we make an asynchronous call to provider.getBalance(address), which retrieves the balance of the specified Ethereum address from the network.

  6. Logging the Balance:
    The retrieved balance, expressed in wei (the smallest unit of ether), is stored in the balance variable. To make it more readable, we utilize the ethers.utils.formatEther(balance) function to convert it from wei to ether. The formatted balance is then displayed using console.log for convenient visualization.

  7. Invoking the main Function:
    The final line of code invokes the main function, triggering the execution of our code and initiating the process of fetching the Ethereum account balance.

Conclusion:

In this blog post, we have explored a code snippet that demonstrates how to fetch the balance of a specific Ethereum account using the ethers.js library and the Infura service. By harnessing the power of web3 development, you gain the ability to interact with the Ethereum blockchain, enabling the creation of decentralized applications and the execution of smart contracts. Understanding the presented code provides you with a solid foundation for further exploration and development in the web3 ecosystem.

Remember to customize the code to fit your specific needs, such as utilizing your own Ethereum address or extending the functionality to perform additional operations on the blockchain. As a web3 developer, continuous learning and adaptation are key to staying ahead in this rapidly evolving landscape. Embrace the opportunities that Ethereum and web3 development offer, and embark on your journey to building innovative and decentralized solutions. Happy coding!

Top comments (0)