Ethers.js is a lightweight JavaScript library designed to interact with the Ethereum blockchain. It is widely used in building decentralized applications (DApps) and is known for its security, modularity, and simplicity. Compared to Web3.js, Ethers.js offers a more modern, secure, and developer-friendly API, making it a popular choice for Web3 development.
Why Use Ethers.js?
- Lightweight: Smaller package size compared to Web3.js.
- Secure: Designed with strong security practices.
- Fully TypeScript compatible: Ideal for modern front-end and backend development.
- Complete Wallet Management: Supports creating, importing, encrypting, and signing wallets.
- Built-in ENS support: Easily resolve Ethereum Name Service names.
- Provider abstraction: Allows seamless switching between different Ethereum nodes (Infura, Alchemy, JSON-RPC, etc.).
Installation
Install via npm:
bashCopyEditnpm install ethers
For use in HTML directly:
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"></script>
Basic Structure
Ethers.js is divided into several key components:
- Provider – Connects to the Ethereum network.
- Signer – Represents an Ethereum account that can sign messages and transactions.
- Contract – Interacts with smart contracts.
- Utils – Provides utility functions like encoding, hashing, etc.
- Wallet – Manages keys and signs transactions.
Connecting to Ethereum
You can connect to Ethereum using a Provider:
const { ethers } = require('ethers');
// Connect to the Ethereum mainnet using a default provider
const provider = ethers.getDefaultProvider('mainnet');
Or via Infura:
const provider = new ethers.providers.InfuraProvider('mainnet', 'YOUR_INFURA_PROJECT_ID');
Getting Wallet Information
Create a new wallet:
const wallet = ethers.Wallet.createRandom();
console.log(wallet.address);
Or connect an existing wallet:
const privateKey = '0xYOUR_PRIVATE_KEY';
const wallet = new ethers.Wallet(privateKey, provider);
Interacting with the Blockchain
1. Get Balance
const balance = await provider.getBalance('0xAddress');
console.log(ethers.utils.formatEther(balance)); // Converts Wei to Ether
2. Send Ether
const tx = await wallet.sendTransaction({
to: '0xRecipientAddress',
value: ethers.utils.parseEther('0.01')
});
await tx.wait();
console.log('Transaction successful:', tx.hash);
Working with Smart Contracts
To interact with a smart contract, you need the contract’s ABI and address:
const contract = new ethers.Contract(contractAddress, contractABI, wallet);
Call a Read Function
const value = await contract.getValue();
console.log(value);
Call a Write Function
const tx = await contract.setValue(42);
await tx.wait();
Listening to Events
contract.on('ValueChanged', (oldValue, newValue) => {
console.log(`Value changed from ${oldValue} to ${newValue}`);
});
Utilities in Ethers.js
- Convert Ether and Wei:
ethers.utils.parseEther('1.0'); // => BigNumber in Wei
ethers.utils.formatEther('1000000000000000000'); // => '1.0'
- Hashing:
ethers.utils.keccak256(ethers.utils.toUtf8Bytes('hello'));
- Signing messages:
javascriptCopyEditconst message = "Hello Ethereum!";
const signature = await wallet.signMessage(message);
console.log(signature);
Ethers.js vs Web3.js
Feature | Ethers.js | Web3.js |
---|---|---|
Package Size | Small (~100KB) | Larger |
TypeScript Support | Full | Partial |
Modular Design | Yes | Limited |
Wallet Integration | Built-in | Requires external |
Modern Syntax | ES6+ Promises | Callback-based (v1) |