0
0
Blockchain / Solidityprogramming~7 mins

Listening to events (frontend) in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Listening to events lets your webpage know when something important happens on the blockchain. This helps your app update automatically without needing to refresh.

You want to show a message when a user receives tokens.
You want to update the balance on the page after a transaction.
You want to notify users when a new item is added to a marketplace.
You want to track when a smart contract changes state.
You want to log blockchain activity in real-time for analytics.
Syntax
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.

Examples
Listen to a Transfer event and print who sent tokens, who received, and how many.
Blockchain / Solidity
contract.on('Transfer', (from, to, amount, event) => {
  console.log(`Tokens moved from ${from} to ${to}: ${amount.toString()}`);
});
Listen to an Approval event to know when someone allows another to spend tokens.
Blockchain / Solidity
contract.on('Approval', (owner, spender, value, event) => {
  console.log(`Approval: ${owner} allowed ${spender} to spend ${value.toString()}`);
});
If no events happen, your app just waits without errors.
Blockchain / Solidity
// 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}`);
});
Use once to listen only to the next event and then stop listening.
Blockchain / Solidity
// Edge case: Only one event emitted
contract.once('Sold', (buyer, price) => {
  console.log(`Item sold to ${buyer} for ${price.toString()}`);
});
Sample Program

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.

Blockchain / Solidity
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);
OutputSuccess
Important Notes

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.

Summary

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.