Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 47 ยท Contract Structure

Events and Logs

Learn Solidity events: emit, indexed parameters, how logs are stored and filtered, listening off-chain, and when to use events instead of storage.

A contract cannot send you an email, and your website cannot sit inside the EVM and watch variables change. Yet apps need to know that "Alice sent 5 tokens to Bob" or "auction 7 ended". Solidity solves this with events: a contract announces that something happened, the network records the announcement in a log, and programs outside the chain read the log later.

Events are one of the cheapest ways to save data on Ethereum, and one of the most used. Every token transfer you have ever seen in a wallet or block explorer was found through an event. This lesson shows how to declare and emit them, what indexed really does, how logs are stored and searched, and how to decide between an event and a storage variable.

Events at a glance

Declare One line describes the event's name and fields.
Emit A function fires it with emit.
Log The node stores it in the transaction receipt.
Listen Apps off-chain query and subscribe.

Contracts can write logs but can never read them back.

1 / 2

Declaring and emitting

An event is declared inside a contract, much like a function signature without a body. You trigger it with emit:

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Piggy {
    mapping(address => uint256) public deposits;

    event Deposited(address indexed from, uint256 amount);
    event Withdrawn(address indexed to, uint256 amount, string note);

    function deposit() external payable {
        deposits[msg.sender] += msg.value;
        emit Deposited(msg.sender, msg.value);
    }
}

Event names use PascalCase by convention and usually describe something that already happened (Deposited, Transferred). Parameters have types and optional names. The names matter to people and tools that read the ABI, not to the EVM.

Emitting an event is not a state change you can observe from inside the chain. It writes a log entry attached to the transaction. If the transaction reverts, its logs are discarded along with every other effect.

What a log contains

A log entry has three parts:

  • the address of the contract that emitted it
  • up to four topics, each 32 bytes
  • a data blob with everything that is not a topic

For an ordinary event, the first topic (topic0) is the keccak-256 hash of the event signature, for example Deposited(address,uint256). That is how tools recognize which event they are looking at. The ERC-20 Transfer(address,address,uint256) event always starts with the same topic, which begins 0xddf252ad, on every chain and every token.

The remaining topics hold the parameters you marked indexed. Everything else is ABI-encoded into the data blob.

Indexed parameters

Mark up to three parameters per event as indexed and each one gets its own topic, which makes it searchable:

SOLIDITY
event Transfer(address indexed from, address indexed to, uint256 value);

Here a wallet can ask: "give me every Transfer where to is my address". Without indexed on to, the app would have to download every Transfer log of the token and decode each one itself.

Some rules and traps:

  • A value type (address, uint, bool, bytes32) is stored in the topic as it is, padded to 32 bytes.
  • A dynamic type such as string, bytes or an array is hashed when indexed. The topic is a fingerprint, so you can search for a known string but you can never recover the original text from the log. If you need the text back, leave it unindexed or emit it a second time in the data.
  • An event can have at most three indexed parameters (four if you mark the event anonymous, which also removes topic0 and is rare).
  • Indexed fields are not cheaper to emit. Each topic adds gas. You pay for searchability.

How logs are stored and filtered

Logs are not part of the state that contracts can read. They live in the transaction receipt, and each block header carries a compact summary called a bloom filter built from the addresses and topics of its logs. A node answering "any Transfer to Bob between blocks 100 and 200?" can skip every block whose bloom filter rules the answer out, and then scan the receipts of the rest.

A filter has an optional contract address and a list of topic positions:

  • topic0: which event
  • topic1, topic2, topic3: values of the indexed parameters, in declaration order
  • A position left empty means "anything"; a position given as a list means "any of these"

Filters can only match topics, never data. So whatever you think you will filter on must be indexed.

Reading logs from outside

Off-chain code asks a node (through a library such as ethers.js or viem) either for past logs in a block range or for a live subscription. The shape of such code, for reference only because it needs a real node:

JavaScript
// Read-only example: needs an RPC connection and a deployed contract.
const logs = await contract.queryFilter(
  contract.filters.Transfer(null, myAddress),
  fromBlock,
  toBlock
);
contract.on("Transfer", (from, to, value) => {
  console.log(from, "sent", value, "to", to);
});

You will write real code like this in Talking to Contracts with JavaScript. Two practical notes. First, logs can disappear if the chain reorganizes before the block is final, so serious apps wait for confirmations. Second, nodes may limit how many blocks a single query can cover.

Events or storage?

Storing a value costs roughly 20,000 gas for the first write to a slot. A log costs around 375 gas plus 375 per topic plus 8 gas per byte of data, so history that nobody on-chain needs is much cheaper as an event.

Use storage when a contract must read the value later: balances, owners, a deadline. Use an event when the information is only for the outside world: an audit trail, a feed for the user interface, an index for a subgraph. Many contracts do both. A token updates balanceOf in storage (so it can check it) and emits Transfer (so everyone else can follow along).

An event is not proof that a state change happened unless it was emitted by the contract you trust. Anyone can deploy a contract that emits a fake Transfer. Always filter by the contract address, and never rely on events inside another contract's logic: contracts cannot read logs at all.

A stand-in event bus

The real log system lives inside Ethereum nodes, so the code below is a stand-in written in plain JavaScript. It keeps the same shape: a log has an address, a list of topics and a data object, topic0 identifies the event, and a filter matches positions with null as a wildcard and arrays as "any of". The hash is a simple checksum instead of keccak-256, and there is no bloom filter.

JS Emit logs and filter by topics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The query for transfers to Carol puts null in the from position and her name in the to position, which is the same trick a wallet uses with contract.filters.Transfer(null, myAddress).

Next, add a subscription: code outside the contract registers a listener and the "chain" calls it whenever a matching log is written. Note that the contract part never reads the logs; it only emits.

JS A tiny subscription bus

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the idea of topic0, topic positions, wildcard and OR filters, and logs that the contract itself cannot read. Stand-in: the checksum hash, the in-memory array (real nodes keep receipts and bloom filters on disk), and the instant callback (a real subscription arrives after the block is produced, and can be undone by a reorg).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a contract do with the logs it (or another contract) has emitted?

    Logs live in transaction receipts, outside the state that the EVM can access. They exist for off-chain programs, so a contract cannot use them as a data source.
  2. 2. You index a string parameter. What ends up in its topic?

    Dynamic types are hashed when indexed. You can search for a known value, but you cannot decode the original text from the topic.
  3. 3. How many parameters of an ordinary (non-anonymous) event can be indexed?

    topic0 is used for the event signature hash, leaving three topics for indexed parameters. Only anonymous events can have four.
  4. 4. Which data is best kept as an event rather than in storage?

    Events are far cheaper than storage but unreadable by contracts. They suit history for outside observers, while values the contract itself needs must be stored.

Summary

  • An event is declared with event and fired with emit; it writes a log into the transaction receipt and is discarded if the transaction reverts.
  • A log has the emitting address, up to four topics and a data blob; topic0 is the hash of the event signature.
  • indexed parameters become topics and can be filtered on; indexed string, bytes and arrays are stored only as hashes.
  • Filters match addresses and topics (with wildcards and "any of" lists), never data, so index what you plan to search.
  • Logs are much cheaper than storage but unreadable on-chain; use storage for what contracts need and events for what the outside world needs.
  • Never trust a log without checking which contract emitted it.

Next: Modifiers and Access Control.