@secondlayer/subgraphs 6.6.1 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,20 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["src/runtime/replay.ts", "src/schema/utils.ts", "src/runtime/block-source.ts", "src/verification.ts", "src/runtime/batch-loader.ts", "src/runtime/state-writes.ts", "src/runtime/observer-http-source.ts", "src/runtime/realm.ts", "src/runtime/reconstruct.ts", "src/runtime/trigger-evaluator.ts", "src/runtime/decoder-bound.ts", "src/runtime/source-matcher.ts"],
3
+ "sources": ["src/runtime/replay.ts", "src/runtime/block-source.ts", "src/verification.ts", "src/runtime/batch-loader.ts", "src/runtime/state-writes.ts", "src/runtime/observer-http-source.ts", "src/runtime/realm.ts", "src/runtime/reconstruct.ts", "src/runtime/trigger-evaluator.ts", "src/runtime/decoder-bound.ts", "src/runtime/source-matcher.ts"],
4
4
  "sourcesContent": [
5
- "import { createHash } from \"node:crypto\";\nimport { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport type { Webhook } from \"@secondlayer/shared/db\";\nimport { getWebhook } from \"@secondlayer/shared/db/queries/webhooks\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, sql } from \"kysely\";\nimport { pgSchemaName as defaultSchemaName } from \"../schema/utils.ts\";\nimport {\n\ttype BlockSource,\n\tPublicApiBlockSource,\n\tbuildHttpClient,\n} from \"./block-source.ts\";\nimport {\n\tblockTimeOf,\n\tbuildSourcesMap,\n\tbuildTraitContracts,\n\temitChainOutbox,\n\temitSbtcOutbox,\n\tevaluateBlock,\n\treferencedEventTypes,\n} from \"./trigger-evaluator.ts\";\n\n/**\n * Replay historical subgraph rows as new outbox entries for a single\n * webhook. Rows are marked `is_replay=TRUE` so the emitter can\n * prioritize live deliveries (90/10 split) and the delivery log can\n * tag replays distinctly.\n *\n * Idempotency: `replayId` is deterministic over `(webhook_id,\n * fromBlock, toBlock)`, so re-running the same replay range is a no-op\n * thanks to the unique `(webhook_id, dedup_key)` constraint. A\n * user who actually wants to re-deliver the same range passes a\n * distinct `replayIdSuffix` (e.g. a timestamp) to get a fresh key.\n */\n\nconst BATCH_SIZE = 500;\n\n/** Default cap on blocks per replay call — overridable via\n * `WEBHOOK_REPLAY_MAX_BLOCKS` for an operator who wants a tighter (or, for a\n * trusted self-host, looser) limit. Read live, not baked in at import. */\nconst WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT = 100_000;\n\nfunction webhookReplayMaxBlocks(): number {\n\tconst raw = process.env.WEBHOOK_REPLAY_MAX_BLOCKS;\n\tif (raw === undefined) return WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT;\n\tconst parsed = Number.parseInt(raw, 10);\n\treturn Number.isFinite(parsed) && parsed > 0\n\t\t? parsed\n\t\t: WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT;\n}\n\n/** Renders a block count the way the original hardcoded message did\n * (\"100k blocks\") for round thousands, falling back to the raw number for a\n * ceiling that isn't a clean multiple of 1000. */\nfunction formatBlockCount(n: number): string {\n\treturn n % 1000 === 0 ? `${n / 1000}k` : `${n}`;\n}\n\n/**\n * One in-flight replay per webhook at a time. Replay is a synchronous scan\n * (the route awaits it fully before responding), so two concurrent requests\n * for the same webhook would otherwise interleave their scans against the\n * same dedup keyspace. In-memory per-process — replay already isn't\n * horizontally coordinated (see `BATCH_SIZE` keyset pagination above), so\n * this matches its existing single-process assumption.\n */\nconst inFlightReplays = new Set<string>();\n\n/** Thrown by {@link replayWebhook} when a replay is already running for the\n * webhook. The route maps this to 409; `force` does not bypass it — a forced\n * re-delivery still has to wait for the previous replay to finish. */\nexport class ReplayInProgressError extends Error {\n\tconstructor() {\n\t\tsuper(\"replay already in progress for this webhook\");\n\t\tthis.name = \"ReplayInProgressError\";\n\t}\n}\n\n/**\n * Test-only seam: directly mark (or clear) a webhook as having an in-flight\n * replay. Two real concurrent `replayWebhook` calls race the same DB fetch,\n * so which one wins the guard isn't deterministic in a test; this lets a test\n * exercise the guard (and the route's 409 mapping) without that race.\n * Production code never calls this.\n */\nexport function __setReplayInFlightForTest(\n\twebhookId: string,\n\tinFlight: boolean,\n): void {\n\tif (inFlight) inFlightReplays.add(webhookId);\n\telse inFlightReplays.delete(webhookId);\n}\n\nfunction replayDedupKey(\n\tsubgraphName: string,\n\ttableName: string,\n\trow: Record<string, unknown>,\n\treplayId: string,\n): string {\n\tconst canonical = `replay:${replayId}:${subgraphName}:${tableName}:${stableStringify(row)}`;\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 32);\n}\n\nfunction stableStringify(obj: Record<string, unknown>): string {\n\tconst keys = Object.keys(obj).sort();\n\treturn JSON.stringify(\n\t\tkeys.reduce<Record<string, unknown>>((acc, k) => {\n\t\t\tacc[k] = obj[k];\n\t\t\treturn acc;\n\t\t}, {}),\n\t);\n}\n\nexport interface ReplayInput {\n\taccountId: string;\n\twebhookId: string;\n\tfromBlock: number;\n\ttoBlock: number;\n\t/** Force re-delivery by appending a unique suffix to the replay id. */\n\treplayIdSuffix?: string;\n}\n\nfunction deterministicReplayId(\n\twebhookId: string,\n\tfromBlock: number,\n\ttoBlock: number,\n\tsuffix?: string,\n): string {\n\tconst canonical = `${webhookId}:${fromBlock}:${toBlock}${suffix ? `:${suffix}` : \"\"}`;\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 16);\n}\n\nexport interface ReplayResult {\n\treplayId: string;\n\tenqueuedCount: number;\n\tscannedCount: number;\n}\n\nasync function resolveSchemaName(\n\tdb: Kysely<Database>,\n\tsubgraphName: string,\n): Promise<string> {\n\tconst row = await db\n\t\t.selectFrom(\"subgraphs\")\n\t\t.select(\"schema_name\")\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\tif (!row) {\n\t\tthrow new Error(\n\t\t\t`Subgraph \"${subgraphName}\" not registered — cannot replay its rows. Deploy the subgraph first.`,\n\t\t);\n\t}\n\treturn row.schema_name ?? defaultSchemaName(subgraphName);\n}\n\nexport async function replayWebhook(input: ReplayInput): Promise<ReplayResult> {\n\tif (input.fromBlock > input.toBlock) {\n\t\tthrow new Error(\"fromBlock must be <= toBlock\");\n\t}\n\tconst maxBlocks = webhookReplayMaxBlocks();\n\tif (input.toBlock - input.fromBlock > maxBlocks) {\n\t\tthrow new Error(\n\t\t\t`replay range exceeds ${formatBlockCount(maxBlocks)} blocks`,\n\t\t);\n\t}\n\n\tconst db = getTargetDb();\n\tconst sub = await getWebhook(db, input.accountId, input.webhookId);\n\tif (!sub) throw new Error(\"Webhook not found\");\n\n\tif (inFlightReplays.has(sub.id)) {\n\t\tthrow new ReplayInProgressError();\n\t}\n\tinFlightReplays.add(sub.id);\n\ttry {\n\t\t// Chain subs have no processed table — they react to raw chain events.\n\t\t// Replay re-runs the pure matcher over the canonical block range instead\n\t\t// of scanning rows.\n\t\tif (sub.kind === \"chain\") {\n\t\t\treturn await replayChainWebhook(db, sub, input);\n\t\t}\n\n\t\tconst subgraphName = sub.subgraph_name;\n\t\tconst tableName = sub.table_name;\n\t\tif (sub.kind !== \"subgraph\" || !subgraphName || !tableName) {\n\t\t\tthrow new Error(\n\t\t\t\t\"replay is only supported for subgraph or chain webhooks\",\n\t\t\t);\n\t\t}\n\n\t\tconst schema = await resolveSchemaName(db, subgraphName);\n\t\tconst replayId = deterministicReplayId(\n\t\t\tsub.id,\n\t\t\tinput.fromBlock,\n\t\t\tinput.toBlock,\n\t\t\tinput.replayIdSuffix,\n\t\t);\n\n\t\tlet scanned = 0;\n\t\tlet enqueued = 0;\n\t\t// Keyset pagination, not a positional skip-count: `_created_at` is written\n\t\t// as the literal NOW() (one value per transaction, so identical for every\n\t\t// row in a block), which makes (_block_height, _created_at) non-unique.\n\t\t// Paging by skip-count over a non-unique sort lets tied rows reorder\n\t\t// between pages and drop rows silently. `_id` is BIGSERIAL and total.\n\t\tlet lastId = 0n;\n\n\t\twhile (true) {\n\t\t\tconst { rows } = await sql<\n\t\t\t\tRecord<string, unknown>\n\t\t\t>`SELECT * FROM ${sql.raw(`\"${schema}\".\"${tableName}\"`)}\n\t\t\t\tWHERE _block_height >= ${sql.lit(input.fromBlock)}\n\t\t\t\t\tAND _block_height <= ${sql.lit(input.toBlock)}\n\t\t\t\t\tAND _id > ${sql.lit(lastId)}\n\t\t\t\tORDER BY _id ASC\n\t\t\t\tLIMIT ${sql.lit(BATCH_SIZE)}`.execute(db);\n\n\t\t\tif (rows.length === 0) break;\n\t\t\tscanned += rows.length;\n\n\t\t\tconst inserts = rows.map((row) => ({\n\t\t\t\twebhook_id: sub.id,\n\t\t\t\tsubgraph_name: subgraphName,\n\t\t\t\ttable_name: tableName,\n\t\t\t\tblock_height: Number(row._block_height),\n\t\t\t\ttx_id: (row._tx_id as string | undefined) ?? null,\n\t\t\t\trow_pk: {\n\t\t\t\t\tblockHeight: Number(row._block_height),\n\t\t\t\t\ttxId: row._tx_id ?? \"\",\n\t\t\t\t\treplayId,\n\t\t\t\t},\n\t\t\t\tevent_type: `${subgraphName}.${tableName}.replay`,\n\t\t\t\tpayload: row,\n\t\t\t\tdedup_key: replayDedupKey(subgraphName, tableName, row, replayId),\n\t\t\t\tis_replay: true,\n\t\t\t}));\n\n\t\t\tconst result = await db\n\t\t\t\t.insertInto(\"webhook_outbox\")\n\t\t\t\t.values(inserts)\n\t\t\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t\t\t.executeTakeFirst();\n\t\t\tenqueued += Number(result.numInsertedOrUpdatedRows ?? 0);\n\n\t\t\tlastId = BigInt(String(rows[rows.length - 1]?._id));\n\t\t\tif (rows.length < BATCH_SIZE) break;\n\t\t}\n\n\t\tlogger.info(\"Replay enqueued\", {\n\t\t\twebhook: sub.name,\n\t\t\treplayId,\n\t\t\tscanned,\n\t\t\tenqueued,\n\t\t\tfromBlock: input.fromBlock,\n\t\t\ttoBlock: input.toBlock,\n\t\t});\n\n\t\treturn { replayId, enqueuedCount: enqueued, scannedCount: scanned };\n\t} finally {\n\t\tinFlightReplays.delete(sub.id);\n\t}\n}\n\nconst CHAIN_REPLAY_BATCH = 200;\n\n/**\n * Replay a chain webhook by re-running the pure matcher over a historical\n * canonical block range and emitting fresh apply rows. Unlike subgraph replay\n * there is no processed table to scan — the matcher is range-driven, so we\n * reload canonical blocks off the public Index/Streams clock and re-match.\n *\n * Rows are emitted with `is_replay=TRUE` and replay-namespaced dedup keys, and —\n * critically — this never advances `trigger_evaluator_state`: replay is\n * historical and must not move the live forward cursor.\n */\nexport async function replayChainWebhook(\n\tdb: Kysely<Database>,\n\tsub: Webhook,\n\tinput: ReplayInput,\n\topts?: { source?: BlockSource },\n): Promise<ReplayResult> {\n\tconst replayId = deterministicReplayId(\n\t\tsub.id,\n\t\tinput.fromBlock,\n\t\tinput.toBlock,\n\t\tinput.replayIdSuffix,\n\t);\n\n\tconst { sources, keyMeta } = buildSourcesMap([sub]);\n\tconst source =\n\t\topts?.source ??\n\t\tnew PublicApiBlockSource(buildHttpClient(), referencedEventTypes([sub]));\n\n\tlet scanned = 0;\n\tlet enqueued = 0;\n\tfor (\n\t\tlet from = input.fromBlock;\n\t\tfrom <= input.toBlock;\n\t\tfrom += CHAIN_REPLAY_BATCH\n\t) {\n\t\tconst to = Math.min(from + CHAIN_REPLAY_BATCH - 1, input.toBlock);\n\t\tconst blocks = await source.loadBlockRange(from, to);\n\t\t// Trait membership only grows; resolve once per batch as of its top height.\n\t\tconst traitContracts = await buildTraitContracts([sub], to);\n\t\tfor (let h = from; h <= to; h++) {\n\t\t\tconst bd = blocks.get(h);\n\t\t\tif (!bd) continue;\n\t\t\tscanned++;\n\t\t\tconst blockTime = blockTimeOf(bd.block);\n\t\t\tconst matches = evaluateBlock(bd, sources, traitContracts);\n\t\t\tif (matches.length > 0) {\n\t\t\t\tenqueued += await emitChainOutbox(\n\t\t\t\t\tdb,\n\t\t\t\t\tmatches,\n\t\t\t\t\tkeyMeta,\n\t\t\t\t\th,\n\t\t\t\t\tbd.block.hash,\n\t\t\t\t\tblockTime,\n\t\t\t\t\t{\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\t// sBTC lifecycle triggers (deposit/withdrawal-create/accept/reject) match\n\t\t\t// against `sbtc_events`, not decoded_events — mirror the live loop so a\n\t\t\t// replay over a historical range backfills sBTC webhooks too. (Settlement\n\t\t\t// `swept_confirmed` is cursor/confirmed_at driven, not block-keyed, so it\n\t\t\t// emits nothing here — documented forward-only.)\n\t\t\tenqueued += await emitSbtcOutbox(db, [sub], h, bd.block.hash, blockTime, {\n\t\t\t\treplayId,\n\t\t\t});\n\t\t}\n\t}\n\n\tlogger.info(\"Chain replay enqueued\", {\n\t\twebhook: sub.name,\n\t\treplayId,\n\t\tscanned,\n\t\tenqueued,\n\t\tfromBlock: input.fromBlock,\n\t\ttoBlock: input.toBlock,\n\t});\n\n\treturn { replayId, enqueuedCount: enqueued, scannedCount: scanned };\n}\n",
6
- "// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n\n/**\n * Double-quotes a Postgres identifier unless it's already a safe bare\n * identifier, escaping any embedded double quotes. Defense-in-depth for the\n * DDL emitters: every name reaching them (schema/table/column names, and the\n * composite names generator.ts builds from them) is validated upstream\n * (`SqlIdentifierSchema` / `SubgraphNameSchema`), so this is a no-op for every\n * currently-valid name — output stays byte-identical. It only changes\n * anything if a hostile name (embedded quote, semicolon, whitespace, ...)\n * somehow reached this far, turning it into an inert quoted identifier\n * instead of raw SQL.\n */\nexport function quotePgIdent(name: string): string {\n\tif (/^[a-z_][a-z0-9_]*$/i.test(name)) return name;\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** `user_account` → `userAccount`. Column and variable names in every emitted\n * ORM surface go through this. */\nexport function snakeToCamel(name: string): string {\n\treturn name.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** `user_account` → `UserAccount`. Type/model names for one table must agree\n * across the Prisma, Drizzle, Kysely, and index-codegen emitters — a user can\n * import from more than one, so this lives here rather than per-generator. */\nexport function pascalCase(name: string): string {\n\tconst camel = snakeToCamel(name);\n\treturn camel.charAt(0).toUpperCase() + camel.slice(1);\n}\n",
7
- "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Transaction } from \"@secondlayer/shared/db\";\nimport {\n\tBillingPausedError,\n\ttype IndexEventRow,\n\ttype IndexHttpClient,\n\ttype IndexStateWriteRow,\n\ttype IndexTransactionRow,\n\tcreateInternalIndexHttpClient,\n} from \"@secondlayer/shared/index-http\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition, SubgraphFilter } from \"../types.ts\";\nimport { deriveVerification } from \"../verification.ts\";\nimport {\n\ttype BlockData,\n\ttype StateWriteFeed,\n\tloadBlockRange,\n\tstateWriteBlocks,\n} from \"./batch-loader.ts\";\nimport { ObserverHttpBlockSource } from \"./observer-http-source.ts\";\nimport { runsInRealm } from \"./realm.ts\";\nimport {\n\treconstructBlock,\n\treconstructEvent,\n\treconstructTransaction,\n\treconstructTxFromEventRow,\n} from \"./reconstruct.ts\";\nimport type { TxRecord } from \"./source-matcher.ts\";\nimport type { StateWriteRow } from \"./state-writes.ts\";\n\n/**\n * Where the subgraph runtime reads canonical chain data. Today it taps the\n * indexer Postgres directly (`PostgresBlockSource`); the re-point adds a\n * `PublicApiBlockSource` that consumes the Streams clock + Index data over\n * HTTP. `matchSources` / handlers / flush / outbox are unchanged — only the\n * loader + tip swap behind this seam.\n */\nexport interface BlockSource {\n\t/**\n\t * Highest canonical block height available to process.\n\t *\n\t * `opts` is an HTTP-plane long-poll hint, ignored by any\n\t * source with no such notion (the Postgres tap: a local DB read is already\n\t * instant, nothing to wait on). `knownHeight` is the last tip THIS caller\n\t * observed; passing `wait` without it is a no-op — the server needs a\n\t * baseline to decide whether anything has changed.\n\t */\n\tgetTip(opts?: { wait?: number; knownHeight?: number }): Promise<number>;\n\t/** Canonical block data for [fromHeight, toHeight], keyed by height. */\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>>;\n\t/** Sparse-scan probe: lowest height in (afterHeight, untilHeight] holding\n\t * an event this source's subgraph could match, or null when the rest of\n\t * the range is empty. Optional — only event-scoped sources support it. */\n\tnextDataHeight?(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null>;\n\t/**\n\t * Per-decoder committed heights from the SAME response `getTip()` just\n\t * fetched (no extra request) — undefined for a source with no such notion\n\t * (the Postgres tap: local mode reads `decoder_checkpoints` directly and\n\t * never needs this). Lets a caller (the chain evaluator) narrow its own\n\t * bound to the decoders it actually reads instead of `getTip()`'s\n\t * conservative cross-decoder floor. Call AFTER `getTip()`.\n\t */\n\tgetDecodedHeights?(): Record<string, number | null> | undefined;\n}\n\n/** A (decoded event type, optional contract scope) pair the sparse probe\n * checks. Contract scoping is what makes token-subgraph reindexes leap over\n * everything that isn't their token. */\nexport type SparseProbeTarget = { eventType: string; contractId?: string };\n\n/** Sparse scanning is sound only when EVERY source is an event-type filter —\n * a contract_call/contract_deploy source matches transactions, which the\n * event probe can't see. */\nexport function canSparseScan(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\treturn filters.every((f) => Boolean(EVENT_FILTER_TO_INDEX_TYPE[f.type]));\n}\n\n/** Most contracts one filter may pin before it is treated as unscoped (the\n * Index list-filter ceiling; beyond it a per-contract walk fan-out costs more\n * than it saves). */\nconst MAX_PINNED_CONTRACTS = 20;\n\n/**\n * Concrete contract ids a filter pins, or null when it pins none the Index can\n * be asked for. Wildcards, trait scope and factory scope resolve per block\n * against registry state the Index cannot see, so they stay unscoped: scoping\n * them would change which events a handler receives.\n */\nfunction pinnedContracts(filter: SubgraphFilter): string[] | null {\n\tconst f = filter as {\n\t\tcontractId?: string | readonly string[];\n\t\tassetIdentifier?: string;\n\t\ttrait?: unknown;\n\t\tfactory?: unknown;\n\t};\n\tif (f.trait || f.factory) return null;\n\tconst ids = Array.isArray(f.contractId)\n\t\t? [...f.contractId]\n\t\t: f.contractId\n\t\t\t? [f.contractId as string]\n\t\t\t: f.assetIdentifier\n\t\t\t\t? [f.assetIdentifier.split(\"::\")[0] as string]\n\t\t\t\t: [];\n\tif (ids.length === 0 || ids.length > MAX_PINNED_CONTRACTS) return null;\n\tif (ids.some((id) => !id || id.includes(\"*\"))) return null;\n\treturn ids;\n}\n\n/**\n * The (decoded event type, contract scope) pairs a subgraph's filters can\n * match. One function feeds BOTH the sparse probe and the event walks, so a\n * new contract-pinning filter field is added here once.\n *\n * Per event type: if ANY filter for it is unscoped, a single unscoped target\n * covers everything (today's behavior); otherwise one target per distinct\n * pinned contract.\n */\nexport function sparseProbeTargets(\n\tsubgraph: SubgraphDefinition,\n): SparseProbeTarget[] {\n\tconst byType = new Map<string, Set<string> | \"all\">();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst eventType = EVENT_FILTER_TO_INDEX_TYPE[f.type];\n\t\tif (!eventType) continue;\n\t\tconst pinned = pinnedContracts(f);\n\t\tconst prev = byType.get(eventType);\n\t\tif (!pinned || prev === \"all\") {\n\t\t\tbyType.set(eventType, \"all\");\n\t\t\tcontinue;\n\t\t}\n\t\tconst set = prev ?? new Set<string>();\n\t\tfor (const id of pinned) set.add(id);\n\t\tbyType.set(eventType, set);\n\t}\n\tconst targets: SparseProbeTarget[] = [];\n\tfor (const [eventType, scope] of byType) {\n\t\tif (scope === \"all\") targets.push({ eventType });\n\t\telse\n\t\t\tfor (const contractId of scope) targets.push({ eventType, contractId });\n\t}\n\treturn targets;\n}\n\n/** Lowest height this instance holds `state_writes` for; null when none. */\nexport type StateWritesCoverage = () => Promise<number | null>;\n\n/** How long a coverage answer is reused. Coverage only appears (the node\n * starts delivering `state_writes`) or reaches lower (a backfill). */\nconst COVERAGE_TTL_MS = 60_000;\n\n/** A coverage read cached per process; `forget` drops the cached answer. */\nexport type CachedCoverage = StateWritesCoverage & { forget(): void };\n\n/** Cache a coverage read per process; a failed read counts as no coverage. */\nexport function cachedCoverage(\n\tread: () => Promise<number | null>,\n\tttlMs: number = COVERAGE_TTL_MS,\n): CachedCoverage {\n\tlet cached: { at: number; value: Promise<number | null> } | undefined;\n\tconst coverage = () => {\n\t\tconst now = Date.now();\n\t\tif (!cached || now - cached.at > ttlMs) {\n\t\t\tcached = { at: now, value: read().catch(() => null) };\n\t\t}\n\t\treturn cached.value;\n\t};\n\treturn Object.assign(coverage, {\n\t\tforget: () => {\n\t\t\tcached = undefined;\n\t\t},\n\t});\n}\n\n/** The DB tap's coverage: the lowest `state_writes` height, one PK probe. */\nexport const dbStateWritesCoverage: CachedCoverage = cachedCoverage(\n\tasync () => {\n\t\tconst row = await getSourceDb()\n\t\t\t.selectFrom(\"state_writes\")\n\t\t\t.select(\"block_height\")\n\t\t\t.orderBy(\"block_height\", \"asc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? Number(row.block_height) : null;\n\t},\n);\n\nlet httpCoverage: StateWritesCoverage | undefined;\n/** The Index API's coverage: the first `/v1/index/state-writes` row. */\nfunction httpStateWritesCoverage(): StateWritesCoverage {\n\thttpCoverage ??= cachedCoverage(() =>\n\t\tbuildHttpClient().firstStateWriteHeight(),\n\t);\n\treturn httpCoverage;\n}\n\n/**\n * The contracts whose writes a state subgraph would read from `state_writes`,\n * or null when it keeps `vm_events` whatever the instance holds.\n *\n * Only a subgraph running in the deterministic realm (stored level `state`)\n * whose sources the CURRENT rules still derive as `state`. A subgraph stored\n * as `state` before `map_insert` dropped to `events` keeps its `vm_events`\n * feed: `state_writes` cannot tell an insert from a set, so it would silently\n * lose those events.\n */\nexport function stateWriteContracts(\n\tsubgraph: SubgraphDefinition | undefined,\n): StateWriteFeed | null {\n\tif (!subgraph || !runsInRealm(subgraph)) return null;\n\tif (deriveVerification(subgraph).level !== \"state\") return null;\n\tconst contracts = new Set<string>();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst pinned = pinnedContracts(f);\n\t\t// A source with no fixed contract (wildcard, factory) needs every\n\t\t// contract's writes.\n\t\tif (!pinned) return { contracts: null };\n\t\tfor (const id of pinned) contracts.add(id);\n\t}\n\treturn { contracts: [...contracts] };\n}\n\n/**\n * The `state_writes` feed for a subgraph, or null when it keeps today's\n * `vm_events` feed. Derived, never configured: a state subgraph switches only\n * once this instance holds `state_writes` from the subgraph's `startBlock`\n * on, so a node that does not deliver them (or started delivering them after\n * the subgraph's range began) changes nothing.\n */\nexport async function stateWriteFeed(\n\tsubgraph: SubgraphDefinition | undefined,\n\tcoverage: StateWritesCoverage = dbStateWritesCoverage,\n): Promise<StateWriteFeed | null> {\n\tconst feed = stateWriteContracts(subgraph);\n\tif (!feed) return null;\n\tconst from = await coverage();\n\tif (from === null || from > (subgraph?.startBlock ?? 0)) return null;\n\treturn feed;\n}\n\n/** Reads directly from the shared indexer Postgres (the original behavior). */\nexport class PostgresBlockSource implements BlockSource {\n\t/** `feed`: read write events from `state_writes` (see {@link stateWriteFeed}). */\n\tconstructor(private readonly feed?: StateWriteFeed | undefined) {}\n\n\tasync getTip(): Promise<number> {\n\t\tconst progress = await getSourceDb()\n\t\t\t.selectFrom(\"index_progress\")\n\t\t\t.selectAll()\n\t\t\t.where(\"network\", \"=\", process.env.NETWORK ?? \"mainnet\")\n\t\t\t.executeTakeFirst();\n\t\treturn progress ? Number(progress.highest_seen_block) : 0;\n\t}\n\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\treturn loadBlockRange(getSourceDb(), fromHeight, toHeight, {\n\t\t\tstateWrites: this.feed,\n\t\t});\n\t}\n}\n\n// Subgraph source filter types that map to a decoded Index event_type. The\n// `_event` suffix is the runtime's raw form; print is keyed `print_event`.\nconst EVENT_FILTER_TO_INDEX_TYPE: Record<string, string> = {\n\tstx_transfer: \"stx_transfer\",\n\tstx_mint: \"stx_mint\",\n\tstx_burn: \"stx_burn\",\n\tstx_lock: \"stx_lock\",\n\tft_transfer: \"ft_transfer\",\n\tft_mint: \"ft_mint\",\n\tft_burn: \"ft_burn\",\n\tnft_transfer: \"nft_transfer\",\n\tnft_mint: \"nft_mint\",\n\tnft_burn: \"nft_burn\",\n\tprint_event: \"print\",\n\tnested_contract_call: \"nested_contract_call\",\n\tvar_set: \"var_set\",\n\tmap_set: \"map_set\",\n\tmap_insert: \"map_insert\",\n\tmap_delete: \"map_delete\",\n};\n\n// Tx-level source types — matched against /v1/index/transactions, not events.\nconst TX_SOURCE_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\n// Second clock (ordinal). Never part of a tx's classic event set: a\n// contract_call/contract_deploy source fetches every CLASSIC type, and vm\n// types are fetched only when a vm source names them.\nexport const VM_INDEX_EVENT_TYPES: ReadonlySet<string> = new Set([\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n]);\nconst CLASSIC_INDEX_EVENT_TYPES = [\n\t...new Set(Object.values(EVENT_FILTER_TO_INDEX_TYPE)),\n].filter((t) => !VM_INDEX_EVENT_TYPES.has(t));\n\nfunction sourceFilters(subgraph: SubgraphDefinition): SubgraphFilter[] {\n\tconst sources = subgraph.sources;\n\treturn Array.isArray(sources)\n\t\t? (sources as SubgraphFilter[])\n\t\t: Object.values(sources as Record<string, SubgraphFilter>);\n}\n\n/**\n * True when any source matches transactions (contract_call / contract_deploy):\n * the handler receives the full tx, so the loader must fetch real transactions.\n * Event-only subgraphs skip walkTransactions and synthesize the tx from joined\n * event context instead (the ~37x reindex over-fetch; see indexing-speed plan).\n */\nexport function needsTransactionData(subgraph: SubgraphDefinition): boolean {\n\treturn sourceFilters(subgraph).some((f) => TX_SOURCE_TYPES.has(f.type));\n}\n\n/** Build the (few) event-bearing txs from joined event context, one per tx_id —\n * the event-only replacement for draining every transaction in the range. */\nfunction synthesizeTxsFromEvents(events: IndexEventRow[]): Transaction[] {\n\tconst byId = new Map<string, Transaction>();\n\tfor (const e of events) {\n\t\tif (!byId.has(e.tx_id)) byId.set(e.tx_id, reconstructTxFromEventRow(e));\n\t}\n\treturn [...byId.values()];\n}\n\n/**\n * The Index event_types the loader must fetch for a set of source filter types.\n * A contract_call/contract_deploy source matches a tx and hands its FULL event\n * set to the handler, so when one is present we fetch every classic event type\n * (the matched tx's events must be complete); otherwise just the referenced\n * types. VM types ride a second clock and are fetched only when referenced.\n * Shared by the subgraph loader and the chain-trigger evaluator.\n */\nexport function indexEventTypesForFilterTypes(filterTypes: string[]): string[] {\n\tconst types = new Set<string>();\n\tif (filterTypes.some((t) => TX_SOURCE_TYPES.has(t))) {\n\t\tfor (const t of CLASSIC_INDEX_EVENT_TYPES) types.add(t);\n\t}\n\tfor (const t of filterTypes) {\n\t\tconst indexType = EVENT_FILTER_TO_INDEX_TYPE[t];\n\t\tif (indexType) types.add(indexType);\n\t}\n\treturn [...types];\n}\n\n/** Index event_types a subgraph's sources require. Empty when sources are absent. */\nexport function referencedIndexEventTypes(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\tif (!subgraph.sources) return [];\n\treturn indexEventTypesForFilterTypes(\n\t\tsourceFilters(subgraph).map((f) => f.type),\n\t);\n}\n\n/**\n * streams-index eligibility: every source must be a known event-type or\n * contract_call/contract_deploy filter (no array-style sources, which leak the\n * unreconstructable `_eventId`). Trait scope IS allowed — trait resolution\n * reads the contract registry on the platform DB (`targetDb`), which the\n * processor always holds, so it's source-independent. Everything else stays on\n * the DB tap.\n */\nexport function isStreamsIndexEligible(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\tfor (const f of filters) {\n\t\tconst known =\n\t\t\tEVENT_FILTER_TO_INDEX_TYPE[f.type] || TX_SOURCE_TYPES.has(f.type);\n\t\tif (!known) return false;\n\t}\n\treturn true;\n}\n\n/** Merge of overlapping walks: one row per (type, height, event_index). */\nfunction dedupeEvents(rows: IndexEventRow[]): IndexEventRow[] {\n\tconst seen = new Set<string>();\n\treturn rows.filter((e) => {\n\t\tconst key = `${e.event_type}|${e.block_height}|${e.event_index}`;\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\n/** Streams clock + Index data plane, reconstructed into raw BlockData rows. */\nexport class PublicApiBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly http: IndexHttpClient,\n\t\tprivate readonly eventTypes: string[],\n\t\t/** When set, enables the sparse-scan probe (event-scoped subgraphs). */\n\t\tprivate readonly probeTargets?: SparseProbeTarget[] | undefined,\n\t\t/** False for event-only subgraphs → skip walkTransactions, synthesize the\n\t\t * tx from joined event context. Defaults true (safe / unchanged). */\n\t\tprivate readonly needsTransactions = true,\n\t\t/** Write events from `state_writes` instead of the vm event walks. */\n\t\tprivate readonly feed?: StateWriteFeed | undefined,\n\t) {}\n\n\t/**\n\t * What the event walks fetch. Event-only subgraphs walk exactly what their\n\t * filters can match (contract-scoped where a filter pins one); tx-level\n\t * sources need every event of a matched tx, so they walk each type whole.\n\t */\n\tprivate walkTargets(): SparseProbeTarget[] {\n\t\tconst scoped = this.needsTransactions ? undefined : this.probeTargets;\n\t\t// Under a state_writes feed, write events come from the writes walk.\n\t\tconst types = this.feed\n\t\t\t? this.eventTypes.filter((t) => !VM_INDEX_EVENT_TYPES.has(t))\n\t\t\t: this.eventTypes;\n\t\treturn types.flatMap((eventType) => {\n\t\t\tconst own = scoped?.filter((t) => t.eventType === eventType);\n\t\t\treturn own?.length ? own : [{ eventType }];\n\t\t});\n\t}\n\n\t/** Lowest height in (after, until] any probe target hits, or null. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.probeTargets?.length) return afterHeight + 1;\n\t\tconst hits = await Promise.all(\n\t\t\tthis.probeTargets.map((t) =>\n\t\t\t\tthis.http.firstEventHeight(\n\t\t\t\t\tt.eventType,\n\t\t\t\t\tafterHeight + 1,\n\t\t\t\t\tuntilHeight,\n\t\t\t\t\tt.contractId,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst found = hits.filter((h): h is number => h !== null);\n\t\treturn found.length ? Math.min(...found) : null;\n\t}\n\n\tgetTip(opts?: { wait?: number; knownHeight?: number }): Promise<number> {\n\t\t// VM rows land with ingest. Decoded Index tip can lag; use the source\n\t\t// field when this loader fetches any vm type.\n\t\tif (this.eventTypes.some((t) => VM_INDEX_EVENT_TYPES.has(t))) {\n\t\t\treturn this.http.getIndexSourceTip(opts);\n\t\t}\n\t\t// Scope the tip (and, with `wait`, what counts as \"nothing new\") to\n\t\t// exactly the classic types THIS source reads instead of the global\n\t\t// cross-decoder floor. Without this, any of the ~15 classic decoders\n\t\t// committing — most unrelated to what this source actually walks —\n\t\t// moves the global floor and makes an unrelated `wait` return early.\n\t\treturn this.http.getIndexTip({ ...opts, eventTypes: this.eventTypes });\n\t}\n\n\t/** Reads the SAME envelope `getTip()` just cached on `this.http` — call\n\t * this only after `getTip()` has resolved at least once. */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.http.getDecodedHeights();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\t// Event-only subgraphs join tx context onto events (withTx) and skip the\n\t\t// walkTransactions over-fetch entirely; tx-level sources fetch real txs.\n\t\tconst withTx = !this.needsTransactions;\n\t\tconst [blocks, txRows, eventLists, writes] = await Promise.all([\n\t\t\tthis.http.walkBlocks(fromHeight, toHeight),\n\t\t\tthis.needsTransactions\n\t\t\t\t? this.http.walkTransactions(fromHeight, toHeight)\n\t\t\t\t: Promise.resolve<IndexTransactionRow[]>([]),\n\t\t\tPromise.all(\n\t\t\t\tthis.walkTargets().map((t) =>\n\t\t\t\t\tthis.http.walkEvents(\n\t\t\t\t\t\tt.eventType,\n\t\t\t\t\t\tfromHeight,\n\t\t\t\t\t\ttoHeight,\n\t\t\t\t\t\twithTx,\n\t\t\t\t\t\tt.contractId,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.feed ? this.walkWrites(fromHeight, toHeight, this.feed) : null,\n\t\t]);\n\t\tconst events = dedupeEvents(eventLists.flat());\n\n\t\tconst map = new Map<number, BlockData>();\n\t\t// Seed every canonical height (incl. empty blocks) so catch-up doesn't\n\t\t// file them as gaps.\n\t\tfor (const b of blocks) {\n\t\t\tmap.set(b.block_height, {\n\t\t\t\tblock: reconstructBlock(b),\n\t\t\t\ttxs: [],\n\t\t\t\tevents: [],\n\t\t\t});\n\t\t}\n\t\t// For event-only subgraphs, materialize only the event-bearing txs from\n\t\t// joined event context instead of every transaction in the range.\n\t\tconst txs = this.needsTransactions\n\t\t\t? txRows.map(reconstructTransaction)\n\t\t\t: synthesizeTxsFromEvents(events);\n\t\tfor (const t of txs) {\n\t\t\tmap.get(t.block_height)?.txs.push(t);\n\t\t}\n\t\tfor (const e of events) {\n\t\t\tconst bd = map.get(e.block_height);\n\t\t\tif (!bd) continue;\n\t\t\t// vm rows ride their own clock: never merged into `events`, whose\n\t\t\t// order is classic event_index.\n\t\t\tif (VM_INDEX_EVENT_TYPES.has(e.event_type)) {\n\t\t\t\tbd.vmEvents ??= [];\n\t\t\t\tbd.vmEvents.push(reconstructEvent(e));\n\t\t\t} else {\n\t\t\t\tbd.events.push(reconstructEvent(e));\n\t\t\t}\n\t\t}\n\t\tif (writes) {\n\t\t\tfor (const [height, fed] of writes) {\n\t\t\t\tconst bd = map.get(height);\n\t\t\t\tif (!bd) continue;\n\t\t\t\tbd.txs.push(...fed.txs);\n\t\t\t\tbd.vmEvents = fed.vmEvents;\n\t\t\t}\n\t\t}\n\t\t// Canonical ordering — multi-type event walks merge here, per clock.\n\t\tfor (const bd of map.values()) {\n\t\t\tbd.txs.sort((a, b) => (a.tx_index ?? 0) - (b.tx_index ?? 0));\n\t\t\tbd.events.sort((a, b) => a.event_index - b.event_index);\n\t\t\tbd.vmEvents?.sort((a, b) => a.event_index - b.event_index);\n\t\t}\n\t\treturn map;\n\t}\n\n\t/** Each height's named writes as events, the writing txs rebuilt from the\n\t * joined `tx_*` fields. One walk per contract, merged in ordinal order. */\n\tprivate async walkWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tfeed: StateWriteFeed,\n\t): Promise<ReturnType<typeof stateWriteBlocks>> {\n\t\tconst walks = await Promise.all(\n\t\t\t(feed.contracts ?? [undefined]).map((c) =>\n\t\t\t\tthis.http.walkStateWrites(fromHeight, toHeight, c),\n\t\t\t),\n\t\t);\n\t\tconst writesByHeight = new Map<number, Map<number, StateWriteRow>>();\n\t\tconst txsByHeight = new Map<number, Map<number, TxRecord>>();\n\t\tfor (const row of walks.flat()) {\n\t\t\tconst writes = writesByHeight.get(row.block_height) ?? new Map();\n\t\t\twrites.set(row.ordinal, row);\n\t\t\twritesByHeight.set(row.block_height, writes);\n\t\t\tconst tx = writeTx(row);\n\t\t\tif (tx) {\n\t\t\t\tconst txs = txsByHeight.get(row.block_height) ?? new Map();\n\t\t\t\ttxs.set(row.tx_index as number, tx);\n\t\t\t\ttxsByHeight.set(row.block_height, txs);\n\t\t\t}\n\t\t}\n\t\treturn stateWriteBlocks(\n\t\t\tnew Map(\n\t\t\t\t[...writesByHeight].map(([h, w]) => [\n\t\t\t\t\th,\n\t\t\t\t\t[...w.values()].sort((a, b) => a.ordinal - b.ordinal),\n\t\t\t\t]),\n\t\t\t),\n\t\t\tnew Map([...txsByHeight].map(([h, t]) => [h, [...t.values()]])),\n\t\t);\n\t}\n}\n\n/** The writing tx a `tx_context=true` row carries; null for block-level\n * writes or a row whose tx the Index could not join. */\nfunction writeTx(row: IndexStateWriteRow): TxRecord | null {\n\tif (row.tx_index === null || !row.tx_id) return null;\n\treturn {\n\t\ttx_id: row.tx_id,\n\t\ttx_index: row.tx_index,\n\t\ttype: row.tx_type ?? \"\",\n\t\tsender: row.tx_sender ?? \"\",\n\t\tstatus: row.tx_status ?? \"\",\n\t\tcontract_id: row.tx_contract_id ?? null,\n\t\tfunction_name: row.tx_function_name ?? null,\n\t};\n}\n\n/**\n * Wraps a primary source and falls back to a secondary, per call, when the\n * primary throws. Use it to make the HTTP (Streams+Index) plane a SOFT dependency:\n * if api is unavailable, the processor reads the Postgres tap and keeps advancing\n * instead of stalling. Safe to mix mid-stream — both taps read the same canonical\n * chain at the same heights and the cursor is forward-only. Stateless (no breaker)\n * so it's failover-safe across replicas; the primary is retried every call and\n * resumes transparently once healthy.\n */\nexport class FallbackBlockSource implements BlockSource {\n\t/** True when the LAST `getTip()` call actually used the primary — guards\n\t * `getDecodedHeights()` against returning the primary's stale cached\n\t * envelope from an earlier success after a call that just fell back. */\n\tprivate lastTipFromPrimary = false;\n\n\tconstructor(\n\t\tprivate readonly primary: BlockSource,\n\t\tprivate readonly fallback: BlockSource,\n\t) {}\n\n\tasync getTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\ttry {\n\t\t\tconst tip = await this.primary.getTip(opts);\n\t\t\tthis.lastTipFromPrimary = true;\n\t\t\treturn tip;\n\t\t} catch (err) {\n\t\t\t// A billing refusal is not the api being down: the DB tap would\n\t\t\t// quietly serve different data, so let the caller pause instead.\n\t\t\tif (err instanceof BillingPausedError) throw err;\n\t\t\tlogger.warn(\"block source primary getTip failed — using DB tap\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tthis.lastTipFromPrimary = false;\n\t\t\t// The DB tap has no wait/long-poll notion — a plain read is already\n\t\t\t// instant, so `opts` is dropped here rather than forwarded.\n\t\t\treturn this.fallback.getTip();\n\t\t}\n\t}\n\n\t/** Only meaningful right after a `getTip()` that used the primary — the\n\t * fallback (Postgres tap) has no such notion, and returning the\n\t * primary's stale cache after a fallback would mismatch the returned\n\t * tip. Local mode's own `decoderBoundTip` never calls this. */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\tif (!this.lastTipFromPrimary) return undefined;\n\t\treturn this.primary.getDecodedHeights?.();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\ttry {\n\t\t\treturn await this.primary.loadBlockRange(fromHeight, toHeight);\n\t\t} catch (err) {\n\t\t\tif (err instanceof BillingPausedError) throw err;\n\t\t\tlogger.warn(\"block source primary loadBlockRange failed — using DB tap\", {\n\t\t\t\tfrom: fromHeight,\n\t\t\t\tto: toHeight,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.loadBlockRange(fromHeight, toHeight);\n\t\t}\n\t}\n\n\t/** Probe via the primary only; a probe failure just means \"no skip\" —\n\t * the caller falls back to plain batch advancement. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.primary.nextDataHeight) return afterHeight + 1;\n\t\ttry {\n\t\t\treturn await this.primary.nextDataHeight(afterHeight, untilHeight);\n\t\t} catch {\n\t\t\treturn afterHeight + 1;\n\t\t}\n\t}\n}\n\nconst postgresBlockSource = new PostgresBlockSource();\n\n/** The Postgres tap for a subgraph: its `state_writes` feed when it has one. */\nfunction postgresSourceFor(feed: StateWriteFeed | null): BlockSource {\n\treturn feed ? new PostgresBlockSource(feed) : postgresBlockSource;\n}\n\n/**\n * HTTP (Streams+Index) chain source for a set of decoded event types, wrapped so\n * it falls back to the Postgres tap when api is down. Used by the chain-trigger\n * evaluator (which isn't subgraph-scoped, so it can't go through resolveBlockSource).\n *\n * `needsTransactions` defaults true (safe/unchanged) but the evaluator passes\n * `chainSubsNeedTransactions(chainSubs)` so a tick with no contract_call/deploy\n * trigger skips `walkTransactions` entirely — one fewer HTTP round trip and a\n * smaller `walkEvents` payload (no `tx_context` join) on every such tick.\n *\n * `httpClient` defaults to a fresh client (unchanged behavior) — pass one in\n * to reuse across calls. The evaluator's own long-lived loop does this so\n * `IndexHttpClient.waitIsSupported()` reflects what THIS\n * server actually supports instead of resetting every tick.\n */\nexport function buildChainBlockSource(\n\teventTypes: string[],\n\tneedsTransactions = true,\n\thttpClient: IndexHttpClient = buildHttpClient(),\n): BlockSource {\n\treturn new FallbackBlockSource(\n\t\tnew PublicApiBlockSource(\n\t\t\thttpClient,\n\t\t\teventTypes,\n\t\t\tundefined,\n\t\t\tneedsTransactions,\n\t\t),\n\t\tpostgresBlockSource,\n\t);\n}\n\nexport function buildHttpClient(): IndexHttpClient {\n\treturn createInternalIndexHttpClient();\n}\n\n/**\n * Resolve the block source for a subgraph. `SUBGRAPH_SOURCE=streams-index`\n * opts eligible subgraphs onto the public Streams clock + Index data;\n * `SUBGRAPH_SOURCE=observer-http` pages internal observer-events (experimental).\n * Default stays on the Postgres tap.\n */\nexport async function resolveBlockSource(\n\tsubgraph?: SubgraphDefinition,\n): Promise<BlockSource> {\n\tif (process.env.SUBGRAPH_SOURCE === \"observer-http\") {\n\t\tconst baseUrl = process.env.OBSERVER_HTTP_URL;\n\t\tif (!baseUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t\"SUBGRAPH_SOURCE=observer-http requires OBSERVER_HTTP_URL\",\n\t\t\t);\n\t\t}\n\t\treturn new ObserverHttpBlockSource({\n\t\t\tbaseUrl,\n\t\t\ttoken: process.env.OBSERVER_HTTP_EXPORT_TOKEN || null,\n\t\t});\n\t}\n\tif (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tsubgraph &&\n\t\tisStreamsIndexEligible(subgraph)\n\t) {\n\t\t// Soft-depend on api: fall back to the Postgres tap per-call if the HTTP\n\t\t// plane is down, so the processor keeps advancing instead of stalling.\n\t\t// Both read the same feed, decided by the plane this source reads.\n\t\tconst feed =\n\t\t\t(await stateWriteFeed(subgraph, httpStateWritesCoverage())) ?? undefined;\n\t\treturn new FallbackBlockSource(\n\t\t\tnew PublicApiBlockSource(\n\t\t\t\tbuildHttpClient(),\n\t\t\t\treferencedIndexEventTypes(subgraph),\n\t\t\t\t// The sparse probe reads vm_events; a state_writes feed walks\n\t\t\t\t// every block instead of skipping on another table's rows.\n\t\t\t\tcanSparseScan(subgraph) && !feed\n\t\t\t\t\t? sparseProbeTargets(subgraph)\n\t\t\t\t\t: undefined,\n\t\t\t\tneedsTransactionData(subgraph),\n\t\t\t\tfeed,\n\t\t\t),\n\t\t\tpostgresSourceFor(feed ?? null),\n\t\t);\n\t}\n\tif (process.env.SUBGRAPH_SOURCE === \"streams-index\" && subgraph) {\n\t\tlogger.debug(\"Subgraph not streams-index eligible, using DB tap\", {\n\t\t\tsubgraph: subgraph.name,\n\t\t});\n\t}\n\treturn postgresSourceFor(await stateWriteFeed(subgraph));\n}\n",
5
+ "import { createHash } from \"node:crypto\";\nimport { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport type { Webhook } from \"@secondlayer/shared/db\";\nimport { getWebhook } from \"@secondlayer/shared/db/queries/webhooks\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { Kysely } from \"kysely\";\nimport {\n\ttype BlockSource,\n\tPublicApiBlockSource,\n\tbuildHttpClient,\n} from \"./block-source.ts\";\nimport {\n\tblockTimeOf,\n\tbuildSourcesMap,\n\tbuildTraitContracts,\n\temitChainOutbox,\n\temitSbtcOutbox,\n\tevaluateBlock,\n\treferencedEventTypes,\n} from \"./trigger-evaluator.ts\";\n\n/**\n * Replay a historical block range as new outbox entries for a single\n * webhook. Rows are marked `is_replay=TRUE` so the emitter can\n * prioritize live deliveries (90/10 split) and the delivery log can\n * tag replays distinctly.\n *\n * Idempotency: `replayId` is deterministic over `(webhook_id,\n * fromBlock, toBlock)`, so re-running the same replay range is a no-op\n * thanks to the unique `(webhook_id, dedup_key)` constraint. A\n * user who actually wants to re-deliver the same range passes a\n * distinct `replayIdSuffix` (e.g. a timestamp) to get a fresh key.\n */\n\n/** Default cap on blocks per replay call — overridable via\n * `WEBHOOK_REPLAY_MAX_BLOCKS` for an operator who wants a tighter (or, for a\n * trusted self-host, looser) limit. Read live, not baked in at import. */\nconst WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT = 100_000;\n\nfunction webhookReplayMaxBlocks(): number {\n\tconst raw = process.env.WEBHOOK_REPLAY_MAX_BLOCKS;\n\tif (raw === undefined) return WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT;\n\tconst parsed = Number.parseInt(raw, 10);\n\treturn Number.isFinite(parsed) && parsed > 0\n\t\t? parsed\n\t\t: WEBHOOK_REPLAY_MAX_BLOCKS_DEFAULT;\n}\n\n/** Renders a block count the way the original hardcoded message did\n * (\"100k blocks\") for round thousands, falling back to the raw number for a\n * ceiling that isn't a clean multiple of 1000. */\nfunction formatBlockCount(n: number): string {\n\treturn n % 1000 === 0 ? `${n / 1000}k` : `${n}`;\n}\n\n/**\n * One in-flight replay per webhook at a time. Replay is a synchronous scan\n * (the route awaits it fully before responding), so two concurrent requests\n * for the same webhook would otherwise interleave their scans against the\n * same dedup keyspace. In-memory per-process — replay already isn't\n * horizontally coordinated (see `BATCH_SIZE` keyset pagination above), so\n * this matches its existing single-process assumption.\n */\nconst inFlightReplays = new Set<string>();\n\n/** Thrown by {@link replayWebhook} when a replay is already running for the\n * webhook. The route maps this to 409; `force` does not bypass it — a forced\n * re-delivery still has to wait for the previous replay to finish. */\nexport class ReplayInProgressError extends Error {\n\tconstructor() {\n\t\tsuper(\"replay already in progress for this webhook\");\n\t\tthis.name = \"ReplayInProgressError\";\n\t}\n}\n\n/**\n * Test-only seam: directly mark (or clear) a webhook as having an in-flight\n * replay. Two real concurrent `replayWebhook` calls race the same DB fetch,\n * so which one wins the guard isn't deterministic in a test; this lets a test\n * exercise the guard (and the route's 409 mapping) without that race.\n * Production code never calls this.\n */\nexport function __setReplayInFlightForTest(\n\twebhookId: string,\n\tinFlight: boolean,\n): void {\n\tif (inFlight) inFlightReplays.add(webhookId);\n\telse inFlightReplays.delete(webhookId);\n}\n\nexport interface ReplayInput {\n\taccountId: string;\n\twebhookId: string;\n\tfromBlock: number;\n\ttoBlock: number;\n\t/** Force re-delivery by appending a unique suffix to the replay id. */\n\treplayIdSuffix?: string;\n}\n\nfunction deterministicReplayId(\n\twebhookId: string,\n\tfromBlock: number,\n\ttoBlock: number,\n\tsuffix?: string,\n): string {\n\tconst canonical = `${webhookId}:${fromBlock}:${toBlock}${suffix ? `:${suffix}` : \"\"}`;\n\treturn createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 16);\n}\n\nexport interface ReplayResult {\n\treplayId: string;\n\tenqueuedCount: number;\n\tscannedCount: number;\n}\n\nexport async function replayWebhook(input: ReplayInput): Promise<ReplayResult> {\n\tif (input.fromBlock > input.toBlock) {\n\t\tthrow new Error(\"fromBlock must be <= toBlock\");\n\t}\n\tconst maxBlocks = webhookReplayMaxBlocks();\n\tif (input.toBlock - input.fromBlock > maxBlocks) {\n\t\tthrow new Error(\n\t\t\t`replay range exceeds ${formatBlockCount(maxBlocks)} blocks`,\n\t\t);\n\t}\n\n\tconst db = getTargetDb();\n\tconst sub = await getWebhook(db, input.accountId, input.webhookId);\n\tif (!sub) throw new Error(\"Webhook not found\");\n\n\tif (inFlightReplays.has(sub.id)) {\n\t\tthrow new ReplayInProgressError();\n\t}\n\tinFlightReplays.add(sub.id);\n\ttry {\n\t\treturn await replayChainWebhook(db, sub, input);\n\t} finally {\n\t\tinFlightReplays.delete(sub.id);\n\t}\n}\n\nconst CHAIN_REPLAY_BATCH = 200;\n\n/**\n * Replay a webhook by re-running the pure matcher over a historical\n * canonical block range and emitting fresh apply rows. The matcher is\n * range-driven, so we reload canonical blocks off the public Index/Streams\n * clock and re-match.\n *\n * Rows are emitted with `is_replay=TRUE` and replay-namespaced dedup keys, and —\n * critically — this never advances `trigger_evaluator_state`: replay is\n * historical and must not move the live forward cursor.\n */\nexport async function replayChainWebhook(\n\tdb: Kysely<Database>,\n\tsub: Webhook,\n\tinput: ReplayInput,\n\topts?: { source?: BlockSource },\n): Promise<ReplayResult> {\n\tconst replayId = deterministicReplayId(\n\t\tsub.id,\n\t\tinput.fromBlock,\n\t\tinput.toBlock,\n\t\tinput.replayIdSuffix,\n\t);\n\n\tconst { sources, keyMeta } = buildSourcesMap([sub]);\n\tconst source =\n\t\topts?.source ??\n\t\tnew PublicApiBlockSource(buildHttpClient(), referencedEventTypes([sub]));\n\n\tlet scanned = 0;\n\tlet enqueued = 0;\n\tfor (\n\t\tlet from = input.fromBlock;\n\t\tfrom <= input.toBlock;\n\t\tfrom += CHAIN_REPLAY_BATCH\n\t) {\n\t\tconst to = Math.min(from + CHAIN_REPLAY_BATCH - 1, input.toBlock);\n\t\tconst blocks = await source.loadBlockRange(from, to);\n\t\t// Trait membership only grows; resolve once per batch as of its top height.\n\t\tconst traitContracts = await buildTraitContracts([sub], to);\n\t\tfor (let h = from; h <= to; h++) {\n\t\t\tconst bd = blocks.get(h);\n\t\t\tif (!bd) continue;\n\t\t\tscanned++;\n\t\t\tconst blockTime = blockTimeOf(bd.block);\n\t\t\tconst matches = evaluateBlock(bd, sources, traitContracts);\n\t\t\tif (matches.length > 0) {\n\t\t\t\tenqueued += await emitChainOutbox(\n\t\t\t\t\tdb,\n\t\t\t\t\tmatches,\n\t\t\t\t\tkeyMeta,\n\t\t\t\t\th,\n\t\t\t\t\tbd.block.hash,\n\t\t\t\t\tblockTime,\n\t\t\t\t\t{\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\t// sBTC lifecycle triggers (deposit/withdrawal-create/accept/reject) match\n\t\t\t// against `sbtc_events`, not decoded_events — mirror the live loop so a\n\t\t\t// replay over a historical range backfills sBTC webhooks too. (Settlement\n\t\t\t// `swept_confirmed` is cursor/confirmed_at driven, not block-keyed, so it\n\t\t\t// emits nothing here — documented forward-only.)\n\t\t\tenqueued += await emitSbtcOutbox(db, [sub], h, bd.block.hash, blockTime, {\n\t\t\t\treplayId,\n\t\t\t});\n\t\t}\n\t}\n\n\tlogger.info(\"Chain replay enqueued\", {\n\t\twebhook: sub.name,\n\t\treplayId,\n\t\tscanned,\n\t\tenqueued,\n\t\tfromBlock: input.fromBlock,\n\t\ttoBlock: input.toBlock,\n\t});\n\n\treturn { replayId, enqueuedCount: enqueued, scannedCount: scanned };\n}\n",
6
+ "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Transaction } from \"@secondlayer/shared/db\";\nimport {\n\tBillingPausedError,\n\ttype IndexEventRow,\n\ttype IndexHttpClient,\n\ttype IndexStateWriteRow,\n\ttype IndexTransactionRow,\n\tcreateInternalIndexHttpClient,\n} from \"@secondlayer/shared/index-http\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition, SubgraphFilter } from \"../types.ts\";\nimport { deriveVerification } from \"../verification.ts\";\nimport {\n\ttype BlockData,\n\ttype StateWriteFeed,\n\tloadBlockRange,\n\tstateWriteBlocks,\n} from \"./batch-loader.ts\";\nimport { ObserverHttpBlockSource } from \"./observer-http-source.ts\";\nimport { runsInRealm } from \"./realm.ts\";\nimport {\n\treconstructBlock,\n\treconstructEvent,\n\treconstructTransaction,\n\treconstructTxFromEventRow,\n} from \"./reconstruct.ts\";\nimport type { TxRecord } from \"./source-matcher.ts\";\nimport type { StateWriteRow } from \"./state-writes.ts\";\n\n/**\n * Where the subgraph runtime reads canonical chain data. Today it taps the\n * indexer Postgres directly (`PostgresBlockSource`); the re-point adds a\n * `PublicApiBlockSource` that consumes the Streams clock + Index data over\n * HTTP. `matchSources` / handlers / flush are unchanged — only the\n * loader + tip swap behind this seam.\n */\nexport interface BlockSource {\n\t/**\n\t * Highest canonical block height available to process.\n\t *\n\t * `opts` is an HTTP-plane long-poll hint, ignored by any\n\t * source with no such notion (the Postgres tap: a local DB read is already\n\t * instant, nothing to wait on). `knownHeight` is the last tip THIS caller\n\t * observed; passing `wait` without it is a no-op — the server needs a\n\t * baseline to decide whether anything has changed.\n\t */\n\tgetTip(opts?: { wait?: number; knownHeight?: number }): Promise<number>;\n\t/** Canonical block data for [fromHeight, toHeight], keyed by height. */\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>>;\n\t/** Sparse-scan probe: lowest height in (afterHeight, untilHeight] holding\n\t * an event this source's subgraph could match, or null when the rest of\n\t * the range is empty. Optional — only event-scoped sources support it. */\n\tnextDataHeight?(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null>;\n\t/**\n\t * Per-decoder committed heights from the SAME response `getTip()` just\n\t * fetched (no extra request) — undefined for a source with no such notion\n\t * (the Postgres tap: local mode reads `decoder_checkpoints` directly and\n\t * never needs this). Lets a caller (the chain evaluator) narrow its own\n\t * bound to the decoders it actually reads instead of `getTip()`'s\n\t * conservative cross-decoder floor. Call AFTER `getTip()`.\n\t */\n\tgetDecodedHeights?(): Record<string, number | null> | undefined;\n}\n\n/** A (decoded event type, optional contract scope) pair the sparse probe\n * checks. Contract scoping is what makes token-subgraph reindexes leap over\n * everything that isn't their token. */\nexport type SparseProbeTarget = { eventType: string; contractId?: string };\n\n/** Sparse scanning is sound only when EVERY source is an event-type filter —\n * a contract_call/contract_deploy source matches transactions, which the\n * event probe can't see. */\nexport function canSparseScan(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\treturn filters.every((f) => Boolean(EVENT_FILTER_TO_INDEX_TYPE[f.type]));\n}\n\n/** Most contracts one filter may pin before it is treated as unscoped (the\n * Index list-filter ceiling; beyond it a per-contract walk fan-out costs more\n * than it saves). */\nconst MAX_PINNED_CONTRACTS = 20;\n\n/**\n * Concrete contract ids a filter pins, or null when it pins none the Index can\n * be asked for. Wildcards, trait scope and factory scope resolve per block\n * against registry state the Index cannot see, so they stay unscoped: scoping\n * them would change which events a handler receives.\n */\nfunction pinnedContracts(filter: SubgraphFilter): string[] | null {\n\tconst f = filter as {\n\t\tcontractId?: string | readonly string[];\n\t\tassetIdentifier?: string;\n\t\ttrait?: unknown;\n\t\tfactory?: unknown;\n\t};\n\tif (f.trait || f.factory) return null;\n\tconst ids = Array.isArray(f.contractId)\n\t\t? [...f.contractId]\n\t\t: f.contractId\n\t\t\t? [f.contractId as string]\n\t\t\t: f.assetIdentifier\n\t\t\t\t? [f.assetIdentifier.split(\"::\")[0] as string]\n\t\t\t\t: [];\n\tif (ids.length === 0 || ids.length > MAX_PINNED_CONTRACTS) return null;\n\tif (ids.some((id) => !id || id.includes(\"*\"))) return null;\n\treturn ids;\n}\n\n/**\n * The (decoded event type, contract scope) pairs a subgraph's filters can\n * match. One function feeds BOTH the sparse probe and the event walks, so a\n * new contract-pinning filter field is added here once.\n *\n * Per event type: if ANY filter for it is unscoped, a single unscoped target\n * covers everything (today's behavior); otherwise one target per distinct\n * pinned contract.\n */\nexport function sparseProbeTargets(\n\tsubgraph: SubgraphDefinition,\n): SparseProbeTarget[] {\n\tconst byType = new Map<string, Set<string> | \"all\">();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst eventType = EVENT_FILTER_TO_INDEX_TYPE[f.type];\n\t\tif (!eventType) continue;\n\t\tconst pinned = pinnedContracts(f);\n\t\tconst prev = byType.get(eventType);\n\t\tif (!pinned || prev === \"all\") {\n\t\t\tbyType.set(eventType, \"all\");\n\t\t\tcontinue;\n\t\t}\n\t\tconst set = prev ?? new Set<string>();\n\t\tfor (const id of pinned) set.add(id);\n\t\tbyType.set(eventType, set);\n\t}\n\tconst targets: SparseProbeTarget[] = [];\n\tfor (const [eventType, scope] of byType) {\n\t\tif (scope === \"all\") targets.push({ eventType });\n\t\telse\n\t\t\tfor (const contractId of scope) targets.push({ eventType, contractId });\n\t}\n\treturn targets;\n}\n\n/** Lowest height this instance holds `state_writes` for; null when none. */\nexport type StateWritesCoverage = () => Promise<number | null>;\n\n/** How long a coverage answer is reused. Coverage only appears (the node\n * starts delivering `state_writes`) or reaches lower (a backfill). */\nconst COVERAGE_TTL_MS = 60_000;\n\n/** A coverage read cached per process; `forget` drops the cached answer. */\nexport type CachedCoverage = StateWritesCoverage & { forget(): void };\n\n/** Cache a coverage read per process; a failed read counts as no coverage. */\nexport function cachedCoverage(\n\tread: () => Promise<number | null>,\n\tttlMs: number = COVERAGE_TTL_MS,\n): CachedCoverage {\n\tlet cached: { at: number; value: Promise<number | null> } | undefined;\n\tconst coverage = () => {\n\t\tconst now = Date.now();\n\t\tif (!cached || now - cached.at > ttlMs) {\n\t\t\tcached = { at: now, value: read().catch(() => null) };\n\t\t}\n\t\treturn cached.value;\n\t};\n\treturn Object.assign(coverage, {\n\t\tforget: () => {\n\t\t\tcached = undefined;\n\t\t},\n\t});\n}\n\n/** The DB tap's coverage: the lowest `state_writes` height, one PK probe. */\nexport const dbStateWritesCoverage: CachedCoverage = cachedCoverage(\n\tasync () => {\n\t\tconst row = await getSourceDb()\n\t\t\t.selectFrom(\"state_writes\")\n\t\t\t.select(\"block_height\")\n\t\t\t.orderBy(\"block_height\", \"asc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? Number(row.block_height) : null;\n\t},\n);\n\nlet httpCoverage: StateWritesCoverage | undefined;\n/** The Index API's coverage: the first `/v1/index/state-writes` row. */\nfunction httpStateWritesCoverage(): StateWritesCoverage {\n\thttpCoverage ??= cachedCoverage(() =>\n\t\tbuildHttpClient().firstStateWriteHeight(),\n\t);\n\treturn httpCoverage;\n}\n\n/**\n * The contracts whose writes a state subgraph would read from `state_writes`,\n * or null when it keeps `vm_events` whatever the instance holds.\n *\n * Only a subgraph running in the deterministic realm (stored level `state`)\n * whose sources the CURRENT rules still derive as `state`. A subgraph stored\n * as `state` before `map_insert` dropped to `events` keeps its `vm_events`\n * feed: `state_writes` cannot tell an insert from a set, so it would silently\n * lose those events.\n */\nexport function stateWriteContracts(\n\tsubgraph: SubgraphDefinition | undefined,\n): StateWriteFeed | null {\n\tif (!subgraph || !runsInRealm(subgraph)) return null;\n\tif (deriveVerification(subgraph).level !== \"state\") return null;\n\tconst contracts = new Set<string>();\n\tfor (const f of sourceFilters(subgraph)) {\n\t\tconst pinned = pinnedContracts(f);\n\t\t// A source with no fixed contract (wildcard, factory) needs every\n\t\t// contract's writes.\n\t\tif (!pinned) return { contracts: null };\n\t\tfor (const id of pinned) contracts.add(id);\n\t}\n\treturn { contracts: [...contracts] };\n}\n\n/**\n * The `state_writes` feed for a subgraph, or null when it keeps today's\n * `vm_events` feed. Derived, never configured: a state subgraph switches only\n * once this instance holds `state_writes` from the subgraph's `startBlock`\n * on, so a node that does not deliver them (or started delivering them after\n * the subgraph's range began) changes nothing.\n */\nexport async function stateWriteFeed(\n\tsubgraph: SubgraphDefinition | undefined,\n\tcoverage: StateWritesCoverage = dbStateWritesCoverage,\n): Promise<StateWriteFeed | null> {\n\tconst feed = stateWriteContracts(subgraph);\n\tif (!feed) return null;\n\tconst from = await coverage();\n\tif (from === null || from > (subgraph?.startBlock ?? 0)) return null;\n\treturn feed;\n}\n\n/** Reads directly from the shared indexer Postgres (the original behavior). */\nexport class PostgresBlockSource implements BlockSource {\n\t/** `feed`: read write events from `state_writes` (see {@link stateWriteFeed}). */\n\tconstructor(private readonly feed?: StateWriteFeed | undefined) {}\n\n\tasync getTip(): Promise<number> {\n\t\tconst progress = await getSourceDb()\n\t\t\t.selectFrom(\"index_progress\")\n\t\t\t.selectAll()\n\t\t\t.where(\"network\", \"=\", process.env.NETWORK ?? \"mainnet\")\n\t\t\t.executeTakeFirst();\n\t\treturn progress ? Number(progress.highest_seen_block) : 0;\n\t}\n\n\tloadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\treturn loadBlockRange(getSourceDb(), fromHeight, toHeight, {\n\t\t\tstateWrites: this.feed,\n\t\t});\n\t}\n}\n\n// Subgraph source filter types that map to a decoded Index event_type. The\n// `_event` suffix is the runtime's raw form; print is keyed `print_event`.\nconst EVENT_FILTER_TO_INDEX_TYPE: Record<string, string> = {\n\tstx_transfer: \"stx_transfer\",\n\tstx_mint: \"stx_mint\",\n\tstx_burn: \"stx_burn\",\n\tstx_lock: \"stx_lock\",\n\tft_transfer: \"ft_transfer\",\n\tft_mint: \"ft_mint\",\n\tft_burn: \"ft_burn\",\n\tnft_transfer: \"nft_transfer\",\n\tnft_mint: \"nft_mint\",\n\tnft_burn: \"nft_burn\",\n\tprint_event: \"print\",\n\tnested_contract_call: \"nested_contract_call\",\n\tvar_set: \"var_set\",\n\tmap_set: \"map_set\",\n\tmap_insert: \"map_insert\",\n\tmap_delete: \"map_delete\",\n};\n\n// Tx-level source types — matched against /v1/index/transactions, not events.\nconst TX_SOURCE_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\n// Second clock (ordinal). Never part of a tx's classic event set: a\n// contract_call/contract_deploy source fetches every CLASSIC type, and vm\n// types are fetched only when a vm source names them.\nexport const VM_INDEX_EVENT_TYPES: ReadonlySet<string> = new Set([\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n]);\nconst CLASSIC_INDEX_EVENT_TYPES = [\n\t...new Set(Object.values(EVENT_FILTER_TO_INDEX_TYPE)),\n].filter((t) => !VM_INDEX_EVENT_TYPES.has(t));\n\nfunction sourceFilters(subgraph: SubgraphDefinition): SubgraphFilter[] {\n\tconst sources = subgraph.sources;\n\treturn Array.isArray(sources)\n\t\t? (sources as SubgraphFilter[])\n\t\t: Object.values(sources as Record<string, SubgraphFilter>);\n}\n\n/**\n * True when any source matches transactions (contract_call / contract_deploy):\n * the handler receives the full tx, so the loader must fetch real transactions.\n * Event-only subgraphs skip walkTransactions and synthesize the tx from joined\n * event context instead (the ~37x reindex over-fetch; see indexing-speed plan).\n */\nexport function needsTransactionData(subgraph: SubgraphDefinition): boolean {\n\treturn sourceFilters(subgraph).some((f) => TX_SOURCE_TYPES.has(f.type));\n}\n\n/** Build the (few) event-bearing txs from joined event context, one per tx_id —\n * the event-only replacement for draining every transaction in the range. */\nfunction synthesizeTxsFromEvents(events: IndexEventRow[]): Transaction[] {\n\tconst byId = new Map<string, Transaction>();\n\tfor (const e of events) {\n\t\tif (!byId.has(e.tx_id)) byId.set(e.tx_id, reconstructTxFromEventRow(e));\n\t}\n\treturn [...byId.values()];\n}\n\n/**\n * The Index event_types the loader must fetch for a set of source filter types.\n * A contract_call/contract_deploy source matches a tx and hands its FULL event\n * set to the handler, so when one is present we fetch every classic event type\n * (the matched tx's events must be complete); otherwise just the referenced\n * types. VM types ride a second clock and are fetched only when referenced.\n * Shared by the subgraph loader and the chain-trigger evaluator.\n */\nexport function indexEventTypesForFilterTypes(filterTypes: string[]): string[] {\n\tconst types = new Set<string>();\n\tif (filterTypes.some((t) => TX_SOURCE_TYPES.has(t))) {\n\t\tfor (const t of CLASSIC_INDEX_EVENT_TYPES) types.add(t);\n\t}\n\tfor (const t of filterTypes) {\n\t\tconst indexType = EVENT_FILTER_TO_INDEX_TYPE[t];\n\t\tif (indexType) types.add(indexType);\n\t}\n\treturn [...types];\n}\n\n/** Index event_types a subgraph's sources require. Empty when sources are absent. */\nexport function referencedIndexEventTypes(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\tif (!subgraph.sources) return [];\n\treturn indexEventTypesForFilterTypes(\n\t\tsourceFilters(subgraph).map((f) => f.type),\n\t);\n}\n\n/**\n * streams-index eligibility: every source must be a known event-type or\n * contract_call/contract_deploy filter (no array-style sources, which leak the\n * unreconstructable `_eventId`). Trait scope IS allowed — trait resolution\n * reads the contract registry on the platform DB (`targetDb`), which the\n * processor always holds, so it's source-independent. Everything else stays on\n * the DB tap.\n */\nexport function isStreamsIndexEligible(subgraph: SubgraphDefinition): boolean {\n\tif (Array.isArray(subgraph.sources)) return false;\n\tconst filters = sourceFilters(subgraph);\n\tif (filters.length === 0) return false;\n\tfor (const f of filters) {\n\t\tconst known =\n\t\t\tEVENT_FILTER_TO_INDEX_TYPE[f.type] || TX_SOURCE_TYPES.has(f.type);\n\t\tif (!known) return false;\n\t}\n\treturn true;\n}\n\n/** Merge of overlapping walks: one row per (type, height, event_index). */\nfunction dedupeEvents(rows: IndexEventRow[]): IndexEventRow[] {\n\tconst seen = new Set<string>();\n\treturn rows.filter((e) => {\n\t\tconst key = `${e.event_type}|${e.block_height}|${e.event_index}`;\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\n/** Streams clock + Index data plane, reconstructed into raw BlockData rows. */\nexport class PublicApiBlockSource implements BlockSource {\n\tconstructor(\n\t\tprivate readonly http: IndexHttpClient,\n\t\tprivate readonly eventTypes: string[],\n\t\t/** When set, enables the sparse-scan probe (event-scoped subgraphs). */\n\t\tprivate readonly probeTargets?: SparseProbeTarget[] | undefined,\n\t\t/** False for event-only subgraphs → skip walkTransactions, synthesize the\n\t\t * tx from joined event context. Defaults true (safe / unchanged). */\n\t\tprivate readonly needsTransactions = true,\n\t\t/** Write events from `state_writes` instead of the vm event walks. */\n\t\tprivate readonly feed?: StateWriteFeed | undefined,\n\t) {}\n\n\t/**\n\t * What the event walks fetch. Event-only subgraphs walk exactly what their\n\t * filters can match (contract-scoped where a filter pins one); tx-level\n\t * sources need every event of a matched tx, so they walk each type whole.\n\t */\n\tprivate walkTargets(): SparseProbeTarget[] {\n\t\tconst scoped = this.needsTransactions ? undefined : this.probeTargets;\n\t\t// Under a state_writes feed, write events come from the writes walk.\n\t\tconst types = this.feed\n\t\t\t? this.eventTypes.filter((t) => !VM_INDEX_EVENT_TYPES.has(t))\n\t\t\t: this.eventTypes;\n\t\treturn types.flatMap((eventType) => {\n\t\t\tconst own = scoped?.filter((t) => t.eventType === eventType);\n\t\t\treturn own?.length ? own : [{ eventType }];\n\t\t});\n\t}\n\n\t/** Lowest height in (after, until] any probe target hits, or null. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.probeTargets?.length) return afterHeight + 1;\n\t\tconst hits = await Promise.all(\n\t\t\tthis.probeTargets.map((t) =>\n\t\t\t\tthis.http.firstEventHeight(\n\t\t\t\t\tt.eventType,\n\t\t\t\t\tafterHeight + 1,\n\t\t\t\t\tuntilHeight,\n\t\t\t\t\tt.contractId,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst found = hits.filter((h): h is number => h !== null);\n\t\treturn found.length ? Math.min(...found) : null;\n\t}\n\n\tgetTip(opts?: { wait?: number; knownHeight?: number }): Promise<number> {\n\t\t// VM rows land with ingest. Decoded Index tip can lag; use the source\n\t\t// field when this loader fetches any vm type.\n\t\tif (this.eventTypes.some((t) => VM_INDEX_EVENT_TYPES.has(t))) {\n\t\t\treturn this.http.getIndexSourceTip(opts);\n\t\t}\n\t\t// Scope the tip (and, with `wait`, what counts as \"nothing new\") to\n\t\t// exactly the classic types THIS source reads instead of the global\n\t\t// cross-decoder floor. Without this, any of the ~15 classic decoders\n\t\t// committing — most unrelated to what this source actually walks —\n\t\t// moves the global floor and makes an unrelated `wait` return early.\n\t\treturn this.http.getIndexTip({ ...opts, eventTypes: this.eventTypes });\n\t}\n\n\t/** Reads the SAME envelope `getTip()` just cached on `this.http` — call\n\t * this only after `getTip()` has resolved at least once. */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.http.getDecodedHeights();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\t// Event-only subgraphs join tx context onto events (withTx) and skip the\n\t\t// walkTransactions over-fetch entirely; tx-level sources fetch real txs.\n\t\tconst withTx = !this.needsTransactions;\n\t\tconst [blocks, txRows, eventLists, writes] = await Promise.all([\n\t\t\tthis.http.walkBlocks(fromHeight, toHeight),\n\t\t\tthis.needsTransactions\n\t\t\t\t? this.http.walkTransactions(fromHeight, toHeight)\n\t\t\t\t: Promise.resolve<IndexTransactionRow[]>([]),\n\t\t\tPromise.all(\n\t\t\t\tthis.walkTargets().map((t) =>\n\t\t\t\t\tthis.http.walkEvents(\n\t\t\t\t\t\tt.eventType,\n\t\t\t\t\t\tfromHeight,\n\t\t\t\t\t\ttoHeight,\n\t\t\t\t\t\twithTx,\n\t\t\t\t\t\tt.contractId,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.feed ? this.walkWrites(fromHeight, toHeight, this.feed) : null,\n\t\t]);\n\t\tconst events = dedupeEvents(eventLists.flat());\n\n\t\tconst map = new Map<number, BlockData>();\n\t\t// Seed every canonical height (incl. empty blocks) so catch-up doesn't\n\t\t// file them as gaps.\n\t\tfor (const b of blocks) {\n\t\t\tmap.set(b.block_height, {\n\t\t\t\tblock: reconstructBlock(b),\n\t\t\t\ttxs: [],\n\t\t\t\tevents: [],\n\t\t\t});\n\t\t}\n\t\t// For event-only subgraphs, materialize only the event-bearing txs from\n\t\t// joined event context instead of every transaction in the range.\n\t\tconst txs = this.needsTransactions\n\t\t\t? txRows.map(reconstructTransaction)\n\t\t\t: synthesizeTxsFromEvents(events);\n\t\tfor (const t of txs) {\n\t\t\tmap.get(t.block_height)?.txs.push(t);\n\t\t}\n\t\tfor (const e of events) {\n\t\t\tconst bd = map.get(e.block_height);\n\t\t\tif (!bd) continue;\n\t\t\t// vm rows ride their own clock: never merged into `events`, whose\n\t\t\t// order is classic event_index.\n\t\t\tif (VM_INDEX_EVENT_TYPES.has(e.event_type)) {\n\t\t\t\tbd.vmEvents ??= [];\n\t\t\t\tbd.vmEvents.push(reconstructEvent(e));\n\t\t\t} else {\n\t\t\t\tbd.events.push(reconstructEvent(e));\n\t\t\t}\n\t\t}\n\t\tif (writes) {\n\t\t\tfor (const [height, fed] of writes) {\n\t\t\t\tconst bd = map.get(height);\n\t\t\t\tif (!bd) continue;\n\t\t\t\tbd.txs.push(...fed.txs);\n\t\t\t\tbd.vmEvents = fed.vmEvents;\n\t\t\t}\n\t\t}\n\t\t// Canonical ordering — multi-type event walks merge here, per clock.\n\t\tfor (const bd of map.values()) {\n\t\t\tbd.txs.sort((a, b) => (a.tx_index ?? 0) - (b.tx_index ?? 0));\n\t\t\tbd.events.sort((a, b) => a.event_index - b.event_index);\n\t\t\tbd.vmEvents?.sort((a, b) => a.event_index - b.event_index);\n\t\t}\n\t\treturn map;\n\t}\n\n\t/** Each height's named writes as events, the writing txs rebuilt from the\n\t * joined `tx_*` fields. One walk per contract, merged in ordinal order. */\n\tprivate async walkWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tfeed: StateWriteFeed,\n\t): Promise<ReturnType<typeof stateWriteBlocks>> {\n\t\tconst walks = await Promise.all(\n\t\t\t(feed.contracts ?? [undefined]).map((c) =>\n\t\t\t\tthis.http.walkStateWrites(fromHeight, toHeight, c),\n\t\t\t),\n\t\t);\n\t\tconst writesByHeight = new Map<number, Map<number, StateWriteRow>>();\n\t\tconst txsByHeight = new Map<number, Map<number, TxRecord>>();\n\t\tfor (const row of walks.flat()) {\n\t\t\tconst writes = writesByHeight.get(row.block_height) ?? new Map();\n\t\t\twrites.set(row.ordinal, row);\n\t\t\twritesByHeight.set(row.block_height, writes);\n\t\t\tconst tx = writeTx(row);\n\t\t\tif (tx) {\n\t\t\t\tconst txs = txsByHeight.get(row.block_height) ?? new Map();\n\t\t\t\ttxs.set(row.tx_index as number, tx);\n\t\t\t\ttxsByHeight.set(row.block_height, txs);\n\t\t\t}\n\t\t}\n\t\treturn stateWriteBlocks(\n\t\t\tnew Map(\n\t\t\t\t[...writesByHeight].map(([h, w]) => [\n\t\t\t\t\th,\n\t\t\t\t\t[...w.values()].sort((a, b) => a.ordinal - b.ordinal),\n\t\t\t\t]),\n\t\t\t),\n\t\t\tnew Map([...txsByHeight].map(([h, t]) => [h, [...t.values()]])),\n\t\t);\n\t}\n}\n\n/** The writing tx a `tx_context=true` row carries; null for block-level\n * writes or a row whose tx the Index could not join. */\nfunction writeTx(row: IndexStateWriteRow): TxRecord | null {\n\tif (row.tx_index === null || !row.tx_id) return null;\n\treturn {\n\t\ttx_id: row.tx_id,\n\t\ttx_index: row.tx_index,\n\t\ttype: row.tx_type ?? \"\",\n\t\tsender: row.tx_sender ?? \"\",\n\t\tstatus: row.tx_status ?? \"\",\n\t\tcontract_id: row.tx_contract_id ?? null,\n\t\tfunction_name: row.tx_function_name ?? null,\n\t};\n}\n\n/**\n * Wraps a primary source and falls back to a secondary, per call, when the\n * primary throws. Use it to make the HTTP (Streams+Index) plane a SOFT dependency:\n * if api is unavailable, the processor reads the Postgres tap and keeps advancing\n * instead of stalling. Safe to mix mid-stream — both taps read the same canonical\n * chain at the same heights and the cursor is forward-only. Stateless (no breaker)\n * so it's failover-safe across replicas; the primary is retried every call and\n * resumes transparently once healthy.\n */\nexport class FallbackBlockSource implements BlockSource {\n\t/** True when the LAST `getTip()` call actually used the primary — guards\n\t * `getDecodedHeights()` against returning the primary's stale cached\n\t * envelope from an earlier success after a call that just fell back. */\n\tprivate lastTipFromPrimary = false;\n\n\tconstructor(\n\t\tprivate readonly primary: BlockSource,\n\t\tprivate readonly fallback: BlockSource,\n\t) {}\n\n\tasync getTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\ttry {\n\t\t\tconst tip = await this.primary.getTip(opts);\n\t\t\tthis.lastTipFromPrimary = true;\n\t\t\treturn tip;\n\t\t} catch (err) {\n\t\t\t// A billing refusal is not the api being down: the DB tap would\n\t\t\t// quietly serve different data, so let the caller pause instead.\n\t\t\tif (err instanceof BillingPausedError) throw err;\n\t\t\tlogger.warn(\"block source primary getTip failed — using DB tap\", {\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tthis.lastTipFromPrimary = false;\n\t\t\t// The DB tap has no wait/long-poll notion — a plain read is already\n\t\t\t// instant, so `opts` is dropped here rather than forwarded.\n\t\t\treturn this.fallback.getTip();\n\t\t}\n\t}\n\n\t/** Only meaningful right after a `getTip()` that used the primary — the\n\t * fallback (Postgres tap) has no such notion, and returning the\n\t * primary's stale cache after a fallback would mismatch the returned\n\t * tip. Local mode's own `decoderBoundTip` never calls this. */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\tif (!this.lastTipFromPrimary) return undefined;\n\t\treturn this.primary.getDecodedHeights?.();\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\ttry {\n\t\t\treturn await this.primary.loadBlockRange(fromHeight, toHeight);\n\t\t} catch (err) {\n\t\t\tif (err instanceof BillingPausedError) throw err;\n\t\t\tlogger.warn(\"block source primary loadBlockRange failed — using DB tap\", {\n\t\t\t\tfrom: fromHeight,\n\t\t\t\tto: toHeight,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn this.fallback.loadBlockRange(fromHeight, toHeight);\n\t\t}\n\t}\n\n\t/** Probe via the primary only; a probe failure just means \"no skip\" —\n\t * the caller falls back to plain batch advancement. */\n\tasync nextDataHeight(\n\t\tafterHeight: number,\n\t\tuntilHeight: number,\n\t): Promise<number | null> {\n\t\tif (!this.primary.nextDataHeight) return afterHeight + 1;\n\t\ttry {\n\t\t\treturn await this.primary.nextDataHeight(afterHeight, untilHeight);\n\t\t} catch {\n\t\t\treturn afterHeight + 1;\n\t\t}\n\t}\n}\n\nconst postgresBlockSource = new PostgresBlockSource();\n\n/** The Postgres tap for a subgraph: its `state_writes` feed when it has one. */\nfunction postgresSourceFor(feed: StateWriteFeed | null): BlockSource {\n\treturn feed ? new PostgresBlockSource(feed) : postgresBlockSource;\n}\n\n/**\n * HTTP (Streams+Index) chain source for a set of decoded event types, wrapped so\n * it falls back to the Postgres tap when api is down. Used by the chain-trigger\n * evaluator (which isn't subgraph-scoped, so it can't go through resolveBlockSource).\n *\n * `needsTransactions` defaults true (safe/unchanged) but the evaluator passes\n * `chainSubsNeedTransactions(chainSubs)` so a tick with no contract_call/deploy\n * trigger skips `walkTransactions` entirely — one fewer HTTP round trip and a\n * smaller `walkEvents` payload (no `tx_context` join) on every such tick.\n *\n * `httpClient` defaults to a fresh client (unchanged behavior) — pass one in\n * to reuse across calls. The evaluator's own long-lived loop does this so\n * `IndexHttpClient.waitIsSupported()` reflects what THIS\n * server actually supports instead of resetting every tick.\n */\nexport function buildChainBlockSource(\n\teventTypes: string[],\n\tneedsTransactions = true,\n\thttpClient: IndexHttpClient = buildHttpClient(),\n): BlockSource {\n\treturn new FallbackBlockSource(\n\t\tnew PublicApiBlockSource(\n\t\t\thttpClient,\n\t\t\teventTypes,\n\t\t\tundefined,\n\t\t\tneedsTransactions,\n\t\t),\n\t\tpostgresBlockSource,\n\t);\n}\n\nexport function buildHttpClient(): IndexHttpClient {\n\treturn createInternalIndexHttpClient();\n}\n\n/**\n * Resolve the block source for a subgraph. `SUBGRAPH_SOURCE=streams-index`\n * opts eligible subgraphs onto the public Streams clock + Index data;\n * `SUBGRAPH_SOURCE=observer-http` pages internal observer-events (experimental).\n * Default stays on the Postgres tap.\n */\nexport async function resolveBlockSource(\n\tsubgraph?: SubgraphDefinition,\n): Promise<BlockSource> {\n\tif (process.env.SUBGRAPH_SOURCE === \"observer-http\") {\n\t\tconst baseUrl = process.env.OBSERVER_HTTP_URL;\n\t\tif (!baseUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t\"SUBGRAPH_SOURCE=observer-http requires OBSERVER_HTTP_URL\",\n\t\t\t);\n\t\t}\n\t\treturn new ObserverHttpBlockSource({\n\t\t\tbaseUrl,\n\t\t\ttoken: process.env.OBSERVER_HTTP_EXPORT_TOKEN || null,\n\t\t});\n\t}\n\tif (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tsubgraph &&\n\t\tisStreamsIndexEligible(subgraph)\n\t) {\n\t\t// Soft-depend on api: fall back to the Postgres tap per-call if the HTTP\n\t\t// plane is down, so the processor keeps advancing instead of stalling.\n\t\t// Both read the same feed, decided by the plane this source reads.\n\t\tconst feed =\n\t\t\t(await stateWriteFeed(subgraph, httpStateWritesCoverage())) ?? undefined;\n\t\treturn new FallbackBlockSource(\n\t\t\tnew PublicApiBlockSource(\n\t\t\t\tbuildHttpClient(),\n\t\t\t\treferencedIndexEventTypes(subgraph),\n\t\t\t\t// The sparse probe reads vm_events; a state_writes feed walks\n\t\t\t\t// every block instead of skipping on another table's rows.\n\t\t\t\tcanSparseScan(subgraph) && !feed\n\t\t\t\t\t? sparseProbeTargets(subgraph)\n\t\t\t\t\t: undefined,\n\t\t\t\tneedsTransactionData(subgraph),\n\t\t\t\tfeed,\n\t\t\t),\n\t\t\tpostgresSourceFor(feed ?? null),\n\t\t);\n\t}\n\tif (process.env.SUBGRAPH_SOURCE === \"streams-index\" && subgraph) {\n\t\tlogger.debug(\"Subgraph not streams-index eligible, using DB tap\", {\n\t\t\tsubgraph: subgraph.name,\n\t\t});\n\t}\n\treturn postgresSourceFor(await stateWriteFeed(subgraph));\n}\n",
8
7
  "/**\n * Verifiable subgraphs: the determinism contract, the derived level and the\n * pin. Pure (node:crypto only) so the bundler's deploy scan, the API and the\n * runtime realm all read the same rules.\n *\n * A subgraph is never configured as verifiable. Its level is derived from\n * its sources plus a scan of the bundled handler, and only a subgraph whose\n * every input is provable today (`state`: named state writes) has the contract\n * enforced. Everything else gets the same findings as advice.\n */\nimport { createHash } from \"node:crypto\";\nimport type { SubgraphVerification } from \"@secondlayer/shared/schemas/subgraphs\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport type { SubgraphDefinition, SubgraphFilter } from \"./types.ts\";\n\nexport type { SubgraphVerification };\n\n/** Runtime identity baked into every pin: matcher, decode and flush semantics. */\nexport const SUBGRAPHS_RUNTIME: string = `@secondlayer/subgraphs@${pkg.version}`;\n\n// ── Determinism contract ────────────────────────────────────────────────\n\n/**\n * Globals a handler may not touch, with the reason shown to the developer.\n * The deploy scan reports them; the realm replaces each with a getter that\n * throws `NondeterminismError`.\n */\nexport const FORBIDDEN_GLOBALS: Readonly<Record<string, string>> = {\n\tDate: \"wall-clock time differs per run\",\n\tperformance: \"timers differ per run\",\n\tprocess: \"host environment differs per run\",\n\tfetch: \"network reads are not chain inputs\",\n\tcrypto: \"randomness differs per run\",\n\tsetTimeout: \"scheduling order differs per run\",\n\tsetInterval: \"scheduling order differs per run\",\n\tsetImmediate: \"scheduling order differs per run\",\n\tclearTimeout: \"scheduling order differs per run\",\n\tclearInterval: \"scheduling order differs per run\",\n\tqueueMicrotask: \"scheduling order differs per run\",\n\tWeakRef: \"garbage collection timing differs per run\",\n\tFinalizationRegistry: \"garbage collection timing differs per run\",\n\tAtomics: \"shared memory is not single-threaded\",\n\tSharedArrayBuffer: \"shared memory is not single-threaded\",\n\tIntl: \"locale and time zone data differ per host\",\n\tTemporal: \"locale and time zone data differ per host\",\n\teval: \"generated code hides inputs from the scan\",\n\tWebAssembly: \"compiled code hides inputs from the scan\",\n\tShadowRealm: \"a nested realm escapes the allow-list\",\n\trequire: \"imports must be bundled into the handler\",\n};\n\n/**\n * Globals a handler may use: ECMAScript built-ins whose results are fully\n * specified, plus deterministic host encoders. `Math` is narrowed separately\n * ({@link ALLOWED_MATH}).\n */\nexport const ALLOWED_GLOBALS: readonly string[] = [\n\t\"undefined\",\n\t\"NaN\",\n\t\"Infinity\",\n\t\"globalThis\",\n\t\"isNaN\",\n\t\"isFinite\",\n\t\"parseInt\",\n\t\"parseFloat\",\n\t\"decodeURI\",\n\t\"decodeURIComponent\",\n\t\"encodeURI\",\n\t\"encodeURIComponent\",\n\t\"escape\",\n\t\"unescape\",\n\t\"Object\",\n\t\"Function\",\n\t\"Array\",\n\t\"Number\",\n\t\"Boolean\",\n\t\"String\",\n\t\"Symbol\",\n\t\"BigInt\",\n\t\"Math\",\n\t\"JSON\",\n\t\"Reflect\",\n\t\"Proxy\",\n\t\"Promise\",\n\t\"Map\",\n\t\"Set\",\n\t\"WeakMap\",\n\t\"WeakSet\",\n\t\"RegExp\",\n\t\"Iterator\",\n\t\"DisposableStack\",\n\t\"AsyncDisposableStack\",\n\t\"Error\",\n\t\"AggregateError\",\n\t\"SuppressedError\",\n\t\"EvalError\",\n\t\"RangeError\",\n\t\"ReferenceError\",\n\t\"SyntaxError\",\n\t\"TypeError\",\n\t\"URIError\",\n\t\"ArrayBuffer\",\n\t\"DataView\",\n\t\"Int8Array\",\n\t\"Uint8Array\",\n\t\"Uint8ClampedArray\",\n\t\"Int16Array\",\n\t\"Uint16Array\",\n\t\"Int32Array\",\n\t\"Uint32Array\",\n\t\"Float16Array\",\n\t\"Float32Array\",\n\t\"Float64Array\",\n\t\"BigInt64Array\",\n\t\"BigUint64Array\",\n\t\"TextEncoder\",\n\t\"TextDecoder\",\n\t\"atob\",\n\t\"btoa\",\n\t\"console\",\n];\n\n/** `Math` members whose results are exact on every engine. The rest\n * (`sin`, `pow`, `log`, …) are implementation-approximated. */\nexport const ALLOWED_MATH: readonly string[] = [\n\t\"abs\",\n\t\"min\",\n\t\"max\",\n\t\"floor\",\n\t\"ceil\",\n\t\"trunc\",\n\t\"sign\",\n\t\"round\",\n\t\"E\",\n\t\"LN10\",\n\t\"LN2\",\n\t\"LOG10E\",\n\t\"LOG2E\",\n\t\"PI\",\n\t\"SQRT1_2\",\n\t\"SQRT2\",\n];\n\n/** Methods whose output depends on the host's locale data. */\nexport const LOCALE_METHODS: readonly string[] = [\n\t\"toLocaleString\",\n\t\"toLocaleDateString\",\n\t\"toLocaleTimeString\",\n\t\"toLocaleUpperCase\",\n\t\"toLocaleLowerCase\",\n\t\"localeCompare\",\n];\n\n/**\n * One thing the deploy scan found in a bundled handler.\n *\n * - `nondeterministic`: breaks the determinism contract. Fails the deploy of\n * a state subgraph; advice for everything else.\n * - `needs-events`: deterministic, but reads something only re-execution proofs cover\n * (`ctx.client`). Raises the level instead of failing.\n */\nexport interface HandlerFinding {\n\tkind: \"nondeterministic\" | \"needs-events\";\n\t/** What was used, e.g. `Date`, `Math.random`, `import()`, `ctx.client`. */\n\tname: string;\n\treason: string;\n\t/** Original source file when a sourcemap was available, else the bundle. */\n\tfile: string;\n\t/** 1-based. */\n\tline: number;\n\t/** 1-based. */\n\tcolumn: number;\n}\n\nexport function formatFinding(f: HandlerFinding): string {\n\treturn `${f.file}:${f.line}:${f.column} ${f.name}: ${f.reason}`;\n}\n\n// ── Derived level ───────────────────────────────────────────────────────\n\n/**\n * Sources whose every field is a named state write: provable per block from\n * the header-backed witness plus `state_writes`. Not `map_insert`: storage\n * holds `(some v)` for an insert and a set alike, so telling them apart takes\n * re-execution (event proofs).\n */\nconst STATE_SOURCE_TYPES: ReadonlySet<string> = new Set([\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_delete\",\n]);\n\nconst LEVEL_RANK = { state: 0, events: 1, none: 2 } as const;\n\n/** Handler findings listed in `reasons`; the rest are counted. */\nconst MAX_LISTED_FINDINGS = 10;\n\n/**\n * Derive how far a subgraph's rows can be checked. Level = the highest any\n * source or handler read needs. `reasons` lists everything standing between\n * the subgraph and checkable rows; a `state` subgraph with any reason is\n * refused at deploy, so every stored `state` row has none. Never configured,\n * never a flag.\n */\nexport function deriveVerification(\n\tdef: Pick<SubgraphDefinition, \"sources\" | \"backfillMode\">,\n\tfindings: readonly HandlerFinding[] = [],\n): SubgraphVerification {\n\tlet level: keyof typeof LEVEL_RANK = \"state\";\n\tconst raise = (to: keyof typeof LEVEL_RANK) => {\n\t\tif (LEVEL_RANK[to] > LEVEL_RANK[level]) level = to;\n\t};\n\tconst reasons: string[] = [];\n\n\tfor (const [name, source] of Object.entries(def.sources ?? {})) {\n\t\tconst filter = source as SubgraphFilter & { trait?: string };\n\t\tif (filter.trait) {\n\t\t\traise(\"none\");\n\t\t\treasons.push(\n\t\t\t\t`source \"${name}\": trait scope needs a proven contract registry`,\n\t\t\t);\n\t\t} else if (filter.type === \"map_insert\") {\n\t\t\traise(\"events\");\n\t\t\treasons.push(\n\t\t\t\t`map_insert source \"${name}\": map_insert vs map_set needs event proofs`,\n\t\t\t);\n\t\t} else if (!STATE_SOURCE_TYPES.has(filter.type)) {\n\t\t\traise(\"events\");\n\t\t\treasons.push(`${filter.type} source \"${name}\" needs event proofs`);\n\t\t}\n\t}\n\tif (def.backfillMode === \"concurrent\") {\n\t\traise(\"none\");\n\t\treasons.push(\"backfillMode concurrent: tip-first order is not chain order\");\n\t}\n\tif (findings.some((f) => f.kind === \"needs-events\")) raise(\"events\");\n\t// A large bundled library can trip dozens of findings; list a few.\n\tfor (const f of findings.slice(0, MAX_LISTED_FINDINGS)) {\n\t\treasons.push(\n\t\t\tf.kind === \"needs-events\"\n\t\t\t\t? `${formatFinding(f)} (needs event proofs)`\n\t\t\t\t: formatFinding(f),\n\t\t);\n\t}\n\tif (findings.length > MAX_LISTED_FINDINGS) {\n\t\treasons.push(\n\t\t\t`…and ${findings.length - MAX_LISTED_FINDINGS} more handler findings`,\n\t\t);\n\t}\n\n\treturn {\n\t\tlevel,\n\t\treasons,\n\t\tunproven:\n\t\t\treasons.length === 0\n\t\t\t\t? [\n\t\t\t\t\t\t\"tx attribution of writes: event.tx, _tx_id (needs event proofs)\",\n\t\t\t\t\t\t\"intermediate writes within a block (needs event proofs)\",\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t};\n}\n\n/**\n * True when the deploy must be refused: the sources are provable (`state`), so\n * the determinism contract is enforced, and the scan broke it.\n */\nexport function isDeterminismViolation(v: SubgraphVerification): boolean {\n\treturn v.level === \"state\" && v.reasons.length > 0;\n}\n\n// ── Pin ─────────────────────────────────────────────────────────────────\n\nexport interface PinInput {\n\t/** Existing `schema_hash` (name + schema + sources). */\n\tschemaHash: string;\n\t/** Bundled ESM exactly as stored in `subgraphs.handler_code`. */\n\thandlerCode: string;\n\tstartBlock?: number | null;\n\tnetwork: string;\n\t/** Defaults to {@link SUBGRAPHS_RUNTIME}. */\n\truntime?: string;\n}\n\nfunction sha256(input: string): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\n/** What a pin commits to, as stored in `pin_preimage`. */\nexport interface PinFields {\n\t/** sha256 of the bundled handler, hex. */\n\thandlerHash: string;\n\tnetwork: string;\n\truntime: string;\n\tschemaHash: string;\n\tstartBlock: number | null;\n}\n\n/**\n * The canonical JSON a pin is the sha256 of: fixed key order, primitives\n * only. Stored beside the pin so anyone can recompute it from the served\n * handler code.\n */\nexport function pinPreimage(input: PinInput): string {\n\tconst fields: PinFields = {\n\t\thandlerHash: sha256(input.handlerCode),\n\t\tnetwork: input.network,\n\t\truntime: input.runtime ?? SUBGRAPHS_RUNTIME,\n\t\tschemaHash: input.schemaHash,\n\t\tstartBlock: input.startBlock ?? null,\n\t};\n\treturn JSON.stringify(fields);\n}\n\n/**\n * Content hash over everything that shapes a subgraph's rows. Unlike\n * `schema_hash`, it changes with the handler, `startBlock` and runtime, so\n * two deploys with the same pin produce the same rows from the same chain.\n */\nexport function computePin(input: PinInput): string {\n\treturn sha256(pinPreimage(input));\n}\n",
9
8
  "import type {\n\tBlock,\n\tDatabase,\n\tEvent,\n\tTransaction,\n} from \"@secondlayer/shared/db\";\nimport { type Kysely, sql } from \"kysely\";\nimport type { EventRecord, TxRecord } from \"./source-matcher.ts\";\nimport { type StateWriteRow, stateWriteEvents } from \"./state-writes.ts\";\n\n/** A runtime event row. `clock: \"vm\"` marks an opt-in `vm_events` row whose\n * `event_index` is `ordinal` — a second ordinal that never sorts or\n * dedupes against classic `events.event_index`. */\nexport type RuntimeEvent = Event & { clock?: \"vm\" };\n\nexport interface BlockData {\n\tblock: Block;\n\t/** The block's transactions. Under a `state_writes` feed, only the ones\n\t * its named writes hang on (see `stateWriteEvents`). */\n\ttxs: TxRecord[];\n\t/** Classic `events` rows (Streams 1.0 clock). */\n\tevents: Event[];\n\t/** Write events on their own clock: opt-in `vm_events` rows, or named\n\t * `state_writes` for a state subgraph. Absent/empty on `\"*\"` nodes and on\n\t * archives collected without `storage`/`contract_calls`. */\n\tvmEvents?: EventRecord[];\n}\n\n/**\n * Which node storage writes feed a state subgraph's write sources, in place\n * of `vm_events`. `contracts: null` reads every contract's writes (a source\n * with no fixed contract).\n */\nexport interface StateWriteFeed {\n\tcontracts: string[] | null;\n}\n\n/** Each block's writes run through {@link stateWriteEvents} with that block's\n * own transactions, keyed by `tx_index`. */\nexport function stateWriteBlocks(\n\twritesByHeight: ReadonlyMap<number, StateWriteRow[]>,\n\ttxsByHeight: ReadonlyMap<number, readonly TxRecord[]>,\n): Map<number, { txs: TxRecord[]; vmEvents: EventRecord[] }> {\n\tconst out = new Map<number, { txs: TxRecord[]; vmEvents: EventRecord[] }>();\n\tfor (const [height, writes] of writesByHeight) {\n\t\tconst txByIndex = new Map<number, TxRecord>();\n\t\tfor (const tx of txsByHeight.get(height) ?? []) {\n\t\t\tif (tx.tx_index !== undefined) txByIndex.set(tx.tx_index, tx);\n\t\t}\n\t\tout.set(height, stateWriteEvents(writes, txByIndex));\n\t}\n\treturn out;\n}\n\n/** Stable synthetic id for a vm row. Distinct from the classic `tx#index`\n * so a print at event_index N and a map_set at ordinal N never share\n * an identity. */\nexport function vmEventId(txId: string, vmEventIndex: number): string {\n\treturn `${txId}#vm:${vmEventIndex}`;\n}\n\n/**\n * Load a range of blocks with their transactions and events in 4 parallel queries.\n * Returns a Map keyed by block height. Non-canonical blocks are excluded.\n * With `stateWrites`, write events come from `state_writes` instead of\n * `vm_events`.\n */\nexport async function loadBlockRange(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n\ttoHeight: number,\n\topts: { stateWrites?: StateWriteFeed } = {},\n): Promise<Map<number, BlockData>> {\n\tconst feed = opts.stateWrites;\n\tconst [blocks, txs, events, vmRows, writeRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.selectAll()\n\t\t\t.where(\"height\", \">=\", fromHeight)\n\t\t\t.where(\"height\", \"<=\", toHeight)\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"transactions\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t\tdb\n\t\t\t.selectFrom(\"events\")\n\t\t\t.selectAll()\n\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t.execute(),\n\t\tfeed\n\t\t\t? Promise.resolve([])\n\t\t\t: db\n\t\t\t\t\t.selectFrom(\"vm_events\")\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.where(\"block_height\", \">=\", fromHeight)\n\t\t\t\t\t.where(\"block_height\", \"<=\", toHeight)\n\t\t\t\t\t.orderBy(\"ordinal\", \"asc\")\n\t\t\t\t\t.execute(),\n\t\tfeed\n\t\t\t? loadStateWrites(db, fromHeight, toHeight, feed)\n\t\t\t: Promise.resolve([]),\n\t]);\n\n\t// Index by block height (coerce to number — bigint columns may return as string or number)\n\tconst txsByHeight = new Map<number, Transaction[]>();\n\tfor (const tx of txs) {\n\t\tconst h = Number(tx.block_height);\n\t\tconst list = txsByHeight.get(h) ?? [];\n\t\tlist.push(tx);\n\t\ttxsByHeight.set(h, list);\n\t}\n\n\tconst eventsByHeight = new Map<number, Event[]>();\n\tfor (const evt of events) {\n\t\tconst h = Number(evt.block_height);\n\t\tconst list = eventsByHeight.get(h) ?? [];\n\t\tlist.push(evt);\n\t\teventsByHeight.set(h, list);\n\t}\n\n\tconst vmByHeight = new Map<number, RuntimeEvent[]>();\n\tfor (const row of vmRows) {\n\t\tconst h = Number(row.block_height);\n\t\tconst list = vmByHeight.get(h) ?? [];\n\t\tlist.push({\n\t\t\tid: vmEventId(row.tx_id, Number(row.ordinal)),\n\t\t\ttx_id: row.tx_id,\n\t\t\tblock_height: h,\n\t\t\tevent_index: Number(row.ordinal),\n\t\t\ttype: row.type,\n\t\t\tdata: row.data,\n\t\t\tcreated_at: row.created_at,\n\t\t\tclock: \"vm\",\n\t\t} as RuntimeEvent);\n\t\tvmByHeight.set(h, list);\n\t}\n\n\tconst writesByHeight = new Map<number, StateWriteRow[]>();\n\tfor (const row of writeRows) {\n\t\tconst h = Number(row.block_height);\n\t\tconst list = writesByHeight.get(h) ?? [];\n\t\tlist.push({\n\t\t\tordinal: Number(row.ordinal),\n\t\t\ttx_index: row.tx_index === null ? null : Number(row.tx_index),\n\t\t\tkey: row.key,\n\t\t\tvalue_hex: row.value_hex,\n\t\t});\n\t\twritesByHeight.set(h, list);\n\t}\n\tconst named = stateWriteBlocks(writesByHeight, txsByHeight);\n\n\tconst result = new Map<number, BlockData>();\n\tfor (const block of blocks) {\n\t\tconst h = Number(block.height);\n\t\tconst fed = named.get(h);\n\t\tresult.set(h, {\n\t\t\tblock,\n\t\t\ttxs: feed ? (fed?.txs ?? []) : (txsByHeight.get(h) ?? []),\n\t\t\tevents: eventsByHeight.get(h) ?? [],\n\t\t\tvmEvents: feed ? (fed?.vmEvents ?? []) : (vmByHeight.get(h) ?? []),\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/** `state_writes` over the range, scoped to the feed's contracts' keys. */\nasync function loadStateWrites(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n\ttoHeight: number,\n\tfeed: StateWriteFeed,\n): Promise<\n\tArray<{\n\t\tblock_height: number;\n\t\tordinal: number;\n\t\ttx_index: number | null;\n\t\tkey: string;\n\t\tvalue_hex: string;\n\t}>\n> {\n\t// `starts_with`, not LIKE: `_` in a contract name is a LIKE wildcard.\n\tconst scope = feed.contracts\n\t\t? sql`AND (${sql.join(\n\t\t\t\tfeed.contracts.map((c) => sql`starts_with(key, ${`vm::${c}::`})`),\n\t\t\t\tsql` OR `,\n\t\t\t)})`\n\t\t: sql``;\n\tconst { rows } = await sql<{\n\t\tblock_height: number;\n\t\tordinal: number;\n\t\ttx_index: number | null;\n\t\tkey: string;\n\t\tvalue_hex: string;\n\t}>`\n\t\tSELECT block_height, ordinal, tx_index, key, value_hex\n\t\tFROM state_writes\n\t\tWHERE block_height >= ${fromHeight} AND block_height <= ${toHeight} ${scope}\n\t\tORDER BY block_height, ordinal\n\t`.execute(db);\n\treturn rows;\n}\n\n/**\n * Compute average events per block from a loaded batch.\n * Used for adaptive batch sizing.\n */\nexport function avgEventsPerBlock(batch: Map<number, BlockData>): number {\n\tif (batch.size === 0) return 0;\n\tlet totalEvents = 0;\n\tfor (const data of batch.values()) {\n\t\ttotalEvents += data.events.length;\n\t}\n\treturn totalEvents / batch.size;\n}\n",
10
9
  "/**\n * Node storage writes (`state_writes`) → the `var_set` / `map_set` /\n * `map_delete` events a state-level subgraph's handlers receive.\n *\n * The served runtime and client replay both call {@link stateWriteEvents} and\n * nothing else, so the events a handler saw on the server are exactly the ones\n * a verifier recomputes from the header-backed diff.\n */\nimport { vmEventId } from \"./batch-loader.ts\";\nimport type { EventRecord, TxRecord } from \"./source-matcher.ts\";\n\n/** One `state_writes` row (migration 0154), as the DB tap and the API serve it. */\nexport interface StateWriteRow {\n\tordinal: number;\n\t/** Null for a block-level write (no transaction). */\n\ttx_index: number | null;\n\t/** MARF key, e.g. `vm::<contract>::0::<map>::<keyhex>`. */\n\tkey: string;\n\t/** Hex of the stored value string's UTF-8 bytes. */\n\tvalue_hex: string;\n}\n\nexport type StateWriteKey =\n\t| { contractId: string; kind: \"map\"; map: string; rawKey: string }\n\t| { contractId: string; kind: \"var\"; varName: string };\n\n/** clarity_db.rs StoreType discriminants, formatted in decimal inside keys. */\nconst DATA_MAP = \"0\";\nconst VARIABLE = \"1\";\nconst HEX = /^(?:[0-9a-f]{2})+$/;\n\n/**\n * `vm::<c>::0::<map>::<keyhex>` | `vm::<c>::1::<var>`; null for every other key\n * (FT balances, NFT owners, contract metadata, accounts, `__MARF_*`).\n */\nexport function parseStateWriteKey(key: string): StateWriteKey | null {\n\tif (!key.startsWith(\"vm::\")) return null;\n\tconst parts = key.slice(4).split(\"::\");\n\tconst [contractId, store] = parts;\n\tif (!contractId?.includes(\".\")) return null;\n\tif (store === DATA_MAP && parts.length === 4) {\n\t\tconst [, , map, rawKey] = parts;\n\t\tif (!map || !rawKey || !HEX.test(rawKey)) return null;\n\t\treturn { contractId, kind: \"map\", map, rawKey };\n\t}\n\tif (store === VARIABLE && parts.length === 3 && parts[2]) {\n\t\treturn { contractId, kind: \"var\", varName: parts[2] };\n\t}\n\treturn null;\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** The stored value string a `value_hex` encodes (lowercase hex of a CV). */\nfunction storedValue(w: StateWriteRow): string {\n\tconst h = w.value_hex.startsWith(\"0x\") ? w.value_hex.slice(2) : w.value_hex;\n\tconst bytes = new Uint8Array(h.length / 2);\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tbytes[i] = Number.parseInt(h.slice(i * 2, i * 2 + 2), 16);\n\t}\n\tlet value: string;\n\ttry {\n\t\tvalue = utf8.decode(bytes);\n\t} catch {\n\t\tthrow new Error(`state write ${w.ordinal} value is not UTF-8 hex`);\n\t}\n\tvalue = value.toLowerCase();\n\tif (!HEX.test(value)) {\n\t\tthrow new Error(`state write ${w.ordinal} value is not a Clarity value`);\n\t}\n\treturn value;\n}\n\n/** The handler event one named write becomes, or null when it is not one. */\nfunction writeEvent(\n\tw: StateWriteRow,\n): { type: string; data: Record<string, string> } | null {\n\tconst key = parseStateWriteKey(w.key);\n\tif (!key) return null;\n\tconst value = storedValue(w);\n\tif (key.kind === \"var\") {\n\t\treturn {\n\t\t\ttype: \"var_set\",\n\t\t\tdata: {\n\t\t\t\tcontract_identifier: key.contractId,\n\t\t\t\tvar_name: key.varName,\n\t\t\t\traw_value: `0x${value}`,\n\t\t\t},\n\t\t};\n\t}\n\tconst base = {\n\t\tcontract_identifier: key.contractId,\n\t\tmap_name: key.map,\n\t\traw_key: `0x${key.rawKey}`,\n\t};\n\t// put_value stores a map entry as (some value); a delete stores none.\n\tif (value === \"09\") return { type: \"map_delete\", data: base };\n\tif (value.startsWith(\"0a\")) {\n\t\treturn {\n\t\t\ttype: \"map_set\",\n\t\t\tdata: { ...base, raw_value: `0x${value.slice(2)}` },\n\t\t};\n\t}\n\tthrow new Error(\n\t\t`state write ${w.ordinal} map value is neither (some v) nor none`,\n\t);\n}\n\n/**\n * A block's named writes as handler events, in node write order, plus the\n * transactions they hang on.\n *\n * Every returned tx carries `tx_index: 0`, so the runner's (tx_index,\n * event_index) sort dispatches by ordinal alone: node write order, including\n * block-level writes that land between transactions. Block-level writes\n * (`tx_index` null) share one synthetic tx with an empty id.\n *\n * Storage cannot tell `map_insert` from `map_set`, so no `map_insert` event is\n * ever produced; such sources are not state-level.\n */\nexport function stateWriteEvents(\n\twrites: StateWriteRow[],\n\ttxByIndex: ReadonlyMap<number, TxRecord>,\n): { txs: TxRecord[]; vmEvents: EventRecord[] } {\n\tconst txs = new Map<number | null, TxRecord>();\n\tconst vmEvents: EventRecord[] = [];\n\tfor (const w of [...writes].sort((a, b) => a.ordinal - b.ordinal)) {\n\t\tconst event = writeEvent(w);\n\t\tif (!event) continue;\n\t\tlet tx = txs.get(w.tx_index);\n\t\tif (!tx) {\n\t\t\tif (w.tx_index === null) {\n\t\t\t\ttx = { tx_id: \"\", type: \"block\", sender: \"\", status: \"success\" };\n\t\t\t} else {\n\t\t\t\tconst real = txByIndex.get(w.tx_index);\n\t\t\t\tif (!real) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`state write ${w.ordinal} names tx_index ${w.tx_index} the block does not have`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttx = real;\n\t\t\t}\n\t\t\ttx = { ...tx, tx_index: 0 };\n\t\t\ttxs.set(w.tx_index, tx);\n\t\t}\n\t\tvmEvents.push({\n\t\t\tid: vmEventId(tx.tx_id || \"block\", w.ordinal),\n\t\t\ttx_id: tx.tx_id,\n\t\t\ttype: event.type,\n\t\t\tevent_index: w.ordinal,\n\t\t\tdata: event.data,\n\t\t\tclock: \"vm\",\n\t\t});\n\t}\n\treturn { txs: [...txs.values()], vmEvents };\n}\n",
11
10
  "import {\n\tVM_NODE_TO_STORED_TYPE,\n\ttype VmNodeEventType,\n} from \"@secondlayer/shared\";\nimport type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport {\n\ttype BlockData,\n\ttype RuntimeEvent,\n\tvmEventId,\n} from \"./batch-loader.ts\";\nimport type { BlockSource } from \"./block-source.ts\";\n\n/** Duplicated from indexer — do not import `@secondlayer/indexer` (cycle). */\nconst OBSERVER_HTTP_EXPORT_PATH = \"/internal/observer-events\";\n\nexport type ObserverHttpFetch = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport type ObserverHttpBlockSourceOpts = {\n\t/** e.g. http://127.0.0.1:3700 — trailing slash stripped */\n\tbaseUrl: string;\n\ttoken?: string | null;\n\tfetch?: ObserverHttpFetch;\n\t/** Unused on the wire; list filtering is server-side. */\n\tnetwork?: string;\n};\n\ntype ObserverEventsNext = {\n\tafter_height: number;\n\tafter_index_block_hash: string;\n};\n\ntype SbaObserverMessage = {\n\tpath: string;\n\tpayload: unknown;\n\tcontent_sha256: string;\n\tblock_height: number | null;\n\tindex_block_hash: string | null;\n\treceived_at?: string;\n};\n\ntype ObserverEventsResponse = {\n\tevents: SbaObserverMessage[];\n\tnext: ObserverEventsNext | null;\n};\n\ntype ObserverTipResponse = {\n\tblock_height: number;\n\tindex_block_hash: string | null;\n};\n\ntype ObserverTx = {\n\ttxid?: string;\n\ttx_index?: number;\n\ttx_type?: string;\n\tsender_address?: string;\n\tstatus?: string;\n\traw_result?: string | null;\n\traw_tx?: string;\n\tcontract_call?: { contract_id?: string; function_name?: string };\n\tsmart_contract?: { contract_id?: string };\n};\n\ntype ObserverEvent = {\n\ttxid?: string;\n\tevent_index?: number;\n\ttype?: string;\n\t[key: string]: unknown;\n};\n\ntype ObserverNewBlockPayload = {\n\tblock_height?: number;\n\tblock_hash?: string;\n\tparent_block_hash?: string;\n\tburn_block_height?: number;\n\tburn_block_hash?: string | null;\n\tindex_block_hash?: string | null;\n\ttimestamp?: number;\n\tblock_time?: number;\n\tburn_block_time?: number;\n\tburn_block_timestamp?: number;\n\ttransactions?: ObserverTx[];\n\tevents?: ObserverEvent[];\n\t/** Opt-in traces; omitted on `\"*\"` bodies. */\n\tvm_events?: ObserverVmTrace[];\n};\n\ntype ObserverVmTrace = {\n\ttxid?: string;\n\tcommitted?: boolean;\n\ttype?: string;\n\t[key: string]: unknown;\n};\n\nfunction stripTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction blockTimestamp(payload: ObserverNewBlockPayload): number {\n\tfor (const value of [\n\t\tpayload.timestamp,\n\t\tpayload.block_time,\n\t\tpayload.burn_block_time,\n\t\tpayload.burn_block_timestamp,\n\t]) {\n\t\tif (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction eventData(event: ObserverEvent): unknown {\n\tif (typeof event.type === \"string\" && event.type in event) {\n\t\treturn event[event.type] ?? {};\n\t}\n\treturn {};\n}\n\n/** Map a `/new_block` observer payload into subgraph `BlockData`. No Hiro. */\nexport function mapNewBlockPayloadToBlockData(payload: unknown): BlockData {\n\tconst p = payload as ObserverNewBlockPayload;\n\tif (\n\t\ttypeof p.block_height !== \"number\" ||\n\t\t!Number.isFinite(p.block_height) ||\n\t\ttypeof p.index_block_hash !== \"string\" ||\n\t\tp.index_block_hash.length === 0\n\t) {\n\t\tthrow new Error(\n\t\t\t\"observer /new_block payload missing block_height or index_block_hash\",\n\t\t);\n\t}\n\n\tconst height = p.block_height;\n\tconst block = {\n\t\theight,\n\t\thash: p.block_hash ?? \"\",\n\t\tparent_hash: p.parent_block_hash ?? \"\",\n\t\tburn_block_height: p.burn_block_height ?? 0,\n\t\tburn_block_hash: p.burn_block_hash ?? null,\n\t\tindex_block_hash: p.index_block_hash,\n\t\ttimestamp: blockTimestamp(p),\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n\n\tconst txs: Transaction[] = (p.transactions ?? []).map((tx) => {\n\t\tlet contractId: string | null = null;\n\t\tlet functionName: string | null = null;\n\t\tif (tx.tx_type === \"contract_call\" && tx.contract_call) {\n\t\t\tcontractId = tx.contract_call.contract_id ?? null;\n\t\t\tfunctionName = tx.contract_call.function_name ?? null;\n\t\t} else if (tx.tx_type === \"smart_contract\" && tx.smart_contract) {\n\t\t\tcontractId = tx.smart_contract.contract_id ?? null;\n\t\t}\n\t\treturn {\n\t\t\ttx_id: tx.txid ?? \"\",\n\t\t\tblock_height: height,\n\t\t\ttx_index: tx.tx_index ?? 0,\n\t\t\ttype: tx.tx_type ?? \"\",\n\t\t\tsender: tx.sender_address ?? \"\",\n\t\t\tstatus: tx.status ?? \"success\",\n\t\t\tcontract_id: contractId,\n\t\t\tfunction_name: functionName,\n\t\t\tfunction_args: [],\n\t\t\traw_result: tx.raw_result ?? null,\n\t\t\traw_tx: tx.raw_tx ?? \"\",\n\t\t\tcreated_at: new Date(0),\n\t\t} as Transaction;\n\t});\n\n\tconst events: Event[] = (p.events ?? []).map((event) => {\n\t\tconst txId = event.txid ?? \"\";\n\t\tconst eventIndex = event.event_index ?? 0;\n\t\treturn {\n\t\t\tid: `${txId}#${eventIndex}`,\n\t\t\ttx_id: txId,\n\t\t\tblock_height: height,\n\t\t\tevent_index: eventIndex,\n\t\t\ttype: event.type ?? \"\",\n\t\t\tdata: eventData(event),\n\t\t\tcreated_at: new Date(0),\n\t\t} as Event;\n\t});\n\n\t// Opt-in `vm_events` (present only when the observer subscribed to\n\t// `storage` / `contract_calls`). Node type → stored name; own clock.\n\tconst vmEvents: RuntimeEvent[] = [];\n\tfor (const [i, trace] of (p.vm_events ?? []).entries()) {\n\t\tconst nodeType = trace.type;\n\t\tif (typeof nodeType !== \"string\" || !(nodeType in VM_NODE_TO_STORED_TYPE))\n\t\t\tcontinue;\n\t\tconst stored = VM_NODE_TO_STORED_TYPE[nodeType as VmNodeEventType];\n\t\tconst body = trace[nodeType];\n\t\tif (!body || typeof body !== \"object\") continue;\n\t\tconst txId = trace.txid ?? \"\";\n\t\tconst vmIndex = i;\n\t\tvmEvents.push({\n\t\t\tid: vmEventId(txId, vmIndex),\n\t\t\ttx_id: txId,\n\t\t\tblock_height: height,\n\t\t\tevent_index: vmIndex,\n\t\t\ttype: stored,\n\t\t\tdata: body,\n\t\t\tcreated_at: new Date(0),\n\t\t\tclock: \"vm\",\n\t\t} as RuntimeEvent);\n\t}\n\n\treturn { block, txs, events, vmEvents };\n}\n\n/**\n * Experimental BlockSource: pages indexer `/internal/observer-events` and maps\n * raw `/new_block` bodies to `BlockData`. Not the production default.\n */\nexport class ObserverHttpBlockSource implements BlockSource {\n\tprivate readonly baseUrl: string;\n\tprivate readonly token: string | null;\n\tprivate readonly fetchFn: ObserverHttpFetch;\n\n\tconstructor(opts: ObserverHttpBlockSourceOpts) {\n\t\tthis.baseUrl = stripTrailingSlash(opts.baseUrl);\n\t\tthis.token = opts.token ?? null;\n\t\tthis.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n\t}\n\n\tprivate headers(): Record<string, string> {\n\t\tif (!this.token) return {};\n\t\treturn { Authorization: `Bearer ${this.token}` };\n\t}\n\n\tasync getTip(): Promise<number> {\n\t\tconst res = await this.fetchFn(\n\t\t\t`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}/tip`,\n\t\t\t{ headers: this.headers() },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t);\n\t\t}\n\t\tlet body: ObserverTipResponse;\n\t\ttry {\n\t\t\tbody = (await res.json()) as ObserverTipResponse;\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t`observer tip invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\ttypeof body.block_height !== \"number\" ||\n\t\t\t!Number.isFinite(body.block_height)\n\t\t) {\n\t\t\tthrow new Error(\"observer tip missing block_height\");\n\t\t}\n\t\treturn body.block_height;\n\t}\n\n\tasync loadBlockRange(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<Map<number, BlockData>> {\n\t\tconst result = new Map<number, BlockData>();\n\t\tlet afterHeight: number | undefined =\n\t\t\tfromHeight > 0 ? fromHeight - 1 : undefined;\n\t\tlet afterIndexBlockHash: string | undefined;\n\n\t\tfor (;;) {\n\t\t\tconst url = new URL(`${this.baseUrl}${OBSERVER_HTTP_EXPORT_PATH}`);\n\t\t\turl.searchParams.set(\"path\", \"/new_block\");\n\t\t\turl.searchParams.set(\"limit\", \"100\");\n\t\t\tif (afterHeight != null) {\n\t\t\t\turl.searchParams.set(\"after_height\", String(afterHeight));\n\t\t\t}\n\t\t\tif (afterIndexBlockHash) {\n\t\t\t\turl.searchParams.set(\"after_index_block_hash\", afterIndexBlockHash);\n\t\t\t}\n\n\t\t\tconst res = await this.fetchFn(url.toString(), {\n\t\t\t\theaders: this.headers(),\n\t\t\t});\n\t\t\tif (!res.ok) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events HTTP ${res.status}: ${await res.text().catch(() => \"\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet body: ObserverEventsResponse;\n\t\t\ttry {\n\t\t\t\tbody = (await res.json()) as ObserverEventsResponse;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`observer events invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet pastTo = false;\n\t\t\tfor (const message of body.events ?? []) {\n\t\t\t\tif (message.path === \"/new_burn_block\") continue;\n\t\t\t\tconst height = (message.payload as ObserverNewBlockPayload)\n\t\t\t\t\t?.block_height;\n\t\t\t\tif (typeof height === \"number\" && height > toHeight) {\n\t\t\t\t\tpastTo = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst data = mapNewBlockPayloadToBlockData(message.payload);\n\t\t\t\tconst h = data.block.height;\n\t\t\t\tif (h >= fromHeight && h <= toHeight) {\n\t\t\t\t\tresult.set(h, data);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (pastTo || body.next == null) break;\n\t\t\tafterHeight = body.next.after_height;\n\t\t\tafterIndexBlockHash = body.next.after_index_block_hash;\n\t\t}\n\n\t\treturn result;\n\t}\n}\n",
12
11
  "/**\n * Deterministic realm for verifiable (state-level) subgraphs.\n *\n * Handlers run in a `node:vm` context whose global object is a frozen\n * allow-list: every forbidden global ({@link FORBIDDEN_GLOBALS}) is a getter\n * that throws {@link NondeterminismError}, `Math` keeps only exact members,\n * locale-sensitive methods throw, and code generation from strings is off.\n * The handler sees a `ctx` facade that rejects non-integer numbers in rows,\n * refuses concurrent ctx calls, and turns read failures into block aborts.\n *\n * This is a determinism guard, not a security boundary: a handler can still\n * reach host intrinsics through the objects it is handed. The deploy scan\n * and this realm together catch accidental nondeterminism; hostile code is\n * gVisor's job.\n *\n * Only subgraphs whose stored verification level is `state` load here.\n * Everything else keeps the plain `import()` path, unchanged.\n */\nimport vm from \"node:vm\";\nimport type {\n\tSubgraphContext,\n\tSubgraphDefinition,\n\tSubgraphSchema,\n} from \"../types.ts\";\nimport {\n\tALLOWED_GLOBALS,\n\tALLOWED_MATH,\n\tFORBIDDEN_GLOBALS,\n\tLOCALE_METHODS,\n} from \"../verification.ts\";\n\n/**\n * A handler broke the determinism contract at runtime. Infra-class: the\n * block aborts (rollback + retry) instead of skipping the event, because a\n * skip would commit output that depends on the run.\n */\nexport class NondeterminismError extends Error {\n\toverride name = \"NondeterminismError\";\n}\n\n/**\n * A ctx read (DB, chain) failed under a verifiable subgraph. Infra-class like\n * {@link NondeterminismError}: skipping the event would make its rows depend\n * on whether the database was reachable.\n */\nexport class HandlerReadError extends Error {\n\toverride name = \"HandlerReadError\";\n}\n\n/** Errors that abort the whole block rather than skip one event. */\nexport function abortsBlock(err: unknown): boolean {\n\treturn err instanceof NondeterminismError || err instanceof HandlerReadError;\n}\n\n/** Host constructors handed to the realm so `x instanceof Uint8Array` holds\n * for decoded event payloads, which are built in the host realm. */\nconst HOST_GLOBALS = [\n\t\"ArrayBuffer\",\n\t\"DataView\",\n\t\"Int8Array\",\n\t\"Uint8Array\",\n\t\"Uint8ClampedArray\",\n\t\"Int16Array\",\n\t\"Uint16Array\",\n\t\"Int32Array\",\n\t\"Uint32Array\",\n\t\"Float16Array\",\n\t\"Float32Array\",\n\t\"Float64Array\",\n\t\"BigInt64Array\",\n\t\"BigUint64Array\",\n\t\"TextEncoder\",\n\t\"TextDecoder\",\n\t\"atob\",\n\t\"btoa\",\n] as const;\n\nfunction forbid(name: string, reason: string): () => never {\n\treturn () => {\n\t\tthrow new NondeterminismError(`${name}: ${reason}`);\n\t};\n}\n\nfunction createRealm(): vm.Context {\n\tconst host = globalThis as unknown as Record<string, unknown>;\n\tconst sandbox: Record<string, unknown> = Object.create(null);\n\tfor (const name of HOST_GLOBALS) {\n\t\tif (host[name] !== undefined) sandbox[name] = host[name];\n\t}\n\tconst context = vm.createContext(sandbox, {\n\t\tname: \"subgraph-handler\",\n\t\tcodeGeneration: { strings: false, wasm: false },\n\t});\n\tconst g = vm.runInContext(\"globalThis\", context) as Record<string, unknown>;\n\n\tconst allowed = new Set(ALLOWED_GLOBALS);\n\tfor (const name of Object.getOwnPropertyNames(g)) {\n\t\tif (!allowed.has(name)) delete g[name];\n\t}\n\tfor (const [name, reason] of Object.entries(FORBIDDEN_GLOBALS)) {\n\t\tObject.defineProperty(g, name, { get: forbid(name, reason) });\n\t}\n\n\tconst realmMath = g.Math as Record<string, unknown>;\n\tconst safeMath: Record<string, unknown> = {};\n\tconst allowedMath = new Set(ALLOWED_MATH);\n\tfor (const key of Object.getOwnPropertyNames(realmMath)) {\n\t\tif (allowedMath.has(key)) safeMath[key] = realmMath[key];\n\t\telse\n\t\t\tObject.defineProperty(safeMath, key, {\n\t\t\t\tget: forbid(\n\t\t\t\t\t`Math.${key}`,\n\t\t\t\t\tkey === \"random\"\n\t\t\t\t\t\t? \"randomness differs per run\"\n\t\t\t\t\t\t: \"result is engine-approximated\",\n\t\t\t\t),\n\t\t\t});\n\t}\n\tObject.defineProperty(g, \"Math\", { value: Object.freeze(safeMath) });\n\n\tfor (const ctor of [\"String\", \"Number\", \"BigInt\", \"Array\", \"Object\"]) {\n\t\tconst proto = (g[ctor] as { prototype: object }).prototype;\n\t\tfor (const method of LOCALE_METHODS) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(proto, method)) {\n\t\t\t\tObject.defineProperty(proto, method, {\n\t\t\t\t\tvalue: forbid(method, \"output depends on the host's locale data\"),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// No new globals. Not Object.freeze: under Bun, freezing (or redefining\n\t// every binding of) a vm global breaks lookups of its built-ins. Forbidden\n\t// getters and Math are already non-configurable, so they stay locked.\n\tObject.preventExtensions(g);\n\treturn context;\n}\n\n// ── ctx facade ──────────────────────────────────────────────────────────\n\n/** Reject row values whose stored form can differ across engines or runs. */\nexport function checkRowValues(\n\twhere: string,\n\tvalues: Record<string, unknown>,\n): void {\n\tfor (const [col, value] of Object.entries(values)) {\n\t\tcheckValue(value, `${where}.${col}`);\n\t}\n}\n\nfunction checkValue(value: unknown, path: string): void {\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\tif (!Number.isSafeInteger(value)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${path}: ${value} is not a safe integer; verifiable subgraphs store bigint or integers only`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\tcase \"function\":\n\t\tcase \"symbol\":\n\t\t\tthrow new TypeError(`${path}: a ${typeof value} is not a row value`);\n\t\tcase \"object\":\n\t\t\tif (value === null || ArrayBuffer.isView(value)) return;\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\tvalue.forEach((v, i) => checkValue(v, `${path}[${i}]`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const [k, v] of Object.entries(value)) checkValue(v, `${path}.${k}`);\n\t\t\treturn;\n\t\tdefault:\n\t\t\treturn;\n\t}\n}\n\n/**\n * Wrap the runtime ctx for one block. Reads must be awaited one at a time:\n * a second ctx call while a read is pending would order writes by database\n * latency.\n */\nexport function deterministicContext(\n\tctx: SubgraphContext,\n\tschema: SubgraphSchema,\n): SubgraphContext {\n\tlet pendingReads = 0;\n\t// An unknown table is the handler's bug, identical on every run: keep it\n\t// handler-origin (event skipped) rather than a read failure (block abort).\n\tconst knownTable = (table: string) => {\n\t\tif (!Object.prototype.hasOwnProperty.call(schema, table)) {\n\t\t\tthrow new Error(`Table \"${table}\" not found in subgraph schema`);\n\t\t}\n\t};\n\tconst guard = (op: string) => {\n\t\tif (pendingReads > 0) {\n\t\t\tthrow new NondeterminismError(\n\t\t\t\t`ctx.${op} while a ctx read is pending: concurrent ctx calls order writes by database latency; await each read before the next call`,\n\t\t\t);\n\t\t}\n\t};\n\tconst read = async <T>(op: string, run: () => Promise<T>): Promise<T> => {\n\t\tguard(op);\n\t\tpendingReads++;\n\t\ttry {\n\t\t\treturn await run();\n\t\t} catch (err) {\n\t\t\tif (err instanceof NondeterminismError) throw err;\n\t\t\tthrow new HandlerReadError(\n\t\t\t\t`ctx.${op} failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t{ cause: err },\n\t\t\t);\n\t\t} finally {\n\t\t\tpendingReads--;\n\t\t}\n\t};\n\ttype FindMany = (...args: unknown[]) => Promise<Record<string, unknown>[]>;\n\treturn {\n\t\tget block() {\n\t\t\treturn ctx.block;\n\t\t},\n\t\tget tx() {\n\t\t\treturn ctx.tx;\n\t\t},\n\t\tget client(): never {\n\t\t\tthrow new NondeterminismError(\n\t\t\t\t\"ctx.client: contract reads need re-execution proofs\",\n\t\t\t);\n\t\t},\n\t\tinsert(table, row) {\n\t\t\tguard(\"insert\");\n\t\t\tcheckRowValues(`insert ${table}`, row);\n\t\t\tctx.insert(table, row);\n\t\t},\n\t\tupdate(table, where, set) {\n\t\t\tguard(\"update\");\n\t\t\tcheckRowValues(`update ${table}`, where);\n\t\t\tcheckRowValues(`update ${table}`, set);\n\t\t\tctx.update(table, where, set);\n\t\t},\n\t\tupsert(table, key, row) {\n\t\t\tguard(\"upsert\");\n\t\t\tcheckRowValues(`upsert ${table}`, key);\n\t\t\tcheckRowValues(`upsert ${table}`, row);\n\t\t\tctx.upsert(table, key, row);\n\t\t},\n\t\tdelete(table, where) {\n\t\t\tguard(\"delete\");\n\t\t\tctx.delete(table, where);\n\t\t},\n\t\tincrement(table, key, deltas) {\n\t\t\tguard(\"increment\");\n\t\t\tcheckRowValues(`increment ${table}`, key);\n\t\t\tcheckRowValues(`increment ${table}`, deltas);\n\t\t\tctx.increment(table, key, deltas);\n\t\t},\n\t\tfindOne: (table, where) => {\n\t\t\tknownTable(table);\n\t\t\treturn read(\"findOne\", () => ctx.findOne(table, where));\n\t\t},\n\t\tfindMany: (table, ...rest: unknown[]) => {\n\t\t\tknownTable(table);\n\t\t\treturn read(\"findMany\", () => (ctx.findMany as FindMany)(table, ...rest));\n\t\t},\n\t};\n}\n\n// ── Loading ─────────────────────────────────────────────────────────────\n\n/** Definitions this module loaded into a realm. */\nconst realmDefinitions = new WeakSet<SubgraphDefinition>();\n\n/** True for a definition {@link loadDeterministicDefinition} produced: a\n * stored `state` subgraph, whose inputs follow the realm (`state_writes`). */\nexport function runsInRealm(def: SubgraphDefinition): boolean {\n\treturn realmDefinitions.has(def);\n}\n\n/**\n * Evaluate a bundled handler (ESM, as stored in `handler_code`) inside a\n * fresh deterministic realm and return its definition with every handler\n * wrapped to receive the {@link deterministicContext} facade.\n */\nexport async function loadDeterministicDefinition(\n\thandlerCode: string,\n): Promise<SubgraphDefinition> {\n\t// The realm runs scripts, not modules: lower the bundle's single\n\t// `export default` to CommonJS. Bundles have no imports left to resolve.\n\t// Loaded lazily so importing the runner never pulls esbuild.\n\tconst { transform } = await import(\"esbuild\");\n\tconst { code } = await transform(handlerCode, {\n\t\tformat: \"cjs\",\n\t\tloader: \"js\",\n\t\tlogLevel: \"silent\",\n\t});\n\tconst context = createRealm();\n\tconst evaluate = vm.runInContext(\n\t\t`(function (module, exports) {\\n${code}\\n})`,\n\t\tcontext,\n\t\t{ filename: \"handler.js\" },\n\t) as (module: { exports: unknown }, exports: unknown) => void;\n\tconst mod: { exports: Record<string, unknown> } = { exports: {} };\n\tevaluate(mod, mod.exports);\n\tconst def = (mod.exports.default ?? mod.exports) as SubgraphDefinition;\n\t// Declarative parts cross back as host objects, so runtime code never\n\t// sees realm prototypes.\n\tconst sources = structuredClone(def.sources);\n\tconst schema = structuredClone(def.schema);\n\n\t// One facade per block context (the runner builds a fresh ctx per block).\n\tconst facades = new WeakMap<SubgraphContext, SubgraphContext>();\n\tconst handlers: SubgraphDefinition[\"handlers\"] = {};\n\tfor (const [name, handler] of Object.entries(def.handlers ?? {})) {\n\t\thandlers[name] = (event, ctx) => {\n\t\t\tlet facade = facades.get(ctx);\n\t\t\tif (!facade) {\n\t\t\t\tfacade = deterministicContext(ctx, schema);\n\t\t\t\tfacades.set(ctx, facade);\n\t\t\t}\n\t\t\treturn handler(event, facade);\n\t\t};\n\t}\n\tconst loaded = { ...def, sources, schema, handlers };\n\trealmDefinitions.add(loaded);\n\treturn loaded;\n}\n",
13
12
  "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\nimport { vmEventId } from \"./batch-loader.ts\";\n\nexport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\n\n/**\n * Reconstruct the raw `blocks`/`events` row shapes the subgraph runtime expects\n * (the shapes `matchSources` + the handler runner read) from the decoded,\n * flattened rows the public Index API serves. This is what lets\n * `PublicApiBlockSource` feed the EXISTING pipeline byte-identically to the\n * Postgres tap.\n *\n * Two shape gaps the Index API can't avoid, handled here:\n * - Index event rows are flat (`event_type: \"ft_transfer\"`, columns\n * `sender`/`amount`/…); the runtime expects the node's nested `data` keyed by\n * a suffixed `type` (`ft_transfer_event`), with print under `contract_event`.\n * - nft/print Clarity values: the runtime decodes from the canonical hex\n * (`raw_value`), so we place the Index hex there. (The node's verbose\n * serde-tagged `value`, e.g. `{UInt:223}`, is not reproducible from hex and\n * is no longer read — see the nft tokenId normalization in runner.ts.)\n */\n\n/** ISO `block_time` (or null) → unix-seconds integer the runtime expects. */\nfunction isoToUnixSeconds(iso: string | null): number {\n\tif (!iso) return 0;\n\treturn Math.floor(new Date(iso).getTime() / 1000);\n}\n\nexport function reconstructBlock(b: IndexBlockRow): Block {\n\treturn {\n\t\theight: b.block_height,\n\t\thash: b.block_hash,\n\t\tparent_hash: b.parent_hash,\n\t\tburn_block_height: b.burn_block_height,\n\t\tburn_block_hash: b.burn_block_hash,\n\t\t// Present since the blocks endpoint started serving it; older API\n\t\t// deployments omit it, and a null propagates to a clean refusal in\n\t\t// `ctx.client.readOnly` rather than an unpinned tip read.\n\t\tindex_block_hash: b.index_block_hash ?? null,\n\t\ttimestamp: isoToUnixSeconds(b.block_time),\n\t\t// Index serves canonical rows only.\n\t\tcanonical: true,\n\t\tcreated_at: new Date(0),\n\t} as Block;\n}\n\nexport function reconstructTransaction(t: IndexTransactionRow): Transaction {\n\treturn {\n\t\ttx_id: t.tx_id,\n\t\tblock_height: t.block_height,\n\t\ttx_index: t.tx_index,\n\t\ttype: t.tx_type,\n\t\tsender: t.sender,\n\t\tstatus: t.status,\n\t\tcontract_id:\n\t\t\tt.contract_call?.contract_id ?? t.smart_contract?.contract_id ?? null,\n\t\tfunction_name: t.contract_call?.function_name ?? null,\n\t\t// Raw hex ClarityValues — the runner decodes them via its own deserializeCV\n\t\t// path, identical to the DB tap.\n\t\tfunction_args: t.contract_call?.function_args_hex ?? [],\n\t\traw_result: t.contract_call?.result_hex ?? null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\n/**\n * Build a minimal canonical Transaction from an event row's joined tx context\n * (`tx_context=true` on /v1/index/events). For event-only subgraphs this lets\n * the loader materialize only the txs that actually carry a matched event,\n * instead of draining every transaction in the range (the ~37x reindex\n * over-fetch — see docs/sprints/indexing-speed/plan.md). `function_args` /\n * `raw_result` are empty: an event source never reads them (contract_call-only).\n */\nexport function reconstructTxFromEventRow(e: IndexEventRow): Transaction {\n\treturn {\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\ttx_index: e.tx_index ?? 0,\n\t\ttype: e.tx_type ?? \"\",\n\t\tsender: e.tx_sender ?? \"\",\n\t\tstatus: e.tx_status ?? \"success\",\n\t\tcontract_id: e.tx_contract_id ?? null,\n\t\tfunction_name: e.tx_function_name ?? null,\n\t\tfunction_args: [],\n\t\traw_result: null,\n\t\traw_tx: \"\",\n\t\tcreated_at: new Date(0),\n\t} as Transaction;\n}\n\nexport function reconstructEvent(e: IndexEventRow): Event {\n\tconst base = {\n\t\t// Synthetic, deterministic id. The runtime only reads `id` for error logs\n\t\t// and the `*`-wildcard payload (which is streams-index-ineligible).\n\t\tid: `${e.tx_id}#${e.event_index}`,\n\t\ttx_id: e.tx_id,\n\t\tblock_height: e.block_height,\n\t\tevent_index: e.event_index,\n\t\tcreated_at: new Date(0),\n\t};\n\n\tswitch (e.event_type) {\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tasset_identifier: e.asset_identifier,\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\t// Canonical hex → runner decodes tokenId from raw_value.\n\t\t\t\t\traw_value: e.value,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: `${e.event_type}_event`,\n\t\t\t\tdata: {\n\t\t\t\t\tsender: e.sender,\n\t\t\t\t\trecipient: e.recipient,\n\t\t\t\t\tamount: e.amount,\n\t\t\t\t\t// Raw stx_transfer always carries memo (\"\" when empty); Index\n\t\t\t\t\t// returns null for empty — default to \"\" to match the DB tap.\n\t\t\t\t\t...(e.event_type === \"stx_transfer\" ? { memo: e.memo ?? \"\" } : {}),\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"stx_lock_event\",\n\t\t\t\tdata: {\n\t\t\t\t\tlocked_address: e.sender,\n\t\t\t\t\tlocked_amount: e.amount,\n\t\t\t\t\tunlock_height: e.payload.unlock_height,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"print\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\ttype: \"contract_event\",\n\t\t\t\tdata: {\n\t\t\t\t\ttopic: e.payload.topic,\n\t\t\t\t\t// Index serves `contract_id`. Matcher + runner also accept\n\t\t\t\t\t// legacy `contract_identifier`; emit the current field.\n\t\t\t\t\tcontract_id: e.contract_id,\n\t\t\t\t\tvalue: e.payload.value,\n\t\t\t\t\traw_value: e.payload.raw_value,\n\t\t\t\t},\n\t\t\t} as Event;\n\n\t\tcase \"nested_contract_call\":\n\t\tcase \"var_set\":\n\t\tcase \"map_set\":\n\t\tcase \"map_insert\":\n\t\tcase \"map_delete\":\n\t\t\t// Second clock: `event_index` here is ordinal. Distinct id +\n\t\t\t// `clock` so it never dedupes or sorts against a classic row.\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tid: vmEventId(e.tx_id, e.event_index),\n\t\t\t\tclock: \"vm\",\n\t\t\t\ttype: e.event_type,\n\t\t\t\tdata: {\n\t\t\t\t\tcontract_identifier: e.contract_id,\n\t\t\t\t\t...(\"payload\" in e && e.payload && typeof e.payload === \"object\"\n\t\t\t\t\t\t? (e.payload as Record<string, unknown>)\n\t\t\t\t\t\t: {}),\n\t\t\t\t\tsender: \"sender\" in e ? e.sender : undefined,\n\t\t\t\t\tcaller: \"caller\" in e ? e.caller : undefined,\n\t\t\t\t\tfunction_name: \"function_name\" in e ? e.function_name : undefined,\n\t\t\t\t\tfunction_args: \"function_args\" in e ? e.function_args : undefined,\n\t\t\t\t\traw_result: \"raw_result\" in e ? e.raw_result : undefined,\n\t\t\t\t\tmap_name: \"map\" in e ? e.map : undefined,\n\t\t\t\t\tvar_name: \"var_name\" in e ? e.var_name : undefined,\n\t\t\t\t\traw_key: \"raw_key\" in e ? e.raw_key : undefined,\n\t\t\t\t\traw_value: \"raw_value\" in e ? e.raw_value : undefined,\n\t\t\t\t},\n\t\t\t} as Event;\n\t}\n}\n",
14
- "import type {\n\tChainApplyEnvelope,\n\tSbtcDepositEvent,\n\tSbtcWithdrawalEvent,\n\tSbtcWithdrawalSweptConfirmedEvent,\n} from \"@secondlayer/shared\";\nimport type {\n\tDatabase,\n\tInsertWebhookOutbox,\n\tSbtcEventTopic,\n\tSbtcEventsTable,\n\tWebhook,\n} from \"@secondlayer/shared/db\";\nimport { getSourceDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport type { ChainTrigger } from \"@secondlayer/shared/schemas/webhooks\";\nimport type { Kysely, Selectable } from \"kysely\";\nimport type { SubgraphFilter } from \"../types.ts\";\nimport type { BlockData } from \"./batch-loader.ts\";\nimport { indexEventTypesForFilterTypes } from \"./block-source.ts\";\nimport { decoderNamesForIndexEventTypes } from \"./decoder-bound.ts\";\nimport {\n\ttype MatchedTx,\n\ttype TraitContracts,\n\tmatchSources,\n} from \"./source-matcher.ts\";\n\n/** Trigger types that match a whole transaction (not an individual event). */\nconst TX_LEVEL_TRIGGER_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\n\n/**\n * `BlockData.block.timestamp` → the `webhook_outbox.block_time` the emitters\n * below stamp on a row. Unix seconds on every real block source\n * (`PostgresBlockSource` reads it off `blocks`; `PublicApiBlockSource`\n * reconstructs it from the Index API's `block_time`). Undefined/NaN/non-\n * positive (a test's minimal block fixture, or the 0-timestamp bulk-import\n * artifact `decode/health.ts` also guards against) means \"unknown\" — leave\n * `block_time` null rather than writing an Invalid Date or a 1970 sentinel.\n */\nexport function blockTimeOf(block: { timestamp: number }): Date | undefined {\n\treturn Number.isFinite(block.timestamp) && block.timestamp > 0\n\t\t? new Date(block.timestamp * 1000)\n\t\t: undefined;\n}\n\n/** Fired on a Bitcoin confirmation, async to Stacks blocks — handled by the\n * scan-based `emitSbtcSettlementOutbox`, NOT the per-block path. Listed in\n * SBTC_TRIGGER_TYPES so the per-block matcher skips it, but deliberately absent\n * from SBTC_TRIGGER_TO_TOPIC (it has no `sbtc_events` topic). */\nconst SETTLEMENT_TRIGGER_TYPE = \"sbtc_withdrawal_swept_confirmed\";\n\n/**\n * sBTC trigger types — matched via the `sbtc_events` table, NOT via\n * `decoded_events`. Excluded from the chain-event sources map so the\n * `matchSources` engine never sees them; `emitSbtcOutbox` handles them\n * with a dedicated query + match loop.\n */\nconst SBTC_TRIGGER_TYPES = new Set([\n\t\"sbtc_deposit\",\n\t\"sbtc_withdrawal_create\",\n\t\"sbtc_withdrawal_accept\",\n\t\"sbtc_withdrawal_reject\",\n\tSETTLEMENT_TRIGGER_TYPE,\n]);\n\nfunction isSbtcTriggerType(type: string): boolean {\n\treturn SBTC_TRIGGER_TYPES.has(type);\n}\n\nconst SBTC_TRIGGER_TO_TOPIC: Record<string, SbtcEventTopic> = {\n\tsbtc_deposit: \"completed-deposit\",\n\tsbtc_withdrawal_create: \"withdrawal-create\",\n\tsbtc_withdrawal_accept: \"withdrawal-accept\",\n\tsbtc_withdrawal_reject: \"withdrawal-reject\",\n};\n\n/**\n * Pure matching core for direct chain-level webhooks. A single evaluator\n * loop serves ALL chain webhooks: it reads canonical blocks off the public\n * Index/Streams clock (via `PublicApiBlockSource`), runs the same\n * `matchSources` engine the subgraph runtime uses, and routes matches back to\n * the originating webhook. Everything here is pure/sync (DB only for trait\n * resolution) so it's trivially testable.\n *\n * Source keys are `\"{webhookId}#{triggerIndex}\"` — `matchSources` echoes\n * the key as `MatchedTx.sourceName`, letting the emitter recover which\n * webhook (and which trigger) matched. `keyMeta` carries the readable\n * trigger type for the outbox `event_type` / payload.\n */\n\nexport interface TriggerKeyMeta {\n\twebhookId: string;\n\ttriggerIndex: number;\n\ttriggerType: ChainTrigger[\"type\"];\n}\n\nexport interface ChainSourcesMap {\n\tsources: Record<string, SubgraphFilter>;\n\tkeyMeta: Map<string, TriggerKeyMeta>;\n}\n\nfunction sourceKey(webhookId: string, triggerIndex: number): string {\n\treturn `${webhookId}#${triggerIndex}`;\n}\n\nfunction toAmount(v: string | number | undefined): bigint | undefined {\n\treturn v === undefined ? undefined : BigInt(v);\n}\n\n/**\n * Convert a stored `ChainTrigger` (JSON; amounts as string/number) to the\n * runtime `SubgraphFilter` the matcher expects (amounts as bigint). Field names\n * are identical across the two shapes, so this is a copy plus amount coercion.\n */\nexport function chainTriggerToFilter(trigger: ChainTrigger): SubgraphFilter {\n\tconst t = trigger as ChainTrigger & {\n\t\tminAmount?: string | number;\n\t\tmaxAmount?: string | number;\n\t};\n\t// Spread copies all set keys; amounts (string|number) are then overwritten\n\t// with bigint where present. An absent optional amount isn't in the spread,\n\t// so there's nothing to strip.\n\tconst filter = { ...trigger } as Record<string, unknown>;\n\tconst minAmount = toAmount(t.minAmount);\n\tconst maxAmount = toAmount(t.maxAmount);\n\tif (minAmount !== undefined) filter.minAmount = minAmount;\n\tif (maxAmount !== undefined) filter.maxAmount = maxAmount;\n\treturn filter as unknown as SubgraphFilter;\n}\n\nfunction triggersOf(sub: Webhook): ChainTrigger[] {\n\treturn (sub.triggers ?? []) as ChainTrigger[];\n}\n\n/** Build the `matchSources` input from every active chain webhook. */\nexport function buildSourcesMap(chainSubs: Webhook[]): ChainSourcesMap {\n\tconst sources: Record<string, SubgraphFilter> = {};\n\tconst keyMeta = new Map<string, TriggerKeyMeta>();\n\tfor (const sub of chainSubs) {\n\t\ttriggersOf(sub).forEach((trigger, triggerIndex) => {\n\t\t\t// sBTC triggers are handled by emitSbtcOutbox — skip them here so\n\t\t\t// matchSources never tries to find sbtc_events in decoded_events.\n\t\t\tif (isSbtcTriggerType(trigger.type)) return;\n\t\t\tconst key = sourceKey(sub.id, triggerIndex);\n\t\t\tsources[key] = chainTriggerToFilter(trigger);\n\t\t\tkeyMeta.set(key, {\n\t\t\t\twebhookId: sub.id,\n\t\t\t\ttriggerIndex,\n\t\t\t\ttriggerType: trigger.type,\n\t\t\t});\n\t\t});\n\t}\n\treturn { sources, keyMeta };\n}\n\n/** The Index event types the loader must fetch to satisfy all chain triggers. */\nexport function referencedEventTypes(chainSubs: Webhook[]): string[] {\n\tconst filterTypes = new Set<string>();\n\tfor (const sub of chainSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\t// sBTC events live in sbtc_events, not in the Index event stream.\n\t\t\tif (!isSbtcTriggerType(trigger.type)) filterTypes.add(trigger.type);\n\t\t}\n\t}\n\treturn indexEventTypesForFilterTypes([...filterTypes]);\n}\n\n/** Decoder checkpoint names feeding the event types these chain subs read. */\nexport function referencedDecoderNames(chainSubs: Webhook[]): string[] {\n\treturn decoderNamesForIndexEventTypes(referencedEventTypes(chainSubs));\n}\n\n/**\n * True when some active chain webhook has a tx-level trigger\n * (contract_call/contract_deploy) — the only trigger types whose match needs\n * a REAL transaction (`function_args`, `raw_result`, etc., read in\n * `emitChainOutbox`'s TX_LEVEL branch below). Every other trigger type matches\n * off decoded events, which the block source can synthesize a minimal tx for\n * from joined event context instead of fetching every transaction in the\n * range. Mirrors `needsTransactionData` in block-source.ts for subgraphs —\n * same rule, chain-webhook triggers instead of subgraph source filters.\n */\nexport function chainSubsNeedTransactions(chainSubs: Webhook[]): boolean {\n\treturn chainSubs.some((sub) =>\n\t\ttriggersOf(sub).some((trigger) => TX_LEVEL_TRIGGER_TYPES.has(trigger.type)),\n\t);\n}\n\n/** Distinct traits referenced across all chain triggers. */\nexport function referencedTraits(chainSubs: Webhook[]): string[] {\n\tconst traits = new Set<string>();\n\tfor (const sub of chainSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\tconst trait = (trigger as { trait?: string }).trait;\n\t\t\tif (trait) traits.add(trait);\n\t\t}\n\t}\n\treturn [...traits];\n}\n\n/**\n * Resolve each referenced trait to its conforming contract-id set as of\n * `asOfBlock`, from the contract registry (`CONTRACT_REGISTRY_ENABLED` populates\n * it). Empty map when no trigger is trait-scoped → no DB work. Membership only\n * grows, so the evaluator resolves this once per batch, not per block.\n */\nexport async function buildTraitContracts(\n\tchainSubs: Webhook[],\n\tasOfBlock: number,\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<TraitContracts> {\n\t// `contracts` is a SOURCE-plane table; the evaluator/replay run on the TARGET\n\t// handle (an empty same-named copy exists there post-split). Read the registry\n\t// from the source plane — reading off the target silently resolved zero trait\n\t// members, so trait-scoped webhooks never matched. Same class of bug as\n\t// the old emitSbtcOutbox sbtc_events read.\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst resolved: TraitContracts = new Map();\n\tfor (const trait of referencedTraits(chainSubs)) {\n\t\tconst ids = await resolveTraitContractIds(sourceDb, trait, asOfBlock);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\n/** Run the matcher for one block. Thin wrapper for symmetry/testability. */\nexport function evaluateBlock(\n\tblock: BlockData,\n\tsources: Record<string, SubgraphFilter>,\n\ttraitContracts: TraitContracts,\n): MatchedTx[] {\n\treturn matchSources(\n\t\tsources,\n\t\tblock.txs,\n\t\tblock.events,\n\t\ttraitContracts,\n\t\tnew Map(),\n\t\tblock.vmEvents ?? [],\n\t);\n}\n\n// ── Outbox emission ─────────────────────────────────────────────────────────\n\n// Apply-envelope shape is single-sourced as `ChainApplyEnvelope` in\n// `@secondlayer/shared` (shared with the SDK consumer); reorg emits a matching\n// `ChainReorgRollbackEnvelope`, see `handleChainReorg`.\n\n/**\n * Stable dedup identity for a chain delivery — (webhook, tx, event,\n * block_hash). A tx-level match (contract_call/deploy) has no event, so\n * `eventIndex = -1`. `block_hash` is included so a tx that survives a reorg\n * (same tx_id, NEW canonical block) re-delivers an `apply` after its rollback,\n * instead of being suppressed forever; re-processing the SAME canonical block is\n * still idempotent (same hash → same key).\n */\nfunction chainDedupKey(\n\twebhookId: string,\n\ttxId: string,\n\teventIndex: number,\n\tblockHash: string,\n\treplayId?: string,\n\tclock: DeliveryClock = \"classic\",\n): string {\n\t// vm rows are keyed by ordinal — a second clock. Namespace them so\n\t// a print at event_index N and a map_set at ordinal N in the same\n\t// tx are two deliveries, not one suppressed by the dedup constraint.\n\t// Classic keys are byte-identical to before (existing rows stay idempotent).\n\tconst ordinal = clock === \"vm\" ? `vm:${eventIndex}` : `${eventIndex}`;\n\tconst base = `chain:${webhookId}:${txId}:${ordinal}:${blockHash}`;\n\t// Replay keys are namespaced so a re-delivery doesn't collide with the\n\t// already-emitted live apply row (whose outbox entry may be long gone), while\n\t// re-running the SAME replay range stays idempotent (same replayId → same key).\n\treturn replayId ? `replay:${replayId}:${base}` : base;\n}\n\n/** Which ordinal `event_index` carries: classic `events.event_index` or the\n * opt-in `vm_events.ordinal`. Never mixed. */\ntype DeliveryClock = \"classic\" | \"vm\";\n\nconst VM_TRIGGER_TYPES = new Set<string>([\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n]);\n\nfunction clockFor(triggerType: string): DeliveryClock {\n\treturn VM_TRIGGER_TYPES.has(triggerType) ? \"vm\" : \"classic\";\n}\n\nfunction applyRow(\n\tmeta: TriggerKeyMeta,\n\tblockHeight: number,\n\tblockHash: string,\n\ttxId: string,\n\teventIndex: number,\n\tevent: Record<string, unknown>,\n\treplayId?: string,\n\tblockTime?: Date,\n): InsertWebhookOutbox {\n\tconst clock = clockFor(meta.triggerType);\n\tconst payload: ChainApplyEnvelope = {\n\t\taction: \"apply\",\n\t\tblock_hash: blockHash,\n\t\tblock_height: blockHeight,\n\t\tblock_time: blockTime ? blockTime.toISOString() : null,\n\t\ttx_id: txId,\n\t\tcanonical: true,\n\t\ttrigger: meta.triggerType,\n\t\tevent,\n\t};\n\treturn {\n\t\twebhook_id: meta.webhookId,\n\t\tkind: \"chain\",\n\t\tsubgraph_name: null,\n\t\ttable_name: null,\n\t\tblock_height: blockHeight,\n\t\ttx_id: txId,\n\t\trow_pk:\n\t\t\tclock === \"vm\"\n\t\t\t\t? { tx_id: txId, event_index: eventIndex, clock }\n\t\t\t\t: { tx_id: txId, event_index: eventIndex },\n\t\tevent_type: `chain.${meta.triggerType}.apply`,\n\t\tpayload,\n\t\tdedup_key: chainDedupKey(\n\t\t\tmeta.webhookId,\n\t\t\ttxId,\n\t\t\teventIndex,\n\t\t\tblockHash,\n\t\t\treplayId,\n\t\t\tclock,\n\t\t),\n\t\t...(replayId ? { is_replay: true } : {}),\n\t\t...(blockTime ? { block_time: blockTime } : {}),\n\t};\n}\n\n/**\n * Turn one block's matches into `webhook_outbox` rows (apply envelope). For\n * tx-level triggers (contract_call/deploy) we emit ONE row per matched tx\n * (`event_index = -1`); for event-level triggers, one row per matched event.\n * The `(webhook_id, dedup_key)` unique constraint makes re-processing a\n * block idempotent, so the emitter never double-delivers. Returns rows written.\n */\nexport async function emitChainOutbox(\n\tdb: Kysely<Database>,\n\tmatches: MatchedTx[],\n\tkeyMeta: Map<string, TriggerKeyMeta>,\n\tblockHeight: number,\n\tblockHash: string,\n\tblockTime?: Date,\n\topts?: { replayId?: string },\n): Promise<number> {\n\tconst replayId = opts?.replayId;\n\tconst rows: InsertWebhookOutbox[] = [];\n\tfor (const match of matches) {\n\t\tconst meta = keyMeta.get(match.sourceName);\n\t\tif (!meta) continue;\n\t\tconst txId = match.tx.tx_id;\n\t\tif (TX_LEVEL_TRIGGER_TYPES.has(meta.triggerType)) {\n\t\t\trows.push(\n\t\t\t\tapplyRow(\n\t\t\t\t\tmeta,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\tblockHash,\n\t\t\t\t\ttxId,\n\t\t\t\t\t-1,\n\t\t\t\t\t{\n\t\t\t\t\t\ttx_id: txId,\n\t\t\t\t\t\ttype: match.tx.type,\n\t\t\t\t\t\tsender: match.tx.sender,\n\t\t\t\t\t\tstatus: match.tx.status,\n\t\t\t\t\t\tcontract_id: match.tx.contract_id ?? null,\n\t\t\t\t\t\tfunction_name: match.tx.function_name ?? null,\n\t\t\t\t\t\tfunction_args: match.tx.function_args ?? null,\n\t\t\t\t\t\tresult_hex: match.tx.raw_result ?? null,\n\t\t\t\t\t},\n\t\t\t\t\treplayId,\n\t\t\t\t\tblockTime,\n\t\t\t\t),\n\t\t\t);\n\t\t} else {\n\t\t\tfor (const event of match.events) {\n\t\t\t\trows.push(\n\t\t\t\t\tapplyRow(\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\tblockHash,\n\t\t\t\t\t\ttxId,\n\t\t\t\t\t\tevent.event_index,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttx_id: txId,\n\t\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\t\tevent_index: event.event_index,\n\t\t\t\t\t\t\tdata: event.data,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t\tblockTime,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tif (rows.length === 0) return 0;\n\t// Net-inserted (not built) so callers count genuinely new deliveries — a\n\t// re-processed block or a re-run replay returns 0.\n\tconst result = await db\n\t\t.insertInto(\"webhook_outbox\")\n\t\t.values(rows)\n\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t.executeTakeFirst();\n\treturn Number(result.numInsertedOrUpdatedRows ?? 0);\n}\n\n// ── sBTC event matching ──────────────────────────────────────────────────────\n\ntype SbtcRow = Selectable<SbtcEventsTable>;\n\nasync function loadSbtcEventsForBlock(\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\ttopics: SbtcEventTopic[],\n): Promise<SbtcRow[]> {\n\tif (topics.length === 0) return [];\n\treturn db\n\t\t.selectFrom(\"sbtc_events\")\n\t\t.selectAll()\n\t\t.where(\"block_height\", \"=\", blockHeight)\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.where(\"topic\", \"in\", topics)\n\t\t.execute();\n}\n\nfunction toAmountBigInt(v: string | number | undefined): bigint | undefined {\n\treturn v === undefined ? undefined : BigInt(v);\n}\n\nfunction matchSbtcTrigger(trigger: ChainTrigger, row: SbtcRow): boolean {\n\tconst expectedTopic = SBTC_TRIGGER_TO_TOPIC[trigger.type];\n\tif (!expectedTopic || row.topic !== expectedTopic) return false;\n\n\tif (trigger.type === \"sbtc_deposit\") {\n\t\tif (trigger.sender && row.sender !== trigger.sender) return false;\n\t\tif (trigger.bitcoinTxid && row.bitcoin_txid !== trigger.bitcoinTxid)\n\t\t\treturn false;\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tconst min = toAmountBigInt(trigger.minAmount);\n\t\tconst max = toAmountBigInt(trigger.maxAmount);\n\t\tif (min !== undefined || max !== undefined) {\n\t\t\tif (row.amount === null) return false;\n\t\t\tconst amt = BigInt(row.amount);\n\t\t\tif (min !== undefined && amt < min) return false;\n\t\t\tif (max !== undefined && amt > max) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_create\") {\n\t\tif (trigger.sender && row.sender !== trigger.sender) return false;\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tconst min = toAmountBigInt(trigger.minAmount);\n\t\tconst max = toAmountBigInt(trigger.maxAmount);\n\t\tif (min !== undefined || max !== undefined) {\n\t\t\tif (row.amount === null) return false;\n\t\t\tconst amt = BigInt(row.amount);\n\t\t\tif (min !== undefined && amt < min) return false;\n\t\t\tif (max !== undefined && amt > max) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_accept\") {\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tif (trigger.sweepTxid && row.sweep_txid !== trigger.sweepTxid) return false;\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_reject\") {\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction buildSbtcEventPayload(\n\ttriggerType: ChainTrigger[\"type\"],\n\trow: SbtcRow,\n): SbtcDepositEvent | SbtcWithdrawalEvent {\n\tif (triggerType === \"sbtc_deposit\") {\n\t\treturn {\n\t\t\ttopic: \"completed-deposit\",\n\t\t\trequest_id: row.request_id ?? 0,\n\t\t\tsender: row.sender,\n\t\t\tamount: row.amount ?? \"0\",\n\t\t\tbitcoin_txid: row.bitcoin_txid,\n\t\t\tblock_height: row.block_height,\n\t\t\ttx_id: row.tx_id,\n\t\t} satisfies SbtcDepositEvent;\n\t}\n\treturn {\n\t\ttopic: row.topic as\n\t\t\t| \"withdrawal-create\"\n\t\t\t| \"withdrawal-accept\"\n\t\t\t| \"withdrawal-reject\",\n\t\trequest_id: row.request_id ?? 0,\n\t\tsender: row.sender,\n\t\tamount: row.amount,\n\t\tsweep_txid: row.sweep_txid,\n\t\tsettlement_confirmed: false,\n\t\tblock_height: row.block_height,\n\t\ttx_id: row.tx_id,\n\t} satisfies SbtcWithdrawalEvent;\n}\n\n/**\n * Match active sBTC chain webhooks against `sbtc_events` for one block\n * and write apply-envelope rows to `webhook_outbox`. Runs alongside\n * `emitChainOutbox` (which handles decoded_events). Same dedup-key scheme —\n * re-processing the same block is idempotent.\n */\nexport async function emitSbtcOutbox(\n\tdb: Kysely<Database>,\n\tchainSubs: Webhook[],\n\tblockHeight: number,\n\tblockHash: string,\n\tblockTime?: Date,\n\topts?: { replayId?: string; sourceDb?: Kysely<Database> },\n): Promise<number> {\n\tconst sbtcSubs = chainSubs.filter((sub) =>\n\t\ttriggersOf(sub).some((t) => isSbtcTriggerType(t.type)),\n\t);\n\tif (sbtcSubs.length === 0) return 0;\n\n\tconst neededTopics = new Set<SbtcEventTopic>();\n\tfor (const sub of sbtcSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\tconst topic = SBTC_TRIGGER_TO_TOPIC[trigger.type];\n\t\t\tif (topic) neededTopics.add(topic);\n\t\t}\n\t}\n\n\t// `sbtc_events` is a SOURCE-plane table; the evaluator runs on the TARGET\n\t// handle (where an empty same-named table exists post-split). Read the decoded\n\t// rows from the source plane explicitly — reading off `db` here silently\n\t// matched zero rows under the live split, so sBTC webhooks never fired.\n\tconst sbtcRows = await loadSbtcEventsForBlock(\n\t\topts?.sourceDb ?? getSourceDb(),\n\t\tblockHeight,\n\t\t[...neededTopics],\n\t);\n\tif (sbtcRows.length === 0) return 0;\n\n\tconst replayId = opts?.replayId;\n\tconst outboxRows: InsertWebhookOutbox[] = [];\n\n\tfor (const sub of sbtcSubs) {\n\t\ttriggersOf(sub).forEach((trigger, triggerIndex) => {\n\t\t\tif (!isSbtcTriggerType(trigger.type)) return;\n\t\t\tconst meta: TriggerKeyMeta = {\n\t\t\t\twebhookId: sub.id,\n\t\t\t\ttriggerIndex,\n\t\t\t\ttriggerType: trigger.type,\n\t\t\t};\n\t\t\tfor (const row of sbtcRows) {\n\t\t\t\tif (!matchSbtcTrigger(trigger, row)) continue;\n\t\t\t\tconst event = buildSbtcEventPayload(trigger.type, row);\n\t\t\t\toutboxRows.push(\n\t\t\t\t\tapplyRow(\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\tblockHash,\n\t\t\t\t\t\trow.tx_id,\n\t\t\t\t\t\trow.event_index,\n\t\t\t\t\t\tevent as unknown as Record<string, unknown>,\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t\tblockTime,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tif (outboxRows.length === 0) return 0;\n\tconst result = await db\n\t\t.insertInto(\"webhook_outbox\")\n\t\t.values(outboxRows)\n\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t.executeTakeFirst();\n\treturn Number(result.numInsertedOrUpdatedRows ?? 0);\n}\n\n/**\n * Emit the `sbtc_withdrawal_swept_confirmed` webhook. Unlike the per-block sBTC\n * path, this fires on a BITCOIN confirmation (async to Stacks blocks), so it\n * scans `sbtc_settlements` on its own cadence rather than per Stacks block.\n *\n * - Reads/advances a dedicated `last_settlement_scan_at` watermark on `db` (the\n * target/control plane). Null cursor → fast-forward to `now`, emit nothing\n * (forward-only, no historical backfill — mirrors the block cursor).\n * - Scans confirmed settlements with `confirmed_at > cursor` from the SOURCE\n * plane (`sbtc_settlements` is source), joined to the Stacks accept event +\n * block for the envelope anchor.\n * - Per-sub forward-only (`confirmed_at > sub.created_at`) + optional\n * requestId/sweepTxid filters; dedup on `(webhook_id, sweep_txid)` so a\n * reorg→un-confirm→re-confirm never double-fires.\n */\nexport async function emitSbtcSettlementOutbox(\n\tdb: Kysely<Database>,\n\tchainSubs: Webhook[],\n\topts?: { sourceDb?: Kysely<Database>; now?: Date },\n): Promise<number> {\n\tconst settlementSubs = chainSubs.filter((sub) =>\n\t\ttriggersOf(sub).some((t) => t.type === SETTLEMENT_TRIGGER_TYPE),\n\t);\n\tif (settlementSubs.length === 0) return 0;\n\n\tconst now = opts?.now ?? new Date();\n\tconst state = await db\n\t\t.selectFrom(\"trigger_evaluator_state\")\n\t\t.select(\"last_settlement_scan_at\")\n\t\t.where(\"id\", \"=\", true)\n\t\t.executeTakeFirst();\n\n\t// Uninitialized → fast-forward, emit nothing (forward-only).\n\tconst cursor = state?.last_settlement_scan_at ?? null;\n\tif (cursor === null) {\n\t\tawait db\n\t\t\t.updateTable(\"trigger_evaluator_state\")\n\t\t\t.set({ last_settlement_scan_at: now })\n\t\t\t.where(\"id\", \"=\", true)\n\t\t\t.execute();\n\t\treturn 0;\n\t}\n\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst rows = await sourceDb\n\t\t.selectFrom(\"sbtc_settlements as s\")\n\t\t.innerJoin(\"sbtc_events as e\", (join) =>\n\t\t\tjoin\n\t\t\t\t.onRef(\"e.sweep_txid\", \"=\", \"s.sweep_txid\")\n\t\t\t\t.on(\"e.topic\", \"=\", \"withdrawal-accept\")\n\t\t\t\t.on(\"e.canonical\", \"=\", true),\n\t\t)\n\t\t.innerJoin(\"blocks as b\", (join) =>\n\t\t\tjoin\n\t\t\t\t.onRef(\"b.height\", \"=\", \"e.block_height\")\n\t\t\t\t.on(\"b.canonical\", \"=\", true),\n\t\t)\n\t\t.where(\"s.settlement_confirmed\", \"=\", true)\n\t\t.where(\"s.confirmed_at\", \">\", cursor)\n\t\t.select([\n\t\t\t\"s.sweep_txid\",\n\t\t\t\"s.request_id\",\n\t\t\t\"s.btc_confirmations\",\n\t\t\t\"s.block_height as btc_block_height\",\n\t\t\t\"s.confirmed_at\",\n\t\t\t\"e.tx_id\",\n\t\t\t\"e.block_height as stacks_block_height\",\n\t\t\t\"e.amount\",\n\t\t\t\"e.sender\",\n\t\t\t\"b.hash as block_hash\",\n\t\t\t\"b.timestamp as block_timestamp\",\n\t\t])\n\t\t.execute();\n\n\tif (rows.length === 0) return 0;\n\n\tconst outboxRows: InsertWebhookOutbox[] = [];\n\tlet maxConfirmedAt = cursor;\n\tfor (const row of rows) {\n\t\tconst confirmedAt = row.confirmed_at;\n\t\tif (confirmedAt && confirmedAt > maxConfirmedAt)\n\t\t\tmaxConfirmedAt = confirmedAt;\n\t\tif (!confirmedAt) continue;\n\t\tfor (const sub of settlementSubs) {\n\t\t\t// Forward-only: a sub only receives settlements confirmed after it existed.\n\t\t\tif (confirmedAt <= sub.created_at) continue;\n\t\t\tconst trigger = triggersOf(sub).find(\n\t\t\t\t(t) => t.type === SETTLEMENT_TRIGGER_TYPE,\n\t\t\t);\n\t\t\tif (!trigger || trigger.type !== SETTLEMENT_TRIGGER_TYPE) continue;\n\t\t\tif (\n\t\t\t\ttrigger.requestId !== undefined &&\n\t\t\t\ttrigger.requestId !== Number(row.request_id)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttrigger.sweepTxid !== undefined &&\n\t\t\t\ttrigger.sweepTxid !== row.sweep_txid\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toutboxRows.push(settlementApplyRow(sub.id, row));\n\t\t}\n\t}\n\n\tif (outboxRows.length > 0) {\n\t\tawait db\n\t\t\t.insertInto(\"webhook_outbox\")\n\t\t\t.values(outboxRows)\n\t\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t\t.execute();\n\t}\n\n\t// Advance the watermark past every settlement scanned this pass (even ones\n\t// filtered out per-sub — they're in the past for any future subscriber).\n\tawait db\n\t\t.updateTable(\"trigger_evaluator_state\")\n\t\t.set({ last_settlement_scan_at: maxConfirmedAt })\n\t\t.where(\"id\", \"=\", true)\n\t\t.execute();\n\n\treturn outboxRows.length;\n}\n\ntype SettlementScanRow = {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: number;\n\tbtc_block_height: number | null;\n\tconfirmed_at: Date | null;\n\ttx_id: string;\n\tstacks_block_height: number;\n\tamount: string | null;\n\tsender: string | null;\n\tblock_hash: string;\n\tblock_timestamp: number;\n};\n\nfunction settlementApplyRow(\n\twebhookId: string,\n\trow: SettlementScanRow,\n): InsertWebhookOutbox {\n\tconst blockTime = blockTimeOf({ timestamp: Number(row.block_timestamp) });\n\tconst event: SbtcWithdrawalSweptConfirmedEvent = {\n\t\ttopic: \"withdrawal-swept-confirmed\",\n\t\trequest_id: Number(row.request_id),\n\t\tsweep_txid: row.sweep_txid,\n\t\tbtc_confirmations: row.btc_confirmations,\n\t\tbtc_block_height: row.btc_block_height,\n\t\tconfirmed_at: row.confirmed_at ? row.confirmed_at.toISOString() : null,\n\t\tamount: row.amount,\n\t\tsender: row.sender,\n\t};\n\tconst payload: ChainApplyEnvelope = {\n\t\taction: \"apply\",\n\t\tblock_hash: row.block_hash,\n\t\tblock_height: Number(row.stacks_block_height),\n\t\tblock_time: blockTime ? blockTime.toISOString() : null,\n\t\ttx_id: row.tx_id,\n\t\tcanonical: true,\n\t\ttrigger: SETTLEMENT_TRIGGER_TYPE,\n\t\tevent,\n\t};\n\treturn {\n\t\twebhook_id: webhookId,\n\t\tkind: \"chain\",\n\t\tsubgraph_name: null,\n\t\ttable_name: null,\n\t\tblock_height: Number(row.stacks_block_height),\n\t\ttx_id: row.tx_id,\n\t\trow_pk: { sweep_txid: row.sweep_txid },\n\t\tevent_type: `chain.${SETTLEMENT_TRIGGER_TYPE}.apply`,\n\t\tpayload,\n\t\t// Settlement fires on a Bitcoin confirmation, not a Stacks block — dedup on\n\t\t// the sweep so a reorg→un-confirm→re-confirm cycle never re-delivers.\n\t\tdedup_key: `settlement:${webhookId}:${row.sweep_txid}`,\n\t\t...(blockTime ? { block_time: blockTime } : {}),\n\t};\n}\n",
13
+ "import type {\n\tChainApplyEnvelope,\n\tSbtcDepositEvent,\n\tSbtcWithdrawalEvent,\n\tSbtcWithdrawalSweptConfirmedEvent,\n} from \"@secondlayer/shared\";\nimport type {\n\tDatabase,\n\tInsertWebhookOutbox,\n\tSbtcEventTopic,\n\tSbtcEventsTable,\n\tWebhook,\n} from \"@secondlayer/shared/db\";\nimport { getSourceDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport type { ChainTrigger } from \"@secondlayer/shared/schemas/webhooks\";\nimport type { Kysely, Selectable } from \"kysely\";\nimport type { SubgraphFilter } from \"../types.ts\";\nimport type { BlockData } from \"./batch-loader.ts\";\nimport { indexEventTypesForFilterTypes } from \"./block-source.ts\";\nimport { decoderNamesForIndexEventTypes } from \"./decoder-bound.ts\";\nimport {\n\ttype MatchedTx,\n\ttype TraitContracts,\n\tmatchSources,\n} from \"./source-matcher.ts\";\n\n/** Trigger types that match a whole transaction (not an individual event). */\nconst TX_LEVEL_TRIGGER_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\n\n/**\n * `BlockData.block.timestamp` → the `webhook_outbox.block_time` the emitters\n * below stamp on a row. Unix seconds on every real block source\n * (`PostgresBlockSource` reads it off `blocks`; `PublicApiBlockSource`\n * reconstructs it from the Index API's `block_time`). Undefined/NaN/non-\n * positive (a test's minimal block fixture, or the 0-timestamp bulk-import\n * artifact `decode/health.ts` also guards against) means \"unknown\" — leave\n * `block_time` null rather than writing an Invalid Date or a 1970 sentinel.\n */\nexport function blockTimeOf(block: { timestamp: number }): Date | undefined {\n\treturn Number.isFinite(block.timestamp) && block.timestamp > 0\n\t\t? new Date(block.timestamp * 1000)\n\t\t: undefined;\n}\n\n/** Fired on a Bitcoin confirmation, async to Stacks blocks — handled by the\n * scan-based `emitSbtcSettlementOutbox`, NOT the per-block path. Listed in\n * SBTC_TRIGGER_TYPES so the per-block matcher skips it, but deliberately absent\n * from SBTC_TRIGGER_TO_TOPIC (it has no `sbtc_events` topic). */\nconst SETTLEMENT_TRIGGER_TYPE = \"sbtc_withdrawal_swept_confirmed\";\n\n/**\n * sBTC trigger types — matched via the `sbtc_events` table, NOT via\n * `decoded_events`. Excluded from the chain-event sources map so the\n * `matchSources` engine never sees them; `emitSbtcOutbox` handles them\n * with a dedicated query + match loop.\n */\nconst SBTC_TRIGGER_TYPES = new Set([\n\t\"sbtc_deposit\",\n\t\"sbtc_withdrawal_create\",\n\t\"sbtc_withdrawal_accept\",\n\t\"sbtc_withdrawal_reject\",\n\tSETTLEMENT_TRIGGER_TYPE,\n]);\n\nfunction isSbtcTriggerType(type: string): boolean {\n\treturn SBTC_TRIGGER_TYPES.has(type);\n}\n\nconst SBTC_TRIGGER_TO_TOPIC: Record<string, SbtcEventTopic> = {\n\tsbtc_deposit: \"completed-deposit\",\n\tsbtc_withdrawal_create: \"withdrawal-create\",\n\tsbtc_withdrawal_accept: \"withdrawal-accept\",\n\tsbtc_withdrawal_reject: \"withdrawal-reject\",\n};\n\n/**\n * Pure matching core for direct chain-level webhooks. A single evaluator\n * loop serves ALL chain webhooks: it reads canonical blocks off the public\n * Index/Streams clock (via `PublicApiBlockSource`), runs the same\n * `matchSources` engine the subgraph runtime uses, and routes matches back to\n * the originating webhook. Everything here is pure/sync (DB only for trait\n * resolution) so it's trivially testable.\n *\n * Source keys are `\"{webhookId}#{triggerIndex}\"` — `matchSources` echoes\n * the key as `MatchedTx.sourceName`, letting the emitter recover which\n * webhook (and which trigger) matched. `keyMeta` carries the readable\n * trigger type for the outbox `event_type` / payload.\n */\n\nexport interface TriggerKeyMeta {\n\twebhookId: string;\n\ttriggerIndex: number;\n\ttriggerType: ChainTrigger[\"type\"];\n}\n\nexport interface ChainSourcesMap {\n\tsources: Record<string, SubgraphFilter>;\n\tkeyMeta: Map<string, TriggerKeyMeta>;\n}\n\nfunction sourceKey(webhookId: string, triggerIndex: number): string {\n\treturn `${webhookId}#${triggerIndex}`;\n}\n\nfunction toAmount(v: string | number | undefined): bigint | undefined {\n\treturn v === undefined ? undefined : BigInt(v);\n}\n\n/**\n * Convert a stored `ChainTrigger` (JSON; amounts as string/number) to the\n * runtime `SubgraphFilter` the matcher expects (amounts as bigint). Field names\n * are identical across the two shapes, so this is a copy plus amount coercion.\n */\nexport function chainTriggerToFilter(trigger: ChainTrigger): SubgraphFilter {\n\tconst t = trigger as ChainTrigger & {\n\t\tminAmount?: string | number;\n\t\tmaxAmount?: string | number;\n\t};\n\t// Spread copies all set keys; amounts (string|number) are then overwritten\n\t// with bigint where present. An absent optional amount isn't in the spread,\n\t// so there's nothing to strip.\n\tconst filter = { ...trigger } as Record<string, unknown>;\n\tconst minAmount = toAmount(t.minAmount);\n\tconst maxAmount = toAmount(t.maxAmount);\n\tif (minAmount !== undefined) filter.minAmount = minAmount;\n\tif (maxAmount !== undefined) filter.maxAmount = maxAmount;\n\treturn filter as unknown as SubgraphFilter;\n}\n\nfunction triggersOf(sub: Webhook): ChainTrigger[] {\n\treturn (sub.triggers ?? []) as ChainTrigger[];\n}\n\n/** Build the `matchSources` input from every active chain webhook. */\nexport function buildSourcesMap(chainSubs: Webhook[]): ChainSourcesMap {\n\tconst sources: Record<string, SubgraphFilter> = {};\n\tconst keyMeta = new Map<string, TriggerKeyMeta>();\n\tfor (const sub of chainSubs) {\n\t\ttriggersOf(sub).forEach((trigger, triggerIndex) => {\n\t\t\t// sBTC triggers are handled by emitSbtcOutbox — skip them here so\n\t\t\t// matchSources never tries to find sbtc_events in decoded_events.\n\t\t\tif (isSbtcTriggerType(trigger.type)) return;\n\t\t\tconst key = sourceKey(sub.id, triggerIndex);\n\t\t\tsources[key] = chainTriggerToFilter(trigger);\n\t\t\tkeyMeta.set(key, {\n\t\t\t\twebhookId: sub.id,\n\t\t\t\ttriggerIndex,\n\t\t\t\ttriggerType: trigger.type,\n\t\t\t});\n\t\t});\n\t}\n\treturn { sources, keyMeta };\n}\n\n/** The Index event types the loader must fetch to satisfy all chain triggers. */\nexport function referencedEventTypes(chainSubs: Webhook[]): string[] {\n\tconst filterTypes = new Set<string>();\n\tfor (const sub of chainSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\t// sBTC events live in sbtc_events, not in the Index event stream.\n\t\t\tif (!isSbtcTriggerType(trigger.type)) filterTypes.add(trigger.type);\n\t\t}\n\t}\n\treturn indexEventTypesForFilterTypes([...filterTypes]);\n}\n\n/** Decoder checkpoint names feeding the event types these chain subs read. */\nexport function referencedDecoderNames(chainSubs: Webhook[]): string[] {\n\treturn decoderNamesForIndexEventTypes(referencedEventTypes(chainSubs));\n}\n\n/**\n * True when some active chain webhook has a tx-level trigger\n * (contract_call/contract_deploy) — the only trigger types whose match needs\n * a REAL transaction (`function_args`, `raw_result`, etc., read in\n * `emitChainOutbox`'s TX_LEVEL branch below). Every other trigger type matches\n * off decoded events, which the block source can synthesize a minimal tx for\n * from joined event context instead of fetching every transaction in the\n * range. Mirrors `needsTransactionData` in block-source.ts for subgraphs —\n * same rule, chain-webhook triggers instead of subgraph source filters.\n */\nexport function chainSubsNeedTransactions(chainSubs: Webhook[]): boolean {\n\treturn chainSubs.some((sub) =>\n\t\ttriggersOf(sub).some((trigger) => TX_LEVEL_TRIGGER_TYPES.has(trigger.type)),\n\t);\n}\n\n/** Distinct traits referenced across all chain triggers. */\nexport function referencedTraits(chainSubs: Webhook[]): string[] {\n\tconst traits = new Set<string>();\n\tfor (const sub of chainSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\tconst trait = (trigger as { trait?: string }).trait;\n\t\t\tif (trait) traits.add(trait);\n\t\t}\n\t}\n\treturn [...traits];\n}\n\n/**\n * Resolve each referenced trait to its conforming contract-id set as of\n * `asOfBlock`, from the contract registry (`CONTRACT_REGISTRY_ENABLED` populates\n * it). Empty map when no trigger is trait-scoped → no DB work. Membership only\n * grows, so the evaluator resolves this once per batch, not per block.\n */\nexport async function buildTraitContracts(\n\tchainSubs: Webhook[],\n\tasOfBlock: number,\n\topts?: { sourceDb?: Kysely<Database> },\n): Promise<TraitContracts> {\n\t// `contracts` is a SOURCE-plane table; the evaluator/replay run on the TARGET\n\t// handle (an empty same-named copy exists there post-split). Read the registry\n\t// from the source plane — reading off the target silently resolved zero trait\n\t// members, so trait-scoped webhooks never matched. Same class of bug as\n\t// the old emitSbtcOutbox sbtc_events read.\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst resolved: TraitContracts = new Map();\n\tfor (const trait of referencedTraits(chainSubs)) {\n\t\tconst ids = await resolveTraitContractIds(sourceDb, trait, asOfBlock);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\n/** Run the matcher for one block. Thin wrapper for symmetry/testability. */\nexport function evaluateBlock(\n\tblock: BlockData,\n\tsources: Record<string, SubgraphFilter>,\n\ttraitContracts: TraitContracts,\n): MatchedTx[] {\n\treturn matchSources(\n\t\tsources,\n\t\tblock.txs,\n\t\tblock.events,\n\t\ttraitContracts,\n\t\tnew Map(),\n\t\tblock.vmEvents ?? [],\n\t);\n}\n\n// ── Outbox emission ─────────────────────────────────────────────────────────\n\n// Apply-envelope shape is single-sourced as `ChainApplyEnvelope` in\n// `@secondlayer/shared` (shared with the SDK consumer); reorg emits a matching\n// `ChainReorgRollbackEnvelope`, see `handleChainReorg`.\n\n/**\n * Stable dedup identity for a chain delivery — (webhook, tx, event,\n * block_hash). A tx-level match (contract_call/deploy) has no event, so\n * `eventIndex = -1`. `block_hash` is included so a tx that survives a reorg\n * (same tx_id, NEW canonical block) re-delivers an `apply` after its rollback,\n * instead of being suppressed forever; re-processing the SAME canonical block is\n * still idempotent (same hash → same key).\n */\nfunction chainDedupKey(\n\twebhookId: string,\n\ttxId: string,\n\teventIndex: number,\n\tblockHash: string,\n\treplayId?: string,\n\tclock: DeliveryClock = \"classic\",\n): string {\n\t// vm rows are keyed by ordinal — a second clock. Namespace them so\n\t// a print at event_index N and a map_set at ordinal N in the same\n\t// tx are two deliveries, not one suppressed by the dedup constraint.\n\t// Classic keys are byte-identical to before (existing rows stay idempotent).\n\tconst ordinal = clock === \"vm\" ? `vm:${eventIndex}` : `${eventIndex}`;\n\tconst base = `chain:${webhookId}:${txId}:${ordinal}:${blockHash}`;\n\t// Replay keys are namespaced so a re-delivery doesn't collide with the\n\t// already-emitted live apply row (whose outbox entry may be long gone), while\n\t// re-running the SAME replay range stays idempotent (same replayId → same key).\n\treturn replayId ? `replay:${replayId}:${base}` : base;\n}\n\n/** Which ordinal `event_index` carries: classic `events.event_index` or the\n * opt-in `vm_events.ordinal`. Never mixed. */\ntype DeliveryClock = \"classic\" | \"vm\";\n\nconst VM_TRIGGER_TYPES = new Set<string>([\n\t\"nested_contract_call\",\n\t\"var_set\",\n\t\"map_set\",\n\t\"map_insert\",\n\t\"map_delete\",\n]);\n\nfunction clockFor(triggerType: string): DeliveryClock {\n\treturn VM_TRIGGER_TYPES.has(triggerType) ? \"vm\" : \"classic\";\n}\n\nfunction applyRow(\n\tmeta: TriggerKeyMeta,\n\tblockHeight: number,\n\tblockHash: string,\n\ttxId: string,\n\teventIndex: number,\n\tevent: Record<string, unknown>,\n\treplayId?: string,\n\tblockTime?: Date,\n): InsertWebhookOutbox {\n\tconst clock = clockFor(meta.triggerType);\n\tconst payload: ChainApplyEnvelope = {\n\t\taction: \"apply\",\n\t\tblock_hash: blockHash,\n\t\tblock_height: blockHeight,\n\t\tblock_time: blockTime ? blockTime.toISOString() : null,\n\t\ttx_id: txId,\n\t\tcanonical: true,\n\t\ttrigger: meta.triggerType,\n\t\tevent,\n\t};\n\treturn {\n\t\twebhook_id: meta.webhookId,\n\t\tkind: \"chain\",\n\t\tblock_height: blockHeight,\n\t\ttx_id: txId,\n\t\trow_pk:\n\t\t\tclock === \"vm\"\n\t\t\t\t? { tx_id: txId, event_index: eventIndex, clock }\n\t\t\t\t: { tx_id: txId, event_index: eventIndex },\n\t\tevent_type: `chain.${meta.triggerType}.apply`,\n\t\tpayload,\n\t\tdedup_key: chainDedupKey(\n\t\t\tmeta.webhookId,\n\t\t\ttxId,\n\t\t\teventIndex,\n\t\t\tblockHash,\n\t\t\treplayId,\n\t\t\tclock,\n\t\t),\n\t\t...(replayId ? { is_replay: true } : {}),\n\t\t...(blockTime ? { block_time: blockTime } : {}),\n\t};\n}\n\n/**\n * Turn one block's matches into `webhook_outbox` rows (apply envelope). For\n * tx-level triggers (contract_call/deploy) we emit ONE row per matched tx\n * (`event_index = -1`); for event-level triggers, one row per matched event.\n * The `(webhook_id, dedup_key)` unique constraint makes re-processing a\n * block idempotent, so the emitter never double-delivers. Returns rows written.\n */\nexport async function emitChainOutbox(\n\tdb: Kysely<Database>,\n\tmatches: MatchedTx[],\n\tkeyMeta: Map<string, TriggerKeyMeta>,\n\tblockHeight: number,\n\tblockHash: string,\n\tblockTime?: Date,\n\topts?: { replayId?: string },\n): Promise<number> {\n\tconst replayId = opts?.replayId;\n\tconst rows: InsertWebhookOutbox[] = [];\n\tfor (const match of matches) {\n\t\tconst meta = keyMeta.get(match.sourceName);\n\t\tif (!meta) continue;\n\t\tconst txId = match.tx.tx_id;\n\t\tif (TX_LEVEL_TRIGGER_TYPES.has(meta.triggerType)) {\n\t\t\trows.push(\n\t\t\t\tapplyRow(\n\t\t\t\t\tmeta,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\tblockHash,\n\t\t\t\t\ttxId,\n\t\t\t\t\t-1,\n\t\t\t\t\t{\n\t\t\t\t\t\ttx_id: txId,\n\t\t\t\t\t\ttype: match.tx.type,\n\t\t\t\t\t\tsender: match.tx.sender,\n\t\t\t\t\t\tstatus: match.tx.status,\n\t\t\t\t\t\tcontract_id: match.tx.contract_id ?? null,\n\t\t\t\t\t\tfunction_name: match.tx.function_name ?? null,\n\t\t\t\t\t\tfunction_args: match.tx.function_args ?? null,\n\t\t\t\t\t\tresult_hex: match.tx.raw_result ?? null,\n\t\t\t\t\t},\n\t\t\t\t\treplayId,\n\t\t\t\t\tblockTime,\n\t\t\t\t),\n\t\t\t);\n\t\t} else {\n\t\t\tfor (const event of match.events) {\n\t\t\t\trows.push(\n\t\t\t\t\tapplyRow(\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\tblockHash,\n\t\t\t\t\t\ttxId,\n\t\t\t\t\t\tevent.event_index,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttx_id: txId,\n\t\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\t\tevent_index: event.event_index,\n\t\t\t\t\t\t\tdata: event.data,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t\tblockTime,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tif (rows.length === 0) return 0;\n\t// Net-inserted (not built) so callers count genuinely new deliveries — a\n\t// re-processed block or a re-run replay returns 0.\n\tconst result = await db\n\t\t.insertInto(\"webhook_outbox\")\n\t\t.values(rows)\n\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t.executeTakeFirst();\n\treturn Number(result.numInsertedOrUpdatedRows ?? 0);\n}\n\n// ── sBTC event matching ──────────────────────────────────────────────────────\n\ntype SbtcRow = Selectable<SbtcEventsTable>;\n\nasync function loadSbtcEventsForBlock(\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\ttopics: SbtcEventTopic[],\n): Promise<SbtcRow[]> {\n\tif (topics.length === 0) return [];\n\treturn db\n\t\t.selectFrom(\"sbtc_events\")\n\t\t.selectAll()\n\t\t.where(\"block_height\", \"=\", blockHeight)\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.where(\"topic\", \"in\", topics)\n\t\t.execute();\n}\n\nfunction toAmountBigInt(v: string | number | undefined): bigint | undefined {\n\treturn v === undefined ? undefined : BigInt(v);\n}\n\nfunction matchSbtcTrigger(trigger: ChainTrigger, row: SbtcRow): boolean {\n\tconst expectedTopic = SBTC_TRIGGER_TO_TOPIC[trigger.type];\n\tif (!expectedTopic || row.topic !== expectedTopic) return false;\n\n\tif (trigger.type === \"sbtc_deposit\") {\n\t\tif (trigger.sender && row.sender !== trigger.sender) return false;\n\t\tif (trigger.bitcoinTxid && row.bitcoin_txid !== trigger.bitcoinTxid)\n\t\t\treturn false;\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tconst min = toAmountBigInt(trigger.minAmount);\n\t\tconst max = toAmountBigInt(trigger.maxAmount);\n\t\tif (min !== undefined || max !== undefined) {\n\t\t\tif (row.amount === null) return false;\n\t\t\tconst amt = BigInt(row.amount);\n\t\t\tif (min !== undefined && amt < min) return false;\n\t\t\tif (max !== undefined && amt > max) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_create\") {\n\t\tif (trigger.sender && row.sender !== trigger.sender) return false;\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tconst min = toAmountBigInt(trigger.minAmount);\n\t\tconst max = toAmountBigInt(trigger.maxAmount);\n\t\tif (min !== undefined || max !== undefined) {\n\t\t\tif (row.amount === null) return false;\n\t\t\tconst amt = BigInt(row.amount);\n\t\t\tif (min !== undefined && amt < min) return false;\n\t\t\tif (max !== undefined && amt > max) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_accept\") {\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\tif (trigger.sweepTxid && row.sweep_txid !== trigger.sweepTxid) return false;\n\t\treturn true;\n\t}\n\n\tif (trigger.type === \"sbtc_withdrawal_reject\") {\n\t\tif (trigger.requestId !== undefined && row.request_id !== trigger.requestId)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction buildSbtcEventPayload(\n\ttriggerType: ChainTrigger[\"type\"],\n\trow: SbtcRow,\n): SbtcDepositEvent | SbtcWithdrawalEvent {\n\tif (triggerType === \"sbtc_deposit\") {\n\t\treturn {\n\t\t\ttopic: \"completed-deposit\",\n\t\t\trequest_id: row.request_id ?? 0,\n\t\t\tsender: row.sender,\n\t\t\tamount: row.amount ?? \"0\",\n\t\t\tbitcoin_txid: row.bitcoin_txid,\n\t\t\tblock_height: row.block_height,\n\t\t\ttx_id: row.tx_id,\n\t\t} satisfies SbtcDepositEvent;\n\t}\n\treturn {\n\t\ttopic: row.topic as\n\t\t\t| \"withdrawal-create\"\n\t\t\t| \"withdrawal-accept\"\n\t\t\t| \"withdrawal-reject\",\n\t\trequest_id: row.request_id ?? 0,\n\t\tsender: row.sender,\n\t\tamount: row.amount,\n\t\tsweep_txid: row.sweep_txid,\n\t\tsettlement_confirmed: false,\n\t\tblock_height: row.block_height,\n\t\ttx_id: row.tx_id,\n\t} satisfies SbtcWithdrawalEvent;\n}\n\n/**\n * Match active sBTC chain webhooks against `sbtc_events` for one block\n * and write apply-envelope rows to `webhook_outbox`. Runs alongside\n * `emitChainOutbox` (which handles decoded_events). Same dedup-key scheme —\n * re-processing the same block is idempotent.\n */\nexport async function emitSbtcOutbox(\n\tdb: Kysely<Database>,\n\tchainSubs: Webhook[],\n\tblockHeight: number,\n\tblockHash: string,\n\tblockTime?: Date,\n\topts?: { replayId?: string; sourceDb?: Kysely<Database> },\n): Promise<number> {\n\tconst sbtcSubs = chainSubs.filter((sub) =>\n\t\ttriggersOf(sub).some((t) => isSbtcTriggerType(t.type)),\n\t);\n\tif (sbtcSubs.length === 0) return 0;\n\n\tconst neededTopics = new Set<SbtcEventTopic>();\n\tfor (const sub of sbtcSubs) {\n\t\tfor (const trigger of triggersOf(sub)) {\n\t\t\tconst topic = SBTC_TRIGGER_TO_TOPIC[trigger.type];\n\t\t\tif (topic) neededTopics.add(topic);\n\t\t}\n\t}\n\n\t// `sbtc_events` is a SOURCE-plane table; the evaluator runs on the TARGET\n\t// handle (where an empty same-named table exists post-split). Read the decoded\n\t// rows from the source plane explicitly — reading off `db` here silently\n\t// matched zero rows under the live split, so sBTC webhooks never fired.\n\tconst sbtcRows = await loadSbtcEventsForBlock(\n\t\topts?.sourceDb ?? getSourceDb(),\n\t\tblockHeight,\n\t\t[...neededTopics],\n\t);\n\tif (sbtcRows.length === 0) return 0;\n\n\tconst replayId = opts?.replayId;\n\tconst outboxRows: InsertWebhookOutbox[] = [];\n\n\tfor (const sub of sbtcSubs) {\n\t\ttriggersOf(sub).forEach((trigger, triggerIndex) => {\n\t\t\tif (!isSbtcTriggerType(trigger.type)) return;\n\t\t\tconst meta: TriggerKeyMeta = {\n\t\t\t\twebhookId: sub.id,\n\t\t\t\ttriggerIndex,\n\t\t\t\ttriggerType: trigger.type,\n\t\t\t};\n\t\t\tfor (const row of sbtcRows) {\n\t\t\t\tif (!matchSbtcTrigger(trigger, row)) continue;\n\t\t\t\tconst event = buildSbtcEventPayload(trigger.type, row);\n\t\t\t\toutboxRows.push(\n\t\t\t\t\tapplyRow(\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\tblockHash,\n\t\t\t\t\t\trow.tx_id,\n\t\t\t\t\t\trow.event_index,\n\t\t\t\t\t\tevent as unknown as Record<string, unknown>,\n\t\t\t\t\t\treplayId,\n\t\t\t\t\t\tblockTime,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tif (outboxRows.length === 0) return 0;\n\tconst result = await db\n\t\t.insertInto(\"webhook_outbox\")\n\t\t.values(outboxRows)\n\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t.executeTakeFirst();\n\treturn Number(result.numInsertedOrUpdatedRows ?? 0);\n}\n\n/**\n * Emit the `sbtc_withdrawal_swept_confirmed` webhook. Unlike the per-block sBTC\n * path, this fires on a BITCOIN confirmation (async to Stacks blocks), so it\n * scans `sbtc_settlements` on its own cadence rather than per Stacks block.\n *\n * - Reads/advances a dedicated `last_settlement_scan_at` watermark on `db` (the\n * target/control plane). Null cursor → fast-forward to `now`, emit nothing\n * (forward-only, no historical backfill — mirrors the block cursor).\n * - Scans confirmed settlements with `confirmed_at > cursor` from the SOURCE\n * plane (`sbtc_settlements` is source), joined to the Stacks accept event +\n * block for the envelope anchor.\n * - Per-sub forward-only (`confirmed_at > sub.created_at`) + optional\n * requestId/sweepTxid filters; dedup on `(webhook_id, sweep_txid)` so a\n * reorg→un-confirm→re-confirm never double-fires.\n */\nexport async function emitSbtcSettlementOutbox(\n\tdb: Kysely<Database>,\n\tchainSubs: Webhook[],\n\topts?: { sourceDb?: Kysely<Database>; now?: Date },\n): Promise<number> {\n\tconst settlementSubs = chainSubs.filter((sub) =>\n\t\ttriggersOf(sub).some((t) => t.type === SETTLEMENT_TRIGGER_TYPE),\n\t);\n\tif (settlementSubs.length === 0) return 0;\n\n\tconst now = opts?.now ?? new Date();\n\tconst state = await db\n\t\t.selectFrom(\"trigger_evaluator_state\")\n\t\t.select(\"last_settlement_scan_at\")\n\t\t.where(\"id\", \"=\", true)\n\t\t.executeTakeFirst();\n\n\t// Uninitialized → fast-forward, emit nothing (forward-only).\n\tconst cursor = state?.last_settlement_scan_at ?? null;\n\tif (cursor === null) {\n\t\tawait db\n\t\t\t.updateTable(\"trigger_evaluator_state\")\n\t\t\t.set({ last_settlement_scan_at: now })\n\t\t\t.where(\"id\", \"=\", true)\n\t\t\t.execute();\n\t\treturn 0;\n\t}\n\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst rows = await sourceDb\n\t\t.selectFrom(\"sbtc_settlements as s\")\n\t\t.innerJoin(\"sbtc_events as e\", (join) =>\n\t\t\tjoin\n\t\t\t\t.onRef(\"e.sweep_txid\", \"=\", \"s.sweep_txid\")\n\t\t\t\t.on(\"e.topic\", \"=\", \"withdrawal-accept\")\n\t\t\t\t.on(\"e.canonical\", \"=\", true),\n\t\t)\n\t\t.innerJoin(\"blocks as b\", (join) =>\n\t\t\tjoin\n\t\t\t\t.onRef(\"b.height\", \"=\", \"e.block_height\")\n\t\t\t\t.on(\"b.canonical\", \"=\", true),\n\t\t)\n\t\t.where(\"s.settlement_confirmed\", \"=\", true)\n\t\t.where(\"s.confirmed_at\", \">\", cursor)\n\t\t.select([\n\t\t\t\"s.sweep_txid\",\n\t\t\t\"s.request_id\",\n\t\t\t\"s.btc_confirmations\",\n\t\t\t\"s.block_height as btc_block_height\",\n\t\t\t\"s.confirmed_at\",\n\t\t\t\"e.tx_id\",\n\t\t\t\"e.block_height as stacks_block_height\",\n\t\t\t\"e.amount\",\n\t\t\t\"e.sender\",\n\t\t\t\"b.hash as block_hash\",\n\t\t\t\"b.timestamp as block_timestamp\",\n\t\t])\n\t\t.execute();\n\n\tif (rows.length === 0) return 0;\n\n\tconst outboxRows: InsertWebhookOutbox[] = [];\n\tlet maxConfirmedAt = cursor;\n\tfor (const row of rows) {\n\t\tconst confirmedAt = row.confirmed_at;\n\t\tif (confirmedAt && confirmedAt > maxConfirmedAt)\n\t\t\tmaxConfirmedAt = confirmedAt;\n\t\tif (!confirmedAt) continue;\n\t\tfor (const sub of settlementSubs) {\n\t\t\t// Forward-only: a sub only receives settlements confirmed after it existed.\n\t\t\tif (confirmedAt <= sub.created_at) continue;\n\t\t\tconst trigger = triggersOf(sub).find(\n\t\t\t\t(t) => t.type === SETTLEMENT_TRIGGER_TYPE,\n\t\t\t);\n\t\t\tif (!trigger || trigger.type !== SETTLEMENT_TRIGGER_TYPE) continue;\n\t\t\tif (\n\t\t\t\ttrigger.requestId !== undefined &&\n\t\t\t\ttrigger.requestId !== Number(row.request_id)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttrigger.sweepTxid !== undefined &&\n\t\t\t\ttrigger.sweepTxid !== row.sweep_txid\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toutboxRows.push(settlementApplyRow(sub.id, row));\n\t\t}\n\t}\n\n\tif (outboxRows.length > 0) {\n\t\tawait db\n\t\t\t.insertInto(\"webhook_outbox\")\n\t\t\t.values(outboxRows)\n\t\t\t.onConflict((oc) => oc.columns([\"webhook_id\", \"dedup_key\"]).doNothing())\n\t\t\t.execute();\n\t}\n\n\t// Advance the watermark past every settlement scanned this pass (even ones\n\t// filtered out per-sub — they're in the past for any future subscriber).\n\tawait db\n\t\t.updateTable(\"trigger_evaluator_state\")\n\t\t.set({ last_settlement_scan_at: maxConfirmedAt })\n\t\t.where(\"id\", \"=\", true)\n\t\t.execute();\n\n\treturn outboxRows.length;\n}\n\ntype SettlementScanRow = {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: number;\n\tbtc_block_height: number | null;\n\tconfirmed_at: Date | null;\n\ttx_id: string;\n\tstacks_block_height: number;\n\tamount: string | null;\n\tsender: string | null;\n\tblock_hash: string;\n\tblock_timestamp: number;\n};\n\nfunction settlementApplyRow(\n\twebhookId: string,\n\trow: SettlementScanRow,\n): InsertWebhookOutbox {\n\tconst blockTime = blockTimeOf({ timestamp: Number(row.block_timestamp) });\n\tconst event: SbtcWithdrawalSweptConfirmedEvent = {\n\t\ttopic: \"withdrawal-swept-confirmed\",\n\t\trequest_id: Number(row.request_id),\n\t\tsweep_txid: row.sweep_txid,\n\t\tbtc_confirmations: row.btc_confirmations,\n\t\tbtc_block_height: row.btc_block_height,\n\t\tconfirmed_at: row.confirmed_at ? row.confirmed_at.toISOString() : null,\n\t\tamount: row.amount,\n\t\tsender: row.sender,\n\t};\n\tconst payload: ChainApplyEnvelope = {\n\t\taction: \"apply\",\n\t\tblock_hash: row.block_hash,\n\t\tblock_height: Number(row.stacks_block_height),\n\t\tblock_time: blockTime ? blockTime.toISOString() : null,\n\t\ttx_id: row.tx_id,\n\t\tcanonical: true,\n\t\ttrigger: SETTLEMENT_TRIGGER_TYPE,\n\t\tevent,\n\t};\n\treturn {\n\t\twebhook_id: webhookId,\n\t\tkind: \"chain\",\n\t\tblock_height: Number(row.stacks_block_height),\n\t\ttx_id: row.tx_id,\n\t\trow_pk: { sweep_txid: row.sweep_txid },\n\t\tevent_type: `chain.${SETTLEMENT_TRIGGER_TYPE}.apply`,\n\t\tpayload,\n\t\t// Settlement fires on a Bitcoin confirmation, not a Stacks block — dedup on\n\t\t// the sweep so a reorg→un-confirm→re-confirm cycle never re-delivers.\n\t\tdedup_key: `settlement:${webhookId}:${row.sweep_txid}`,\n\t\t...(blockTime ? { block_time: blockTime } : {}),\n\t};\n}\n",
15
14
  "import { committedHeight } from \"@secondlayer/shared\";\nimport { type Database, getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport {\n\tVM_INDEX_EVENT_TYPES,\n\tisStreamsIndexEligible,\n\treferencedIndexEventTypes,\n} from \"./block-source.ts\";\n\n/**\n * Decoder-progress bound for consumers that read decoded Index rows.\n *\n * Each decoded event type is produced by an independent decoder\n * (`decode.<event_type>.v1` — ADR-0008/0010). Index `getTip` tracks\n * `decode.ft_transfer.v1` (or ingestion, on the Postgres tap). A forward-only\n * cursor that processes a height before the decoder feeding a referenced type\n * has committed it misses the match and never revisits.\n *\n * Bound the tip by the MIN committed height over ONLY the decoders the\n * consumer actually reads. A stalled unreferenced decoder (idle pox4) must\n * never gate progress. A referenced decoder with no usable checkpoint stalls\n * the consumer rather than falling through to the raw tip.\n */\n\n/** ADR checkpoint name. Subgraphs does not depend on `@secondlayer/indexer`. */\nexport function decoderNameForEventType(indexEventType: string): string {\n\treturn `decode.${indexEventType}.v1`;\n}\n\nexport function decoderNamesForIndexEventTypes(eventTypes: string[]): string[] {\n\treturn eventTypes\n\t\t.filter((t) => !VM_INDEX_EVENT_TYPES.has(t))\n\t\t.map(decoderNameForEventType);\n}\n\nexport function decoderNamesForSubgraph(\n\tsubgraph: SubgraphDefinition,\n): string[] {\n\treturn decoderNamesForIndexEventTypes(referencedIndexEventTypes(subgraph));\n}\n\n/**\n * True when catch-up/reindex will load decoded Index rows (the race).\n * Postgres tap reads raw `events` at ingest and must not wait on decode.\n * Mirrors `resolveBlockSource`'s streams-index branch.\n */\nexport function usesDecodedIndexPlane(subgraph: SubgraphDefinition): boolean {\n\treturn (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tisStreamsIndexEligible(subgraph)\n\t);\n}\n\n// `committedHeight` moved to `@secondlayer/shared` (streams-cursor.ts) so the\n// Index `/public/status` route and this module share one implementation of\n// the committed-height rule. Re-exported here so existing importers of\n// `./decoder-bound.ts` are unaffected.\nexport { committedHeight };\n\nexport type DecoderBound =\n\t| { kind: \"unbounded\" }\n\t| { kind: \"stall\"; missing: string[] }\n\t| { kind: \"height\"; height: number };\n\n/**\n * True when this process reads Index over HTTP with no guarantee a local\n * decoder ever runs in the same Postgres (a hosted tenant's `webhook-service`,\n * or any instance pointed at `SUBGRAPH_INDEX_API_URL`). `decoderBoundTip` then\n * must not read local `decoder_checkpoints` — that table is empty there and\n * the evaluator stalls forever (otherwise chain webhooks never fire).\n */\nfunction usesRemoteDecoderStatus(): boolean {\n\treturn (\n\t\tprocess.env.SUBGRAPH_SOURCE === \"streams-index\" &&\n\t\tBoolean(process.env.SUBGRAPH_INDEX_API_URL)\n\t);\n}\n\n/** Inverse of `decoderNameForEventType` — decoder names in this codebase are\n * always exactly `decode.<type>.v1`, so stripping the fixed prefix/suffix is\n * a lossless round trip. Needed because the wire's `decoded_heights` map\n * (packages/api/src/index/tip.ts) is keyed by event_type (the Index API's\n * own public vocabulary), not by decoder name. */\nfunction eventTypeForDecoderName(decoderName: string): string {\n\treturn decoderName.replace(/^decode\\./, \"\").replace(/\\.v1$/, \"\");\n}\n\n/**\n * Remote-mode variant of the floor below, scoped to `decoderNames` — same\n * missing/floor semantics as local mode, sourced from `decodedHeights` (the\n * SAME tip envelope `source.getTip()` already fetched; see\n * `IndexHttpClient.getDecodedHeights()`) instead of a local DB read. No\n * network call of its own — this is pure/synchronous.\n *\n * `decodedHeights` absent entirely (an older server that doesn't send the\n * field, or called before any `getTip()`) falls back to `unbounded`: the raw\n * tip IS already the conservative cross-decoder floor (`IndexTip.block_height`\n * — see packages/api/src/index/tip.ts), so trusting it outright is the same\n * as bounding by it explicitly, just without the redundant `Math.min`.\n *\n * A referenced decoder missing from the map, or present with `null` (no\n * checkpoint yet), stalls — same fail-closed rule local mode already applies.\n * An unreferenced decoder stalling (e.g. an idle `print`) never appears in\n * `decoderNames` and so can never gate this.\n */\nfunction remoteDecoderBoundTip(\n\tdecoderNames: string[],\n\tdecodedHeights: Record<string, number | null> | undefined,\n): DecoderBound {\n\tif (!decodedHeights) return { kind: \"unbounded\" };\n\tconst missing: string[] = [];\n\tconst heights: number[] = [];\n\tfor (const decoderName of decoderNames) {\n\t\tconst height = decodedHeights[eventTypeForDecoderName(decoderName)];\n\t\tif (height === undefined || height === null) missing.push(decoderName);\n\t\telse heights.push(height);\n\t}\n\tif (missing.length > 0) return { kind: \"stall\", missing };\n\treturn { kind: \"height\", height: Math.min(...heights) };\n}\n\n/**\n * Data-availability floor for `decoderNames`. On an instance that reads Index\n * over HTTP (`SUBGRAPH_SOURCE=streams-index` + `SUBGRAPH_INDEX_API_URL`),\n * bounds by the referenced decoders' OWN committed heights from\n * `opts.remoteDecodedHeights` (the tip envelope the block source's `getTip()`\n * already fetched — no second request). A stalled UNREFERENCED decoder (e.g.\n * an idle `print`) must never gate progress — this only ever looks at\n * `decoderNames`, so it can't. Falls back to `unbounded` (trust the raw tip,\n * itself the conservative cross-decoder floor) when the caller has no\n * decoded-heights map to hand (an older server, or before any `getTip()`).\n *\n * Otherwise (local mode) reads SOURCE-plane `decoder_checkpoints` directly\n * (same rationale as trait resolution: the consumer handle is often the\n * TARGET, where those rows are empty).\n */\nexport async function decoderBoundTip(\n\tdecoderNames: string[],\n\topts?: {\n\t\tsourceDb?: Kysely<Database>;\n\t\t/** Remote mode only — see `remoteDecoderBoundTip`. */\n\t\tremoteDecodedHeights?: Record<string, number | null>;\n\t},\n): Promise<DecoderBound> {\n\tif (decoderNames.length === 0) return { kind: \"unbounded\" };\n\tif (usesRemoteDecoderStatus()) {\n\t\treturn remoteDecoderBoundTip(decoderNames, opts?.remoteDecodedHeights);\n\t}\n\tconst sourceDb = opts?.sourceDb ?? getSourceDb();\n\tconst rows = await sourceDb\n\t\t.selectFrom(\"decoder_checkpoints\")\n\t\t.select([\"decoder_name\", \"last_cursor\"])\n\t\t.where(\"decoder_name\", \"in\", decoderNames)\n\t\t.execute();\n\tconst byName = new Map(rows.map((r) => [r.decoder_name, r.last_cursor]));\n\tconst missing: string[] = [];\n\tconst heights: number[] = [];\n\tfor (const name of decoderNames) {\n\t\tconst height = committedHeight(byName.get(name));\n\t\tif (height === null) missing.push(name);\n\t\telse heights.push(height);\n\t}\n\tif (missing.length > 0) return { kind: \"stall\", missing };\n\treturn { kind: \"height\", height: Math.min(...heights) };\n}\n\nexport type BoundSourceTip =\n\t| { ok: true; tip: number; floor: number | null }\n\t| { ok: false; missing: string[] };\n\n/** Combine a raw block-source tip with the decoder floor. */\nexport async function boundSourceTip(\n\trawTip: number,\n\tdecoderNames: string[],\n\topts?: {\n\t\tsourceDb?: Kysely<Database>;\n\t\tremoteDecodedHeights?: Record<string, number | null>;\n\t},\n): Promise<BoundSourceTip> {\n\tconst bound = await decoderBoundTip(decoderNames, opts);\n\tif (bound.kind === \"stall\") return { ok: false, missing: bound.missing };\n\tif (bound.kind === \"unbounded\") {\n\t\treturn { ok: true, tip: rawTip, floor: null };\n\t}\n\treturn {\n\t\tok: true,\n\t\ttip: Math.min(rawTip, bound.height),\n\t\tfloor: bound.height,\n\t};\n}\n",
16
15
  "import type { SubgraphFilter } from \"../types.ts\";\n\nexport interface MatchedTx {\n\ttx: TxRecord;\n\tevents: EventRecord[];\n\t/** Source object key — used for handler dispatch */\n\tsourceName: string;\n}\n\nexport type TxRecord = {\n\ttx_id: string;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\t/** Position within the block — the runner sorts dispatch into chain order. */\n\ttx_index?: number;\n\tcontract_id?: string | null;\n\tfunction_name?: string | null;\n\tfunction_args?: unknown | null;\n\traw_result?: string | null;\n};\n\nexport type EventRecord = {\n\tid: string;\n\ttx_id: string;\n\ttype: string;\n\t/** Classic `event_index`, or `ordinal` when `clock === \"vm\"`. */\n\tevent_index: number;\n\tdata: unknown;\n\t/** Set on opt-in `vm_events` rows. Two clocks never sort or dedupe together. */\n\tclock?: \"vm\";\n};\n\n// ── Wildcard matching (shared with v1) ──────────────────────────────\n\nconst patternCache = new Map<string, RegExp>();\n\n/** Match a value against one pattern, or ANY pattern in a set. */\nfunction matchAny(value: string, pattern: string | readonly string[]): boolean {\n\treturn Array.isArray(pattern)\n\t\t? pattern.some((p) => matchPattern(value, p))\n\t\t: matchPattern(value, pattern as string);\n}\n\nfunction matchPattern(value: string, pattern: string): boolean {\n\tif (!pattern.includes(\"*\")) return value === pattern;\n\tlet re = patternCache.get(pattern);\n\tif (!re) {\n\t\tconst regex = pattern\n\t\t\t.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\t\t\t.replace(/\\*/g, \".*\");\n\t\tre = new RegExp(`^${regex}$`);\n\t\tpatternCache.set(pattern, re);\n\t}\n\treturn re.test(value);\n}\n\n// Trait → set of conforming contract IDs, resolved per block by the caller\n// (block-processor) from the contract registry. Kept as injected data so this\n// module stays pure/sync/DB-less.\nexport type TraitContracts = Map<string, ReadonlySet<string>>;\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n/**\n * True when a filter's optional `trait` admits this contract: no trait → always\n * allowed; trait set → the contract must be in the resolved conforming set.\n */\n/** Addresses discovered per source name (factory sets), resolved by the\n * caller as-of the block being processed. */\nexport type FactoryContracts = ReadonlyMap<string, ReadonlySet<string>>;\n\n/**\n * A factory-scoped source matches only contracts its factory has revealed.\n * Same shape as {@link traitAllows}: the set is injected, so this module\n * stays pure and sync.\n */\nfunction factoryAllows(\n\tfilter: { factory?: { from: string; field: string } },\n\tcontractId: string | undefined | null,\n\tfactoryContracts: FactoryContracts,\n): boolean {\n\tif (!filter.factory) return true;\n\tif (!contractId) return false;\n\treturn (factoryContracts.get(filter.factory.from) ?? EMPTY_SET).has(\n\t\tcontractId,\n\t);\n}\n\n/** Read a dotted path off a decoded payload (`\"data.pool\"`). */\nexport function readPath(payload: unknown, path: string): unknown {\n\tlet cur: unknown = payload;\n\tfor (const key of path.split(\".\")) {\n\t\tif (cur === null || typeof cur !== \"object\") return undefined;\n\t\tcur = (cur as Record<string, unknown>)[key];\n\t}\n\treturn cur;\n}\n\nfunction traitAllows(\n\tfilter: SubgraphFilter,\n\tcontractId: string | undefined | null,\n\ttraitContracts: TraitContracts,\n): boolean {\n\tconst trait = (filter as { trait?: string }).trait;\n\tif (!trait) return true;\n\tif (!contractId) return false;\n\treturn (traitContracts.get(trait) ?? EMPTY_SET).has(contractId);\n}\n\n/** Extract the contract id from an asset identifier (`<contract>::<token>`). */\nfunction assetContract(assetId: string | undefined): string | undefined {\n\treturn assetId?.split(\"::\")[0];\n}\n\n/**\n * Contract on a print payload. Legacy `smart_contract_event` rows use\n * `contract_identifier`; current `contract_event` rows use `contract_id`.\n * Matcher and runner must share this — a print that matches on `contract_id`\n * otherwise reaches the handler with `event.contractId === \"\"`.\n */\nexport function printContractId(\n\tdata: Record<string, unknown> | null | undefined,\n): string | undefined {\n\tif (!data) return undefined;\n\tconst id =\n\t\t(typeof data.contract_identifier === \"string\"\n\t\t\t? data.contract_identifier\n\t\t\t: undefined) ??\n\t\t(typeof data.contract_id === \"string\" ? data.contract_id : undefined);\n\treturn id || undefined;\n}\n\n// ── Per-filter-type matchers ────────────────────────────────────────\n\nfunction matchFilter(\n\tfilter: SubgraphFilter,\n\ttransactions: TxRecord[],\n\teventsByTx: Map<string, EventRecord[]>,\n\ttraitContracts: TraitContracts,\n\tfactoryContracts: FactoryContracts = new Map(),\n\tvmEventsByTx: Map<string, EventRecord[]> = new Map(),\n): { tx: TxRecord; events: EventRecord[] }[] {\n\tconst results: { tx: TxRecord; events: EventRecord[] }[] = [];\n\n\tswitch (filter.type) {\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\tcase \"stx_mint\":\n\t\tcase \"stx_burn\":\n\t\tcase \"stx_lock\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => e.type === eventType);\n\t\t\t\tif (matched.length === 0) continue;\n\n\t\t\t\t// Apply address filters\n\t\t\t\tconst filtered = matched.filter((e) => {\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"lockedAddress\" in filter && filter.lockedAddress) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!matchPattern(data.locked_address as string, filter.lockedAddress)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filters\n\t\t\t\t\tif (\"minAmount\" in filter && filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt(\n\t\t\t\t\t\t\t(data.amount ?? data.locked_amount ?? \"0\") as string,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t\"maxAmount\" in filter &&\n\t\t\t\t\t\t(filter as { maxAmount?: bigint }).maxAmount !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount > (filter as { maxAmount: bigint }).maxAmount)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: filtered });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\tcase \"ft_mint\":\n\t\tcase \"ft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\t// Asset identifier filter\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Trait scope — the asset's contract must conform.\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Address filters\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t// Amount filter\n\t\t\t\t\tif (filter.minAmount !== undefined) {\n\t\t\t\t\t\tconst amount = BigInt((data.amount ?? \"0\") as string);\n\t\t\t\t\t\tif (amount < filter.minAmount) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── NFT events ──\n\t\tcase \"nft_transfer\":\n\t\tcase \"nft_mint\":\n\t\tcase \"nft_burn\": {\n\t\t\tconst eventType = `${filter.type}_event`;\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== eventType) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\n\t\t\t\t\tif (filter.assetIdentifier) {\n\t\t\t\t\t\tconst assetId = data.asset_identifier as string | undefined;\n\t\t\t\t\t\tif (!assetId || !matchPattern(assetId, filter.assetIdentifier))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t!traitAllows(\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\tassetContract(data.asset_identifier as string | undefined),\n\t\t\t\t\t\t\ttraitContracts,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (\"sender\" in filter && filter.sender) {\n\t\t\t\t\t\tif (!matchPattern(data.sender as string, filter.sender))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"recipient\" in filter && filter.recipient) {\n\t\t\t\t\t\tif (!matchPattern(data.recipient as string, filter.recipient))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract call ──\n\t\tcase \"contract_call\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"contract_call\") continue;\n\n\t\t\t\t// Contract filter\n\t\t\t\tif (filter.contractId) {\n\t\t\t\t\tif (!tx.contract_id || !matchAny(tx.contract_id, filter.contractId))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Factory scope: only contracts this source's factory revealed.\n\t\t\t\tif (!factoryAllows(filter, tx.contract_id, factoryContracts)) continue;\n\t\t\t\t// Function filter\n\t\t\t\tif (filter.functionName) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!tx.function_name ||\n\t\t\t\t\t\t!matchPattern(tx.function_name, filter.functionName)\n\t\t\t\t\t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Caller filter\n\t\t\t\tif (filter.caller) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.caller)) continue;\n\t\t\t\t}\n\t\t\t\t// Trait scope — the called contract must conform.\n\t\t\t\tif (!traitAllows(filter, tx.contract_id, traitContracts)) continue;\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tif (tx.type !== \"smart_contract\") continue;\n\n\t\t\t\tif (filter.deployer) {\n\t\t\t\t\tif (!matchPattern(tx.sender, filter.deployer)) continue;\n\t\t\t\t}\n\t\t\t\tif (filter.contractName) {\n\t\t\t\t\tconst name = tx.contract_id?.split(\".\")[1] ?? \"\";\n\t\t\t\t\tif (!matchPattern(name, filter.contractName)) continue;\n\t\t\t\t}\n\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tresults.push({ tx, events: txEvents });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase \"nested_contract_call\":\n\t\tcase \"var_set\":\n\t\tcase \"map_set\":\n\t\tcase \"map_insert\":\n\t\tcase \"map_delete\": {\n\t\t\t// vm sources read the vm clock only. A classic tx-level source never\n\t\t\t// sees these rows, and a vm source never sees `events[]`.\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = vmEventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== filter.type) return false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tconst contractId = printContractId(data);\n\t\t\t\t\tif (\"contractId\" in filter && filter.contractId) {\n\t\t\t\t\t\tif (!contractId || !matchAny(contractId, filter.contractId))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!traitAllows(filter, contractId, traitContracts)) return false;\n\t\t\t\t\tif (!factoryAllows(filter, contractId, factoryContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (filter.type === \"nested_contract_call\") {\n\t\t\t\t\t\tif (filter.functionName) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.function_name !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.function_name, filter.functionName)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (filter.caller) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.caller !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.caller, filter.caller)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (filter.sender) {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof data.sender !== \"string\" ||\n\t\t\t\t\t\t\t\t!matchPattern(data.sender, filter.sender)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (filter.type === \"var_set\" && filter.varName) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof data.var_name !== \"string\" ||\n\t\t\t\t\t\t\t!matchPattern(data.var_name, filter.varName)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t(filter.type === \"map_set\" ||\n\t\t\t\t\t\t\tfilter.type === \"map_insert\" ||\n\t\t\t\t\t\t\tfilter.type === \"map_delete\") &&\n\t\t\t\t\t\tfilter.map\n\t\t\t\t\t) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof data.map_name !== \"string\" ||\n\t\t\t\t\t\t\t!matchPattern(data.map_name, filter.map)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\tif (matched.length > 0) results.push({ tx, events: matched });\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\tfor (const tx of transactions) {\n\t\t\t\tconst txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\t\t\t\tconst matched = txEvents.filter((e) => {\n\t\t\t\t\tif (e.type !== \"smart_contract_event\" && e.type !== \"contract_event\")\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tconst data = e.data as Record<string, unknown> | null;\n\t\t\t\t\tif (!data) return false;\n\t\t\t\t\tif (data.topic !== \"print\") return false;\n\n\t\t\t\t\tconst contractId = printContractId(data);\n\t\t\t\t\tif (filter.contractId) {\n\t\t\t\t\t\tif (!contractId || !matchAny(contractId, filter.contractId))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (!traitAllows(filter, contractId, traitContracts)) return false;\n\t\t\t\t\tif (!factoryAllows(filter, contractId, factoryContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t// Topic filter — check the decoded Clarity value's topic field\n\t\t\t\t\t// At this stage data.value is still raw hex; topic filtering happens\n\t\t\t\t\t// after decode in the runner. For now, skip topic filtering here.\n\t\t\t\t\t// The runner will filter by topic after decoding.\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\tif (matched.length > 0) {\n\t\t\t\t\tresults.push({ tx, events: matched });\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn results;\n}\n\n/**\n * Match named filters against a block's transactions and events.\n * Returns matches with sourceName = the object key from sources.\n */\nexport function matchSources(\n\tsources: Record<string, SubgraphFilter>,\n\ttransactions: TxRecord[],\n\tevents: EventRecord[],\n\ttraitContracts: TraitContracts = new Map(),\n\tfactoryContracts: FactoryContracts = new Map(),\n\t/** Opt-in `vm_events` rows (second clock). Only vm-typed sources read them. */\n\tvmEvents: EventRecord[] = [],\n): MatchedTx[] {\n\t// Index events by txId — one map per clock.\n\tconst eventsByTx = new Map<string, EventRecord[]>();\n\tfor (const event of events) {\n\t\tconst list = eventsByTx.get(event.tx_id) ?? [];\n\t\tlist.push(event);\n\t\teventsByTx.set(event.tx_id, list);\n\t}\n\tconst vmEventsByTx = new Map<string, EventRecord[]>();\n\tfor (const event of vmEvents) {\n\t\tconst list = vmEventsByTx.get(event.tx_id) ?? [];\n\t\tlist.push(event);\n\t\tvmEventsByTx.set(event.tx_id, list);\n\t}\n\n\tconst seen = new Set<string>();\n\tconst results: MatchedTx[] = [];\n\n\tfor (const [sourceName, filter] of Object.entries(sources)) {\n\t\tconst matches = matchFilter(\n\t\t\tfilter,\n\t\t\ttransactions,\n\t\t\teventsByTx,\n\t\t\ttraitContracts,\n\t\t\tfactoryContracts,\n\t\t\tvmEventsByTx,\n\t\t);\n\t\tfor (const match of matches) {\n\t\t\tconst dedupeKey = `${match.tx.tx_id}:${sourceName}`;\n\t\t\tif (!seen.has(dedupeKey)) {\n\t\t\t\tseen.add(dedupeKey);\n\t\t\t\tresults.push({ ...match, sourceName });\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results;\n}\n"
17
16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