What is "Ethers.js" or "Web3.js"? Please what is the purpose of these JavaScript libraries, what do they allow a frontend developer to do, and provide an example of a common task you would use them for (e.g., getting the current block number, sending a transaction).
Assistant
Hmm, the user is asking about Ethers.js and Web3.js—two major JavaScript libraries for Ethereum development. They want to know their purpose, what they enable frontend developers to do, and a concrete example.
Okay, first I should clarify that both libraries serve similar core functions but have different design philosophies. Ethers.js is newer and more modular, while Web3.js is the older, more established option. The user is likely a frontend developer exploring Web3 integration, so I should highlight practical use cases rather than diving too deep into technical nuances.
For the example, getting the current block number is a simple read-only operation that demonstrates basic connectivity—it’s safe, gas-free, and universally useful. I’ll structure the response to compare the libraries briefly, then focus on Ethers.js (since it’s more modern) with a clear code snippet. The user might also benefit knowing when to choose one over the other, so I’ll add a quick comparison table.
Avoid overcomplicating—stick to the essentials: purpose, developer capabilities, and one tangible example. No need to discuss wallets or contract deployments unless the user follows up.
Excellent question! Ethers.js and Web3.js are the two dominant JavaScript libraries that serve as the primary bridge between a frontend application (running in a user's browser) and the Ethereum blockchain (or any EVM-compatible chain like Polygon, Avalanche, BSC, etc.).
Core Purpose
They abstract away the immense complexity of direct communication with an Ethereum node. Instead of manually constructing and sending raw JSON-RPC requests (like eth_getBalance, eth_sendTransaction), these libraries provide:
Detect if a user has an injected provider (MetaMask, Coinbase Wallet).
Request the user's account addresses and permissions.
Prompt the user to sign messages or transactions.
Work with Smart Contracts:
Generate JavaScript/TypeScript "contract objects" from an ABI and address.
Call contract methods as if they were normal JavaScript functions (.myMethod(param1, param2)).
Automatically encode/decodes parameters and return values.
Key Difference: Ethers.js vs. Web3.js
Feature
Ethers.js
Web3.js
Philosophy
"The provider is separate from the signer." More modular, smaller bundle.
"The web3 instance does it all." All-in-one, larger bundle.
Size
Smaller (~80kb gzipped)
Larger (~600kb gzipped)
API Style
Cleaner, more modern (e.g., provider.getBlockNumber()).
Legacy style (e.g., web3.eth.getBlockNumber()).
Popularity
Now the industry standard (used by Hardhat, Foundry, Alchemy).
The original, still widely used in legacy projects.
Wallet Support
Built-in Wallet class for private keys.
Relies on web3.eth.accounts (less used).
For new projects, Ethers.js is strongly recommended due to its better design, size, and active maintenance.
Common Task Example: Getting the Current Block Number
Here’s how you'd achieve the exact same task with both libraries.
Using Ethers.js (Modern & Recommended)
javascript
import { ethers } from "ethers";
// 1. Connect to a provider (e.g., Ethereum Mainnet via Infura/Alchemy)
const provider = new ethers.JsonRpcProvider(
"https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY"
);
// 2. Get the latest block number (async operation)
async function getCurrentBlock() {
try {
const blockNumber = await provider.getBlockNumber();
console.log("Current block number:", blockNumber);
return blockNumber;
} catch (error) {
console.error("Error fetching block:", error);
}
}
getCurrentBlock();
Output:Current block number: 18543219 (example)
Using Web3.js (Legacy)
javascript
import Web3 from "web3";
// 1. Create a Web3 instance with a provider
const web3 = new Web3(
"https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY"
);
// 2. Get the latest block number
async function getCurrentBlock() {
try {
const blockNumber = await web3.eth.getBlockNumber();
console.log("Current block number:", blockNumber);
return blockNumber;
} catch (error) {
console.error("Error fetching block:", error);
}
}
getCurrentBlock();
Another Critical Example: Sending a Transaction
This requires user interaction (MetaMask popup) and gas.
With Ethers.js & Injected Wallet (MetaMask)
javascript
// Check if MetaMask (or other injected provider) is available
if (typeof window.ethereum !== 'undefined') {
// 1. Connect to the user's wallet/signer
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner(); // Prompts user to connect account
// 2. Send 0.01 ETH to another address
const tx = await signer.sendTransaction({
to: "0xRecipientAddress...",
value: ethers.parseEther("0.01") // Converts human-readable to wei
});
console.log("Transaction sent! Hash:", tx.hash);
// Wait for mining
await tx.wait();
console.log("Transaction confirmed in block:", tx.blockNumber);
}
Summary
Purpose: To let frontend developers read/write blockchain data and interact with smart contracts.
Allow: Building dApps that connect user wallets, display on-chain data, and execute signed transactions.
Example Tasks:getBlockNumber(), getBalance(), contract.myFunction(), signer.sendTransaction().
Modern Stack Recommendation: Use Ethers.js with a node provider (Alchemy, Infura, QuickNode) and connect to a user's browser-injected wallet (MetaMask) via BrowserProvider. This is the current best practice for secure, efficient frontend Ethereum development.