Ascolto degli eventi
Sottoscriversi ai log
Ascolto degli eventi è una lezione Web3 & DApp Development Fundamentals gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Web3 & DApp Development Fundamentals, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
What Are Events
Smart contracts emit events to log that something happened — a transfer, an approval, a vote. Events are written to the transaction's logs.
- They are cheaper than storage.
- Off-chain apps subscribe to them to stay in sync.
Events in the ABI
To decode events, ethers needs their definitions in the ABI:
const abi = [
"event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);The indexed keyword marks fields you can filter on.
const abi = [
"event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);Listening Live
Subscribe to new events with on. The callback fires whenever the event is emitted:
contract.on("Transfer", (from, to, value, event) => {
console.log(from, "->", to, value);
});This needs a provider that supports subscriptions, such as a WebSocket connection.
contract.on("Transfer", (from, to, value, event) => {
console.log(from, "->", to, value);
});WebSocket Providers
Live subscriptions work best over a persistent connection. Use a WebSocket provider:
const provider = new ethers.WebSocketProvider(
"wss://mainnet.example-rpc.io/KEY"
);HTTP providers can poll for events but a WebSocket pushes them in real time.
const provider = new ethers.WebSocketProvider(
"wss://mainnet.example-rpc.io/KEY"
);Listening Once
If you only care about the first occurrence, use once:
contract.once("Approval", (owner, spender, value) => {
console.log("First approval seen");
});The listener automatically removes itself after firing a single time.
contract.once("Approval", (owner, spender, value) => {
console.log("First approval seen");
});Querying Past Events
To read historical events, use queryFilter over a block range:
const logs = await contract.queryFilter(
"Transfer",
19000000,
19000100
);
for (const log of logs) {
console.log(log.args.from, log.args.value);
}Each log exposes decoded args.
const logs = await contract.queryFilter(
"Transfer",
19000000,
19000100
);
for (const log of logs) {
console.log(log.args.from, log.args.value);
}Filtering by Indexed Fields
Build a filter to match specific indexed values — for example transfers to one address:
const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);Passing null means match any value for that position.
const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);Live Filtered Listening
You can also pass a filter to on to react only to relevant events:
const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
console.log("Received:", value);
});This avoids processing events you do not care about.
const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
console.log("Received:", value);
});Removing Listeners
Long-running apps should clean up listeners to avoid leaks:
contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");Always remove listeners when a component unmounts or a job finishes.
contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");Handling Reorgs
Recent events can be reverted if the chain reorganizes. For reliable indexing:
- Wait several confirmations before treating an event as final.
- Track the block number and re-process if a reorg is detected.
This keeps your off-chain database consistent with the chain.
Provider-Level Log Filters
You can also subscribe at the provider level without a contract instance, using a raw log filter by topic:
provider.on({
address: tokenAddress,
topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
console.log("Raw log:", log);
});This is lower-level but works across many contracts at once.
provider.on({
address: tokenAddress,
topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
console.log("Raw log:", log);
});Quick Check
Test your understanding of event handling.
Recap
You learned to work with contract events.
- Events log on-chain activity to transaction logs.
onsubscribes live (best over a WebSocket provider);oncefires a single time.queryFilterreads historical events over a block range.- Build filters from indexed fields; pass
nullto match any. - Remove listeners to avoid leaks and wait for confirmations against reorgs.
Domande Frequenti
La lezione «Ascolto degli eventi» è gratuita?
Sì — il testo completo di «Ascolto degli eventi» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Web3 & DApp Development Fundamentals, passa a CoddyKit PRO. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.
Cosa imparerò in «Ascolto degli eventi»?
Sottoscriversi ai log Eserciti Web3 & DApp Development Fundamentals con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Web3 & DApp Development Fundamentals?
Non è richiesta alcuna esperienza precedente. Web3 & DApp Development Fundamentals su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Ascolto degli eventi»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Web3 & DApp Development Fundamentals?
Sì. Ogni lezione Web3 & DApp Development Fundamentals include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Connessione a un provider
- Lettura dei dati dei contratti
- Invio delle transazioni
- Ascolto degli eventi