1

Assume the following:

// Tx1
const realCall = await contract.callMain(secondAddress, num);
const waited = await realCall.wait();
console.log(waited.gasUsed.toString(), ' gas used')

it prints: "55834 gas used".

Now, assume the following:

// Tx2
const realCall = await contract.callMain(secondAddress, num, {gasLimit: 72000});
const waited = await realCall.wait();
console.log(waited.gasUsed.toString(), ' gas used')

Now, it prints: "58193 gas Used"

I clearly don't understand how gasLimit argument caused such difference.

Note that I'm 100% sure of the followings:

  1. The exact code of solidity is run in both transactions.
  2. The state in the smart contract are the same.

Would appreciate what's going on. I thought that gasUsed is calculated by summing up the costs for each opcode and so on. how does gasLimit cause such anomaly ?

Even if I run Tx1 multiple times, it prints the same gasUsed. So all good till now. It's gasLimit definitely that makes things confusing.

I'm testing this on Goerli from ethers.js and provider is infura.

Update

I am adding a source code via gist link

1 Answer 1

0

Without seeing the contract you're calling, it's hard to tell you exactly what is causing this.

However, one thing I would like to point out in your assumptions is:

  1. The state of the smart contract are the same

Is technically correct, but you are missing something. Contracts have access to the GAS opcode, which gives the remaining gas available to current execution. This means that, while the state of the contract itself is the same, the state that they can access (GAS, in this case) is different. Contracts can do different things depending on how much gas is available to them. I can't say for sure without seeing the contract in question, but this highlights that differing gas limits can affect the gas usage of a contract execution

1
  • Thanks so much for answering. 1) I added gist link for the code. 2) I understand go-ethereum code, even though different gas limits are passed to EVM, the opcode calculation still should result in the same number. In the end, gasUsed that go ethereum returns is initialGas - remainingGas. Take a look at this - gasLimit is passed to this function which reduces and reduces by each opcode. It all suggests that gasUsed must be the same. If not, where does it go wrong ?
    – Neo
    Feb 14 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.