Solidity events are a powerful feature that allow you to log and track changes in your smart contracts. They are similar to events in other programming languages and are used to record actions that have occurred on the blockchain.
What are Events?
Events are declared in your smart contract using the event
keyword. They can have parameters, which are the data that is emitted with the event. Here's an example of a simple event declaration:
event MyEvent(string message);
When this event is emitted, it will log a message to the blockchain.
Emitting Events
To emit an event, you use the emit
keyword followed by the event name and the arguments you want to log. For example:
emit MyEvent("This is an event!");
Using Events
Events can be used in various ways, such as:
- Auditing: You can use events to keep track of changes to your smart contract and ensure that it behaves as expected.
- Interacting with Front-End: Events can be used to trigger actions in your front-end application when certain conditions are met on the blockchain.
Example
Here's a simple example of a contract that emits an event when a new record is added:
contract MyContract {
struct Record {
string name;
uint256 value;
}
Record[] public records;
event RecordAdded(string name, uint256 value);
function addRecord(string memory _name, uint256 _value) public {
records.push(Record(_name, _value));
emit RecordAdded(_name, _value);
}
}
In this example, when a new record is added, the RecordAdded
event is emitted with the name and value of the new record.
More Information
For more information on Solidity events, check out our comprehensive guide on Solidity Events.