How to avoid transaction fail when the front-end calls the contract

Preface: As a developer, you must have experienced that the gas fee exceeded the limit when calling the contract, but you don't know what error was reported. At this time, the require error contract verification is usually triggered. For users, he does not understand why a transaction costs such a large amount of gas, so how can we as developers try to avoid this situation?

 

一、static call

        ethersJS V5 docs are clearer than V6. Let's go directly to the official documentation to explain:

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.

         We can see that this is a state change that does not execute a transaction, but instead requires the node to pretend to call without a state change and return a result. This doesn't actually change any state, and is free. In some cases, this can be used to determine whether a transaction failed or succeeded. Simply give an example:

// 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 document address

        ethers V6 document address

Two, wagmi library 

        If you are using the wagmi library, it has already encapsulated the calling method for us. give a chestnut

import { prepareWriteContract } from '@wagmi/core'


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

Summarize

        Through the above method, the user can greatly avoid the error of triggering transcatin expected to fail. It can be counted as a bonus point for optimizing the front-end interactive experience.

Guess you like

Origin blog.csdn.net/qq_31915745/article/details/131997405