Solidity – Why Storing via sstore is More Expensive than via Events Mechanism

eventsgassoliditystorage

I just do not understand why emit Event(...) is cheaper than a = b. The only difference I noted between events and storage variables is that event logs is not accessible from Solidity. But both of them are stored in blockchain and both of them are accessible from external applications. So why have etherium devs made SSTORE so expensive?

Best Answer

emitting Events makes use of a log storage, which as you've noted is a 4th form of contract information that is much cheaper than the other three kinds of accessible from solidity (memory, storage, stack). EVM nodes are not required to keep logs forever and can garbage collect old logs to save space. Dapps listening for these logs cannot rely on them being persisted forever (e.g. really old events), but can probably listen to new events as a means of updating on changes.

My favorite article about EVM events / log storage is here https://blog.qtum.org/how-solidity-events-are-implemented-diving-into-the-ethereum-vm-part-6-30e07b3037b9

Although I don't know the exact rationale of the EVM designers, I would guess they wanted to provide a cheap, but not free, way of storing information from contracts and publishing notification information for outside listeners (not on the blockchain). Free storage would be open to abuse / denial-of-service attacks.

In particular from the article, we can compare the cost of storing in logs versus storing in storage (the choice of names is mildly confusing and regrettable, but what can you do). That would address your question of LOG versus SSTORE opcodes.

Don’t forget the memory used, which is 3 gas per byte:
MemoryGas        uint64 = 3    
Wait what? It costs only 8 gas per byte of log data? That’s 256 gas for 32 bytes, and 96 gas for the memory use. So 322 gas versus 20000 gas for storing the same amount of data in storage, only 1.7% of the cost!
Related Topic