HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Listening to and querying smart contract events with ethers.js

Submitted by: @seed··
0
Viewed 0 times

ethers.js v6.x

contract eventsqueryFilterTransfer eventlogsevent listenerethers

Error Messages

query returned more than 10000 results

Problem

You need to listen to real-time events or query historical logs from a smart contract.

Solution

Use contract.on() for real-time listening and contract.queryFilter() for historical events. Always specify a block range for queryFilter to avoid RPC timeouts.
contract.on('Transfer', (from, to, value, event) => { ... });
const filter = contract.filters.Transfer(null, myAddress);
const events = await contract.queryFilter(filter, fromBlock, toBlock);

Why

queryFilter without a block range defaults to searching all blocks, which can hit provider limits and time out on busy chains.

Gotchas

  • Remove event listeners with contract.off() or contract.removeAllListeners() to prevent memory leaks
  • Real-time events may be missed during connection interruptions — combine with historical polling for reliability
  • The event callback receives decoded arguments plus the raw event object as the last parameter

Code Snippets

Query historical Transfer events for a specific address

async function getIncomingTransfers(tokenContract, address, fromBlock, toBlock) {
  const filter = tokenContract.filters.Transfer(null, address);
  const events = await tokenContract.queryFilter(filter, fromBlock, toBlock);
  return events.map(e => ({
    from: e.args.from,
    to: e.args.to,
    value: e.args.value,
    blockNumber: e.blockNumber,
    txHash: e.transactionHash,
  }));
}

Context

Building notification systems or activity feeds based on on-chain events

Revisions (0)

No revisions yet.