Escuta de eventos
Inscreva-se em registros
Escuta de eventos é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Escuta de eventos” é grátis?
Sim — o texto completo de “Escuta de eventos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
O que vou aprender em “Escuta de eventos”?
Inscreva-se em registros Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?
Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Escuta de eventos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?
Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.