ethers.js¶
Introduction¶
ethers.js is a complete, compact JavaScript library for interacting with the Ethereum blockchain. Created by Richard Moore (ricmoo) in 2016, ethers.js has become one of the preferred libraries for Ethereum developers thanks to its clean API, thorough documentation, strong TypeScript support, and security-focused design philosophy.
ethers.js provides comprehensive functionality including connecting to Ethereum nodes, managing wallets, interacting with smart contracts, and signing transactions. Compared to the earlier Web3.js, ethers.js adopts a more modern design with a smaller footprint (~88KB minified), cleaner API, and better type safety. It is widely used in DApp frontends, Node.js scripts, wallet applications, and more, powering tens of thousands of projects across the Ethereum ecosystem.
Core Features¶
Provider¶
Provider is the core component for ethers.js to communicate with the blockchain: - JsonRpcProvider: Connects to an Ethereum JSON-RPC node - WebSocketProvider: Connects via WebSocket, supporting real-time event subscriptions - AlchemyProvider / InfuraProvider: Quickly connects to Alchemy, Infura, and other node services - EtherscanProvider: Queries on-chain data via the Etherscan API - FallbackProvider: Configures multiple Providers with automatic failover - BrowserProvider: Obtains a Provider from browser wallets (MetaMask, etc.)
Providers offer read-only access to on-chain data, such as querying balances, fetching blocks, and estimating Gas.
Signer¶
Signer represents an account that can sign transactions and messages: - Wallet: A wallet created from a private key or mnemonic, capable of signing transactions - JsonRpcSigner: A signer obtained from a Provider, typically from a browser wallet - VoidSigner: A read-only signer for simulating transactions without actually signing - HDNodeWallet: A hierarchical deterministic wallet supporting mnemonics and derivation paths
Signer is a superset of Provider - it can both read on-chain data and send transactions.
Contract¶
The Contract class provides a high-level interface for interacting with smart contracts: - Contract Instantiation: Creates a contract object using a contract address, ABI, and Provider/Signer - Read-Only Function Calls: Automatically identifies view and pure functions without sending transactions - Sending Transactions: Calls state-changing functions, automatically building and sending transactions - Event Listening: Listens for contract events and responds to on-chain changes in real time - Event Filtering: Queries historical events with support for complex filter conditions - Function Overload Support: Correctly handles Solidity function overloading - Gas Estimation: Estimates Gas consumption before sending transactions
Utilities¶
ethers.js provides a rich utility function library: - Unit Conversion: parseEther, formatEther, etc., for converting between wei and ether - Address Operations: Address validation, checksum formatting, ENS resolution - Hash Functions: keccak256, sha256, ripemd160, etc. - ABI Encoding/Decoding: AbiCoder for encoding and decoding function calls - Signing and Verification: Message signing, signature verification, ERC-712 structured signing - Big Number: BigNumber class for handling large integer arithmetic, avoiding precision issues - Byte Operations: Hexadecimal strings, Uint8Array, byte concatenation, etc.
TypeScript Support¶
ethers.js is written in TypeScript and provides complete type definitions: - Type Safety: Catches type errors at compile time, reducing runtime bugs - IntelliSense: IDE provides accurate code completion and parameter hints - Interface Definitions: Automatically generates typed interfaces from contract ABIs - Generics Support: Complex generic types ensure accurate type inference
Even in JavaScript projects, type hints are available through .d.ts files.
Security Design¶
ethers.js places a high priority on security in its design: - Immutable Objects: Most objects are immutable, preventing accidental modifications - Secure Defaults: Gas estimation, nonce management, etc., use secure strategies by default - Parameter Validation: Strict validation of all input parameters, preventing injection attacks - Auditing and Testing: Code has undergone rigorous auditing with high test coverage - Zero Dependencies: The core library has zero dependencies, reducing supply chain attack risks
Key Characteristics¶
Excellent API Design: ethers.js has a clean, intuitive API that aligns with JavaScript developer conventions. Async operations use Promises with async/await support, resulting in highly readable code.
Thorough Documentation: Official documentation is comprehensive, including API references, migration guides, and tutorial examples. Every function has clear descriptions and code samples.
Small Size: The core library is ~88KB minified, much smaller than Web3.js. Modular design allows on-demand imports, further reducing bundle size.
TypeScript Native: Written in TypeScript with accurate and complete type definitions, providing the best development experience.
Actively Maintained: Author Richard Moore continuously maintains the library, responding quickly to issues and updates. The community is active with numerous third-party plugins and tools.
Good Compatibility: Supports modern browsers, Node.js, React Native, and other environments. Compatible with Ethereum mainnet, testnets, and various Layer 2s and sidechains.
Plugin Ecosystem: Supports plugin extensions for features like hardware wallet integration, ENS enhancements, custom Providers, etc.
Version History¶
ethers v4: Early version that established the design philosophy and API style of ethers.js.
ethers v5 (2020): Major refactor, completely rewritten in TypeScript. Improved API design, enhanced type safety, and became the most popular version. Supports EIP-1559, ENS, ERC-20/ERC-721, and other standards.
ethers v6 (2023): Latest version with further modernization. Adopts ES2020 features, uses native BigInt instead of custom BigNumber for improved performance. Enhanced Provider and Wallet APIs with improved WebSocket support. Better tree-shaking support for reduced bundle size.
Currently v5 and v6 are maintained in parallel, with v5 still widely used and v6 gradually becoming mainstream.
Basic Usage Examples¶
Connecting to the Ethereum Network:
import { ethers } from 'ethers';
// Connect to Ethereum mainnet (via default Provider)
const provider = ethers.getDefaultProvider('mainnet');
// Or connect to a custom RPC
const provider = new ethers.JsonRpcProvider('https://eth.llamarpc.com');
Query Account Balance:
const balance = await provider.getBalance('vitalik.eth');
console.log(ethers.formatEther(balance)); // Convert wei to ETH
Create a Wallet and Send a Transaction:
const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);
const tx = await wallet.sendTransaction({
to: '0x...',
value: ethers.parseEther('0.1')
});
await tx.wait(); // Wait for transaction confirmation
Interact with a Smart Contract:
const abi = ['function balanceOf(address) view returns (uint)'];
const contract = new ethers.Contract('0x...', abi, provider);
const balance = await contract.balanceOf('0x...');
Use Cases¶
DApp Frontend Development: Virtually all Ethereum DApp frontends use ethers.js or Web3.js to interact with the chain. ethers.js is lightweight, easy to use, and the preferred library.
Wallet Applications: Wallets like MetaMask, Frame, and Rainbow use ethers.js for core functions including transaction signing, balance queries, and contract interactions.
Backend Services: Node.js backends use ethers.js for listening to on-chain events, automating transactions, data indexing, and more.
Automation Scripts: Developers write scripts for batch operations like token airdrops, bulk transfers, and data aggregation.
Testing and Deployment: Development frameworks such as Hardhat and Foundry integrate ethers.js for contract testing and deployment scripts.
On-Chain Data Analysis: Researchers use ethers.js to extract on-chain data for analysis and visualization.
Bots and Automation: MEV bots, liquidation bots, and arbitrage bots use ethers.js to quickly respond to on-chain events.
Education and Prototyping: The clean API makes ethers.js an ideal tool for learning Ethereum development.
Comparison with Other Libraries¶
ethers.js vs Web3.js: - ethers.js is more lightweight (88KB vs 300KB+) - ethers.js has better TypeScript support - ethers.js API is cleaner and more modern - Web3.js has a longer history and more mature ecosystem - Both are functionally equivalent; choose based on preference
ethers.js vs viem: - viem is an emerging TypeScript-first library with better performance - viem uses native BigInt, more modern - viem has better modularity and tree-shaking support - ethers.js has a more mature ecosystem and more thorough documentation - viem is rising quickly and may become the future mainstream choice
Related Concepts¶
- Web3.js - Another mainstream Ethereum JavaScript library
- viem - An emerging TypeScript-first Ethereum library
- Hardhat - A smart contract development framework that integrates ethers.js
- MetaMask - A browser wallet compatible with ethers.js
- WalletConnect - A wallet connection protocol supporting ethers.js
- RainbowKit - Wallet connection components built on ethers.js/wagmi
- ERC-712 - Structured data signing standard supported by ethers.js
Related Links¶
- Official Website: https://ethers.org
- GitHub: https://github.com/ethers-io/ethers.js
- v6 Documentation: https://docs.ethers.org/v6/
- v5 Documentation: https://docs.ethers.org/v5/
- Playground: https://playground.ethers.org
- Discord: https://discord.gg/6jyGVDK6Jx
- NPM: https://www.npmjs.com/package/ethers
- Twitter: https://twitter.com/ethersproject