0
0
Blockchain / Solidityprogramming~5 mins

Event filtering in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Event filtering helps you listen only to the important messages from the blockchain. It saves time and resources by ignoring unrelated events.

You want to track when a specific user receives tokens.
You need to monitor only failed transactions in a smart contract.
You want to update your app only when a certain item is sold.
You want to watch for events from a specific contract address.
You want to filter events by a date or block number range.
Syntax
Blockchain / Solidity
contractInstance.events.EventName({ filter: { key: value }, fromBlock: startBlock, toBlock: endBlock }, callback);
Use filter to specify which event data you want to listen to.
Use fromBlock and toBlock to limit the range of blocks checked.
Examples
This listens only to Transfer events where the sender is '0x123...'.
Blockchain / Solidity
contractInstance.events.Transfer({ filter: { from: '0x123...' } }, (error, event) => { console.log(event); });
This listens to Approval events from block 100 to the latest block.
Blockchain / Solidity
contractInstance.events.Approval({ fromBlock: 100, toBlock: 'latest' }, (error, event) => { console.log(event); });
This listens only to MyEvent events where the status is 'success'.
Blockchain / Solidity
contractInstance.events.MyEvent({ filter: { status: 'success' } }, (error, event) => { console.log(event); });
Sample Program

This program connects to the Ethereum mainnet and listens for Transfer events from a specific address only. It prints the event details when such an event happens.

Blockchain / Solidity
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

const abi = [
  {
    "anonymous": false,
    "inputs": [
      {"indexed": true, "name": "from", "type": "address"},
      {"indexed": true, "name": "to", "type": "address"},
      {"indexed": false, "name": "value", "type": "uint256"}
    ],
    "name": "Transfer",
    "type": "event"
  }
];

const contractAddress = '0xYourTokenContractAddress';
const contractInstance = new web3.eth.Contract(abi, contractAddress);

// Listen only to Transfer events where 'from' is a specific address
contractInstance.events.Transfer({ filter: { from: '0x1234567890abcdef1234567890abcdef12345678' }, fromBlock: 'latest' })
.on('data', event => {
  console.log('Filtered Transfer event:', event.returnValues);
})
.on('error', console.error);
OutputSuccess
Important Notes

Event filtering reduces the amount of data your app processes, making it faster and cheaper.

Filters only work on indexed event parameters.

Always specify fromBlock to avoid missing events or scanning too many blocks.

Summary

Event filtering lets you listen only to events you care about.

Use filters on event parameters and block ranges to narrow down events.

This helps your app stay efficient and responsive.