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"));