EIPs Explained

ERC-165 · Final(最终) · ERC · 2018-01-23

ERC-165: Standard Interface Detection

一个 supportsInterface(bytes4) 函数,让任何合约都能声明自己实现了哪些接口,这样其他合约和应用在调用之前就能先检查。

它解决什么问题?

仅凭一个合约地址,你无法知道该合约能做什么。如果某个市场收到一个地址,它无法判断这个地址是 NFT 合约、多代币合约,还是别的东西。它可以调用某个函数然后碰运气,但缺失的函数可能会 revert,或者落入执行意外操作的 fallback。

ERC-165 为合约提供了一种标准方式来声明"我实现了接口 X",也为调用方提供了一种安全的查询方式。

它如何运作

接口 ID。 接口由其所有函数的 4 字节函数选择器的异或(XOR)来标识。例如,ERC-165 自身的 ID 就是 supportsInterface(bytes4) 的选择器,即 0x01ffc9a7。

声明。 符合标准的合约需要实现:

function supportsInterface(bytes4 interfaceID) external view returns (bool);

它必须返回:

  • 对 0x01ffc9a7(ERC-165 自身)返回 true
  • 对 0xffffffff 返回 false
  • 对它实现的其他每个接口返回 true,其余返回 false

该函数最多只能使用 30,000 gas。

检测。 要检查一个合约是否支持 ERC-165,使用 30,000 gas 发起 STATICCALL(EIP-214)。先查询 supportsInterface(0x01ffc9a7),它必须返回 true。再查询 supportsInterface(0xffffffff),它必须返回 false。第二项检查用于识别那些 fallback 对任何调用都返回 true 的旧合约。如果两项检查都通过,就可以直接查询任意接口 ID。

示例代码

在自定义接口之外同时实现 ERC-165:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IERC165 {
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

interface IGreeter {
    function greet() external view returns (string memory);
}

contract Greeter is IERC165, IGreeter {
    function supportsInterface(bytes4 id) external pure returns (bool) {
        return id == type(IERC165).interfaceId   // 0x01ffc9a7
            || id == type(IGreeter).interfaceId;
    }

    function greet() external pure returns (string memory) {
        return "hello";
    }
}

检查某个地址是否为 ERC-721 合约(ethers v6):

import { Contract, JsonRpcProvider } from "ethers";

const provider = new JsonRpcProvider(process.env.RPC_URL);
const c = new Contract(addr, ["function supportsInterface(bytes4) view returns (bool)"], provider);

const isErc165 =
  (await c.supportsInterface("0x01ffc9a7")) && !(await c.supportsInterface("0xffffffff"));
const isErc721 = isErc165 && (await c.supportsInterface("0x80ac58cd"));

需要注意

  • ERC-721 和 ERC-1155 要求实现 ERC-165,因此 NFT 市场可以自动识别代币类型。ERC-20 出现得更早,并不要求实现它。
  • 接口 ID 只涵盖函数选择器。事件、返回类型和可选函数都不包含在内。
  • 返回 true 的合约只是在做声明。ERC-165 并不能证明这些函数的行为是正确的。
  • 在 Solidity 中,type(I).interfaceId 会替你计算该 ID。OpenZeppelin 的 ERC165 基础合约是常见的起点。
  • ERC-1820 是基于注册表的替代方案,普通账户(EOA)也可以注册接口。

#interface #introspection #standard #erc

详细信息

作者
Christian Reitwießner <[email protected]>, Nick Johnson <[email protected]>, Fabian Vogelsteller <[email protected]>, Jordi Baylina <[email protected]>, Konrad Feldmeier <[email protected]>, William Entriken <[email protected]>
状态
Final(最终)
类型
Standards Track / ERC
创建日期
2018-01-23
依赖的提案
被以下提案依赖

机器可读数据: Markdown · JSON