In some cases, you need to index events from a smart contract that is deployed from another smart contract. It would quickly become impractical to update your indexer source code with the information about the new contract. Apibara provides dynamic event filters to add new event filters at runtime.
Use cases for dynamic event filters include indexing:
- DEX pools that are created by pool factories,
- game rounds that are created by the main instance of the on-chain game.
The first step is to create a root event filter to detect when a new smart contract is deployed.
Then, every time a
PairCreated event is emitted, you can use the information in
the event to add a new event filter for the newly created pair. Call
info.add_event_filters method to add a list of event filters to the indexer.
In this example, the indexer starts tracking the
pair_created = decode_event(pair_created_decoder, event.data)info.add_event_filters(filters=[EventFilter.from_event_name("Swap", address=pair_created.pair),EventFilter.from_event_name("Sync", address=pair_created.pair),])
Notice that the indexer will re-scan the current block to detect if any event matches the newly-added filters. If that's the case, the event handler will be called one more time with the new events only.