0
0
Blockchain / Solidityprogramming~7 mins

Web3.js vs ethers.js in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Web3.js and ethers.js help your app talk to the blockchain. They make it easy to read data and send transactions.

You want to build a website that shows cryptocurrency balances.
You need to send tokens or interact with smart contracts from your app.
You want to listen for blockchain events like new transactions.
You are learning how to connect your app to Ethereum or similar blockchains.
You want to create a wallet or decentralized app (dApp).
Syntax
Blockchain / Solidity
const Web3 = require('web3');
const web3 = new Web3(provider);

const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider(url);

Both libraries connect to blockchain nodes using a provider.

Web3.js uses a Web3 object; ethers.js uses a Provider and Signer.

Examples
Get the latest block number using Web3.js.
Blockchain / Solidity
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

web3.eth.getBlockNumber().then(console.log);
Get the latest block number using ethers.js.
Blockchain / Solidity
const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

provider.getBlockNumber().then(console.log);
Check an account balance with Web3.js and convert from Wei to Ether.
Blockchain / Solidity
const web3 = new Web3(provider);
const balance = await web3.eth.getBalance('0xabc...');
console.log(web3.utils.fromWei(balance, 'ether'));
Check an account balance with ethers.js and format it to Ether.
Blockchain / Solidity
const provider = new ethers.providers.JsonRpcProvider(url);
const balance = await provider.getBalance('0xabc...');
console.log(ethers.utils.formatEther(balance));
Sample Program

This program uses ethers.js to get the latest block number and the ETH balance of a famous address.

Blockchain / Solidity
import { ethers } from 'ethers';

async function main() {
  const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
  const blockNumber = await provider.getBlockNumber();
  console.log(`Latest block number: ${blockNumber}`);

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

main();
OutputSuccess
Important Notes

Web3.js is older and has more features but can be heavier to use.

ethers.js is smaller, simpler, and often easier for beginners.

Both work well; choice depends on your project needs and preferences.

Summary

Web3.js and ethers.js let your app talk to Ethereum blockchain.

Web3.js is bigger and older; ethers.js is lighter and simpler.

Both can get blockchain data and send transactions easily.