Gas Costs – Can a Transaction’s Gas Cost Change?

gasout-of-gas

I encountered a strange issue on Ropsten Testnet. I deployed a payable contract successfully and tried to send ethers to it. I didn't know how much gas it required, so I gradually increased gasLimit. After a few "out of gas" errors, I finally made a successful call.

I inspected the successful transaction on etherscan.io and noted down the Gas Used By Transaction field, let's say it was 30,123. Then I tried to send the exact same transaction (with 31,000 gas to be safe), and I was very surprised that this new call also failed with "out of gas", i.e. it consumed all of the 31,000 gas..

-How- can the same transaction require different amounts of gas? Is it up to the miner? It shouldn't be.

If relevant, my transaction does not change anything inside the contract. The contract just takes the money and sends it back to the sender, i.e. contract myContract{ function () payable { msg.sender.send(msg.value); } } But -I think- even if it did change something, the gas cost should remain constant. It should only depend on the contract code, and not the state, right?

Thanks for any help,

Update

I kept trying (and failing), until I increased gasLimit like crazy, up to 50,000 and it worked again! with the exact same 30,123 gas used. This makes sense, but it's still curious why it didn't work before, with more than enough amounts of gas.

Update 2

I created the contract with this source code:

contract c{ function () payable { msg.sender.send(msg.value); } }

I compiled it with Solidity and deployed here, and tried to send 1 wei (which it will send back to me), here are my trials:

  1. With 50,000 gas, success! It used 28,520 of it. You can see it here.
  2. With 28,521 gas, fail.. It's here
  3. It also failed with 30,000 gas, here.

Feel free to send your test ethers to it, if you want to try. Don't worry, it won't keep them 🙂

Best Answer

Can a transaction's gas cost change?

Yes.

Is it up to the miner? It shouldn't be.

By incorporating your transaction into a block, the miners are providing a service, which means you're taking part in a market.

The explanation of gasPrice in this previous answer helps illustrate this. (In short, miners will optimise the gasPrice for their revenue.)

This further previous question might also be useful in explaining why gas estimates can be inaccurate, though it's perhaps less useful if you're certain nothing is changing in your contract: What are the limitations to estimateGas and when would its estimate be considerably wrong?

Related Topic