Lesson 4 of 5 Interacting with Contracts Using web3.js

Events and Logs

Events are how contracts tell applications what happened. This lesson explains how logs are stored, how to query past events with filters, how to subscribe to new events over WebSocket, and how to handle block ranges and chain reorganisations.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how logs, topics and data are stored.
  • Explain how to query past events with filters.
  • Explain how to subscribe to new events.
  • Explain how reorganisations affect event processing.

How events are stored

An emit statement writes a log into the transaction receipt. Each log has the emitting contract's address, up to four topics and a data field. Topic 0 is the Keccak-256 hash of the event signature, and each indexed parameter becomes another topic; non-indexed parameters are ABI-encoded in the data. Nodes index logs by address and topics, which makes topic filters efficient, and every block header includes a bloom filter that lets nodes skip blocks quickly.

Logs are not part of contract state: contracts cannot read them, and they cost much less than storage. They are the standard way to build activity feeds, notifications and off-chain databases (indexers) of contract activity.

True or false

Logs and topics

Exam skills 1.3.4

Check how events are stored and who can read them.

Log in to try this activity Interactive activities are free with an account.

Querying past events

getPastEvents retrieves historical events with eth_getLogs and decodes them.

const events = await counter.getPastEvents("Increment", {
  fromBlock: 0,
  toBlock: "latest",
});
console.log(events.map((e) => e.returnValues.by));   // [ 5n, 7n ]

const mine = await token.getPastEvents("Transfer", {
  filter: { to: myAddress },     // works because 'to' is indexed
  fromBlock: 9_000_000n,
  toBlock: 9_010_000n,
});

The filter option matches indexed parameters only; filtering on a non-indexed parameter must be done in JavaScript after fetching. Node providers limit the block range or the number of results of one eth_getLogs request, so applications reading long histories query in pages of block ranges. Passing "allEvents" returns every event of the contract.

Scenario questions

Querying history

Exam skills 1.3.4

Write efficient queries for past events.

Log in to try this activity Interactive activities are free with an account.

Subscribing to new events

With a WebSocket provider, contract.events.Name() creates a subscription that delivers each new matching event as it is mined.

const web3 = new Web3("ws://127.0.0.1:8545");
const counter = new web3.eth.Contract(abi, address);
const sub = counter.events.Increment();
sub.on("data", (e) => console.log("Live event", e.returnValues.by));
sub.on("error", console.error);
// later: await sub.unsubscribe();

Subscriptions are not available over HTTP. Long-running listeners must also handle reconnection, because WebSocket connections drop, and must catch up on events missed while disconnected by querying the gap with getPastEvents.

Reorganisations and confirmation

Near the head of the chain, a block can occasionally be replaced by a competing block. Its logs are then removed; subscriptions deliver such logs again with removed: true. Applications that take irreversible actions on events, such as crediting a deposit or shipping goods, should wait for several confirmations or for finality before acting, while user interfaces can show events immediately as pending.

The following diagram shows a block replaced near the head of the chain.

Reorganisations and confirmation. Near the head of the chain a block can occasionally be replaced by a competing block, and its logs are removed; subscriptions deliver them again with removed: true. A user interface can show an event at once as pending, but an application that takes an irreversible action, such as crediting a deposit, should wait for several confirmations or for finality.
Show events at once; act on them only when settled.
Sort into groups

Act now or wait?

Exam skills 1.3.4 · 7.1.3

Decide whether an application can act on an event as soon as it arrives or should wait for confirmations or finality.

Log in to try this activity Interactive activities are free with an account.
Worked example

An efficient history page

A wallet must show all ERC-20 transfers to the user over the last year. A developer fetches every Transfer event of the token in one request and filters in JavaScript; the provider returns an error about too many results. What is the better approach?

Filter at the node using the indexed parameter: filter: { to: userAddress }, which becomes a topic filter. Query in block-range pages (for example 10,000 blocks at a time), and cache results so that later visits fetch only new blocks. For heavy use, an indexing service that stores events in a database is more efficient still.

Worked example

A contract that reads events

A developer wants contract B to check whether contract A ever emitted a Paid(user) event for a user before allowing a withdrawal. Is this possible?

No. Contracts cannot read logs. Contract A must record the fact in storage, for example mapping(address => bool) public paid, and expose it through a view function that contract B calls. Events are for off-chain readers only.

Check yourself

Why can getPastEvents filter Transfer events by the to address?

Show answer

Because to is an indexed parameter, stored as a log topic that nodes can filter. Non-indexed parameters are in the log data and must be filtered after fetching.

Exam Tips

Remember for the exam

  • Topic 0 is the event signature hash; indexed parameters are topics; the rest is data.
  • getPastEvents uses eth_getLogs; filter works only on indexed parameters; page long ranges.
  • events.Name() subscriptions need a WebSocket provider and reconnection handling.
  • Contracts cannot read events; wait for confirmations before irreversible actions.