Events
More about Solidity
Throughout this course, we have seen smart contract data stored in two places:
- State Variables (i.e. in storage)
- Function Bodies (i.e. in memory)
Let's now look at the advantages and disadvantages of each data location:
-Storage: this data location is persistent between transactions and so we don't have to worry about state variables being lost. However, reading and writing to storage is computationally expensive and therefore, requires a substantial amount of gas to perform. -Memory: this data location is not persistent between transactions; therefore, values that you write in memory in one transaction will be lost after the transaction is finished executing. However, reading and writing to storage is computationally cheap and therefore, requires little gas.
This brings up a good question: what if we wanted to permanently store data (and lets assume that this data is immutable) on the blockchain without having to use state variables? This leads us to the topic of this section: events.
Defining Events
Events are data structures that we can then "emit." We first examine the syntax for defining events:
The definition of an event goes in the body of a smart contract (but never within a function body). Below is a simple example of an event definition:
Emitting Events
Now that we understand how to define events, we will now explore how to emit an instance of an event. Consider the following function:
To emit the transfer event we defined earlier, we implement the following:
where the arguments of the Transfer event are arbitrary.