In this short tutorial, I would like to show you the basics of events in Solidity. Specifically, I will explain what are the events in solidity and how to use them in our smart contract.
Following the Solidity documentation:
“Events are inheritable members of contracts. When you call them, they cause the arguments to be stored in the transaction’s log — a special data structure in the blockchain. These logs are associated with the address of the contract, are incorporated into the blockchain, and stay there as long as a block is accessible”
Events are used to inform external users that something happened on the blockchain. Smart contracts themselves cannot listen to any events.
All information in the blockchain is public and any actions can be found by looking into the transactions close enough but events are a shortcut to ease the development of outside systems in cooperation with smart contracts.
Solidity defines events with the event keyword. After events are called, their arguments are placed in the blockchain. To use events first, you need to declare them in the following way:
event moneySent(address _from, address _to, uint _amount);
The definition of the event contains the name of the event and the parameters you want to save when you trigger the event.
Then you need to emit your event within the function:
emit moneySent(msg.sender, _to, _amount);
Solidity events are interfaces with Ethereum Virtual Machine logging functionality. You can add an attribute indexed to up to three parameters. When parameters do not have the indexed attribute, they are ABI-encoded into the data portion of the log.
To better understand the event let’s see the full code.
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract MyContract{
mapping(address => uint) public Balance;
event moneySent(address _from, address _to, uint _amount);
constructor public {
owner = msg.sender;
moneyBalance[msg.sender] = 50;
}
function sendMoney(address _to, uint _amount) public returns(bool) {
require(msg.sender = owner; "You are not allowe");
require(Balance[msg.sender] >= _amount; "Not enough money");
moneyBalance[msg.sender] -= _amount;
moneyBalance[_to] += _amount;
emit moneySent(msg.sender, _to, _amount);
return true;
}