Library Installation
To begin interacting with the Ethereum ecosystem, the ethers library provides a comprehensive suite of tools. You can include it in your project via npm:
npm install ethers
Importing the Library
Depending on your environment, you can import the library using ES6 modules or CommonJS syntax:
// ES6 Module syntax
import { ethers } from "ethers";
// CommonJS syntax
// const { ethers } = require("ethers");
Browser-Based Implementation
For rapid prototyping or simple web pages, you can load the library directly from a CDN. Its recommended to host a local copy for production environments to ensure security and availability.
<!-- ES6 Module Approach -->
<script type="module">
import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.min.js";
</script>
<!-- UMD Approach -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js" type="application/javascript"></script>
Core Architectural Concepts
- Provider: A read-only interface to the Ethereum network. It allows you to query blockchain state, such as account balances and block data.
- Signer: An abstraction of an Ethereum acount, typically backed by a private key. It is required for signing transactions and messages.
- Contract: A programmatic representation of a smart contract on the network, allowing you to interact with its functions as if they were local JavaScript methods.
Connecting to MetaMask
MetaMask is the primary gateway for web-based dApps. It acts as both a Provider (connecting to the network) and a Signer (managing keys).
// Initialize the provider using the window.ethereum object injected by MetaMask
const activeProvider = new ethers.BrowserProvider(window.ethereum);
// Request access to the user's accounts and retrieve the Signer
const userSigner = await activeProvider.getSigner();
Connecting via JSON-RPC
For server-side applications or when connecting to specific nodes (like Geth, Erigon, or services like Infura), use the JSON-RPC provider.
// Connect to a local node or a remote RPC endpoint
const rpcUrl = "http://127.0.0.1:8545";
const remoteProvider = new ethers.JsonRpcProvider(rpcUrl);
// If the node manages accounts, you can retrieve a signer
const nodeSigner = await remoteProvider.getSigner();
Executing Blockchain Queries
Once a provider is established, you can perform various read-only operations to fetch on-chain data.
Retrieve Current Block Height
const blockHeight = await activeProvider.getBlockNumber();
console.log(`Current Block: ${blockHeight}`);
Checking Account Balances
You can query balances using public addresses or ENS names. The resulting value is returned as a BigInt in Wei, which usually requires formatting.
const targetAddress = "vitalik.eth";
const rawAmount = await activeProvider.getBalance(targetAddress);
// Convert Wei to Ether for human readability
const ethValue = ethers.formatEther(rawAmount);
console.log(`Balance of ${targetAddress}: ${ethValue} ETH`);