Events in Smart Contracts

Learn how to define and use events in Solidity.

In the final lesson, we'll learn about events in Solidity. Events allow notifying Ethereum users in real time about changes with a smart contract. We'll learn how to define events, send them, and subscribe to them programmatically.

Defining events

Before sending an event, we need to define what fields an event contains. Defining an event is similar to defining a struct. We need to use the event keyword, specify the event’s name, and then provide a list of fields each event will have. Event fields provide additional data we can send with each event.

Press + to interact
contract NameService {
event NewNameRegistered(
address targetAddress
);
// The rest of the code
...
}

To send an event from a smart contract, we need to use the emit keyword, specify the name of the event we want to emit, and provide values for each field.

Press + to interact
function registerName(string name, address target) public {
emit NewNameRegistered(target)
}
...