Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Events vs Functions in Solidity

Michael Macaulay
Level Up Coding
Published in
2 min readApr 18, 2021

--

Functions are fundamental to any programming language, serving as reusable pieces of code that can be invoked as required.

In Solidity, functions are capable of reading, modifying, storing, & writing data within a smart contract. Functions can receive arguments (parameters), and if specified, they can also return certain values. Let’s look at a brief example.

function owner() public view returns(address) {
return _owner;
}

This function merely returns the address of the owner. It doesn’t modify any data and thus uses the view keyword. As it is public, anyone can access it. You would call this function when you want to fetch the owner's address.

owner();

Now, let’s discuss events. While they appear similar to functions, they serve different purposes.

Events in Solidity accept arguments and log them within the transaction’s log, a unique data structure within the blockchain. Their primary role is to notify external services about certain occurrences within the blockchain. However, they do not store data; instead, they ‘fire and forget’. The content inside an event is not visible to smart contracts, including the smart contract that triggered the event.

Think of an event as analogous to console.log() in JavaScript.

Apps connected to a node can subscribe to event notifications, allowing them to be alerted about changes without making any changes themselves.

Let’s take a look at an event:

event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);

This event logs three arguments within the transaction’s log: the sender’s address, the receiver’s address, and the token ID. The indexed keyword is used to facilitate searching for data within the transaction's log.

You might emit this event when transferring an ERC721 token from one user to another within your smart contract.

Emitting events resembles calling a function, but there’s a key difference: events use the emit keyword. This distinction informs developers that an event is being invoked, rather than a function.

For example:

emit Transfer(_from, _to, _tokenId)

The emit keyword was introduced in Solidity version 0.4.21 to distinguish event emissions from function calls, enhancing clarity and robustness within the language.

Read more about events in the official Solidity documentation.

--

--

No responses yet

Write a response