Interacting with the Blockchain: Web3.js and Ethers.js

In the previous lessons, we explored how smart contracts are written and deployed. However, a smart contract sitting on the blockchain is useless if users cannot interact with it. To bridge the gap between a standard web browser and the Ethereum blockchain, developers use specialized JavaScript libraries. The two most prominent libraries in the ecosystem are Web3.js and Ethers.js.

These libraries allow your frontend application to talk to an Ethereum node via JSON-RPC, enabling functionalities like sending Ether, calling smart contract functions, and reading block data.

The Communication Flow: How DApps Talk to the Chain

Before diving into the code, it is essential to understand the architecture of a Decentralized Application (DApp). Unlike traditional apps where the frontend talks to a centralized database, a DApp talks to a blockchain node.

[ User Browser ] <---> [ Web3.js / Ethers.js ] <---> [ Ethereum Node (Infura/Alchemy/Local) ] <---> [ Blockchain ]
    

The library acts as a translator. It takes JavaScript commands and converts them into JSON-RPC requests that the Ethereum node can understand. It also handles the complex task of signing transactions with private keys.

Introduction to Web3.js

Web3.js is the "OG" library of the Ethereum ecosystem. Maintained by the Ethereum Foundation for a long time, it is highly comprehensive and follows a structure that mirrors the Ethereum JSON-RPC spec closely.

Key Features of Web3.js:

  • Large Ecosystem: Being the oldest library, it has the most documentation and community support.
  • Modular Packages: You can import only the parts you need (e.g., web3-eth, web3-utils).
  • PromiEvent: A unique feature that combines Promises and EventEmitters, allowing you to track a transaction through multiple stages (submission, receipt, confirmation).

Introduction to Ethers.js

Ethers.js is a modern, lightweight alternative that has gained massive popularity due to its simplicity, small bundle size, and excellent TypeScript support. It focuses on being a "complete and compact" library for interacting with the Ethereum Blockchain.

Key Features of Ethers.js:

  • Small Size: It is significantly smaller than Web3.js, which improves web performance.
  • Separation of Concerns: It clearly separates the "Provider" (reading data) from the "Signer" (writing data/signing transactions).
  • ENS Support: Native support for Ethereum Name Service (e.g., user.eth instead of 0x123...).
  • Security: It has a very robust way of handling private keys and mnemonic phrases.

Practical Code Example: Connecting to a Wallet

To interact with a blockchain, you first need a provider. If the user has MetaMask installed, it injects a provider into the browser window.

Example using Ethers.js:

// Check if MetaMask is installed
if (window.ethereum) {
    // Initialize the provider
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    
    // Request account access
    await provider.send("eth_requestAccounts", []);
    
    // Get the signer (for sending transactions)
    const signer = provider.getSigner();
    const address = await signer.getAddress();
    
    console.log("Connected account:", address);
}
    

Example using Web3.js:

// Check if MetaMask is installed
if (window.ethereum) {
    // Initialize Web3
    const web3 = new Web3(window.ethereum);
    
    // Request account access
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    
    console.log("Connected account:", accounts[0]);
}
    

Web3.js vs Ethers.js: Which one to choose?

Choosing between the two often comes down to project requirements and personal preference.

  • Choose Web3.js if: You are working on a legacy project, need broad community support, or prefer a library that strictly follows the JSON-RPC specification.
  • Choose Ethers.js if: You want a modern, lightweight, and type-safe library. It is generally preferred for new projects due to its cleaner API and better handling of providers and signers.

Common Mistakes to Avoid

  • Hardcoding Private Keys: Never include your private key in frontend code. Always use a wallet provider like MetaMask or a secure backend environment.
  • Ignoring BigNumber: JavaScript cannot handle 256-bit integers (standard in Solidity). Always use the BigNumber utility provided by these libraries to avoid precision errors.
  • Not Handling Network Changes: Users might switch from Ethereum Mainnet to Polygon or Goerli. Your code should listen for the "chainChanged" event and update the UI accordingly.
  • Missing Error Handling: Blockchain transactions can fail due to "Out of Gas" or user rejection. Always wrap your calls in try-catch blocks.

Real-World Use Cases

These libraries are the backbone of the decentralized web. Here is how they are used today:

  • DeFi Dashboards: Fetching token balances and calculating yields from protocols like Uniswap or Aave.
  • NFT Marketplaces: Allowing users to mint, list, and buy digital art by interacting with ERC-721 contracts.
  • Governance Portals: Enabling DAO members to sign and submit votes on proposals without paying gas (using meta-transactions).

Interview Notes: Key Concepts for Developers

  • What is a Provider? A read-only connection to the blockchain. It allows you to query blocks, transactions, and state.
  • What is a Signer? An abstraction of an Ethereum Account that can be used to sign messages and transactions to change the state of the blockchain.
  • What is an ABI? The Application Binary Interface. It is a JSON file that tells the library which functions a smart contract has and what parameters they take.
  • How do you handle events? Both libraries allow you to "subscribe" to smart contract events to update your UI in real-time when a transaction is confirmed.

Summary

Web3.js and Ethers.js are essential tools for any blockchain developer. While Web3.js offers a mature and comprehensive ecosystem, Ethers.js provides a modern, developer-friendly experience. Understanding how to use these libraries to connect wallets, call contract functions, and handle blockchain data is the final step in becoming a full-stack DApp developer. In the next topic, we will explore how to integrate these libraries into a React frontend for a complete user experience.

Related Topics: smart-contract-deployment-scripts, ethereum-json-rpc-explained, building-your-first-dapp-frontend.