ERC-7786 · Final(最终) · ERC · 2024-10-14
ERC-7786: Cross-Chain Messaging Gateway
用于发送和接收任意跨链消息的统一网关接口,使合约可以通过任何桥(原生或通过适配器)跨链通信,而不会被锁定在单一厂商的 API 上。
它解决什么问题?
每个桥或跨链消息协议都有自己的接口、自己的工作流和自己的信任模型。为某个协议构建的合约无法在不重写的情况下切换到另一个协议,也没有人能写出适用于任何桥的通用"跨链应用"。
ERC-7786 定义了一个小型的通用接口:用于发送消息的源网关,以及用于接收消息的接收方回调。协议可以直接实现它,也可以有人围绕现有协议构建适配器。桥特有的功能以可选的**属性(attributes)**传递。它也适用于非 EVM 链,因为地址使用与链无关的 ERC-7930 格式。
它如何运作
消息包含发送方、接收方、不透明的 payload、可选的原生代币 value,以及一个 attributes 列表。发送方和接收方是 ERC-7930 的 Interoperable Address(二进制,按 CAIP-350 序列化),同时编码了链和账户。
**发送。**源链的网关实现 IERC7786GatewaySource:
sendMessage(recipient, payload, attributes)触发MessageSent,并可能返回一个非零的sendId。对于未知属性它必须以UnsupportedAttributerevert;如果附带了 ETH 但网关不支持 value,也必须 revert。supportsAttribute(bytes4)告诉调用者有哪些功能。每个属性是bytes4 key ++ value;建议以函数选择器作为 key,例如minGasLimit(uint256)→0x39f87ba1,这样每个元素都可以用abi.encodeWithSignature构造。- 可能还需要额外步骤,例如支付目标链的 gas("后处理");具体方式不在范围之内。
接收。目标侧的协议调用接收方的 receiveMessage(receiveId, sender, payload),接收方必须返回它的选择器(0x2432ef26)。接收方必须检查调用者是它所信任的网关。
**必需的保证:安全性(只有已发送并已最终确认的消息才会被投递,且只投递一次)和活性(只要支付了费用,最终会被投递)。及时性和去中心化信任是建议项。
示例代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC7786GatewaySource {
function sendMessage(bytes calldata recipient, bytes calldata payload, bytes[] calldata attributes)
external payable returns (bytes32 sendId);
}
interface IERC7786Recipient {
function receiveMessage(bytes32 receiveId, bytes calldata sender, bytes calldata payload)
external payable returns (bytes4);
}
contract PingPong is IERC7786Recipient {
address public immutable gateway;
constructor(address g) { gateway = g; }
function ping(bytes calldata remote /* ERC-7930 address */) external payable {
bytes[] memory attrs = new bytes[](0);
IERC7786GatewaySource(gateway).sendMessage{value: msg.value}(remote, "ping", attrs);
}
function receiveMessage(bytes32, bytes calldata, bytes calldata payload)
external payable returns (bytes4)
{
require(msg.sender == gateway, "untrusted gateway");
// handle payload ...
return IERC7786Recipient.receiveMessage.selector;
}
}