Listening to events on frontend in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When a frontend listens to blockchain events, it waits for updates from the network. Understanding how the time to process these events grows helps us build smooth user experiences.
We want to know how the work changes as more events come in.
Analyze the time complexity of the following code snippet.
const contract = new ethers.Contract(address, abi, provider);
contract.on('Transfer', (from, to, amount) => {
console.log(`Transfer from ${from} to ${to} of ${amount}`);
updateUI(from, to, amount);
});
This code listens for 'Transfer' events from a blockchain contract and updates the frontend each time an event happens.
- Primary operation: The event handler runs every time a 'Transfer' event is emitted.
- How many times: Once per event, which depends on how many transfers occur on the blockchain.
Each new event triggers the handler once, so the total work grows with the number of events.
| Input Size (n events) | Approx. Operations |
|---|---|
| 10 | 10 event handler calls |
| 100 | 100 event handler calls |
| 1000 | 1000 event handler calls |
Pattern observation: The work grows directly with the number of events received.
Time Complexity: O(n)
This means the time to process events grows linearly with the number of events received.
[X] Wrong: "The event listener runs once and handles all events at once."
[OK] Correct: Each event triggers the handler separately, so the total work adds up with more events.
Understanding how event listeners scale helps you build responsive apps that handle real-time blockchain data smoothly. This skill shows you can manage asynchronous data efficiently.
"What if the event handler also loops through a list of transactions each time it runs? How would the time complexity change?"
Practice
Solution
Step 1: Understand what events represent
Events are signals emitted by smart contracts when something important happens.Step 2: Connect event listening to frontend behavior
Listening to these events lets the frontend update immediately without waiting for manual refresh.Final Answer:
To react instantly to changes happening on the blockchain -> Option CQuick Check:
Listening to events = instant frontend updates [OK]
- Confusing event listening with sending transactions
- Thinking events compile contracts
- Believing events mine blocks
Transfer using ethers.js?Solution
Step 1: Recall ethers.js event listening syntax
In ethers.js, the method to listen to events ison.Step 2: Match the correct method with parameters
The correct syntax iscontract.on(eventName, callback).Final Answer:
contract.on('Transfer', (from, to, amount) => { console.log(from, to, amount); }); -> Option DQuick Check:
ethers.js uses .on() for events [OK]
- Using .listen() which does not exist in ethers.js
- Using .addEventListener() which is DOM method, not ethers.js
- Using .subscribe() which is not ethers.js syntax
Deposit event is emitted with arguments user='0x123' and amount=100?
contract.on('Deposit', (user, amount) => {
console.log(`User ${user} deposited ${amount} tokens`);
});Solution
Step 1: Understand event callback parameters
The callback receives event arguments in order: user and amount.Step 2: Check the console.log output format
The template string inserts user and amount correctly into the message.Final Answer:
User 0x123 deposited 100 tokens -> Option BQuick Check:
Event args used correctly = correct message [OK]
- Assuming parameters are undefined if not destructured
- Confusing objects with strings in output
- Expecting syntax errors from correct code
contract.on('Approval', (owner, spender, value) => {
console.log(owner, spender, value);
});
// Later in the code
contract.off('Approval');Solution
Step 1: Understand how to remove event listeners in ethers.js
To remove a listener, you must pass the exact callback function used when adding it.Step 2: Check the code's
The code callsoffusagecontract.off('Approval')without the callback, so it won't remove the listener.Final Answer:
Theoffmethod requires the same callback function to remove the listener -> Option AQuick Check:
Remove listener = same callback needed [OK]
- Calling .off() without callback removes nothing
- Changing event name case incorrectly
- Thinking callback must be async
MessageSent event on your frontend and update the UI only for messages sent by the current user. Which approach correctly filters events before updating the UI?Solution
Step 1: Understand event filtering on frontend
ethers.js does not support filtering events by passing filter objects inonmethod directly.Step 2: Use callback logic to filter events
Listen to all events, then check inside the callback if the sender matches the current user before updating UI.Final Answer:
Listen to allMessageSentevents and inside the callback check ifsender === currentUserbefore updating UI -> Option AQuick Check:
Filter inside callback = correct approach [OK]
- Trying to filter events via .on() parameters
- Modifying ABI to filter events (not possible)
- Using .once() which listens only once, not continuously
