Événements et journalisation des données
Apprenez à utiliser les événements pour journaliser des informations sur la blockchain, ce qui permet une surveillance et une indexation efficaces par les applications externes.
Événements et journalisation des données est une leçon Blockchain Smart Contracts with Solidity gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Blockchain Smart Contracts with Solidity, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
What are Solidity Events?
Smart contracts often need to communicate with the outside world. This is where events come in!
Events are a special feature in Solidity that allow your smart contracts to publish information to the blockchain log.
Think of them as notifications that external applications can listen for.
The Power of Event Logs
Events are crucial because directly reading contract state from off-chain applications can be inefficient and costly.
- Cost-Effective: Storing data in events is cheaper than storing it in contract state.
- Indexable History: They provide a historical record of actions, easily searchable by off-chain tools.
- Monitoring: Wallets, explorers, and dApps can "subscribe" to events to react to changes.
Defining Your First Event
Declaring an event is similar to defining a function, but you use the event keyword.
You specify a name for the event and a list of parameters it will carry, just like function arguments.
These parameters define the data that will be logged when the event is emitted.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EventExample {
// Declares an event named 'LogMessage'
// It takes a string and a number as parameters
event LogMessage(string message, uint256 timestamp);
}Triggering an Event
Once an event is declared, you can "trigger" it using the emit keyword within any function of your contract.
When emit is called, the event's data is recorded in the transaction's log, but not directly in the contract's storage.
This makes events a lightweight way to signal information.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EventExample {
event LogMessage(string message, uint256 timestamp);
function doSomethingAndLog(string memory _msg) public {
// Emits the LogMessage event
// current timestamp is block.timestamp
emit LogMessage(_msg, block.timestamp);
}
}Making Events Searchable
You can add the indexed keyword to up to three event parameters. This makes them searchable and filterable by off-chain applications.
indexedparameters: Stored in a special part of the log called "topics."- Non-
indexedparameters: Stored in the "data" part of the log. - Benefit: Off-chain tools can quickly find transactions related to specific indexed values.
Event with Indexed Parameters
Let's see how to declare and emit an event with an indexed parameter.
Notice how `sender` is marked `indexed`, making it easy to filter for all events from a specific address.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract IndexedEventExample {
event Transfer(address indexed from, address indexed to, uint256 amount);
function transferTokens(address _to, uint256 _amount) public {
// Imagine some transfer logic here
// Then emit the event
emit Transfer(msg.sender, _to, _amount);
}
}Logs are Not State
It's important to understand that event logs are not stored within the contract's state.
- State: Data stored directly in the contract, readable by other contracts and functions. Expensive.
- Logs: Part of the blockchain's transaction receipts. They are immutable and persistent, but not directly accessible by other contracts. Cheaper.
Events are primarily for off-chain consumption.
Practical Event Applications
Events are used everywhere in smart contracts. Here are some common applications:
- Token Transfers: ERC-20 and ERC-721 standards heavily rely on `Transfer` and `Approval` events.
- Ownership Changes: Notifying when a contract's owner is updated.
- Data Updates: Signalling when important contract variables have changed.
- User Interface Feedback: DApps listen for events to update UI in real-time.
Off-Chain Interaction
While Solidity contracts can't directly read events, off-chain applications (like web dApps) use web3 libraries (e.g., Web3.js, Ethers.js) to:
- Filter Past Events: Query historical blockchain data for specific events.
- Subscribe to New Events: Listen for events as they are emitted in real-time.
This enables powerful, responsive decentralized applications.
Event Concepts Check
Consider the following Solidity event declaration:
event UserRegistered(
address indexed userAddress,
string userName,
uint256 indexed registrationTime
);
Which parameters are indexed and therefore easily searchable by off-chain tools?
Recap: Events & Logging
You've learned about the power of events in Solidity!
- Events are emitted by contracts to log data on the blockchain.
- They are crucial for off-chain monitoring, indexing, and dApp interaction.
- Use the `event` keyword to declare and `emit` to trigger them.
- `indexed` parameters make events easily searchable.
This mechanism is vital for building responsive and data-driven decentralized applications.
Questions Fréquemment Posées
La leçon « Événements et journalisation des données » est-elle gratuite ?
Oui — le texte complet de « Événements et journalisation des données » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Blockchain Smart Contracts with Solidity, passe à CoddyKit PRO. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Événements et journalisation des données » ?
Apprenez à utiliser les événements pour journaliser des informations sur la blockchain, ce qui permet une surveillance et une indexation efficaces par les applications externes. Tu pratiques Blockchain Smart Contracts with Solidity avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Blockchain Smart Contracts with Solidity ?
Aucune expérience préalable n'est requise. Blockchain Smart Contracts with Solidity sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Événements et journalisation des données » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Blockchain Smart Contracts with Solidity ?
Oui. Chaque leçon Blockchain Smart Contracts with Solidity inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Variables d’état et organisation du stockage
- Mappings et tableaux dynamiques
- Événements et journalisation des données
- Emplacements de stockage et optimisation du gas