ERC-7654 · Draft(草案) · ERC · 2024-03-13
ERC-7654: Request Method Types
一个草案接口:通过类似 HTTP 的 GET、POST、PUT 入口以及自描述的参数类型来暴露合约的函数,使客户端能以同样的方式发现并调用任何合约。
它解决什么问题?
每个合约都有自己的函数名和参数列表。客户端必须事先知道合约的 ABI 才能对它做任何事,而且没有通用的方式去问一个合约"你能做什么,每个操作需要什么参数?"。
ERC-7654 借用了大家熟悉的 Web 请求方法模式。合约不再暴露任意的函数,而是暴露一组固定的入口(get、post、put)以及用于发现的函数。这样客户端就可以列出可用的方法,读取它们的说明和参数类型,并以通用的方式调用它们。
它如何运作
共有四种方法类型:
| 类型 | 含义 | 是否安全(只读)? |
|---|---|---|
GET |
读取记录 | 是 |
POST |
创建记录 | 否 |
PUT |
更新记录 | 否 |
OPTIONS |
列出支持的方法类型 | 是 |
这里有意不设 DELETE:在链上删除数据效率低下,所以规范建议用一个把记录标记为无效的 PUT,再配合一个隐藏这些记录的 GET。
客户端的工作流程:
- 调用
options(),查看合约支持哪些方法类型。 - 调用
getMethods(type),列出某个类型的方法名。 - 调用
getMethodInstruction(name),读取人类可读的说明。 - 调用
getMethodReqAndRes(name),获取请求和响应的参数类型(规范Types库中的 Solidity 类型枚举)。 - 对请求进行 ABI 编码,并带上方法名调用
get、post或put。 - 对
bytes响应进行 ABI 解码。post和put还会触发Response(bytes)。
示例代码
接口节选:
// SPDX-License-Identifier: CC0-1.0
pragma solidity >=0.8.0;
interface IRequestMethodTypes {
enum MethodTypes { GET, POST, PUT, OPTIONS }
event Response(bytes _response);
function getMethods(MethodTypes _methodTypes) external view returns (string[] memory);
function getMethodInstruction(string memory _methodName) external view returns (string memory);
function get(string memory _methodName, bytes memory _methodReq) external view returns (bytes memory);
function post(string memory _methodName, bytes memory _methodReq) external payable returns (bytes memory);
function put(string memory _methodName, bytes memory _methodReq) external payable returns (bytes memory);
function options() external returns (MethodTypes[] memory);
}
调用一个假设的 getUser 方法(ethers v6):
import { AbiCoder, Contract } from "ethers";
const abi = AbiCoder.defaultAbiCoder();
const c = new Contract(addr, [
"function getMethods(uint8) view returns (string[])",
"function get(string,bytes) view returns (bytes)",
], provider);
console.log(await c.getMethods(0)); // GET methods, e.g. ["getUser"]
const raw = await c.get("getUser", abi.encode(["address"], [userAddress]));
const [name, score] = abi.decode(["string", "uint256"], raw);
需要注意
- 状态为 Draft;接口仍可能变化。
- 方法通过字符串名称分派,参数被打包进
bytes,与普通的带类型函数相比,这会多消耗 gas,也失去了编译期的类型检查。 - 标准工具(浏览器、钱包、ERC-20/721 集成)期望的是普通的函数选择器,因此只使用这种模式的合约不会被它们识别。
post和put会改变状态,必须有自己的访问控制;方法类型的标签只是描述性的,并不强制执行。