Solidity Events Explained

Kaan Kaçar
Coinmonks
4 min readMay 19, 2023

--

As a junior developer, one of the fundamental concepts you’ll encounter is events and emits in Solidity. Events play a crucial role in creating transparent and auditable smart contracts by providing a way to communicate and record important information on the blockchain. In this guide, we will explore events and emits in Solidity, their significance, and how to effectively use them in your smart contract journey.

In Solidity, events are a way to log and notify external entities (such as user interfaces or other smart contracts) about specific occurrences within a smart contract. They serve as a mechanism for emitting and recording data onto the blockchain, making it transparent and easily accessible. Emits, on the other hand, are used to trigger or emit events within the smart contract code.

Events are similar to logs or records that capture important information, allowing external observers to react to them and obtain relevant data. They are stored on the blockchain as part of the transaction history and can be retrieved even after the transaction is complete.

Why Use Events?

To me, the most important aspect of events is gas efficiency. Emitting events is a gas-efficient way to store and communicate information on the blockchain. Events consume less gas compared to updating storage variables.

But also, vvents facilitate off-chain analysis of smart contract activities. External tools can monitor events, analyze data, and provide valuable insights without interacting directly with the blockchain.

Defining and Emitting Events:

a. Event Declaration:

To define an event, you need to declare it within the contract. An event declaration consists of the event’s name, a list of parameters (if any), and their data types. Here’s an example:

contract MyContract {
event NewTransaction(uint indexed transactionId, address sender, uint amount);

// Rest of the contract code...
}

In this example, we define an event named “NewTransaction” that takes three parameters: transactionId (an unsigned integer), sender (an Ethereum address), and amount (an unsigned integer).

b. Emitting Events:

To emit an event within the contract, you use the emit keyword followed by the event name and any necessary parameters. Here's an example of emitting the NewTransaction event:

function performTransaction(address _receiver, uint _amount) public {
// Perform the transaction logic...

emit NewTransaction(transactionId, msg.sender, _amount);

// Rest of the function code...
}

In this example, we emit the NewTransaction event with the values of transactionId, msg.sender (the address of the caller), and _amount.

Event Log and Retrieval:

a. Event Structure and Data:

When an event is emitted, it generates an event log that is stored on the blockchain. The event log contains the event’s name, the values of its parameters, and additional metadata such as the block number and transaction hash. This structure allows events to be indexed and easily searchable.

b. Retrieving Events:

To retrieve events, you can utilize the Ethereum blockchain’s APIs or libraries such as Web3.js. The process involves specifying the contract address and the event’s signature, which is derived from the event’s name and parameter types.

Here’s an example of how to retrieve events using Web3.js:

const contract = new web3.eth.Contract(abi, contractAddress);
contract.getPastEvents('NewTransaction', {
filter: { sender: '0x123abc' }, // Optional event filtering
fromBlock: 0, // Start block number
toBlock: 'latest' // End block number
})
.then(function(events) {
// Process the retrieved events
console.log(events);
})
.catch(function(error) {
// Handle errors
console.error(error);
});

In this example, we use the getPastEvents method to retrieve past events named 'NewTransaction' emitted by the specified contract address. We can also provide optional filters, such as filtering events based on the sender's address. The retrieved events are then available for further processing and analysis.

Filtering and Subscribing to Events:

a. Event Filters:

Event filters allow you to specify conditions for retrieving specific events based on their parameters. This filtering capability is particularly useful when dealing with a large number of events or when you are interested in specific subsets of events.

Continuing from the previous example, let’s consider adding a filter based on the transaction amount:

contract.getPastEvents('NewTransaction', {
filter: { sender: '0x123abc', amount: 100 }, // Filter by sender and amount
fromBlock: 0,
toBlock: 'latest'
})
.then(function(events) {
// Process the filtered events
console.log(events);
})
.catch(function(error) {
// Handle errors
console.error(error);
});

In this updated example, we include an additional filter condition amount: 100, which filters the events emitted by '0x123abc' and have an amount value of 100.

b. Event Subscriptions:

Besides retrieving past events, you can also subscribe to events in real-time using event subscriptions. Event subscriptions enable your application to listen for and react to events as they occur, providing a dynamic and interactive user experience.

Here’s an example of subscribing to events using Web3.js:

contract.events.NewTransaction()
.on('data', function(event) {
// Handle the received event data
console.log(event);
})
.on('error', function(error) {
// Handle errors
console.error(error);
});

In this example, we subscribe to the ‘NewTransaction’ event and handle the received event data in the data callback. Any time the event is emitted, the callback function will be triggered, allowing you to perform actions or update the user interface accordingly.

You can use events, for example, in a decentralized exchange. Events are commonly used in decentralized exchanges to notify users about order placements, trade executions, and liquidity pool changes.

Final Words:

Events serve as a communication mechanism for smart contracts, allowing transparent recording and retrieval of important information on the blockchain. You can use them in your decentralized exchanges, payment systems, supply chain management projects etc. possibilities are endless. Event away my friends.

If you found this article informative and helpful, please consider following me for more blockchain and cryptocurrency-related content. You can also subscribe to my email list to receive updates on my latest articles and projects.

--

--