Blockchain Cryptocurrency Dev Tools Ethereum Web3
Ranjithkumar  

Web3.js vs. Ethers.js : Ethereum Dapp

When it comes to building decentralized applications (dApps) on the Ethereum blockchain, two JavaScript libraries dominate the scene: Web3.js and Ethers.js. Both offer powerful functionalities, but they cater to different development preferences. This blog post will delve into the key differences between these libraries to help you choose the right one for your project.

Web3.js: The OG of Ethereum Development

Web3.js, created by the Ethereum Foundation, boasts the title of the original Ethereum JavaScript library. It offers a comprehensive suite of tools for interacting with the Ethereum network. Developers can use Web3.js to:

  • Manage Accounts: Create, import, and interact with Ethereum accounts.
  • Work with Smart Contracts: Deploy, call functions, and read data from smart contracts.
  • Send Transactions: Send Ether (ETH) and interact with dApps on the Ethereum blockchain.

Web3.js enjoys a larger developer community and boasts a wealth of existing resources and documentation. However, some drawbacks come with its maturity:

  • Size: Web3.js is a larger library compared to Ethers.js, which can impact application performance.
  • API Complexity: The Web3.js API can be less intuitive for beginners, with a more functional programming style.
  • Limited Modularization: Web3.js functions are bundled together, making it less flexible for developers who only need specific functionalities.

Ethers.js: The Lightweight Contender

Ethers.js, developed by a community of Ethereum enthusiasts, presents a more modern approach to Ethereum development. It prioritizes:

  • Lightweight Design: Ethers.js boasts a significantly smaller footprint compared to Web3.js, leading to faster application load times.
  • Modular Architecture: Ethers.js offers a modular design, allowing developers to import only the functionalities they need for their project.
  • Object-Oriented Approach: The Ethers.js API utilizes an object-oriented syntax, often considered more intuitive for developers familiar with modern JavaScript practices.

While Ethers.js offers these advantages, it’s important to consider its limitations:

  • Smaller Community: Compared to Web3.js, Ethers.js has a smaller developer community and fewer existing resources.
  • Limited Blockchain Support: Ethers.js primarily focuses on Ethereum development and offers limited support for other blockchains.

Choosing Your Weapon

So, which library should you choose? Here’s a quick breakdown to help you decide:

  • Web3.js is a good choice if:
    • You need a comprehensive set of functionalities.
    • You value a larger developer community and established resources.
    • You’re comfortable with a more functional programming style.
  • Ethers.js is a good choice if:
    • You prioritize a lightweight and performant library.
    • You prefer a modular architecture and object-oriented approach.
    • You’re building a purely Ethereum-focused dApp.

Ultimately, the best choice depends on your specific project requirements and development preferences. Consider experimenting with both libraries to see which one feels more comfortable for you. Remember, a strong understanding of both Web3.js and Ethers.js will equip you to excel in the ever-evolving world of Ethereum development.

Reading Account Balance with Web3.js and Ethers.js

Here’s a code sample showcasing how to read an account balance for both Web3.js and Ethers.js:

Web3.js:

const Web3 = require('web3');

// Replace with your provider URL
const providerUrl = 'wss://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';

const web3 = new Web3(new Web3.providers.WebsocketProvider(providerUrl));

// Replace with the address you want to check balance
const address = '0xYOUR_ETHEREUM_ADDRESS';

async function getBalanceWeb3() {
  try {
    const balance = await web3.eth.getBalance(address);
    console.log(`Web3.js: Account balance (wei) - ${balance}`);
    
    // Convert wei to Ether (optional)
    const ethBalance = web3.utils.fromWei(balance, 'ether');
    console.log(`Web3.js: Account balance (ether) - ${ethBalance}`);
  } catch (error) {
    console.error('Error fetching balance:', error);
  }
}

getBalanceWeb3();

Ethers.js:

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

// Replace with your provider URL
const providerUrl = 'wss://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';

const provider = new ethers.providers.JsonRpcProvider(providerUrl);

// Replace with the address you want to check balance
const address = '0xYOUR_ETHEREUM_ADDRESS';

async function getBalanceEthers() {
  try {
    const balance = await provider.getBalance(address);
    console.log(`Ethers.js: Account balance (wei) - ${balance.toString()}`);
    
    // Convert wei to Ether (optional)
    const ethBalance = ethers.utils.formatEther(balance);
    console.log(`Ethers.js: Account balance (ether) - ${ethBalance}`);
  } catch (error) {
    console.error('Error fetching balance:', error);
  }
}

getBalanceEthers();

Remember:

  • Replace YOUR_INFURA_PROJECT_ID with your actual Infura project ID or any other Ethereum node provider you’re using.
  • Replace 0xYOUR_ETHEREUM_ADDRESS with the address you want to check the balance for.
  • These code snippets only showcase the basic functionality. You might need to modify them based on your specific needs.

Sending Transactions with Web3.js and Ethers.js

Here’s a code example demonstrating how to send a transaction using both Web3.js and Ethers.js:

Web3.js:

const Web3 = require('web3');

// Replace with your provider URL
const providerUrl = 'wss://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';

const web3 = new Web3(new Web3.providers.WebsocketProvider(providerUrl));

// Replace with your private key (**never share this!**)
const privateKey = 'YOUR_PRIVATE_KEY';

// Replace with recipient address
const toAddress = '0xRECIPIENT_ADDRESS';

// Transaction value in wei
const value = web3.utils.toWei('0.01', 'ether');

async function sendTransactionWeb3() {
  try {
    const account = web3.eth.accounts.privateKeyToAccount(privateKey);
    const signedTx = await account.signTransaction({
      from: account.address,
      to: toAddress,
      value,
      gas: 21000, // adjust gas limit as needed
    });

    const txHash = await web3.eth.sendSignedTransaction(signedTx);
    console.log(`Web3.js: Transaction sent, hash: ${txHash}`);
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

sendTransactionWeb3();

Ethers.js:

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

// Replace with your provider URL
const providerUrl = 'wss://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';

const provider = new ethers.providers.JsonRpcProvider(providerUrl);

// Replace with your private key (**never share this!**)
const privateKey = 'YOUR_PRIVATE_KEY';

// Replace with recipient address
const toAddress = '0xRECIPIENT_ADDRESS';

// Transaction value in ether
const value = ethers.utils.parseEther('0.01');

async function sendTransactionEthers() {
  try {
    const wallet = new ethers.Wallet(privateKey, provider);
    const tx = await wallet.sendTransaction({
      to: toAddress,
      value,
      gasLimit: 21000, // adjust gas limit as needed
    });

    console.log(`Ethers.js: Transaction sent, hash: ${tx.hash}`);
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
}

sendTransactionEthers();

Important Notes:

  • Never share your private key! It grants access to your Ethereum account and funds.
  • Adjust the gasLimit value based on current network conditions for a successful transaction.
  • These examples showcase a basic transaction. You might need to modify them depending on your specific needs (e.g., gas price, data for smart contract interactions).
  • Remember to replace the placeholders with your actual values.

Both Web3.js and Ethers.js empower developers to build powerful dApps on the Ethereum blockchain. While Web3.js offers a wider range of functionalities and a larger community, Ethers.js shines with its lightweight design and modular approach. Ultimately, the best choice depends on your project’s specific requirements and development preferences. Consider experimenting with both libraries to discover which one aligns better with your workflow. With a strong understanding of both Web3.js and Ethers.js, you’ll be well-equipped to navigate the ever-evolving world of Ethereum development.

Leave A Comment