【问题标题】:How can I retrieve the revert reason of a failed transaction using web3.js and Metamask?如何使用 web3.js 和 Metamask 检索失败事务的还原原因?
【发布时间】:2023-02-01 18:57:49
【问题描述】:

我正在使用 web3.eth.Contract.methods.myMethod().send() 和 metamask 来签署交易,但是当交易恢复时,我想向用户显示原因。

我尝试启用 handleRevert 选项来获取还原原因,但是当我这样做时,Metamask 继续向区块链发送请求并在浏览器控制台上重复相同的错误

【问题讨论】:

    标签: javascript web3js


    【解决方案1】:

    您可以通过处理由 send() 返回的 Promise 中的事务调用抛出的错误来检索失败事务的还原原因。错误消息通常包含还原原因。

    这是一个例子:

    web3.eth.Contract.methods.myMethod().send({ from: myAccount })
        .then(function(receipt) {
            // handle success
        })
        .catch(function(error) {
            console.error(error.message); // this will contain the revert reason
        });
    

    请注意,错误消息返回的还原原因是一个字符串,可能需要对其进行解析以检索智能合约中定义的实际还原原因。

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2013-08-05
      • 2019-03-23
      • 2021-08-23
      • 2022-06-27
      相关资源
      最近更新 更多