第1节:ethers v6 概览与安装
小白入门:https://github.com/dukedaily/solidity-expert ,欢迎star转发,文末加V入群。
职场进阶: https://dukeweb3.com
ethers 是前端和 Node.js 端与 EVM 链交互的主流库。v6(2023 发布)相对 v5 做了较大重构:API 扁平化、原生 BigInt、Provider 改名。本章按 v6 展开,最后一节给出 v5→v6 迁移速查。
安装
npm install ethers
验证版本:
node -e "console.log(require('ethers').version)"
三个核心对象
ethers 的 API 围绕三类对象组织:
- Provider:只读节点,能查链上状态(余额、交易、合约数据),不能签名发交易。
- Signer:持有私钥的签名者,能发交易。
Wallet是 Signer 的实现。 - Contract:合约实例,持有地址 + ABI + Provider/Signer,暴露 ABI 定义的所有方法。
Provider 速览
三种常用 Provider:
import { ethers } from "ethers";
// 1) 通过公共节点(RPC URL)
const rpc = new ethers.JsonRpcProvider("https://eth.llamarpc.com");
// 2) 浏览器钱包(MetaMask 等)
const browser = new ethers.BrowserProvider(window.ethereum);
// 3) 默认聚合 Provider(开发快速用)
const fallback = ethers.getDefaultProvider("mainnet");
Hello ethers
读 vitalik.eth 的 ETH 余额:
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider("https://eth.llamarpc.com");
const addr = await provider.resolveName("vitalik.eth");
const wei = await provider.getBalance(addr);
console.log(`${ethers.formatEther(wei)} ETH`);
返回值是 bigint(v6 原生),不再是 v5 的 BigNumber。
与 v5 的高层差异
细节见第 6 节,总览:
- 命名空间扁平:
ethers.providers.JsonRpcProvider→ethers.JsonRpcProvider。 - utils 扁平:
ethers.utils.formatEther→ethers.formatEther。 - BigNumber 淘汰:v6 用原生
bigint(1n、10n ** 18n)。 Web3Provider改名为BrowserProvider。
小结
ethers v6 把 API 压平、拥抱 ES2020 原生 BigInt,适合新项目。下一节深入 Provider 与 Signer。