How much gas does it cost to emit an event?
Is there a formula for calculating how much gas the emission of an event will cost given that its parameters sum up to n bytes of data?
Any info or estimates are useful,
Thanks :)
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityFirst, the parameters are:
LogDataGas uint64 = 8 // Per byte in a LOG* operation's data.
LogGas uint64 = 375 // Per LOG* operation.
LogTopicGas uint64 = 375
MemoryGas uint64 = 3
https://github.com/ethereum/go-ethereum/blob/master/params/protocol_params.go
Then, the formula is the following:
gas = static gas + dynamic gas
dynamic gas = cost of memory gas + cost of log gas
Static gas for makeLog
is 375, memory gas is 3
The dynamic gas is calculated as:
func makeGasLog(n uint64) gasFunc {
return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
requestedSize, overflow := stack.Back(1).Uint64WithOverflow()
if overflow {
return 0, ErrGasUintOverflow
}
gas, err := memoryGasCost(mem, memorySize)
if err != nil {
return 0, err
}
if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow {
return 0, ErrGasUintOverflow
}
if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow {
return 0, ErrGasUintOverflow
}
var memorySizeGas uint64
if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow {
return 0, ErrGasUintOverflow
}
if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow {
return 0, ErrGasUintOverflow
}
return gas, nil
}
}
For example if you have 2 topics + 200 bytes of log.Data
the cost will be:
375 (static cost)
200 = 200 bytes of memory for log.Data x 3 cost of memory = 600 gas for memory gas
2 x 375 = 750 for topic gas
8 x 200 = 1600 for log.Data cost
Total cost: 375 + 600 + 750 + 1600
= 3,325
gas units
2 topics in this example means topics0 and topics1 , since the topic0 is used for index of the signature of the event, for your practical use there is only topic1 left to store something useful , like an address or hash.
Let's use the following sample contract to see how much gas it costs to emit an empty event:
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21;
contract Foo {
event MyEvent();
function emitMyEvent() external returns (uint256 gasCost) {
uint256 initialGas = gasleft();
emit MyEvent();
gasCost = initialGas - gasleft();
}
}
Configuration:
The result is 784 gas: