Events in Solidity: A Beginner's Guide
Tags: solidity, webdev, ethereum, beginners
Published: 2023-01-18 04:32:48

Blockchain technology has the potential to revolutionize a wide range of industries, and the Ethereum blockchain is one of the most popular platforms for building decentralized applications (dApps). One of the key features of Ethereum is the ability for smart contracts to interact with one another and with external clients through the use of events.

In this post, we'll take a look at what _events_ are in the context of smart contract development, and how they can be used to create powerful dApps.

## So, what are events in Solidity? 

> In simple terms, events are a way for smart contracts to emit log statements that are stored on the blockchain. They can be used to notify external clients or other contracts of changes or actions taken within a contract.

Events are defined using the "event" keyword, and can include any number of parameters of various types. They can be emitted using the "emit" keyword within a contract's function. When an event is emitted, it creates a log entry on the blockchain that includes the event's name and its associated parameters.

For example, let's say we have a smart contract for a virtual lemonade stand. Every time someone buys a cup of lemonade, we want to keep track of how many cups have been sold. We can use an event to log this information.

```
event CupSold(uint cupsSold);
```

Every time a customer buys a cup of lemonade, we would increment a variable to keep track of the total number of cups sold and then "emit" the event, like this:

```
function buyLemonade() public {
    cupsSold++;
    emit CupSold(cupsSold);
}
```

This would create a log that says a cup was sold and includes the total number of cups sold up until that point. This information can be accessed by anyone who has a copy of the contract's code and can be used to track the success of the lemonade stand.

Another example is for a virtual auction house, Every time an item is sold, we want to notify the seller that their item has been sold and notify the buyer that they have won the auction.

```
event ItemSold(address seller, address buyer, uint price);
event AuctionWon(address buyer, uint price);
```

Every time an auction ends and an item is sold, we would "emit" the two events, like this:

```
function auctionEnd(address winner, uint finalPrice) public {
    emit ItemSold(msg.sender, winner, finalPrice);
    emit AuctionWon(winner, finalPrice);
}
```

This would create two logs, one log that says an item was sold and includes the address of the seller, the address of the buyer, and the final price. And the other log will state that the auction was won by the buyer and the price that the item was sold for.

These logs can be accessed by external clients or other contracts through **_web3.js_** or **_ether.js_**, or other tools like **_Truffle_** and **_Hardhat_**. They allow you to listen and filter events emitted by a smart contract and retrieve the events from the blockchain.

As a blockchain developer, it is important to understand how to use events effectively in your smart contract development. The key thing to **keep in mind **is that :

- Events are a way to create a log of important actions or data changes within a smart contract that can be stored on the blockchain and accessed by external clients or other contracts.
- When designing an event, it is important to consider what information you want to include in the log entry, as well as how that information will be used by external clients or other contracts. You should also consider the privacy and security implications of the information you are logging.
- One thing to keep in mind is that events are stored on the blockchain and can be accessed by anyone. This means that if you are logging sensitive information, you should take steps to ensure that it is properly encrypted or hashed.
- Another important thing to keep in mind is that events are not the same as function calls. While function calls allow smart contracts to interact with one another, events are used to create log entries that can be accessed by external clients.
- It's also important to note that events can be listened to, which means that external clients or other contracts can react to specific events. For example, an external client could listen for the "CupSold" event and use the information provided in the log entry to update a visual representation of the lemonade stand's sales or trigger some action.

## Now how to read these emitted events
There are several ways to read emitted events from a smart contract. One common way is to use a client like web3.js or ether.js, which is a JavaScript library that allows you to interact with the Ethereum blockchain.

- web3.js way
Once you have web3.js set up and connected to the Ethereum network, you can use the "web3.eth.getPastEvents" method to retrieve past events from a contract. The method takes in the contract address, the event name, and an options object as arguments.

For example, to retrieve all past "CupSold" events from the lemonade contract, you could use the following code:

```
const lemonadeContract = new web3.eth.Contract(lemonadeABI, lemonadeAddress);
lemonadeContract.getPastEvents("CupSold", {
    fromBlock: 0,
    toBlock: "latest"
}, (error, events) => {
    console.log(events);
});
```

This will return an array of objects, each object representing a past "CupSold" event, including the block number, transaction hash, and the values of the event's parameters.

Another common way to read emitted events is by using a tool such as an Ethereum block explorer, which allows you to search for and view contract events on the blockchain without having to write any code.

You can also use tools like Truffle which is a development environment, testing framework and asset pipeline for Ethereum, that allows you to listen to events emitted by your smart contract with their built-in event emitter, Truffle emits.

- Ether.js way
Ether.js is a JavaScript library similar to web3.js that allows you to interact with the Ethereum blockchain. It can be used to read events emitted by smart contracts in a similar way to web3.js.

Here's an example of how you could use Ether.js to retrieve all past "CupSold" events from the lemonade contract:

```
const ethers = require('ethers');
const provider = new ethers.providers.JsonRpcProvider();

const contract = new ethers.Contract(lemonadeAddress, lemonadeABI, provider);
contract.on("CupSold", (seller, buyer, price) => {
    console.log(`A cup of lemonade was sold for ${price} by ${seller} to ${buyer}`);
});
```

This will log a message to the console every time a "CupSold" event is emitted by the lemonade contract.

You can also use the contract.queryFilter() function to get all events that match certain criteria.

```
const filter = contract.queryFilter("CupSold", {
    fromBlock: 0,
    toBlock: "latest"
});
filter.then((events) => {
    console.log(events)
});
```

This will return an array of objects, each object representing a past "CupSold" event, including the block number, transaction hash, and the values of the event's parameters.

In summary, you can use web3.js or Ether.js to read events emitted by a smart contract. Both libraries allow you to filter the events by block number and retrieve the events by event name. The main difference is the syntax, but the idea is the same, retrieve events emitted by a smart contract.

It's also important to note that, both web3.js and Ether.js allows you to listen to events, so you can trigger an action when the event is emitted. This can be useful for creating dapps that respond to events in real-time.