EIPs Explained

EIP-2831 · Stagnant(停滞) · Interface · 2020-07-26

EIP-2831: Transaction Replacement Message Type

对 EIP-1193 钱包提供者 API 的一项已停滞的扩展:当待处理交易被替换时发出 tx_speedup、tx_cancel 和 tx_replacement 事件,让 dapp 无需轮询即可跟踪。

它解决什么问题?

钱包允许用户"加速"或"取消"一笔待处理交易。其底层是同一种手法:以相同的 nonce 和更高的手续费广播一笔新交易,让它在原交易被打包之前将其替换。

发起原交易的 dapp 只知道旧哈希。一旦被替换,这个哈希就永远不会确认,而 dapp 没有标准方式得知新哈希。开发者最终只能逐区块轮询或靠猜测。EIP-2831 提议由提供者直接告诉 dapp。

它如何运作

它为 EIP-1193 提供者(window.ethereum)新增三个事件,采用 Node.js EventEmitter 风格的 provider.on(...):

事件 含义 替换交易必须保持不变的内容
tx_speedup 同一笔交易,手续费更高 nonce、to、value、data
tx_cancel 原交易作废 nonce、相同的 from/to、金额为零、无 data
tx_replacement 完全不同的交易 仅 nonce

每个事件传递相同的载荷:

interface TxReplacementInfo {
  readonly oldTx: string;  // hash of the superseded transaction
  readonly newTx: string;  // hash of the replacement
  readonly nonce: string;
  readonly from: string;
}

规范把替换定义为相同 nonce 加上高出 10% 的 gas 价格,这反映了撰写时常见的节点内存池规则。不支持这些事件的提供者应忽略订阅,或抛出错误。

示例代码

在浏览器 dapp 中监听替换(假设提供者实现了该提案):

const ethereum = (window as any).ethereum;

let watched = await ethereum.request({
  method: "eth_sendTransaction",
  params: [{ from: account, to: recipient, value: "0x2386f26fc10000" }],
});

function onReplaced(kind: string) {
  return ({ oldTx, newTx, nonce }: { oldTx: string; newTx: string; nonce: string }) => {
    if (oldTx !== watched) return;
    console.log(`${kind}: ${oldTx} -> ${newTx} (nonce ${nonce})`);
    watched = newTx; // keep tracking the transaction that may actually confirm
  };
}

ethereum.on("tx_speedup", onReplaced("sped up"));
ethereum.on("tx_cancel", onReplaced("cancelled"));
ethereum.on("tx_replacement", onReplaced("replaced"));

需要注意

  • 状态:Stagnant。不要假定任何钱包会发出这些事件;请做特性检测并准备回退方案。
  • 一个处处可用的稳健回退方案:监视发送者的 nonce。一旦带有该 nonce 的交易被打包,就查出它是哪个哈希。ethers v6 等库在 tx.wait() 期间就是这样检测替换的,并抛出描述取消或替换的 TRANSACTION_REPLACED 错误。
  • 对于 EIP-1559 交易,"更高的 gas 价格"意味着同时提高 maxFeePerGas 和 maxPriorityFeePerGas;具体需要提高多少是节点内存池的策略,而不是协议规则。
  • 规范附录中的示例从未定义的 message.data 解构;请像上面那样直接使用监听器的参数。

#wallet #provider #interface #dapp #stagnant

详细信息

作者
Gregory Markou (@GregTheGreek)
状态
Stagnant(停滞)
类型
Standards Track / Interface
创建日期
2020-07-26
依赖的提案

机器可读数据: Markdown · JSON