Skip to content

watchLogs: block-scoped log subscription helper #36

@koko1123

Description

@koko1123

Motivation

The pattern of "on each new block, fetch filtered logs and process them" is fundamental to nearly every on-chain bot:

  • Liquidation keepers watching for margin threshold events
  • Arbitrage bots watching for reserve updates
  • Searchers watching for specific contract interactions

Currently this requires manually combining subscription.zig (newHeads) + provider.getLogs(), handling missed blocks on reconnect, and managing deduplication. A watchLogs helper abstracts all of this.

API

New function in event.zig (or a new watcher.zig):

pub fn watchLogs(
    allocator: std.mem.Allocator,
    provider: *Provider,
    filter: LogFilter,
    opts: WatchOpts,
    callback: *const fn (log: Log) void,
) !void

pub const WatchOpts = struct {
    /// How many blocks behind to start fetching from. Default: 0 (current).
    start_block_lag: u64 = 0,
    /// Re-fetch logs for reorged blocks. Default: true
    handle_reorgs: bool = true,
    /// Reconnect options for the underlying WebSocket.
    reconnect: ReconnectOpts = .{},
};

Behaviour

  1. Subscribe to newHeads via WebSocket
  2. On each new block, call eth_getLogs with the filter scoped to [blockNumber, blockNumber]
  3. On reconnect, back-fill any missed blocks between last-seen and current head
  4. On reorg detection (block hash mismatch on sequential blocks), re-fetch the reorged range

Use case: liquidation keeper

// Watch for positions approaching liquidation on perpcity
try watchLogs(allocator, &provider, .{
    .address = PERP_MANAGER,
    .topics = &.{comptime eth.keccak.eventTopic("PositionOpened(address,bytes32,uint256)")},
}, .{}, handlePositionEvent);

Relationship

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions