ethers.js 学习笔记
单位换算、编码、Provider、合约调用与事件示例。
原笔记混有 ethers 不同版本的 API。示例保留用于学习回顾,使用前请对照对应版本文档。
本篇目录 · 11 节收起目录
获取 URL
以下是几种获取节点 URL 的方法:
-
Infura: Infura 是一个流行的以太坊节点提供者,提供免费和付费计划。您可以在 Infura 上注册账户并获取要连接到的以太坊网络的 URL。URL 通常如下所示:
https://mainnet.infura.io/v3/YOUR_PROJECT_ID -
Alchemy: 您也可以获取要连接到的节点的 URL,URL 通常如下所示:
https://eth-mainnet.alchemyapi.io/v2/YOUR_API_KEY -
本地节点 (Ganache, Geth, etc.): 您还可以使用 Ganache 或 Geth 等工具运行本地节点。默认的 URL 如下所示:
http://localhost:8545 -
公共以太坊网络:对于像主网、Ropsten、Rinkeby 等公共以太坊网络,您可以找到提供免费访问或注册付费服务的公共节点提供者。
导入ethers
import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/6.2.3/ethers.js";import { ethers } from "ethers";BigInt
你可以利用ethers.getBigInt()函数将string number等类型转换为BigInt。BigInt支持很多运算,例如加减乘除、取模mod,幂运算pow,绝对值abs等运算。
注意,超过js最大安全整数的数值将不能转换。数值带后缀n会自动转换成BigInt。
const oneGwei = ethers.getBigInt("1000000000"); // 从十进制字符串生成
ethers.getBigInt("0x3b9aca00"); // 从hex字符串生成
ethers.getBigInt(1000000000); // 从数字生成
// 不能从js最大的安全整数之外的数字生成BigNumber,下面代码会报错
// ethers.getBigInt(Number.MAX_SAFE_INTEGER);
console.log("js中最大安全整数:", Number.MAX_SAFE_INTEGER);
// 运算
console.log("加法:", oneGwei + 1n); // 1,000,000,001
console.log("减法:", oneGwei - 1n); // 999,999,999
console.log("乘法:", oneGwei * 2n); // 2,000,000,000
console.log("除法:", oneGwei / 2n); // 500,000,000
// 比较
console.log("是否相等:", oneGwei == 1000000000n); // true单位转换
1 ETH = 10^18 wei
我们经常将数值在用户可读的字符串(以ether为单位)和机器可读的数值(以wei为单位)之间转换。例如,钱包可以为用户界面指定余额(以ether为单位)和gas价格(以gwei为单位),但是在发送交易时,两者都必须转换成以wei为单位的数值。代码参考
| Name | Decimals |
|---|---|
| wei | 0 |
| kwei | 3 |
| mwei | 6 |
| gwei | 9 |
| szabo | 12 |
| finney | 15 |
| ether | 18 |
ethers.parseEther
将 ETH 转换为 Wei,即 ETH 的最小单位,也是以太坊区块链中使用的最小单位。
// converts 1 ETH to 1,000,000,000,000,000,000 Wei.
ethers.parseEther('1');ethers.formatEther
将 Wei 转换为 ETH,以便更容易阅读的格式。
// converts 1,000,000,000,000,000,000 Wei to 1 Ether.
ethers.formatEther('1000000000000000000');ethers.parseUnits
将较大的单位转换为较小的单位。例如,从 1 ETH 转换为 1,000,000,000 Gwei。
// 将 1 ETH 转换为具有 9 位小数的 Gwei。它将任何令牌单位转换为具有指定小数精度的最小单位,该小数精度在第二个参数中声明。
ethers.parseUnits('1', 9);
const transactionAmount = ethers.parseUnits("0.05", "ether");
console.log(`0.05 Ether in Wei: ${transactionAmount.toString()}`);
console.log(ethers.parseUnits("1.0").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", "ether").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", 18).toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", "gwei").toString());
// { BigNumber: "1000000000" }
console.log(ethers.parseUnits("1.0", 9).toString());
// { BigNumber: "1000000000" }
console.log(ethers.parseEther("1.0").toString());
// { BigNumber: "1000000000000000000" } 等同于parseUnits(value, "ether")ethers.formatUnits
Converts smaller units to larger units. (E.g. from Gwei to ETH)
// 单位从具有指定小数精度的最小单位转换为较大单位,该小数精度在第二个参数中声明。
ethers.formatUnits('1000000000', "ether");
const oneGwei = ethers.getBigInt("1000000000");
console.log(ethers.formatUnits(oneGwei, 0));
// '1000000000'
console.log(ethers.formatUnits(oneGwei, "gwei"));
// '1.0'
console.log(ethers.formatUnits(oneGwei, 9));
// '1.0'
console.log(ethers.formatUnits(oneGwei, "ether"));
// `0.000000001`
console.log(ethers.formatUnits(1000000000, "gwei"));
// '1.0'
console.log(ethers.formatEther(oneGwei));
// `0.000000001` 等同于formatUnits(value, "ether")编码和解码
hexlify()
将值转换为其十六进制表示形式。
const hexValue = ethers.hexlify(42);
console.log(hexValue); // Output: '0x2a'encodeRlp()
使用递归长度前缀(RLP)编码对数据进行编码,常用于编码交易数据和参数。
const encodedData = ethers.encodeRlp(['Hello', 'world']);
console.log(encodedData); // Output: '0xc88348656c6c6f87776f726c64'toUtf8Bytes()
将 UTF-8 编码的字符串转换为其对应的字节。由于以太坊智能合约以字节形式存储和操作数据,因此需要将字符串转换为字节。
const uft8Bytes = ethers.toUtf8Bytes('STRING');const { toUtf8Bytes, encodeRlp, toBeHex } = ethers;
// transactionData
const transactionData = {
assetId: 1,
owner: '0xBf49Bd2B2c2f69c53A40306917112945e27577A4',
description: "fantastic token"
};
// Encode as a hexadecimal string
const assetIdHex = toBeHex(BigInt(transactionData.assetId));
const owner = toBeHex(BigInt(transactionData.owner));
// Convert to UTF-8 bytes
const descriptionBytes = toUtf8Bytes(transactionData.description);
// RLP encode the complete transaction data
const rlpEncodedTransaction = encodeRlp([assetIdHex, owner, descriptionBytes]);
console.log(`RLP encoded transaction data: ${rlpEncodedTransaction}`);加密
我们可以选择任一密码算法,但以下考虑因素将有助于我们做出决定:
- 安全性:两种算法都经过了长时间的广泛研究和审查。Keccak256 是以太坊中选择的哈希函数,因此,如果您在以太坊生态系统中工作,它可能是首选。
- 互操作性:如果开发涉及使用 SHA-256 的其他生态系统或协议,则
sha256()可能是更好的选择。
keccak256()
基于 Keccak-256 算法,从输入数据生成一个 256 位的哈希值。
const hash = ethers.keccak256("Hello, world!"); sha256()
类似于 keccak256(),它基于 SHA-256 算法从输入数据生成一个 256 位的哈希值。
const hash = ethers.sha256("Hello, world!");const documentData = "secret document"
// SHA-256
const sha256Hash = ethers.utils.sha256(ethers.utils.toUtf8Bytes(documentData));
// Keccak-256
const keccak256Hash = ethers.utils.keccak256(sha256Hash);
// it should be 0xd73931a00e470929e3db691d445afd39a55581037792ac1a10cdb6cc5cdef649
console.log(`final hash: ${keccak256Hash}`);provider
// const provider = new ethers.getDefaultProvider();
import "dotenv/config";
const ALCHEMY_API_KEY = process.env.ALCHEMY_API_KEY;
const INFURA_API_KEY = process.env.INFURA_API_KEY;
const provider = getDefaultProvider("sepolia", {
alchemy: ALCHEMY_API_KEY,
infura: INFURA_API_KEY,
});
const provider = new ethers.JsonRpcProvider(process.env.ALCHEMY_API_KEY);const main = async () => {
// 查询余额
const balance = await provider.getBalance(`0x...`);
console.log(balance);
// vitalick.eth是vitalik的ENS域名
const balance = await providerETH.getBalance(`vitalik.eth`);
// 测试网目前不支持ENS域名,只能用钱包地址查询
const balanceSepolia = await providerSepolia.getBalance(`0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045`);
// 将余额输出在console(主网)
console.log(`ETH Balance of vitalik: ${ethers.formatEther(balance)} ETH`);
// 输出vitalik Sepolia测试网ETH余额
console.log(`Sepolia ETH Balance of vitalik: ${ethers.formatEther(balanceSepolia)} ETH`);
// 查询钱包历史交易次数,参数也可以直接传一个wallet对象
const txCount = await provider.getTransactionCount(`vitalik.eth`);
console.log(transactionCount);
// 查询provider连接到了哪条链
const network = await provider.getNetwork();
console.log(network.toJSON());
// 查询区块高度
const blockNumber = await provider.getBlockNumber();
console.log(blockNumber);
// 查询当前建议的gas设置,返回的数据格式为`bigint`
const feeData = await provider.getFeeData();
console.log(feeData);
// 查询区块信息,参数为要查询的区块高度
const block = await provider.getBlock(0);
console.log(block);
// 给定合约地址查询合约bytecode,参数为合约地址,例子用的WETH地址
const code = await providerETH.getCode("0xc778417e063141139fce010982780140aa0cd5ab");
console.log(code);
}
main();Contracts
只读合约
// 只读`Contract`:参数分别是合约地址,合约`abi`和`provider`变量(只读)
const contract = new ethers.Contract(`address`, `abi`, `provider`);
// 第1种输入abi的方式: 复制abi全文
// WETH的abi可以在这里复制:https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
const abiWETH = '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view",...太长后面省略...';
const addressWETH = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; // WETH Contract
const contractWETH = new ethers.Contract(addressWETH, abiWETH, provider);
// 由于`abi`可读性太差,`ethers`创新的引入了`Human-Readable Abi`(人类可读abi)。开发者可以通过`function signature`和`event signature`来写`abi`。我们用这个方法创建稳定币`DAI`的合约实例:
// 第2种输入abi的方式:输入程序需要用到的函数,逗号分隔,ethers会自动帮你转换成相应的abi
// 人类可读abi,以ERC20合约为例
const abiERC20 = [
"function name() view returns (string)",
"function symbol() view returns (string)",
"function totalSupply() view returns (uint256)",
"function balanceOf(address) view returns (uint)",
];
const addressDAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; // DAI Contract
const contractDAI = new ethers.Contract(addressDAI, abiERC20, provider);
// 只读Contract,读取属性
const main = async () => {
// 名称
const nameWETH = await contractWETH.name();
// 代号
const symbolWETH = await contractWETH.symbol();
// owner
const owner = await contract.ownerOf(symbolWETH);
// 总供给
const totalSupplyWETH = await contractWETH.totalSupply();
// 某个钱包地址持仓
const balance = await contractWETH.balanceOf(vitalik.eth);
}
状态更改的合约(Signers/Wallets)
签名着 (Signers)
要发送交易,必须拥有一个外部拥有的账户。一个账户通常将其私钥加密并安全地存储在某个地方。Signers 封装了所有与账户交互的操作。它获取私钥并对交易进行签名。
Signers 类不仅可以代表 EOA,还可以代表其他类型的签名者,如合约钱包或外部钱包提供者,例如 MetaMask。由于它是一个抽象类,因此不能直接实例化。必须通过 Wallets 来完成的。
钱包(Wallets)
一、创建钱包
Wallets 是 Signers 类的具体实现。它简化了与以太坊区块链的交互。它直接访问私钥管理,并适用于应用程序内部使用。
// 创建随机私钥的`Wallet`对象。这种方法创建的钱包是单机的,我们需要用`connect(provider)`函数,连接到以太坊节点。这种方法创建的钱包可以用`mnemonic`获取助记词
const wallet1 = ethers.Wallet.createRandom();
const wallet1WithProvider = wallet1.connect(provider);
const mnemonic = wallet1.mnemonic; // 获取助记词
// 利用私钥和provider创建wallet对象
const privateKey = '0x...';
const wallet2 = new ethers.Wallet(privateKey, provider);
// 从助记词创建wallet对象
const wallet3 = ethers.Wallet.fromPhrase(mnemonic.phrase);
// 如果用户有来自钱包应用的加密钱包 JSON 文件,则可以使用以下方法解密账户信息。
const wallet4 = await ethers.Wallet.fromEncryptedJson(json, password);二、发送交易
① wallet直接发送交易
// 创建交易请求,参数:to为接收地址,value为ETH数额
const tx = {
to: address1,
value: ethers.parseEther("0.001")
}
//发送交易,获得收据
const txRes = await wallet.sendTransaction(tx);
const receipt = await txRes.wait(); // 等待链上确认交易
console.log(receipt); // 打印交易的收据② 先签署再广播
-
构建交易
构建交易需要一些参数:接收者的地址、要转移的值/物品、gas limit 和 gas price。
const amountToTransfer = ethers.parseEther('0.1'); //这会把 ETH 转换为 Wei. const tx = { to: 'RECIPIENT ADDRESS', value: amountToTransfer, gasLimit: 21000, gasPrice: ethers.parseUnits('10', 'gwei'), //这表明燃气价格以 Gwei 衡量。 } -
签署交易
当所有信息就绪时,我们可以对交易进行签名。回顾一下:Wallet 管理私钥,因此参与签署交易。这个过程生成一个数字签名,证明了交易的真实性和授权性。
const signedTx = await wallet.signTransaction(tx); -
广播交易
回顾一下:Provider 连接到网络中的一个节点。我们还可以获取广播的交易哈希以供参考,特别是用于检查交易是否已被挖掘,并一旦被挖掘,从区块链中检索其详细信息。
const sentTx = await provider.sendTransaction(signedTx); console.log('Transaction Hash: ', sentTx.hash); //Display the hash. -
等待确认
以太坊平均每 12 秒形成一个新的区块,但不是立即。因此,我们需要等待交易被挖掘。
await sentTx.wait(); console.log('Congratulation! Transaction confirmed.');
三、可读写合约
// 可读写`Contract`:参数分别是合约地址,合约`abi`和`signer`变量(wallet对象)
const contract1 = new ethers.Contract(`address`, `abi`, `signer`);
// 或者也可以利用下面的方法,将可读合约转换为可写合约
const contract2 = contract.connect(signer);/*
发送交易。其中`METHOD_NAME`为调用的函数名,`args`为函数参数,`[, overrides]`是可以选择传入的数据,包括:
- gasPrice:gas价格
- gasLimit:gas上限
- value:调用时传入的ether(单位是wei)
- nonce:nonce
*/
const tx = await contract.METHOD_NAME(args [, overrides]);
// 等待链上确认交易
await tx.wait();
// 调用desposit()函数,存入0.001 ETH
// 发起交易
const tx1 = await contract.deposit({value: ethers.parseEther("0.001")});
// 等待交易上链
await tx.wait();
const balance_deposit = await contract.balanceOf(address);
console.log(`存款后持仓: ${ethers.formatEther(balance_deposit)}`);
// 调用transfer()函数,给vitalik转账0.001 ETH")
// 发起交易
const tx2 = await contract.transfer("vitalik.eth", ethers.parseEther("0.001"));
// 等待交易上链
await tx2.wait();
const balance_transfer = await contract.balanceOf(address);
console.log(`转账后持仓: ${ethers.formatEther(balance_transfer)}`);四、部署智能合约
在以太坊上,智能合约的部署是一种特殊的交易:将编译智能合约得到的字节码发送到0地址。如果这个合约的构造函数有参数的话,需要利用abi.encode将参数编码为字节码,然后附在在合约字节码的尾部一起发送。
const factoryERC20 = new ethers.ContractFactory(abiERC20, bytecodeERC20, wallet);// 1. 利用contractFactory部署ERC20代币合约
console.log("利用contractFactory部署ERC20代币合约");
// 部署合约,填入constructor的参数
const contractERC20 = await factoryERC20.deploy("WTF Token", "WTF");
console.log(`合约地址: ${contractERC20.target}`);
console.log("部署合约的交易详情:")
console.log(contractERC20.deploymentTransaction());
console.log("等待合约部署上链");
await contractERC20.waitForDeployment();
// 也可以用 contractERC20.deployTransaction.wait()
console.log("合约已上链");// 打印合约的name()和symbol(),然后调用mint()函数,给自己地址mint 10,000代币
console.log("调用mint()函数,给自己地址mint 10,000代币");
console.log(`合约名称: ${await contractERC20.name()}`);
console.log(`合约代号: ${await contractERC20.symbol()}`);
let tx = await contractERC20.mint("10000");
console.log("等待交易上链");
await tx.wait();
console.log(`mint后地址中代币余额: ${await contractERC20.balanceOf(wallet)}`);
console.log(`代币总供给: ${await contractERC20.totalSupply()}`);// 调用transfer()函数,给Vitalik转账1000代币
console.log("调用transfer()函数,给Vitalik转账1,000代币");
tx = await contractERC20.transfer("vitalik.eth", "1000");
console.log("等待交易上链");
await tx.wait();
console.log(`Vitalik钱包中的代币余额: ${await contractERC20.balanceOf("vitalik.eth")}`);Event(事件)
智能合约释放出的事件存储于以太坊虚拟机的日志中。日志分为两个主题topics和数据data部分,其中事件哈希和indexed变量存储在topics中,作为索引方便以后搜索;没有indexed变量存储在data中,不能被直接检索,但可以存储更复杂的数据结构。
// 以ERC20代币中的`Transfer`转账事件为例,在合约中它是这样声明的:
event Transfer(address indexed from, address indexed to, uint256 amount);检索事件
我们可以利用Ethers中合约类型的queryFilter()函数读取合约释放的事件。
const transferEvents = await contract.queryFilter('事件名', 起始区块, 结束区块);queryFilter()包含3个参数,分别是事件名(必填),起始区块(选填),和结束区块(选填)。检索结果会以数组的方式返回。
注意:要检索的事件必须包含在合约的
abi中。起始区块到结束区块的最大区间为500,否则会报错message: 'You can make eth_getLogs requests with up to a 500 block range.
创建包含检索事件的abi。
// WETH ABI,只包含我们关心的Transfer事件
const abiWETH = [
"event Transfer(address indexed from, address indexed to, uint amount)"
];声明WETH合约实例。
// 测试网WETH地址
const addressWETH = '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6';
// 声明合约实例
const contract = new ethers.Contract(addressWETH, abiWETH, provider);获取过去10个区块内的Transfer事件,并打印出1个。我们可以看到,topics中有3个数据,对应事件哈希,from,和to;而data中只有一个数据amount。另外,ethers还会根据ABI自动解析事件,结果显示在args成员中。
// 得到当前block
const block = await provider.getBlockNumber();
console.log(`当前区块高度: ${block}`);
console.log(`打印事件详情:`);
const transferEvents = await contract.queryFilter('Transfer', block - 10, block);
// 打印第1个Transfer事件
console.log(transferEvents[0]);
// 解析Transfer事件的数据(变量在args中)
console.log("解析事件:");
const amount = ethers.formatUnits(ethers.getBigInt(transferEvents[0].args["amount"]), "ether");
console.log(`地址 ${transferEvents[0].args["from"]} 转账${amount} WETH 到地址 ${transferEvents[0].args["to"]}`);监听合约事件
contract.on("eventName", function);
contract.once("eventName", function);监听USDT合约
-
声明合约变量:我们只关心
USDT合约的Transfer事件,把它填入到abi中就可以。// USDT的合约地址 const contractAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7' // 构建USDT的Transfer的ABI const abi = [ "event Transfer(address indexed from, address indexed to, uint value)" ]; // 生成USDT合约对象 const contractUSDT = new ethers.Contract(contractAddress, abi, provider); -
利用contract.once()函数,监听一次Transfer事件,并打印结果。
// 只监听一次 console.log("利用contract.once(),监听一次Transfer事件"); contractUSDT.once('Transfer', (from, to, value)=>{ // 打印结果 console.log( `${from} -> ${to} ${ethers.formatUnits(ethers.getBigInt(value), 6)}` ) })
过滤器
const filter = contract.filters.EVENT_NAME( ...args );过滤器的使用
contract.on(filter, (res) => {
console.log(`${res.args[0]} -> ${res.args[1]} ${ethers.formatUnits(res.args[2], 6)}`);
})
const logs = contract.queryFilter(filter, fromBlock, toBlock);staticCall
ethers.js将eth_call封装在staticCall方法中,方便开发者模拟交易的结果,并避免发送可能失败的交易。
console.log("用staticCall尝试调用transfer转账1 DAI,msg.sender为Vitalik地址");
// 发起交易
const tx = await contractDAI.transfer.staticCall("vitalik.eth", ethers.parseEther("1"), {from: await provider.resolveName("vitalik.eth")});
console.log(`交易会成功吗?:`, tx); // trueconsole.log("用staticCall尝试调用transfer转账10000 DAI,msg.sender为测试钱包地址");
const tx2 = await contractDAI.transfer.staticCall("vitalik.eth", ethers.parseEther("10000"), {from: address});
console.log(`交易会成功吗?:`, tx2); // 失败info识别ERC721合约
利用ERC165的supportsInterface()函数,识别合约是否为ERC721标准。如果是,则返回true;反之,则报错或返回false。
注意此处的代码中的
selectorERC721常量被提取出main函数
// 利用ERC165的supportsInterface,确定合约是否为ERC721标准
// ERC721接口的ERC165 identifier
const selectorERC721 = "0x80ac58cd";
const main = async () => {
try {
// 利用ERC165的supportsInterface,确定合约是否为ERC721标准
const isERC721 = await contractERC721.supportsInterface(selectorERC721);
console.log("利用ERC165的supportsInterface,确定合约是否为ERC721标准");
console.log(`合约是否为ERC721标准: ${isERC721}`);
}catch (e) {
// 如果不是ERC721,则会报错
console.log(e);
}
}