Listening to events lets your webpage know when something important happens on the blockchain. This helps your app update automatically without needing to refresh.
Listening to events (frontend) in Blockchain / Solidity
const contract = new ethers.Contract(contractAddress, contractABI, provider); contract.on('EventName', (param1, param2, event) => { // Your code here to handle the event console.log('Event received:', param1, param2); });
You need the contract address, ABI, and a provider (like MetaMask or Infura) to listen to events.
The callback function receives event parameters and an event object with extra info.
contract.on('Transfer', (from, to, amount, event) => { console.log(`Tokens moved from ${from} to ${to}: ${amount.toString()}`); });
contract.on('Approval', (owner, spender, value, event) => { console.log(`Approval: ${owner} allowed ${spender} to spend ${value.toString()}`); });
// Edge case: No events emitted yet // The listener will wait silently until an event happens. contract.on('NewItem', (itemId) => { console.log(`New item added with ID: ${itemId}`); });
once to listen only to the next event and then stop listening.// Edge case: Only one event emitted contract.once('Sold', (buyer, price) => { console.log(`Item sold to ${buyer} for ${price.toString()}`); });
This program connects to the Ethereum mainnet and listens for Transfer events on a token contract. When a transfer happens, it prints details about who sent tokens, who received them, the amount, and the block number.
import { ethers } from 'ethers'; // Example contract info (replace with real values) const contractAddress = '0x1234567890abcdef1234567890abcdef12345678'; const contractABI = [ 'event Transfer(address indexed from, address indexed to, uint256 value)' ]; async function main() { // Connect to Ethereum mainnet via default provider const provider = ethers.getDefaultProvider('homestead'); // Create contract instance const contract = new ethers.Contract(contractAddress, contractABI, provider); console.log('Listening for Transfer events...'); // Listen to Transfer events contract.on('Transfer', (from, to, value, event) => { console.log(`Transfer event detected:`); console.log(`From: ${from}`); console.log(`To: ${to}`); console.log(`Value: ${value.toString()}`); console.log('Event block number:', event.blockNumber); }); } main().catch(console.error);
Listening to events is fast and efficient because it waits for blockchain changes instead of checking repeatedly.
Time complexity is low since events are pushed to your app only when they happen.
Common mistake: forgetting to remove listeners when the component unmounts, which can cause memory leaks.
Use once if you only want to listen to a single event occurrence.
Listening to blockchain events lets your app react instantly to changes.
You need contract address, ABI, and a provider to listen to events.
Use contract.on for continuous listening and contract.once for a single event.