ERC-205 · Stagnant(停滞) · ERC · 2017-02-06
ERC-205: ENS support for contract ABIs
让 ENS 名称发布其合约的 ABI,调用者只需一个名称就能同时查到合约的地址和接口。
它解决什么问题?
调用合约需要它的地址和 ABI,也就是对函数和事件的 JSON 描述。ENS 解决了地址这部分:mytoken.eth 可以解析为地址。但 ABI 仍然得从别处获取,比如网站、GitHub 仓库或区块浏览器。对于一次性的交互,以及接口会随时间变化的合约,这很不方便。
ABI 很小。规范指出,即便是 The DAO 那个庞大的 ABI,原始 JSON 也只有约 9.4 KB,压缩后约 1.1 KB。因此 ERC-205 提议把它们直接存放在 ENS 中,紧挨着地址。
它如何运作
ERC-205 定义了一种新的解析器配置(resolver profile):
function ABI(bytes32 node, uint256 contentTypes) view returns (uint256, bytes);
它的 ERC-165 接口 ID 是 0x2203ab56。
contentTypes 是调用者能处理的编码的位掩码。解析器返回其中一种,如果没有合适的就返回 (0, "")。
| ID | 编码 | 说明 |
|---|---|---|
| 1 | JSON | 标准格式,但体积最大 |
| 2 | zlib 压缩的 JSON | 体积小,便于链下解码 |
| 4 | CBOR | 紧凑,在 EVM 中更易解析 |
| 8 | URI | 指向别处(HTTP、IPFS、Swarm……) |
查找顺序: 先向解析器查询名称本身,例如 mytoken.eth。如果没有返回内容,就对该名称所指向的地址做反向查询(ERC-181),再查询那条记录。合约可以在自己的反向记录上发布其规范 ABI,而单个名称可以覆盖它,例如使用精简过的 ABI。
示例代码
用 ethers v6 通过 ENS 获取 JSON ABI:
import { Contract, JsonRpcProvider, namehash, toUtf8String } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const name = "example.eth";
const resolverInfo = await provider.getResolver(name);
if (!resolverInfo) throw new Error("no resolver");
const resolver = new Contract(
resolverInfo.address,
["function ABI(bytes32 node, uint256 contentTypes) view returns (uint256, bytes)"],
provider,
);
const [type, data] = await resolver.ABI(namehash(name), 1); // accept JSON only
if (type === 1n) {
const abi = JSON.parse(toUtf8String(data));
const target = new Contract((await provider.resolveName(name))!, abi, provider);
}