Listening to Events
Subscribe to logs.
Listening to Events is a free Web3 & DApp Development Fundamentals lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Web3 & DApp Development Fundamentals learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Frequently asked questions
Is the “Listening to Events” lesson free?
Yes — the full text of “Listening to Events” is free to read here on the web, and the Web3 & DApp Development Fundamentals course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Web3 & DApp Development Fundamentals course, upgrade to CoddyKit PRO.
What will I learn in “Listening to Events”?
Subscribe to logs. You practise Web3 & DApp Development Fundamentals with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Web3 & DApp Development Fundamentals?
No prior experience is required. Web3 & DApp Development Fundamentals on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Listening to Events” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Web3 & DApp Development Fundamentals lesson?
Yes. Every Web3 & DApp Development Fundamentals lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Connecting to a Provider
- Reading Contract Data
- Sending Transactions
- Listening to Events