0

I am doing a simple HelloWorld class trying out several things including emitting events. My contract code is below:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract HelloWorld { string public myMessage = "Hello World!";

event MessageReturned( string message );

function setMessage( string memory newMessage ) external {
    myMessage = newMessage;
}

function getMessage() external view returns( string memory ) {
    return myMessage;
}

function sayMessage() external view {
    emit MessageReturned( myMessage );
}

}

I got surprised I got a TypeError when I tried to compile with truffle compile. I received this message form solc:

TypeError: Function cannot be declared as view because this expression (potentially) modifies the state.
  --> project:/contracts/HelloWorld.sol:18:14:
   |
18 |         emit MessageReturned( myMessage );
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Could anyone please help explain to me why emitting an event is treated as a state change here? What goes behind the scenes to cause it to mine?

1 Answers1

0

This answer might clarify it alongside this one.

In essence, transactions receipts (containing the logs) are used to form the Transaction Receipt Trie, which will update the Transaction Receipts Root that is recorded in the header of a block (a new block is essentially an update of the state of the blockchain).

Hence, emitting an event is indeed a state changing operation, so the view / pure visibility modifiers are forbidden. It's not that Events can cause state change, but more that events will cause state change.

hroussille
  • 7,661
  • 2
  • 6
  • 29
  • I see, as I understand the reference above events are actually causing the EVM to log, which is an internal transaction. Thank you @hroussille – CodeCalibre Apr 29 '22 at 11:01