前端调用合约如何避免出现transaction fail

前言: 作为开发,你一定经历过调用合约的时候发现 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.

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

// call method in v5 docs
// contract.callStatic.METHOD_NAME( ...args [ , overrides ] ) ⇒ Promise< any >

 const preTransaction = async () => { 
   try {
    const preCall = await contract.callStatic.transferFrom(from, to)   
   } catch(e) {
    console.log('err =', e)
  }        
 }

        ehtersV5 文档地址

        ethers V6 文档地址

二、 wagmi库 

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

import { prepareWriteContract } from '@wagmi/core'


const simulate = await prepareWriteContract({
      address: contractAddress,
      abi: contractAbi,
      functionName: 'transfer',
      args: [],
})
console.debug('market order simulate =', simulate)

总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值