EIPs Explained

ERC-7615 · Draft(草案) · ERC · 2024-02-03

ERC-7615: Atomic Push-based Data Feed Among Contracts

一种面向合约的草案发布/订阅模式:发布者函数运行时,会在同一笔交易中对为该函数选择器注册的每个订阅者调用 exec(),以取代监视事件的链下 keeper。

它解决什么问题?

当一个合约需要对另一个合约中发生的事情(价格更新、NFT 转移、投票结束)作出反应时,通常的答案是链下 keeper:一个机器人监视事件,并发送后续交易。这增加了对机器人的信任、两个步骤之间的延迟,以及状态不一致的窗口期。

ERC-7615 提议由源合约(发布者)在同一次调用内直接把更新推送给感兴趣的合约(订阅者)。规范中的例子:预言机把价格推送给借贷协议,由其当场清算;NFT 合约告知质押合约某个代币发生了移动,使其可以解除质押,让用户无需转移 NFT 就能质押;DAO 合约在投票结束时立即执行投票结果。

它如何运作

  1. 发布者函数被调用,并运行内部的 _push(selector, data) 钩子。
  2. 发布者查找为该函数的 selector 注册的订阅者。
  3. 它对每个订阅者调用 exec(selector, data)。
  4. 订阅者据此行动,也可以选择调用发布者的 inbox(selector) 来获取更完整的数据(参考实现把它保存在 transient storage 中,见 EIP-1153)。

订阅有两种:

  • 无条件(IPushForce):forceApprove(selector, target) 使对该选择器的每次调用都推送给 target。适合价格喂价。
  • 有条件(IPushFree):approve(selector, target, data) 只在调用与 data(例如某个特定的 tokenId)匹配时才推送。为其他所有人节省 gas。

订阅者实现带有 exec 和 isLocked 的 IExec。在移除订阅(cancel / forceCancel)之前,发布者必须检查 isLocked,因此依赖该喂价的订阅者不会被单方面切断。发布者还可以通过 renounceForceApprove / renounceForceCancel 永久放弃添加或移除无条件订阅者的权力。

示例代码

一个只信任某一个发布者的订阅者:

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

interface IExec {
    function isLocked(bytes4 selector, bytes calldata data) external returns (bool);
    function exec(bytes4 selector, bytes calldata data) external;
}

contract PriceSubscriber is IExec {
    address public immutable publisher;
    bytes4 public immutable priceSelector;
    uint256 public lastPrice;
    uint256 public openPositions;

    constructor(address pub, bytes4 sel) { publisher = pub; priceSelector = sel; }

    function exec(bytes4 selector, bytes calldata data) external {
        require(msg.sender == publisher, "untrusted caller"); // exec is public
        require(selector == priceSelector, "unexpected selector");
        lastPrice = abi.decode(data, (uint256));
        // ... check positions and liquidate if needed
    }

    // Refuse unsubscription while positions depend on the feed.
    function isLocked(bytes4, bytes calldata) external view returns (bool) {
        return openPositions > 0;
    }
}

需要注意

  • 状态:Draft。
  • 发布者的调用者要为每个订阅者的 exec 支付 gas。订阅者列表过长或开销过大,可能使发布者的函数变得昂贵,甚至超过区块 gas limit,所以 approve 和 forceApprove 需要访问控制。
  • exec 任何人都可以调用;订阅者必须验证 msg.sender 并校验数据。
  • 调用不受信任的订阅者会打开回到发布者的重入路径;请使用重入保护和 checks-effects-interactions 模式。
  • isLocked 始终返回 true 的订阅者永远无法被移除;发布者在订阅它之前应检查这一点。

#oracle #pubsub #automation #hooks #defi

详细信息

作者
Elaine Zhang (@lanyinzly) <[email protected]>, Jerry <[email protected]>, Amandafanny <[email protected]>, Shouhao Wong (@wangshouh) <[email protected]>, Doris Che (@Cheyukj) <[email protected]>, Henry Yuan (@onehumanbeing) <[email protected]>
状态
Draft(草案)
类型
Standards Track / ERC
创建日期
2024-02-03

机器可读数据: Markdown · JSON