Escucha de eventos
Suscribirse a registros
Escucha de eventos es una lección gratuita de Web3 & DApp Development Fundamentals en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web3 & DApp Development Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «Escucha de eventos» es gratis?
Sí — el texto completo de «Escucha de eventos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web3 & DApp Development Fundamentals, actualiza a CoddyKit PRO. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
¿Qué aprenderé en «Escucha de eventos»?
Suscribirse a registros Practicas Web3 & DApp Development Fundamentals con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Web3 & DApp Development Fundamentals?
No se requiere experiencia previa. Web3 & DApp Development Fundamentals en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Escucha de eventos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Web3 & DApp Development Fundamentals?
Sí. Cada lección de Web3 & DApp Development Fundamentals incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.