0

I'm using ethers.js to interact with my smart contract and send a transaction. However, when the transaction fails (reverts), I can't access the receipt or the gas used, because ethers.js throws an error before I can capture those details.

Here's the code I'm using to send a transaction:

try { // Attempt to send the transaction to the contract const tx = await signer.sendTransaction(txRequest); // An error is thrown here in case of revert // Wait for the transaction to be mined and get the receipt const receipt = await tx.wait(); totalGasUsed += Number(receipt.gasUsed); } catch (error) { console.log(error); } 

error:

Error: VM Exception while processing transaction: reverted with reason string 'revert message'

Is there a way to get the gas used by a failed (reverted) transaction with ether.js?

1 Answer 1

0

When you use signer.sendTransaction(txRequest), ethers.js internally runs estimateGas() before actually sending the transaction. If the estimation phase detects the call would revert, it never sends the transaction. So, that isn’t a transaction failure on-chain, it’s a pre-flight fail.

You need to override the gas limit manually to force sending the transaction anyway, that you can do by passing the gasLimit field while creating your txRequest object, like:

const txRequest = { to: contractAddress, data: data, gasLimit: 100_000, // manually specify the gas limit, pick a safe value for your tx }; 

Now ethers will not simulate the transaction and just send it, and you can simply log the gasUsed in your catch block using error.receipt.gasUsed, like:

try { const tx = await signer.sendTransaction(txRequest); console.log("Sent Tx:", tx.hash); const receipt = await tx.wait(); // If the tx reverts, this throws console.log("Mined in block:", receipt.blockNumber); // Doesn't get logged if the tx gets reverted } catch (error) { // You will land here if it reverts on-chain console.log("Gas used:", error.receipt.gasUsed); } 
2
  • The thrown error doesn't include a receipt field, so I can't directly access the gas used from the error object. The only workaround is to fetch the latest block and inspect the most recent transaction, but that method isn't always reliable. Commented Apr 24 at 17:24
  • It will include the receipt field once you override the gasLimit. I've tested that on my end for a reverting transaction. Commented Apr 24 at 18:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.