Events in Solidity.
**Events are the way Solidity **and the EVM provides developers with logging functionality used to write information to a data structure on the blockchain that lives outside of smart contracts’ storage variables.
Events are an abstraction on top of the EVM’s low-level logging functionality, opcodes LOG0 to LOG4. The specific opcode used will depend on the number of topics the event declares using the indexed keyword. A topic is just a variable that we want to be included in the event and tells Solidity we want to be able to filter on the variable as well.
The low-level logs are stored in the transaction receipt of the transaction under the transaction receipts trie. Logs are written by the smart contract when the contract emits events, but these logs cannot be ready by the smart contract. The inaccessibility of the logs allows developers to store data on-chain that is more searchable and gas efficient than saving data to the smart contract’s storage variables.
Events are defined in smart contracts using the event keyword. Here is the transfer event from the ERC20 smart contract. It is emitted whenever tokens are transferred from 1 account to another.
Here we can see the different components of an event:
the event's name Transfer
the event's topics from (sender's address), to (the receiver's address), value (the amount transferred).
if a variable in the event is not marked as indexed it will be included when the event is emitted, but code listening on the event will not be ablel to filter on non-indexed varables (aka topics).
Whenever a Transfer event is emitted, the from, to and value data will be contained in the event.
Emiting Events
Once an event has been defined we can emit the event from the smart contract. Continuing on from the ERC20 smart contract let's see where the Transfer event is emitted.
Listening to Events
If you remember the definition of an Event from above, smart contracts can write events, but not read events. So how do we listen/read to data that smart contracts cannot read?
We listen to and read events from code connected to a provider. From what we've learned so far in this course we could do this in JS code using an ethers provider to connect to a contract and listen to transfer events and do something with the event data.
Top comments (0)