排错:调用只读方法时,遇到 UNPREDICTABLE_GAS_LIMIT

  • 胡键
  • 更新于 2023-08-02 17:59
  • 阅读 683

调用只读方法时,遇到 UNPREDICTABLE_GAS_LIMIT

症状

开发以太坊应用时,调用只读方法时遇到类似以下内容的报错信息:

ERROR Error: Uncaught (in promise): Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"code":-32000,"message":"execution reverted"}, method="call", transaction={"to":"0xE6183d3094b9r360B121Ec1330afAE76A74d1cbF","data":"0xdb699765000000000000000000000000b2b7bedd7d7fc19804c7dd4a4e8174c4c73c220d0000000000000000000000000000000000000000000000000de0b6b3b7640000000000000000000000000000000000000000000000000000000000006c915aef"}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.0.24)
    at d.makeError (main.a577643548eb15e6832e.js:1)
    at d.throwError (main.a577643548eb15e6832e.js:1)
    at Z (main.a577643548eb15e6832e.js:1)
    at $e.<anonymous> (main.a577643548eb15e6832e.js:1)
    at Generator.throw (<anonymous>)
    at a (main.a577643548eb15e6832e.js:1)
    at l.invoke (polyfills.797d13e303959ed8dd77.js:1)
    at Object.onInvoke (main.a577643548eb15e6832e.js:1)
    at l.invoke (polyfills.797d13e303959ed8dd77.js:1)
    at a.run (polyfills.797d13e303959ed8dd77.js:1)
    at Z (polyfills.797d13e303959ed8dd77.js:1)
    at polyfills.797d13e303959ed8dd77.js:1
    at a (main.a577643548eb15e6832e.js:1)
    at l.invoke (polyfills.797d13e303959ed8dd77.js:1)
    at Object.onInvoke (main.a577643548eb15e6832e.js:1)
    at l.invoke (polyfills.797d13e303959ed8dd77.js:1)
    at a.run (polyfills.797d13e303959ed8dd77.js:1)
    at polyfills.797d13e303959ed8dd77.js:1
    at l.invokeTask (polyfills.797d13e303959ed8dd77.js:1)
    at Object.onInvokeTask (main.a577643548eb15e6832e.js:1)

原因

看到上面这样的信息,十有八九会让开发者摸不着头脑,但最可能的原因是:调用了合约中不存在的方法。这种情况在 ethers.js 搭配 Human-Readable ABI 时尤其容易出现:比如因手抖而导致的拼写错误。

解决

检查调用地址(上文中的 to)对应的合约中是否有要调用的方法并进行修改:

  • 方法名是否错误,即调用地址和合约方法不匹配

  • 方法参数是否错误

  • 方法名最后是否带有分号等其他符号,注意:只需复制字符串内容即可,不要把其他符号复制进来。以下是对比:

    • 对:function testMethod(uint256) public view returns (uint256)
    • 错:function testMethod(uint256) public view returns (uint256);

若对 ethers.js 的 Human-Readable ABI 不熟,可以参见:

备注

为何这里专门强调只读方法,这是因为一般情况下这个错误根本不应该发生:没有任何交易发送,怎么可能会需要有预估 gas limit 之类的东西。

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
胡键
胡键
CSM / 架构师 / 创业者,先后就职于中兴和 SAP,现专注于工业物联网、机器学习和区块链。同时,作为机器学习和区块链技术活动的组织者和分享者活跃于本地社区。