赞
踩
前言: 作为开发,你一定经历过调用合约的时候发现 gas fee 超出限制,但是不知道报了什么错。这个时候一般都是触发了require错误合约校验。对于用户来说他不理解为什么一笔交易会花费如此大的gas,那我们作为开发如何尽量避免这种情况的产生呢?
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)
- }
- }
如果你使用的是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 的报错。可以算作一个优化前端交互体验的加分点。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。