当前位置:   article > 正文

前端调用合约如何避免出现transaction fail_ethersjs static call

ethersjs static call

前言: 作为开发,你一定经历过调用合约的时候发现 gas fee 超出限制,但是不知道报了什么错。这个时候一般都是触发了require错误合约校验。对于用户来说他不理解为什么一笔交易会花费如此大的gas,那我们作为开发如何尽量避免这种情况的产生呢?

 

一、static call

        ethersJS V5 文档的解释比 V6更清晰。 我们直接来看官方文档解释:

Rather than executing the state-change of a transaction, it is possible to ask a node to pretend that a call is not state-changing and return the result.

This does not actually change any state, but is free. This in some cases can be used to determine if a transaction will fail or succeed.

         我们可以看到,这是一种不执行交易的状态更改,而是要求节点假装调用没有状态更改并返回结果的调用。这实际上并不改变任何状态,而且是免费的。在某些情况下,这可用于确定交易是失败还是成功。简单举个例子:

  1. // call method in v5 docs
  2. // contract.callStatic.METHOD_NAME( ...args [ , overrides ] ) ⇒ Promise< any >
  3. const preTransaction = async () => {
  4. try {
  5. const preCall = await contract.callStatic.transferFrom(from, to)
  6. } catch(e) {
  7. console.log('err =', e)
  8. }
  9. }

        ehtersV5 文档地址

        ethers V6 文档地址

二、 wagmi库 

        如果你使用的是wagmi库,它已经替我们封装好了调用方法。举个栗子

  1. import { prepareWriteContract } from '@wagmi/core'
  2. const simulate = await prepareWriteContract({
  3. address: contractAddress,
  4. abi: contractAbi,
  5. functionName: 'transfer',
  6. args: [],
  7. })
  8. console.debug('market order simulate =', simulate)

总结

        通过上面的方法,可以大大避免用户触发 transcatin expected to fail 的报错。可以算作一个优化前端交互体验的加分点。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/877819
推荐阅读
相关标签
  

闽ICP备14008679号