Search code examples
ethereumsolidityweb3jsgo-ethereum

Why does my Ethereum transaction cost 21000 more gas than I expect?


Somehow I am getting insanely high gas costs compared to what I think I should be seeing.

I have a function in solidity:

function setMessage(uint8[] _fMessage) public returns (uint256){
    emit Message(_fMessage);
}

And my event:

 event Message(uint8[] message);

When I call it using this: EthProj.setMessage.sendTransaction([72, 193, 77], {from: my address})

where EthProj is my contract, this is using up 25027 gas.

When I run eth.getTransactionReceipt with the transactionHash of my transaction it says: gasUsed: 25027.

According to this: https://github.com/djrtwo/evm-opcode-gas-costs/blob/master/opcode-gas-costs_EIP-150_revision-1e18248_2017-04-12.csv, more specificially this part: LOG0 375 + 8 * (number of bytes in log data) it should only cost about 400 gas as there are only 3 bytes in the event.

Where is this massive cost coming from?


Solution

  • Every transaction has an immediate 21000 intrinsic gas cost. From the Ethereum documentation:

    21000 gas is charged for any transaction as a "base fee". This covers the cost of an elliptic curve operation to recover the sender address from the signature as well as the disk and bandwidth space of storing the transaction.

    From there, every opcode executed consumes gas. This includes things like reading state, returning a value, emitting an event, etc. The calculation you're referring to is only for the portion where the event data is written out to state.

    For a more thorough explanation of how much gas a transaction will consume, look at the opcode gas spreadsheet (this version is from the initial launch, but I haven't seen an updated one yet). You can also look at this write-up on transaction costs.