Events

Events are a special type of function. Their purpose is to log data on the blockchain and actions that you want to retrieve at a later date. They can be subscribed to to receive an update whenever a new event is generated, almost in real time.

Essentially, you want them to keep a registry of the things that are happening inside your smart contract to later analyze them in order to fix bugs and to understand what happened if you need to read the past in an easy way.

Here's how you declare events inside your smart contract in Solidity:

pragma solidity 0.5.0
contract EventsExample {
event LogUserAddress(address userAddress);
function registerUser() public {
emit LogUserAddress(msg.sender);
}
}

In this example, you can see how an event is declared and emitted. When you declare your event, you have to decide the parameters that it will be able to receive; all of them are always optional, so you can omit them.

When you emit the event inside a function, you must make sure that they are of the right type. In the declaration, you can add a name for each parameter, or you can leave it with just the type, as follows:

event LogUserAddress(address);

It's good practice to name the parameters inside the event, to help others understand the purpose of each of those parameters.

You can also add an optional keyword called indexed. It's a modifier to the parameter of the event that allows you to search past events for that specific event. Think of indexed parameters as searchable entries in a database:

event LogUserAddress(address indexed userAddress);

Note that you must name the parameters that are indexed. Later you'll see how to retrieve those events and search for specific ones with web3.js.