第5节:工具函数

小白入门:https://github.com/dukedaily/solidity-expert ,欢迎star转发,文末加V入群。

职场进阶: https://dukeweb3.com

v6 把原本 ethers.utils.* 下的工具全部提到 顶层命名空间,直接通过 ethers.xxx 调用。

单位换算

import { ethers } from "ethers";

// ETH / wei
ethers.parseEther("1.5"); // 1500000000000000000n
ethers.formatEther(1500000000000000000n); // "1.5"

// 任意 token decimals
ethers.parseUnits("100", 6); // 100000000n(6 位 USDC)
ethers.formatUnits(100000000n, 6); // "100.0"

// gwei 快捷写法
ethers.parseUnits("30", "gwei"); // 30000000000n

地址工具

ethers.isAddress("0xA0b8...eB48"); // true / false
ethers.getAddress("0xa0b8...eb48"); // 返回 checksum 格式
ethers.ZeroAddress; // 0x0000...0000

Hash 与 ABI 编码

// keccak256
ethers.keccak256(ethers.toUtf8Bytes("foo"));

// abi encode / decode
const coder = ethers.AbiCoder.defaultAbiCoder();

const data = coder.encode(
  ["address", "uint256"],
  ["0x0000000000000000000000000000000000000001", 42n],
);

const [addr, value] = coder.decode(["address", "uint256"], data);

Function selector

const iface = new ethers.Interface(["function transfer(address,uint256)"]);

const selector = iface.getFunction("transfer").selector;
// "0xa9059cbb"

// 反向:从 selector 查方法
const frag = iface.getFunction("0xa9059cbb");

ENS 解析

需要 Provider 支持(主流 mainnet Provider 都支持):

const addr = await provider.resolveName("vitalik.eth");
const name = await provider.lookupAddress(addr);

console.log(name, "->", addr);

常用常量

ethers.MaxUint256; // 2**256 - 1
ethers.ZeroAddress; // 0x0000...0000
ethers.ZeroHash; // 0x0000...0000 (32 字节)

小结

v6 的工具函数全在 ethers.* 下,少一层嵌套。下一节对照 v5 做一张迁移速查表收尾。