@secondlayer/subgraphs 3.22.0 → 3.23.1

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.
Files changed (36) hide show
  1. package/dist/src/index.d.ts +118 -9
  2. package/dist/src/index.js +159 -14
  3. package/dist/src/index.js.map +7 -6
  4. package/dist/src/runtime/block-processor.d.ts +43 -2
  5. package/dist/src/runtime/block-processor.js +155 -12
  6. package/dist/src/runtime/block-processor.js.map +7 -6
  7. package/dist/src/runtime/catchup.d.ts +43 -2
  8. package/dist/src/runtime/catchup.js +155 -12
  9. package/dist/src/runtime/catchup.js.map +7 -6
  10. package/dist/src/runtime/context.d.ts +77 -3
  11. package/dist/src/runtime/context.js +142 -1
  12. package/dist/src/runtime/context.js.map +6 -5
  13. package/dist/src/runtime/processor.js +159 -16
  14. package/dist/src/runtime/processor.js.map +7 -6
  15. package/dist/src/runtime/reindex.d.ts +43 -2
  16. package/dist/src/runtime/reindex.js +155 -12
  17. package/dist/src/runtime/reindex.js.map +7 -6
  18. package/dist/src/runtime/reorg.d.ts +43 -2
  19. package/dist/src/runtime/reorg.js +155 -12
  20. package/dist/src/runtime/reorg.js.map +7 -6
  21. package/dist/src/runtime/replay.d.ts +3 -3
  22. package/dist/src/runtime/replay.js +2 -1
  23. package/dist/src/runtime/replay.js.map +3 -3
  24. package/dist/src/runtime/runner.d.ts +102 -5
  25. package/dist/src/runtime/source-matcher.d.ts +2 -2
  26. package/dist/src/runtime/stats.d.ts +3 -3
  27. package/dist/src/schema/index.d.ts +46 -5
  28. package/dist/src/service.js +159 -16
  29. package/dist/src/service.js.map +7 -6
  30. package/dist/src/testing/index.d.ts +52 -5
  31. package/dist/src/testing/index.js +172 -6
  32. package/dist/src/testing/index.js.map +6 -5
  33. package/dist/src/triggers/index.d.ts +2 -2
  34. package/dist/src/types.d.ts +43 -2
  35. package/dist/src/validate.d.ts +43 -2
  36. package/package.json +6 -4
@@ -1,25 +1,26 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/runtime/context.ts", "../src/schema/generator.ts", "../src/schema/utils.ts", "../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/print-validate.ts", "../src/runtime/source-matcher.ts", "../src/runtime/block-processor.ts", "../src/runtime/block-source.ts", "../src/runtime/batch-loader.ts", "../src/runtime/reconstruct.ts", "../src/runtime/outbox-emit.ts", "../src/runtime/subscription-state.ts", "../src/runtime/emitter-matcher.ts", "../src/runtime/stats.ts", "../src/runtime/catchup.ts"],
3
+ "sources": ["../src/runtime/context.ts", "../src/schema/generator.ts", "../src/schema/utils.ts", "../src/runtime/chain-read.ts", "../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/print-validate.ts", "../src/runtime/source-matcher.ts", "../src/runtime/block-processor.ts", "../src/runtime/block-source.ts", "../src/runtime/batch-loader.ts", "../src/runtime/reconstruct.ts", "../src/runtime/outbox-emit.ts", "../src/runtime/subscription-state.ts", "../src/runtime/emitter-matcher.ts", "../src/runtime/stats.ts", "../src/runtime/catchup.ts"],
4
4
  "sourcesContent": [
5
- "import type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { formatUnits } from \"@secondlayer/stacks/utils\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { TYPE_MAP, emitJournalDDL } from \"../schema/generator.ts\";\nimport type { ComputedValue, SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\n/** Reorg journal entries older than this many blocks are prunable — far past\n * Stacks finality (observed reorg depth is single digits). */\nexport const JOURNAL_RETENTION_BLOCKS = 300;\n\n/** Schemas whose `_journal` table existence has been ensured this process.\n * Populated only after a successful flush (a rolled-back CREATE must retry). */\nconst journalEnsured = new Set<string>();\n\ninterface WriteOp {\n\tkind: \"insert\" | \"update\" | \"delete\" | \"increment\";\n\ttable: string;\n\tdata: Record<string, unknown>;\n\t/** For update: SET clause. For increment: column → signed delta. */\n\tset?: Record<string, unknown>;\n}\n\nexport interface FlushWrite {\n\top: \"insert\" | \"update\" | \"delete\";\n\ttable: string;\n\t/** Full row data (for inserts) or where+set merged (for updates). Bigints stringified. */\n\trow: Record<string, unknown>;\n\t/** Stable identifier for dedup — `{blockHeight, txId, rowIndex}` */\n\tpk: { blockHeight: number; txId: string; rowIndex: number };\n}\n\nexport interface FlushManifest {\n\tcount: number;\n\twrites: FlushWrite[];\n}\n\nexport interface BlockMeta {\n\theight: number;\n\thash: string;\n\ttimestamp: number;\n\tburnBlockHeight: number;\n}\n\nexport interface TxMeta {\n\ttxId: string;\n\tsender: string;\n\ttype: string;\n\tstatus: string;\n\tcontractId?: string | null;\n\tfunctionName?: string | null;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n\tif (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n\t\tthrow new Error(`Invalid column name: ${name}`);\n\t}\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n *\n * Row reads (findOne/findMany) are read-your-writes: they overlay the pending\n * ops queue on the DB state, so a handler observes every write queued earlier\n * in the same block. Without this, accumulator patterns (balance = f(existing))\n * silently lose all but the last same-block delta per row (fix-f040 B1).\n * Aggregate reads (count/sum/min/max) remain pre-flush DB state.\n */\nexport class SubgraphContext {\n\treadonly block: BlockMeta;\n\tprivate _tx: TxMeta;\n\tprivate readonly db: AnyDb;\n\tprivate readonly pgSchemaName: string;\n\tprivate readonly subgraphSchema: SubgraphSchema;\n\t/** Pending writes for this block. `protected` so the in-memory test\n\t * context (`@secondlayer/subgraphs/testing`) can materialize them through\n\t * the SAME overlay this class uses — never a second implementation. */\n\tprotected readonly ops: WriteOp[] = [];\n\t/**\n\t * BYO data plane: handler writes land in a user-owned DB whose flush can't\n\t * share the managed block transaction, so a crash replays the block. When\n\t * set, flush() prepends a replace-per-height DELETE for every inserted table\n\t * (`_block_height = N` → re-INSERT), making block reprocessing idempotent.\n\t * Non-idempotent `update` handlers are rejected at deploy, not here.\n\t */\n\tprivate readonly byo: boolean;\n\t/**\n\t * Record pre-images of keyed mutations into the schema's `_journal` so a\n\t * reorg can restore prior row states (fix-f040 B2). Enabled on the live\n\t * path only — deep reindex/backfill heights are past finality, and the\n\t * journal would just be churn the pruner deletes.\n\t */\n\tprivate readonly journal: boolean;\n\n\tconstructor(\n\t\tdb: AnyDb,\n\t\tpgSchemaName: string,\n\t\tsubgraphSchema: SubgraphSchema,\n\t\tblock: BlockMeta,\n\t\ttx: TxMeta,\n\t\tbyo = false,\n\t\tjournal = false,\n\t) {\n\t\tthis.db = db;\n\t\tthis.pgSchemaName = pgSchemaName;\n\t\tthis.subgraphSchema = subgraphSchema;\n\t\tthis.block = block;\n\t\tthis._tx = tx;\n\t\tthis.byo = byo;\n\t\tthis.journal = journal;\n\t}\n\n\tget tx(): TxMeta {\n\t\treturn this._tx;\n\t}\n\n\t/** Update the current transaction context (used by runner between events) */\n\tsetTx(tx: TxMeta): void {\n\t\tthis._tx = tx;\n\t}\n\n\t// --- Write operations (batched) ---\n\n\tinsert(table: string, row: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({\n\t\t\tkind: \"insert\",\n\t\t\ttable,\n\t\t\tdata: { ...row, _block_height: this.block.height, _tx_id: this._tx.txId },\n\t\t});\n\t}\n\n\tupdate(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"update\", table, data: where, set });\n\t}\n\n\tupsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return;\n\t\tconst keyColumns = Object.keys(key);\n\n\t\t// Check if there's a matching uniqueKeys constraint\n\t\tconst hasUniqueConstraint = tableDef.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\n\t\tconst meta = { _block_height: this.block.height, _tx_id: this._tx.txId };\n\n\t\tif (hasUniqueConstraint) {\n\t\t\t// Use ON CONFLICT for proper upsert\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: { ...key, ...row, ...meta, _upsert_keys: keyColumns },\n\t\t\t});\n\t\t} else {\n\t\t\t// Fallback: log warning, use findOne + conditional insert/update\n\t\t\tlogger.warn(\n\t\t\t\t\"upsert called without matching uniqueKeys constraint, using fallback\",\n\t\t\t\t{\n\t\t\t\t\ttable,\n\t\t\t\t\tkeys: keyColumns,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: {\n\t\t\t\t\t...key,\n\t\t\t\t\t...row,\n\t\t\t\t\t...meta,\n\t\t\t\t\t_upsert_fallback_keys: keyColumns,\n\t\t\t\t\t_upsert_fallback_set: row,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tdelete(table: string, where: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"delete\", table, data: where });\n\t}\n\n\t/**\n\t * Atomic counter update — the blessed accumulator primitive. Compiles to\n\t * `INSERT ... ON CONFLICT (key) DO UPDATE SET col = COALESCE(t.col,0) + delta`,\n\t * so deltas commute: same-block, replayed-in-order, and concurrent updates\n\t * all land correctly without read-modify-write. Missing row inserts the\n\t * delta as the initial value. Requires a uniqueKeys constraint matching\n\t * `key`; deltas may be negative.\n\t */\n\tincrement(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\tdeltas: Record<string, bigint | number>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tconst keyColumns = Object.keys(key);\n\t\tconst hasUniqueConstraint = tableDef?.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\t\tif (!hasUniqueConstraint) {\n\t\t\tthrow new Error(\n\t\t\t\t`increment(\"${table}\") requires a uniqueKeys constraint on [${keyColumns.join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t\tfor (const [col, v] of Object.entries(deltas)) {\n\t\t\tvalidateColumnName(col);\n\t\t\tif (keyColumns.includes(col)) {\n\t\t\t\tthrow new Error(`increment(\"${table}\"): \"${col}\" is a key column`);\n\t\t\t}\n\t\t\tif (typeof v !== \"bigint\" && typeof v !== \"number\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`increment(\"${table}\"): delta for \"${col}\" must be bigint or number`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis.ops.push({\n\t\t\tkind: \"increment\",\n\t\t\ttable,\n\t\t\tdata: {\n\t\t\t\t...key,\n\t\t\t\t_block_height: this.block.height,\n\t\t\t\t_tx_id: this._tx.txId,\n\t\t\t\t_upsert_keys: keyColumns,\n\t\t\t},\n\t\t\tset: { ...deltas },\n\t\t});\n\t}\n\n\t// --- Ops checkpoint (per-event atomicity) ---\n\n\t/** Current length of the pending-ops queue. Pair with {@link rollbackTo}. */\n\topsCheckpoint(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Discard ops queued after a checkpoint. The runner wraps each handler\n\t * invocation so a thrown handler contributes nothing — without this, a\n\t * transfer handler that debited then threw flushes a one-sided debit\n\t * (fix-f040 B6).\n\t */\n\trollbackTo(checkpoint: number): void {\n\t\tif (checkpoint < 0 || checkpoint > this.ops.length) return;\n\t\tthis.ops.length = checkpoint;\n\t}\n\n\t/** Partial update — sets only specified fields, preserves everything else */\n\tpatch(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.update(table, where, set);\n\t}\n\n\t/**\n\t * Find-then-merge-or-insert. Values can be functions: (existing) => newValue.\n\t * Async because it reads existing row first.\n\t */\n\tasync patchOrInsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, ComputedValue>,\n\t): Promise<void> {\n\t\tconst existing = await this.findOne(table, key);\n\t\tconst resolved: Record<string, unknown> = {};\n\t\tfor (const [k, v] of Object.entries(row)) {\n\t\t\tresolved[k] = typeof v === \"function\" ? v(existing) : v;\n\t\t}\n\t\tthis.upsert(table, key, resolved);\n\t}\n\n\t/** Format a bigint amount with decimal places */\n\tformatUnits(value: bigint, decimals: number): string {\n\t\treturn formatUnits(value, decimals);\n\t}\n\n\t// --- Read operations (immediate) ---\n\n\t/**\n\t * Committed rows matching `where`, BEFORE the pending-ops overlay. The one\n\t * seam a different backing store replaces (the in-memory test context);\n\t * everything above it — validation, overlay, op queueing, flush semantics\n\t * — stays here so the two can't diverge.\n\t */\n\tprotected async readRows(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tlimit?: number,\n\t): Promise<Record<string, unknown>[]> {\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst { clause } = buildWhereClause(where);\n\t\tconst query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}${\n\t\t\tlimit !== undefined ? ` LIMIT ${limit}` : \"\"\n\t\t}`;\n\t\tconst { rows } = await sql.raw(query).execute(this.db);\n\t\treturn (rows as Record<string, unknown>[]).map((r) =>\n\t\t\tthis.coerceRow(table, r),\n\t\t);\n\t}\n\n\tasync findOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown> | null> {\n\t\tthis.validateTable(table);\n\t\tconst row = (await this.readRows(table, where, 1))[0] ?? null;\n\t\treturn this.overlayOne(table, where, row);\n\t}\n\n\tasync findMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown>[]> {\n\t\tthis.validateTable(table);\n\t\treturn this.overlayMany(table, where, await this.readRows(table, where));\n\t}\n\n\t// --- Pending-ops overlay (read-your-writes) ---\n\n\t/**\n\t * Replay pending ops for `table` over a single DB-read result so reads\n\t * observe earlier same-block writes. Mirrors flush semantics: upserts\n\t * merge non-key/non-meta columns, increments add deltas, updates/deletes\n\t * apply by where-match. Overlaid rows synthesized from pending inserts\n\t * lack DB-generated columns (_id, _created_at).\n\t */\n\tprotected overlayOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRow: Record<string, unknown> | null,\n\t): Record<string, unknown> | null {\n\t\tif (this.ops.length === 0) return dbRow;\n\t\tlet row = dbRow;\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\trow = this.applyOpToRow(op, row, where);\n\t\t}\n\t\treturn row;\n\t}\n\n\tprotected overlayMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRows: Record<string, unknown>[],\n\t): Record<string, unknown>[] {\n\t\tif (this.ops.length === 0) return [...dbRows];\n\t\tlet result = [...dbRows];\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\tif (op.kind === \"update\") {\n\t\t\t\tfor (let i = 0; i < result.length; i++) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked by loop condition\n\t\t\t\t\tif (rowMatches(result[i]!, op.data))\n\t\t\t\t\t\tresult[i] = { ...result[i], ...(op.set ?? {}) };\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\tresult = result.filter((r) => !rowMatches(r, op.data));\n\t\t\t} else {\n\t\t\t\t// insert / increment — merge into the keyed row, or append if the\n\t\t\t\t// new row satisfies the filter.\n\t\t\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst idx = upsertKeys\n\t\t\t\t\t? result.findIndex((r) =>\n\t\t\t\t\t\t\tupsertKeys.every((k) => valEq(r[k], clean[k])),\n\t\t\t\t\t\t)\n\t\t\t\t\t: -1;\n\t\t\t\tif (idx >= 0) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked above\n\t\t\t\t\tconst existing = result[idx]!;\n\t\t\t\t\tresult[idx] = this.applyOpToRow(op, existing, where) ?? existing;\n\t\t\t\t} else {\n\t\t\t\t\tconst created = this.applyOpToRow(op, null, where);\n\t\t\t\t\tif (created) result.push(created);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Apply one pending op to a candidate row state (null = row absent). */\n\tprotected applyOpToRow(\n\t\top: WriteOp,\n\t\trow: Record<string, unknown> | null,\n\t\twhere: Record<string, unknown>,\n\t): Record<string, unknown> | null {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst clean = stripControlKeys(op.data);\n\n\t\tswitch (op.kind) {\n\t\t\tcase \"insert\": {\n\t\t\t\tif (row) {\n\t\t\t\t\t// Same entity? Compare on the upsert key — a plain insert (no\n\t\t\t\t\t// key) can never target an existing row.\n\t\t\t\t\tif (upsertKeys?.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\t// Mirror ON CONFLICT DO UPDATE: non-key, non-meta cols only.\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [k, v] of Object.entries(clean)) {\n\t\t\t\t\t\t\tif (!upsertKeys.includes(k) && !k.startsWith(\"_\")) merged[k] = v;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\treturn rowMatches(clean, where) ? { ...clean } : null;\n\t\t\t}\n\t\t\tcase \"increment\": {\n\t\t\t\tconst deltas = op.set ?? {};\n\t\t\t\tif (row) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: increment always carries _upsert_keys\n\t\t\t\t\tif (upsertKeys!.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\t\t\tmerged[col] = toBigIntOr0(merged[col]) + toBigIntOr0(d);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\tif (!rowMatches(clean, where)) return null;\n\t\t\t\tconst created: Record<string, unknown> = { ...clean };\n\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\tcreated[col] = toBigIntOr0(d);\n\t\t\t\t}\n\t\t\t\treturn created;\n\t\t\t}\n\t\t\tcase \"update\":\n\t\t\t\treturn row && rowMatches(row, op.data)\n\t\t\t\t\t? { ...row, ...(op.set ?? {}) }\n\t\t\t\t\t: row;\n\t\t\tcase \"delete\":\n\t\t\t\treturn row && rowMatches(row, op.data) ? null : row;\n\t\t}\n\t}\n\n\t// --- Aggregate reads ---\n\n\tasync count(table: string, where?: Record<string, unknown>): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(*)::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\tasync sum(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COALESCE(SUM(\"${column}\"), 0) AS total FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn BigInt(\n\t\t\t(rows as Record<string, unknown>[])[0]?.total?.toString() ?? \"0\",\n\t\t);\n\t}\n\n\tasync min(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MIN(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync max(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MAX(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync countDistinct(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(DISTINCT \"${column}\")::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\t/** Coerce string values from Postgres back to BigInt for uint/int columns */\n\tprivate coerceRow(\n\t\ttable: string,\n\t\trow: Record<string, unknown>,\n\t): Record<string, unknown> {\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return row;\n\t\tconst result = { ...row };\n\t\tfor (const [col, def] of Object.entries(tableDef.columns)) {\n\t\t\tif (\n\t\t\t\t(def.type === \"uint\" || def.type === \"int\") &&\n\t\t\t\ttypeof result[col] === \"string\"\n\t\t\t) {\n\t\t\t\tresult[col] = BigInt(result[col] as string);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t// --- Flush ---\n\n\t/** Number of pending write operations */\n\tget pendingOps(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Execute all batched writes in a single transaction.\n\t * Auto-populates _block_height, _tx_id, _created_at on inserts.\n\t *\n\t * Returns a {@link FlushManifest} describing every write so downstream\n\t * consumers (subscription emitter) can fan out outbox rows atomically\n\t * with the flush itself.\n\t */\n\tasync flush(): Promise<FlushManifest> {\n\t\tif (this.ops.length === 0) return { count: 0, writes: [] };\n\n\t\tawait this.ensureJournalTable();\n\n\t\tconst opsToFlush = [...this.ops];\n\t\tthis.ops.length = 0;\n\n\t\tconst statements = this.buildStatements(opsToFlush);\n\n\t\tif (\"isTransaction\" in this.db) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(this.db);\n\t\t\t}\n\t\t} else {\n\t\t\tawait (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(tx);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst writes: FlushWrite[] = opsToFlush.map((op, rowIndex) => {\n\t\t\tconst blockHeight =\n\t\t\t\t(op.data._block_height as number | undefined) ?? this.block.height;\n\t\t\tconst txId = (op.data._tx_id as string | undefined) ?? this._tx.txId;\n\t\t\tconst baseRow =\n\t\t\t\top.kind === \"update\" || op.kind === \"increment\"\n\t\t\t\t\t? { ...op.data, ...(op.set ?? {}) }\n\t\t\t\t\t: { ...op.data };\n\t\t\t// Strip upsert control keys — not part of the row shape\n\t\t\t(baseRow as Record<string, unknown>)._upsert_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_set = undefined;\n\t\t\treturn {\n\t\t\t\t// Increments surface as \"updated\" to subscribers — the row payload\n\t\t\t\t// carries the key + the applied delta, not the absolute value.\n\t\t\t\top: op.kind === \"increment\" ? \"update\" : op.kind,\n\t\t\t\ttable: op.table,\n\t\t\t\trow: jsonSafe(baseRow),\n\t\t\t\tpk: { blockHeight, txId, rowIndex },\n\t\t\t};\n\t\t});\n\n\t\treturn { count: opsToFlush.length, writes };\n\t}\n\n\t/** Prepare a single insert row, returning its data, columns, upsert key for batching. */\n\tprivate prepareInsert(op: WriteOp): {\n\t\tdata: Record<string, unknown>;\n\t\tcols: string[];\n\t\tvals: string[];\n\t\tupsertKeys: string[] | undefined;\n\t\tbatchKey: string;\n\t} {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst data = { ...op.data };\n\t\t// biome-ignore lint/performance/noDelete: must remove key, not set undefined — Object.keys must not include these\n\t\tdelete data._upsert_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_set;\n\n\t\t// _block_height and _tx_id are captured at insert/upsert time (not flush time)\n\t\t// to ensure correct tx attribution when multiple txs are batched per block\n\t\tif (!data._block_height) data._block_height = this.block.height;\n\t\tif (!data._tx_id) data._tx_id = this._tx.txId;\n\t\tdata._created_at = \"NOW()\";\n\n\t\tconst cols = Object.keys(data);\n\t\tcols.forEach(validateColumnName);\n\t\tconst vals = cols.map((c) =>\n\t\t\tdata[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n\t\t);\n\n\t\t// Batch key: table + sorted columns + upsert key signature (spread to avoid mutating cols)\n\t\tconst batchKey = `${op.table}:${[...cols].sort().join(\",\")}:${upsertKeys ? [...upsertKeys].sort().join(\",\") : \"\"}`;\n\n\t\treturn { data, cols, vals, upsertKeys, batchKey };\n\t}\n\n\t/**\n\t * Lazily create `_journal` for schemas deployed before it existed. Cached\n\t * per process only once CONFIRMED present (to_regclass) — a CREATE issued\n\t * inside a block tx could roll back with it, so self-created tables are\n\t * re-verified on the next flush instead of trusted.\n\t */\n\tprivate async ensureJournalTable(): Promise<void> {\n\t\tif (!this.journal || journalEnsured.has(this.pgSchemaName)) return;\n\t\tconst { rows } = await sql\n\t\t\t.raw(`SELECT to_regclass('\"${this.pgSchemaName}\".\"_journal\"') AS r`)\n\t\t\t.execute(this.db);\n\t\tif ((rows as { r: unknown }[])[0]?.r) {\n\t\t\tjournalEnsured.add(this.pgSchemaName);\n\t\t\treturn;\n\t\t}\n\t\t// Schema names are generator-produced lowercase identifiers, so the\n\t\t// unquoted form emitJournalDDL emits is safe.\n\t\tfor (const stmt of emitJournalDDL(this.pgSchemaName)) {\n\t\t\tawait sql.raw(stmt).execute(this.db);\n\t\t}\n\t}\n\n\t/** SQL type of a user column (for casting journal key VALUES), if known. */\n\tprivate columnSqlType(table: string, col: string): string | undefined {\n\t\tconst def = this.subgraphSchema[table]?.columns?.[col];\n\t\treturn def ? TYPE_MAP[def.type] : undefined;\n\t}\n\n\t/**\n\t * Journal pre-images for a keyed batch: one `_journal` row per key with the\n\t * row's current state (`prev_row`), or NULL when the key doesn't exist yet\n\t * (the mutation will create it — a revert deletes it). Emitted BEFORE the\n\t * mutation statement, same transaction.\n\t */\n\tprivate journalCaptureSQL(\n\t\ttable: string,\n\t\tkeyCols: string[],\n\t\t/** One escaped-literal tuple per key, ordered like keyCols. */\n\t\tkeyLiteralRows: string[][],\n\t): string {\n\t\tconst cast = (col: string, expr: string) => {\n\t\t\tconst t = this.columnSqlType(table, col);\n\t\t\treturn t ? `CAST(${expr} AS ${t})` : expr;\n\t\t};\n\t\tconst keyObj = keyCols\n\t\t\t.map((k) => `'${k}', ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\", \");\n\t\tconst joinCond = keyCols\n\t\t\t.map((k) => `t.\"${k}\" = ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\" AND \");\n\t\tconst valuesList = keyLiteralRows\n\t\t\t.map((r) => `(${r.join(\", \")})`)\n\t\t\t.join(\", \");\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object(${keyObj}), to_jsonb(t.*) ` +\n\t\t\t`FROM (VALUES ${valuesList}) AS v(${keyCols.map((k) => `\"${k}\"`).join(\", \")}) ` +\n\t\t\t`LEFT JOIN \"${this.pgSchemaName}\".\"${table}\" t ON ${joinCond}`\n\t\t);\n\t}\n\n\t/** Journal pre-images of rows a where-clause mutation will touch, keyed by `_id`. */\n\tprivate journalCaptureByWhereSQL(table: string, clause: string): string {\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object('_id', t.\"_id\"), to_jsonb(t.*) ` +\n\t\t\t`FROM \"${this.pgSchemaName}\".\"${table}\" t WHERE ${clause}`\n\t\t);\n\t}\n\n\t/** Build SQL statements from write ops, batching compatible INSERTs. */\n\tprivate buildStatements(ops: WriteOp[]): string[] {\n\t\tconst statements: string[] = [];\n\n\t\t// BYO replace-per-height: clear this block's prior inserts before\n\t\t// re-inserting so a replayed block (no cross-DB tx) stays idempotent.\n\t\t// One DELETE per distinct inserted table; upserts/updates self-heal.\n\t\tif (this.byo) {\n\t\t\tconst insertTables = new Set<string>();\n\t\t\tfor (const op of ops)\n\t\t\t\tif (op.kind === \"insert\") insertTables.add(op.table);\n\t\t\tfor (const table of insertTables) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`DELETE FROM \"${this.pgSchemaName}\".\"${table}\" WHERE \"_block_height\" = ${this.block.height}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Group consecutive inserts by batch key\n\t\ttype InsertBatch = {\n\t\t\ttable: string;\n\t\t\tcols: string[];\n\t\t\trows: string[][];\n\t\t\tupsertKeys: string[] | undefined;\n\t\t};\n\n\t\t// Consecutive increments on the same (table, key cols, delta cols)\n\t\t// coalesce: same-key deltas SUM (they commute), then compile to one\n\t\t// multi-row INSERT ... ON CONFLICT DO UPDATE SET c = COALESCE(c,0)+EXCLUDED.c.\n\t\ttype IncrementBatch = {\n\t\t\ttable: string;\n\t\t\tkeyCols: string[];\n\t\t\tdeltaCols: string[];\n\t\t\t/** key signature → { key values, summed deltas, insert-time meta } */\n\t\t\trows: Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\tkeys: Record<string, unknown>;\n\t\t\t\t\tdeltas: Record<string, bigint>;\n\t\t\t\t\tmeta: { blockHeight: unknown; txId: unknown };\n\t\t\t\t}\n\t\t\t>;\n\t\t};\n\n\t\tlet currentBatch: InsertBatch | null = null;\n\t\tlet currentBatchKey = \"\";\n\t\tlet incBatch: IncrementBatch | null = null;\n\t\tlet incBatchKey = \"\";\n\n\t\tconst flushIncrementBatch = () => {\n\t\t\tif (!incBatch) return;\n\t\t\tconst batch = incBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst cols = [\n\t\t\t\t...batch.keyCols,\n\t\t\t\t...batch.deltaCols,\n\t\t\t\t\"_block_height\",\n\t\t\t\t\"_tx_id\",\n\t\t\t\t\"_created_at\",\n\t\t\t];\n\t\t\tif (this.journal) {\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tbatch.keyCols,\n\t\t\t\t\t\tArray.from(batch.rows.values()).map((r) =>\n\t\t\t\t\t\t\tbatch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// NOT insert-on-conflict: Postgres validates the PROPOSED insert\n\t\t\t// tuple against CHECK constraints BEFORE conflict arbitration, so a\n\t\t\t// negative delta against an EXISTING row (every debit on a uint\n\t\t\t// balance) errors even though DO UPDATE would produce a legal value\n\t\t\t// (prod halts at sbtc 341445 / usdcx 5269728; empirically verified).\n\t\t\t// UPDATE-first lets the CHECK see the FINAL value; the guarded\n\t\t\t// INSERT covers missing rows — where a negative delta is a GENUINE\n\t\t\t// violation and must still fail loudly.\n\t\t\tfor (const r of batch.rows.values()) {\n\t\t\t\tconst keyPred = batch.keyCols\n\t\t\t\t\t.map((k) => `\"${k}\" = ${escapeLiteral(r.keys[k])}`)\n\t\t\t\t\t.join(\" AND \");\n\t\t\t\tconst updSet = batch.deltaCols\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(c) =>\n\t\t\t\t\t\t\t`\"${c}\" = COALESCE(\"${c}\", 0) + (${String(r.deltas[c] ?? 0n)})`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tstatements.push(\n\t\t\t\t\t`UPDATE ${qualifiedTable} SET ${updSet} WHERE ${keyPred}`,\n\t\t\t\t);\n\t\t\t\tconst insertVals = [\n\t\t\t\t\t...batch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t...batch.deltaCols.map((c) => String(r.deltas[c] ?? 0n)),\n\t\t\t\t\tescapeLiteral(r.meta.blockHeight),\n\t\t\t\t\tescapeLiteral(r.meta.txId),\n\t\t\t\t\t\"NOW()\",\n\t\t\t\t];\n\t\t\t\tstatements.push(\n\t\t\t\t\t`INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) ` +\n\t\t\t\t\t\t`SELECT ${insertVals.join(\", \")} ` +\n\t\t\t\t\t\t`WHERE NOT EXISTS (SELECT 1 FROM ${qualifiedTable} WHERE ${keyPred})`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tincBatch = null;\n\t\t\tincBatchKey = \"\";\n\t\t};\n\n\t\tconst flushInsertBatch = () => {\n\t\t\tif (!currentBatch) return;\n\t\t\tconst batch = currentBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst colList = batch.cols.map((c) => `\"${c}\"`).join(\", \");\n\n\t\t\t// Deduplicate by upsert key — last row wins (Postgres rejects duplicate keys in one INSERT)\n\t\t\tlet rows = batch.rows;\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tconst seen = new Map<string, number>();\n\t\t\t\tfor (let i = 0; i < rows.length; i++) {\n\t\t\t\t\tconst key = keyIndices.map((ki) => rows[i][ki]).join(\"\\0\");\n\t\t\t\t\tseen.set(key, i);\n\t\t\t\t}\n\t\t\t\tif (seen.size < rows.length) {\n\t\t\t\t\trows = Array.from(seen.values()).map((i) => rows[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst valuesList = rows.map((r) => `(${r.join(\", \")})`).join(\", \");\n\t\t\tlet stmt = `INSERT INTO ${qualifiedTable} (${colList}) VALUES ${valuesList}`;\n\n\t\t\t// Plain inserts are append-only (revert = delete by _block_height);\n\t\t\t// only keyed upserts can overwrite state worth journaling.\n\t\t\tif (this.journal && batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tuKeys,\n\t\t\t\t\t\trows.map((r) => keyIndices.map((ki) => r[ki])),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst batchKeys = batch.upsertKeys;\n\t\t\t\tconst updateCols = batch.cols.filter(\n\t\t\t\t\t(c) => !batchKeys.includes(c) && !c.startsWith(\"_\"),\n\t\t\t\t);\n\t\t\t\tif (updateCols.length > 0) {\n\t\t\t\t\tconst setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n\t\t\t\t} else {\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.push(stmt);\n\t\t\tcurrentBatch = null;\n\t\t\tcurrentBatchKey = \"\";\n\t\t};\n\n\t\tfor (const op of ops) {\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n\t\t\tif (op.kind === \"insert\") {\n\t\t\t\tflushIncrementBatch();\n\t\t\t\tconst { cols, vals, upsertKeys, batchKey } = this.prepareInsert(op);\n\n\t\t\t\tif (batchKey === currentBatchKey && currentBatch) {\n\t\t\t\t\t// Same table + columns + upsert key — append to batch\n\t\t\t\t\tcurrentBatch.rows.push(vals);\n\t\t\t\t} else {\n\t\t\t\t\t// Different batch — flush previous and start new\n\t\t\t\t\tflushInsertBatch();\n\t\t\t\t\tcurrentBatch = { table: op.table, cols, rows: [vals], upsertKeys };\n\t\t\t\t\tcurrentBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"increment\") {\n\t\t\t\tflushInsertBatch();\n\t\t\t\tconst keyCols = [...(op.data._upsert_keys as string[])].sort();\n\t\t\t\tconst deltaCols = Object.keys(op.set ?? {}).sort();\n\t\t\t\tconst batchKey = `inc:${op.table}:${keyCols.join(\",\")}:${deltaCols.join(\",\")}`;\n\t\t\t\tif (batchKey !== incBatchKey || !incBatch) {\n\t\t\t\t\tflushIncrementBatch();\n\t\t\t\t\tincBatch = { table: op.table, keyCols, deltaCols, rows: new Map() };\n\t\t\t\t\tincBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst keySig = keyCols.map((k) => escapeLiteral(clean[k])).join(\"\\0\");\n\t\t\t\tconst existing = incBatch.rows.get(keySig);\n\t\t\t\tif (existing) {\n\t\t\t\t\tfor (const c of deltaCols) {\n\t\t\t\t\t\texisting.deltas[c] =\n\t\t\t\t\t\t\t(existing.deltas[c] ?? 0n) + toBigIntOr0(op.set?.[c]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst deltas: Record<string, bigint> = {};\n\t\t\t\t\tfor (const c of deltaCols) deltas[c] = toBigIntOr0(op.set?.[c]);\n\t\t\t\t\tincBatch.rows.set(keySig, {\n\t\t\t\t\t\tkeys: clean,\n\t\t\t\t\t\tdeltas,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\tblockHeight: op.data._block_height ?? this.block.height,\n\t\t\t\t\t\t\ttxId: op.data._tx_id ?? this._tx.txId,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Non-insert — flush any pending batches first\n\t\t\t\tflushInsertBatch();\n\t\t\t\tflushIncrementBatch();\n\n\t\t\t\tif (op.kind === \"update\") {\n\t\t\t\t\tconst setEntries = Object.entries(op.set ?? {});\n\t\t\t\t\tfor (const [k] of setEntries) validateColumnName(k);\n\t\t\t\t\tconst setClauses = setEntries.map(\n\t\t\t\t\t\t([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n\t\t\t\t\t);\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t`UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n\t\t\t\t\t);\n\t\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Flush any remaining batches\n\t\tflushInsertBatch();\n\t\tflushIncrementBatch();\n\n\t\treturn statements;\n\t}\n\n\tprivate validateTable(table: string): void {\n\t\tif (!this.subgraphSchema[table]) {\n\t\t\tthrow new Error(\n\t\t\t\t`Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// --- Helpers ---\n\n/** Drop internal upsert control keys from an op's data. */\nfunction stripControlKeys(\n\tdata: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst {\n\t\t_upsert_keys: _a,\n\t\t_upsert_fallback_keys: _b,\n\t\t_upsert_fallback_set: _c,\n\t\t...clean\n\t} = data;\n\treturn clean;\n}\n\n/** Loose value equality across bigint/number/string representations. */\nfunction valEq(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (a == null || b == null) return false;\n\treturn String(a) === String(b);\n}\n\n/** Does `row` satisfy every column constraint in `where`? */\nfunction rowMatches(\n\trow: Record<string, unknown>,\n\twhere: Record<string, unknown>,\n): boolean {\n\treturn Object.entries(where).every(([k, v]) => valEq(row[k], v));\n}\n\nfunction toBigIntOr0(v: unknown): bigint {\n\tif (typeof v === \"bigint\") return v;\n\tif (v == null) return 0n;\n\ttry {\n\t\treturn BigInt(String(v));\n\t} catch {\n\t\treturn 0n;\n\t}\n}\n\n/** Coerce a row for JSON serialization — bigints become strings. */\nfunction jsonSafe(row: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(row)) {\n\t\tout[k] = typeof v === \"bigint\" ? v.toString() : v;\n\t}\n\treturn out;\n}\n\nfunction escapeLiteral(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\tif (typeof value === \"object\")\n\t\treturn `'${JSON.stringify(value, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v)).replace(/'/g, \"''\")}'::jsonb`;\n\t// String — escape single quotes\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n\tclause: string;\n\tvalues: unknown[];\n} {\n\tconst entries = Object.entries(where);\n\tif (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n\tfor (const [k] of entries) validateColumnName(k);\n\tconst parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n\treturn { clause: parts.join(\" AND \"), values: [] };\n}\n",
5
+ "import type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { formatUnits } from \"@secondlayer/stacks/utils\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { TYPE_MAP, emitJournalDDL } from \"../schema/generator.ts\";\nimport type { ComputedValue, SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\n/** Reorg journal entries older than this many blocks are prunable — far past\n * Stacks finality (observed reorg depth is single digits). */\nexport const JOURNAL_RETENTION_BLOCKS = 300;\n\n/** Schemas whose `_journal` table existence has been ensured this process.\n * Populated only after a successful flush (a rolled-back CREATE must retry). */\nconst journalEnsured = new Set<string>();\n\ninterface WriteOp {\n\tkind: \"insert\" | \"update\" | \"delete\" | \"increment\";\n\ttable: string;\n\tdata: Record<string, unknown>;\n\t/** For update: SET clause. For increment: column → signed delta. */\n\tset?: Record<string, unknown>;\n}\n\nexport interface FlushWrite {\n\top: \"insert\" | \"update\" | \"delete\";\n\ttable: string;\n\t/** Full row data (for inserts) or where+set merged (for updates). Bigints stringified. */\n\trow: Record<string, unknown>;\n\t/** Stable identifier for dedup — `{blockHeight, txId, rowIndex}` */\n\tpk: { blockHeight: number; txId: string; rowIndex: number };\n}\n\nexport interface FlushManifest {\n\tcount: number;\n\twrites: FlushWrite[];\n}\n\nimport { type ChainReadClient, createChainReadClient } from \"./chain-read.ts\";\n\nexport interface BlockMeta {\n\theight: number;\n\thash: string;\n\ttimestamp: number;\n\tburnBlockHeight: number;\n\t/**\n\t * Nakamoto StacksBlockId — the identifier `?tip=` accepts, and the only way\n\t * to pin a read-only call to THIS block. Null on rows ingested before it\n\t * was persisted; `ctx.client.readOnly` refuses to run rather than silently\n\t * reading at the node's tip.\n\t */\n\tindexBlockHash?: string | null;\n}\n\nexport interface TxMeta {\n\ttxId: string;\n\tsender: string;\n\ttype: string;\n\tstatus: string;\n\tcontractId?: string | null;\n\tfunctionName?: string | null;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n\tif (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n\t\tthrow new Error(`Invalid column name: ${name}`);\n\t}\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n *\n * Row reads (findOne/findMany) are read-your-writes: they overlay the pending\n * ops queue on the DB state, so a handler observes every write queued earlier\n * in the same block. Without this, accumulator patterns (balance = f(existing))\n * silently lose all but the last same-block delta per row (fix-f040 B1).\n * Aggregate reads (count/sum/min/max) remain pre-flush DB state.\n */\nexport class SubgraphContext {\n\treadonly block: BlockMeta;\n\tprivate _tx: TxMeta;\n\tprivate readonly db: AnyDb;\n\tprivate readonly pgSchemaName: string;\n\tprivate readonly subgraphSchema: SubgraphSchema;\n\t/** Pending writes for this block. `protected` so the in-memory test\n\t * context (`@secondlayer/subgraphs/testing`) can materialize them through\n\t * the SAME overlay this class uses — never a second implementation. */\n\tprotected readonly ops: WriteOp[] = [];\n\t/**\n\t * BYO data plane: handler writes land in a user-owned DB whose flush can't\n\t * share the managed block transaction, so a crash replays the block. When\n\t * set, flush() prepends a replace-per-height DELETE for every inserted table\n\t * (`_block_height = N` → re-INSERT), making block reprocessing idempotent.\n\t * Non-idempotent `update` handlers are rejected at deploy, not here.\n\t */\n\tprivate readonly byo: boolean;\n\t/**\n\t * Record pre-images of keyed mutations into the schema's `_journal` so a\n\t * reorg can restore prior row states (fix-f040 B2). Enabled on the live\n\t * path only — deep reindex/backfill heights are past finality, and the\n\t * journal would just be churn the pruner deletes.\n\t */\n\tprivate readonly journal: boolean;\n\n\t/** Memoized per block; see the `client` getter. */\n\tprotected _client?: ChainReadClient;\n\n\tconstructor(\n\t\tdb: AnyDb,\n\t\tpgSchemaName: string,\n\t\tsubgraphSchema: SubgraphSchema,\n\t\tblock: BlockMeta,\n\t\ttx: TxMeta,\n\t\tbyo = false,\n\t\tjournal = false,\n\t) {\n\t\tthis.db = db;\n\t\tthis.pgSchemaName = pgSchemaName;\n\t\tthis.subgraphSchema = subgraphSchema;\n\t\tthis.block = block;\n\t\tthis._tx = tx;\n\t\tthis.byo = byo;\n\t\tthis.journal = journal;\n\t}\n\n\t/**\n\t * Chain reads pinned to THIS block. Lazily built so a handler that never\n\t * reads never touches the node config, and so the in-memory test context\n\t * can override it without a node.\n\t */\n\tget client(): ChainReadClient {\n\t\tthis._client ??= createChainReadClient({\n\t\t\tblockHeight: this.block.height,\n\t\t\tindexBlockHash: this.block.indexBlockHash,\n\t\t});\n\t\treturn this._client;\n\t}\n\n\tget tx(): TxMeta {\n\t\treturn this._tx;\n\t}\n\n\t/** Update the current transaction context (used by runner between events) */\n\tsetTx(tx: TxMeta): void {\n\t\tthis._tx = tx;\n\t}\n\n\t// --- Write operations (batched) ---\n\n\tinsert(table: string, row: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({\n\t\t\tkind: \"insert\",\n\t\t\ttable,\n\t\t\tdata: { ...row, _block_height: this.block.height, _tx_id: this._tx.txId },\n\t\t});\n\t}\n\n\tupdate(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"update\", table, data: where, set });\n\t}\n\n\tupsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, unknown>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return;\n\t\tconst keyColumns = Object.keys(key);\n\n\t\t// Check if there's a matching uniqueKeys constraint\n\t\tconst hasUniqueConstraint = tableDef.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\n\t\tconst meta = { _block_height: this.block.height, _tx_id: this._tx.txId };\n\n\t\tif (hasUniqueConstraint) {\n\t\t\t// Use ON CONFLICT for proper upsert\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: { ...key, ...row, ...meta, _upsert_keys: keyColumns },\n\t\t\t});\n\t\t} else {\n\t\t\t// Fallback: log warning, use findOne + conditional insert/update\n\t\t\tlogger.warn(\n\t\t\t\t\"upsert called without matching uniqueKeys constraint, using fallback\",\n\t\t\t\t{\n\t\t\t\t\ttable,\n\t\t\t\t\tkeys: keyColumns,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.ops.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\ttable,\n\t\t\t\tdata: {\n\t\t\t\t\t...key,\n\t\t\t\t\t...row,\n\t\t\t\t\t...meta,\n\t\t\t\t\t_upsert_fallback_keys: keyColumns,\n\t\t\t\t\t_upsert_fallback_set: row,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tdelete(table: string, where: Record<string, unknown>): void {\n\t\tthis.validateTable(table);\n\t\tthis.ops.push({ kind: \"delete\", table, data: where });\n\t}\n\n\t/**\n\t * Atomic counter update — the blessed accumulator primitive. Compiles to\n\t * `INSERT ... ON CONFLICT (key) DO UPDATE SET col = COALESCE(t.col,0) + delta`,\n\t * so deltas commute: same-block, replayed-in-order, and concurrent updates\n\t * all land correctly without read-modify-write. Missing row inserts the\n\t * delta as the initial value. Requires a uniqueKeys constraint matching\n\t * `key`; deltas may be negative.\n\t */\n\tincrement(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\tdeltas: Record<string, bigint | number>,\n\t): void {\n\t\tthis.validateTable(table);\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tconst keyColumns = Object.keys(key);\n\t\tconst hasUniqueConstraint = tableDef?.uniqueKeys?.some(\n\t\t\t(uk) =>\n\t\t\t\tuk.length === keyColumns.length &&\n\t\t\t\tuk.every((c) => keyColumns.includes(c)),\n\t\t);\n\t\tif (!hasUniqueConstraint) {\n\t\t\tthrow new Error(\n\t\t\t\t`increment(\"${table}\") requires a uniqueKeys constraint on [${keyColumns.join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t\tfor (const [col, v] of Object.entries(deltas)) {\n\t\t\tvalidateColumnName(col);\n\t\t\tif (keyColumns.includes(col)) {\n\t\t\t\tthrow new Error(`increment(\"${table}\"): \"${col}\" is a key column`);\n\t\t\t}\n\t\t\tif (typeof v !== \"bigint\" && typeof v !== \"number\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`increment(\"${table}\"): delta for \"${col}\" must be bigint or number`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis.ops.push({\n\t\t\tkind: \"increment\",\n\t\t\ttable,\n\t\t\tdata: {\n\t\t\t\t...key,\n\t\t\t\t_block_height: this.block.height,\n\t\t\t\t_tx_id: this._tx.txId,\n\t\t\t\t_upsert_keys: keyColumns,\n\t\t\t},\n\t\t\tset: { ...deltas },\n\t\t});\n\t}\n\n\t// --- Ops checkpoint (per-event atomicity) ---\n\n\t/** Current length of the pending-ops queue. Pair with {@link rollbackTo}. */\n\topsCheckpoint(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Discard ops queued after a checkpoint. The runner wraps each handler\n\t * invocation so a thrown handler contributes nothing — without this, a\n\t * transfer handler that debited then threw flushes a one-sided debit\n\t * (fix-f040 B6).\n\t */\n\trollbackTo(checkpoint: number): void {\n\t\tif (checkpoint < 0 || checkpoint > this.ops.length) return;\n\t\tthis.ops.length = checkpoint;\n\t}\n\n\t/** Partial update — sets only specified fields, preserves everything else */\n\tpatch(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tset: Record<string, unknown>,\n\t): void {\n\t\tthis.update(table, where, set);\n\t}\n\n\t/**\n\t * Find-then-merge-or-insert. Values can be functions: (existing) => newValue.\n\t * Async because it reads existing row first.\n\t */\n\tasync patchOrInsert(\n\t\ttable: string,\n\t\tkey: Record<string, unknown>,\n\t\trow: Record<string, ComputedValue>,\n\t): Promise<void> {\n\t\tconst existing = await this.findOne(table, key);\n\t\tconst resolved: Record<string, unknown> = {};\n\t\tfor (const [k, v] of Object.entries(row)) {\n\t\t\tresolved[k] = typeof v === \"function\" ? v(existing) : v;\n\t\t}\n\t\tthis.upsert(table, key, resolved);\n\t}\n\n\t/** Format a bigint amount with decimal places */\n\tformatUnits(value: bigint, decimals: number): string {\n\t\treturn formatUnits(value, decimals);\n\t}\n\n\t// --- Read operations (immediate) ---\n\n\t/**\n\t * Committed rows matching `where`, BEFORE the pending-ops overlay. The one\n\t * seam a different backing store replaces (the in-memory test context);\n\t * everything above it — validation, overlay, op queueing, flush semantics\n\t * — stays here so the two can't diverge.\n\t */\n\tprotected async readRows(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tlimit?: number,\n\t): Promise<Record<string, unknown>[]> {\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst { clause } = buildWhereClause(where);\n\t\tconst query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}${\n\t\t\tlimit !== undefined ? ` LIMIT ${limit}` : \"\"\n\t\t}`;\n\t\tconst { rows } = await sql.raw(query).execute(this.db);\n\t\treturn (rows as Record<string, unknown>[]).map((r) =>\n\t\t\tthis.coerceRow(table, r),\n\t\t);\n\t}\n\n\tasync findOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown> | null> {\n\t\tthis.validateTable(table);\n\t\tconst row = (await this.readRows(table, where, 1))[0] ?? null;\n\t\treturn this.overlayOne(table, where, row);\n\t}\n\n\tasync findMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t): Promise<Record<string, unknown>[]> {\n\t\tthis.validateTable(table);\n\t\treturn this.overlayMany(table, where, await this.readRows(table, where));\n\t}\n\n\t// --- Pending-ops overlay (read-your-writes) ---\n\n\t/**\n\t * Replay pending ops for `table` over a single DB-read result so reads\n\t * observe earlier same-block writes. Mirrors flush semantics: upserts\n\t * merge non-key/non-meta columns, increments add deltas, updates/deletes\n\t * apply by where-match. Overlaid rows synthesized from pending inserts\n\t * lack DB-generated columns (_id, _created_at).\n\t */\n\tprotected overlayOne(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRow: Record<string, unknown> | null,\n\t): Record<string, unknown> | null {\n\t\tif (this.ops.length === 0) return dbRow;\n\t\tlet row = dbRow;\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\trow = this.applyOpToRow(op, row, where);\n\t\t}\n\t\treturn row;\n\t}\n\n\tprotected overlayMany(\n\t\ttable: string,\n\t\twhere: Record<string, unknown>,\n\t\tdbRows: Record<string, unknown>[],\n\t): Record<string, unknown>[] {\n\t\tif (this.ops.length === 0) return [...dbRows];\n\t\tlet result = [...dbRows];\n\t\tfor (const op of this.ops) {\n\t\t\tif (op.table !== table) continue;\n\t\t\tif (op.kind === \"update\") {\n\t\t\t\tfor (let i = 0; i < result.length; i++) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked by loop condition\n\t\t\t\t\tif (rowMatches(result[i]!, op.data))\n\t\t\t\t\t\tresult[i] = { ...result[i], ...(op.set ?? {}) };\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\tresult = result.filter((r) => !rowMatches(r, op.data));\n\t\t\t} else {\n\t\t\t\t// insert / increment — merge into the keyed row, or append if the\n\t\t\t\t// new row satisfies the filter.\n\t\t\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst idx = upsertKeys\n\t\t\t\t\t? result.findIndex((r) =>\n\t\t\t\t\t\t\tupsertKeys.every((k) => valEq(r[k], clean[k])),\n\t\t\t\t\t\t)\n\t\t\t\t\t: -1;\n\t\t\t\tif (idx >= 0) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: idx bounds-checked above\n\t\t\t\t\tconst existing = result[idx]!;\n\t\t\t\t\tresult[idx] = this.applyOpToRow(op, existing, where) ?? existing;\n\t\t\t\t} else {\n\t\t\t\t\tconst created = this.applyOpToRow(op, null, where);\n\t\t\t\t\tif (created) result.push(created);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Apply one pending op to a candidate row state (null = row absent). */\n\tprotected applyOpToRow(\n\t\top: WriteOp,\n\t\trow: Record<string, unknown> | null,\n\t\twhere: Record<string, unknown>,\n\t): Record<string, unknown> | null {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst clean = stripControlKeys(op.data);\n\n\t\tswitch (op.kind) {\n\t\t\tcase \"insert\": {\n\t\t\t\tif (row) {\n\t\t\t\t\t// Same entity? Compare on the upsert key — a plain insert (no\n\t\t\t\t\t// key) can never target an existing row.\n\t\t\t\t\tif (upsertKeys?.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\t// Mirror ON CONFLICT DO UPDATE: non-key, non-meta cols only.\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [k, v] of Object.entries(clean)) {\n\t\t\t\t\t\t\tif (!upsertKeys.includes(k) && !k.startsWith(\"_\")) merged[k] = v;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\treturn rowMatches(clean, where) ? { ...clean } : null;\n\t\t\t}\n\t\t\tcase \"increment\": {\n\t\t\t\tconst deltas = op.set ?? {};\n\t\t\t\tif (row) {\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: increment always carries _upsert_keys\n\t\t\t\t\tif (upsertKeys!.every((k) => valEq(row[k], clean[k]))) {\n\t\t\t\t\t\tconst merged = { ...row };\n\t\t\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\t\t\tmerged[col] = toBigIntOr0(merged[col]) + toBigIntOr0(d);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn merged;\n\t\t\t\t\t}\n\t\t\t\t\treturn row;\n\t\t\t\t}\n\t\t\t\tif (!rowMatches(clean, where)) return null;\n\t\t\t\tconst created: Record<string, unknown> = { ...clean };\n\t\t\t\tfor (const [col, d] of Object.entries(deltas)) {\n\t\t\t\t\tcreated[col] = toBigIntOr0(d);\n\t\t\t\t}\n\t\t\t\treturn created;\n\t\t\t}\n\t\t\tcase \"update\":\n\t\t\t\treturn row && rowMatches(row, op.data)\n\t\t\t\t\t? { ...row, ...(op.set ?? {}) }\n\t\t\t\t\t: row;\n\t\t\tcase \"delete\":\n\t\t\t\treturn row && rowMatches(row, op.data) ? null : row;\n\t\t}\n\t}\n\n\t// --- Aggregate reads ---\n\n\tasync count(table: string, where?: Record<string, unknown>): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(*)::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\tasync sum(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COALESCE(SUM(\"${column}\"), 0) AS total FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn BigInt(\n\t\t\t(rows as Record<string, unknown>[])[0]?.total?.toString() ?? \"0\",\n\t\t);\n\t}\n\n\tasync min(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MIN(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync max(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<bigint | null> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT MAX(\"${column}\") AS val FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\tconst val = (rows as Record<string, unknown>[])[0]?.val;\n\t\treturn val != null ? BigInt(val.toString()) : null;\n\t}\n\n\tasync countDistinct(\n\t\ttable: string,\n\t\tcolumn: string,\n\t\twhere?: Record<string, unknown>,\n\t): Promise<number> {\n\t\tthis.validateTable(table);\n\t\tvalidateColumnName(column);\n\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n\t\tconst whereClause = where ? `WHERE ${buildWhereClause(where).clause}` : \"\";\n\t\tconst { rows } = await sql\n\t\t\t.raw(\n\t\t\t\t`SELECT COUNT(DISTINCT \"${column}\")::int AS count FROM ${qualifiedTable} ${whereClause}`,\n\t\t\t)\n\t\t\t.execute(this.db);\n\t\treturn Number((rows as Record<string, unknown>[])[0]?.count ?? 0);\n\t}\n\n\t/** Coerce string values from Postgres back to BigInt for uint/int columns */\n\tprivate coerceRow(\n\t\ttable: string,\n\t\trow: Record<string, unknown>,\n\t): Record<string, unknown> {\n\t\tconst tableDef = this.subgraphSchema[table];\n\t\tif (!tableDef) return row;\n\t\tconst result = { ...row };\n\t\tfor (const [col, def] of Object.entries(tableDef.columns)) {\n\t\t\tif (\n\t\t\t\t(def.type === \"uint\" || def.type === \"int\") &&\n\t\t\t\ttypeof result[col] === \"string\"\n\t\t\t) {\n\t\t\t\tresult[col] = BigInt(result[col] as string);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t// --- Flush ---\n\n\t/** Number of pending write operations */\n\tget pendingOps(): number {\n\t\treturn this.ops.length;\n\t}\n\n\t/**\n\t * Execute all batched writes in a single transaction.\n\t * Auto-populates _block_height, _tx_id, _created_at on inserts.\n\t *\n\t * Returns a {@link FlushManifest} describing every write so downstream\n\t * consumers (subscription emitter) can fan out outbox rows atomically\n\t * with the flush itself.\n\t */\n\tasync flush(): Promise<FlushManifest> {\n\t\tif (this.ops.length === 0) return { count: 0, writes: [] };\n\n\t\tawait this.ensureJournalTable();\n\n\t\tconst opsToFlush = [...this.ops];\n\t\tthis.ops.length = 0;\n\n\t\tconst statements = this.buildStatements(opsToFlush);\n\n\t\tif (\"isTransaction\" in this.db) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(this.db);\n\t\t\t}\n\t\t} else {\n\t\t\tawait (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(tx);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst writes: FlushWrite[] = opsToFlush.map((op, rowIndex) => {\n\t\t\tconst blockHeight =\n\t\t\t\t(op.data._block_height as number | undefined) ?? this.block.height;\n\t\t\tconst txId = (op.data._tx_id as string | undefined) ?? this._tx.txId;\n\t\t\tconst baseRow =\n\t\t\t\top.kind === \"update\" || op.kind === \"increment\"\n\t\t\t\t\t? { ...op.data, ...(op.set ?? {}) }\n\t\t\t\t\t: { ...op.data };\n\t\t\t// Strip upsert control keys — not part of the row shape\n\t\t\t(baseRow as Record<string, unknown>)._upsert_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_keys = undefined;\n\t\t\t(baseRow as Record<string, unknown>)._upsert_fallback_set = undefined;\n\t\t\treturn {\n\t\t\t\t// Increments surface as \"updated\" to subscribers — the row payload\n\t\t\t\t// carries the key + the applied delta, not the absolute value.\n\t\t\t\top: op.kind === \"increment\" ? \"update\" : op.kind,\n\t\t\t\ttable: op.table,\n\t\t\t\trow: jsonSafe(baseRow),\n\t\t\t\tpk: { blockHeight, txId, rowIndex },\n\t\t\t};\n\t\t});\n\n\t\treturn { count: opsToFlush.length, writes };\n\t}\n\n\t/** Prepare a single insert row, returning its data, columns, upsert key for batching. */\n\tprivate prepareInsert(op: WriteOp): {\n\t\tdata: Record<string, unknown>;\n\t\tcols: string[];\n\t\tvals: string[];\n\t\tupsertKeys: string[] | undefined;\n\t\tbatchKey: string;\n\t} {\n\t\tconst upsertKeys = op.data._upsert_keys as string[] | undefined;\n\t\tconst data = { ...op.data };\n\t\t// biome-ignore lint/performance/noDelete: must remove key, not set undefined — Object.keys must not include these\n\t\tdelete data._upsert_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_keys;\n\t\t// biome-ignore lint/performance/noDelete: same as above\n\t\tdelete data._upsert_fallback_set;\n\n\t\t// _block_height and _tx_id are captured at insert/upsert time (not flush time)\n\t\t// to ensure correct tx attribution when multiple txs are batched per block\n\t\tif (!data._block_height) data._block_height = this.block.height;\n\t\tif (!data._tx_id) data._tx_id = this._tx.txId;\n\t\tdata._created_at = \"NOW()\";\n\n\t\tconst cols = Object.keys(data);\n\t\tcols.forEach(validateColumnName);\n\t\tconst vals = cols.map((c) =>\n\t\t\tdata[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n\t\t);\n\n\t\t// Batch key: table + sorted columns + upsert key signature (spread to avoid mutating cols)\n\t\tconst batchKey = `${op.table}:${[...cols].sort().join(\",\")}:${upsertKeys ? [...upsertKeys].sort().join(\",\") : \"\"}`;\n\n\t\treturn { data, cols, vals, upsertKeys, batchKey };\n\t}\n\n\t/**\n\t * Lazily create `_journal` for schemas deployed before it existed. Cached\n\t * per process only once CONFIRMED present (to_regclass) — a CREATE issued\n\t * inside a block tx could roll back with it, so self-created tables are\n\t * re-verified on the next flush instead of trusted.\n\t */\n\tprivate async ensureJournalTable(): Promise<void> {\n\t\tif (!this.journal || journalEnsured.has(this.pgSchemaName)) return;\n\t\tconst { rows } = await sql\n\t\t\t.raw(`SELECT to_regclass('\"${this.pgSchemaName}\".\"_journal\"') AS r`)\n\t\t\t.execute(this.db);\n\t\tif ((rows as { r: unknown }[])[0]?.r) {\n\t\t\tjournalEnsured.add(this.pgSchemaName);\n\t\t\treturn;\n\t\t}\n\t\t// Schema names are generator-produced lowercase identifiers, so the\n\t\t// unquoted form emitJournalDDL emits is safe.\n\t\tfor (const stmt of emitJournalDDL(this.pgSchemaName)) {\n\t\t\tawait sql.raw(stmt).execute(this.db);\n\t\t}\n\t}\n\n\t/** SQL type of a user column (for casting journal key VALUES), if known. */\n\tprivate columnSqlType(table: string, col: string): string | undefined {\n\t\tconst def = this.subgraphSchema[table]?.columns?.[col];\n\t\treturn def ? TYPE_MAP[def.type] : undefined;\n\t}\n\n\t/**\n\t * Journal pre-images for a keyed batch: one `_journal` row per key with the\n\t * row's current state (`prev_row`), or NULL when the key doesn't exist yet\n\t * (the mutation will create it — a revert deletes it). Emitted BEFORE the\n\t * mutation statement, same transaction.\n\t */\n\tprivate journalCaptureSQL(\n\t\ttable: string,\n\t\tkeyCols: string[],\n\t\t/** One escaped-literal tuple per key, ordered like keyCols. */\n\t\tkeyLiteralRows: string[][],\n\t): string {\n\t\tconst cast = (col: string, expr: string) => {\n\t\t\tconst t = this.columnSqlType(table, col);\n\t\t\treturn t ? `CAST(${expr} AS ${t})` : expr;\n\t\t};\n\t\tconst keyObj = keyCols\n\t\t\t.map((k) => `'${k}', ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\", \");\n\t\tconst joinCond = keyCols\n\t\t\t.map((k) => `t.\"${k}\" = ${cast(k, `v.\"${k}\"`)}`)\n\t\t\t.join(\" AND \");\n\t\tconst valuesList = keyLiteralRows\n\t\t\t.map((r) => `(${r.join(\", \")})`)\n\t\t\t.join(\", \");\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object(${keyObj}), to_jsonb(t.*) ` +\n\t\t\t`FROM (VALUES ${valuesList}) AS v(${keyCols.map((k) => `\"${k}\"`).join(\", \")}) ` +\n\t\t\t`LEFT JOIN \"${this.pgSchemaName}\".\"${table}\" t ON ${joinCond}`\n\t\t);\n\t}\n\n\t/** Journal pre-images of rows a where-clause mutation will touch, keyed by `_id`. */\n\tprivate journalCaptureByWhereSQL(table: string, clause: string): string {\n\t\treturn (\n\t\t\t`INSERT INTO \"${this.pgSchemaName}\".\"_journal\" (\"block_height\", \"table_name\", \"row_key\", \"prev_row\") ` +\n\t\t\t`SELECT ${this.block.height}, '${table}', jsonb_build_object('_id', t.\"_id\"), to_jsonb(t.*) ` +\n\t\t\t`FROM \"${this.pgSchemaName}\".\"${table}\" t WHERE ${clause}`\n\t\t);\n\t}\n\n\t/** Build SQL statements from write ops, batching compatible INSERTs. */\n\tprivate buildStatements(ops: WriteOp[]): string[] {\n\t\tconst statements: string[] = [];\n\n\t\t// BYO replace-per-height: clear this block's prior inserts before\n\t\t// re-inserting so a replayed block (no cross-DB tx) stays idempotent.\n\t\t// One DELETE per distinct inserted table; upserts/updates self-heal.\n\t\tif (this.byo) {\n\t\t\tconst insertTables = new Set<string>();\n\t\t\tfor (const op of ops)\n\t\t\t\tif (op.kind === \"insert\") insertTables.add(op.table);\n\t\t\tfor (const table of insertTables) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`DELETE FROM \"${this.pgSchemaName}\".\"${table}\" WHERE \"_block_height\" = ${this.block.height}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Group consecutive inserts by batch key\n\t\ttype InsertBatch = {\n\t\t\ttable: string;\n\t\t\tcols: string[];\n\t\t\trows: string[][];\n\t\t\tupsertKeys: string[] | undefined;\n\t\t};\n\n\t\t// Consecutive increments on the same (table, key cols, delta cols)\n\t\t// coalesce: same-key deltas SUM (they commute), then compile to one\n\t\t// multi-row INSERT ... ON CONFLICT DO UPDATE SET c = COALESCE(c,0)+EXCLUDED.c.\n\t\ttype IncrementBatch = {\n\t\t\ttable: string;\n\t\t\tkeyCols: string[];\n\t\t\tdeltaCols: string[];\n\t\t\t/** key signature → { key values, summed deltas, insert-time meta } */\n\t\t\trows: Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\tkeys: Record<string, unknown>;\n\t\t\t\t\tdeltas: Record<string, bigint>;\n\t\t\t\t\tmeta: { blockHeight: unknown; txId: unknown };\n\t\t\t\t}\n\t\t\t>;\n\t\t};\n\n\t\tlet currentBatch: InsertBatch | null = null;\n\t\tlet currentBatchKey = \"\";\n\t\tlet incBatch: IncrementBatch | null = null;\n\t\tlet incBatchKey = \"\";\n\n\t\tconst flushIncrementBatch = () => {\n\t\t\tif (!incBatch) return;\n\t\t\tconst batch = incBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst cols = [\n\t\t\t\t...batch.keyCols,\n\t\t\t\t...batch.deltaCols,\n\t\t\t\t\"_block_height\",\n\t\t\t\t\"_tx_id\",\n\t\t\t\t\"_created_at\",\n\t\t\t];\n\t\t\tif (this.journal) {\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tbatch.keyCols,\n\t\t\t\t\t\tArray.from(batch.rows.values()).map((r) =>\n\t\t\t\t\t\t\tbatch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\t// NOT insert-on-conflict: Postgres validates the PROPOSED insert\n\t\t\t// tuple against CHECK constraints BEFORE conflict arbitration, so a\n\t\t\t// negative delta against an EXISTING row (every debit on a uint\n\t\t\t// balance) errors even though DO UPDATE would produce a legal value\n\t\t\t// (prod halts at sbtc 341445 / usdcx 5269728; empirically verified).\n\t\t\t// UPDATE-first lets the CHECK see the FINAL value; the guarded\n\t\t\t// INSERT covers missing rows — where a negative delta is a GENUINE\n\t\t\t// violation and must still fail loudly.\n\t\t\tfor (const r of batch.rows.values()) {\n\t\t\t\tconst keyPred = batch.keyCols\n\t\t\t\t\t.map((k) => `\"${k}\" = ${escapeLiteral(r.keys[k])}`)\n\t\t\t\t\t.join(\" AND \");\n\t\t\t\tconst updSet = batch.deltaCols\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(c) =>\n\t\t\t\t\t\t\t`\"${c}\" = COALESCE(\"${c}\", 0) + (${String(r.deltas[c] ?? 0n)})`,\n\t\t\t\t\t)\n\t\t\t\t\t.join(\", \");\n\t\t\t\tstatements.push(\n\t\t\t\t\t`UPDATE ${qualifiedTable} SET ${updSet} WHERE ${keyPred}`,\n\t\t\t\t);\n\t\t\t\tconst insertVals = [\n\t\t\t\t\t...batch.keyCols.map((k) => escapeLiteral(r.keys[k])),\n\t\t\t\t\t...batch.deltaCols.map((c) => String(r.deltas[c] ?? 0n)),\n\t\t\t\t\tescapeLiteral(r.meta.blockHeight),\n\t\t\t\t\tescapeLiteral(r.meta.txId),\n\t\t\t\t\t\"NOW()\",\n\t\t\t\t];\n\t\t\t\tstatements.push(\n\t\t\t\t\t`INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) ` +\n\t\t\t\t\t\t`SELECT ${insertVals.join(\", \")} ` +\n\t\t\t\t\t\t`WHERE NOT EXISTS (SELECT 1 FROM ${qualifiedTable} WHERE ${keyPred})`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tincBatch = null;\n\t\t\tincBatchKey = \"\";\n\t\t};\n\n\t\tconst flushInsertBatch = () => {\n\t\t\tif (!currentBatch) return;\n\t\t\tconst batch = currentBatch;\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${batch.table}\"`;\n\t\t\tconst colList = batch.cols.map((c) => `\"${c}\"`).join(\", \");\n\n\t\t\t// Deduplicate by upsert key — last row wins (Postgres rejects duplicate keys in one INSERT)\n\t\t\tlet rows = batch.rows;\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tconst seen = new Map<string, number>();\n\t\t\t\tfor (let i = 0; i < rows.length; i++) {\n\t\t\t\t\tconst key = keyIndices.map((ki) => rows[i][ki]).join(\"\\0\");\n\t\t\t\t\tseen.set(key, i);\n\t\t\t\t}\n\t\t\t\tif (seen.size < rows.length) {\n\t\t\t\t\trows = Array.from(seen.values()).map((i) => rows[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst valuesList = rows.map((r) => `(${r.join(\", \")})`).join(\", \");\n\t\t\tlet stmt = `INSERT INTO ${qualifiedTable} (${colList}) VALUES ${valuesList}`;\n\n\t\t\t// Plain inserts are append-only (revert = delete by _block_height);\n\t\t\t// only keyed upserts can overwrite state worth journaling.\n\t\t\tif (this.journal && batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst uKeys = batch.upsertKeys;\n\t\t\t\tconst keyIndices = uKeys.map((k) => batch.cols.indexOf(k));\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.journalCaptureSQL(\n\t\t\t\t\t\tbatch.table,\n\t\t\t\t\t\tuKeys,\n\t\t\t\t\t\trows.map((r) => keyIndices.map((ki) => r[ki])),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (batch.upsertKeys && batch.upsertKeys.length > 0) {\n\t\t\t\tconst batchKeys = batch.upsertKeys;\n\t\t\t\tconst updateCols = batch.cols.filter(\n\t\t\t\t\t(c) => !batchKeys.includes(c) && !c.startsWith(\"_\"),\n\t\t\t\t);\n\t\t\t\tif (updateCols.length > 0) {\n\t\t\t\t\tconst setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n\t\t\t\t} else {\n\t\t\t\t\tstmt += ` ON CONFLICT (${batchKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatements.push(stmt);\n\t\t\tcurrentBatch = null;\n\t\t\tcurrentBatchKey = \"\";\n\t\t};\n\n\t\tfor (const op of ops) {\n\t\t\tconst qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n\t\t\tif (op.kind === \"insert\") {\n\t\t\t\tflushIncrementBatch();\n\t\t\t\tconst { cols, vals, upsertKeys, batchKey } = this.prepareInsert(op);\n\n\t\t\t\tif (batchKey === currentBatchKey && currentBatch) {\n\t\t\t\t\t// Same table + columns + upsert key — append to batch\n\t\t\t\t\tcurrentBatch.rows.push(vals);\n\t\t\t\t} else {\n\t\t\t\t\t// Different batch — flush previous and start new\n\t\t\t\t\tflushInsertBatch();\n\t\t\t\t\tcurrentBatch = { table: op.table, cols, rows: [vals], upsertKeys };\n\t\t\t\t\tcurrentBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t} else if (op.kind === \"increment\") {\n\t\t\t\tflushInsertBatch();\n\t\t\t\tconst keyCols = [...(op.data._upsert_keys as string[])].sort();\n\t\t\t\tconst deltaCols = Object.keys(op.set ?? {}).sort();\n\t\t\t\tconst batchKey = `inc:${op.table}:${keyCols.join(\",\")}:${deltaCols.join(\",\")}`;\n\t\t\t\tif (batchKey !== incBatchKey || !incBatch) {\n\t\t\t\t\tflushIncrementBatch();\n\t\t\t\t\tincBatch = { table: op.table, keyCols, deltaCols, rows: new Map() };\n\t\t\t\t\tincBatchKey = batchKey;\n\t\t\t\t}\n\t\t\t\tconst clean = stripControlKeys(op.data);\n\t\t\t\tconst keySig = keyCols.map((k) => escapeLiteral(clean[k])).join(\"\\0\");\n\t\t\t\tconst existing = incBatch.rows.get(keySig);\n\t\t\t\tif (existing) {\n\t\t\t\t\tfor (const c of deltaCols) {\n\t\t\t\t\t\texisting.deltas[c] =\n\t\t\t\t\t\t\t(existing.deltas[c] ?? 0n) + toBigIntOr0(op.set?.[c]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst deltas: Record<string, bigint> = {};\n\t\t\t\t\tfor (const c of deltaCols) deltas[c] = toBigIntOr0(op.set?.[c]);\n\t\t\t\t\tincBatch.rows.set(keySig, {\n\t\t\t\t\t\tkeys: clean,\n\t\t\t\t\t\tdeltas,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\tblockHeight: op.data._block_height ?? this.block.height,\n\t\t\t\t\t\t\ttxId: op.data._tx_id ?? this._tx.txId,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Non-insert — flush any pending batches first\n\t\t\t\tflushInsertBatch();\n\t\t\t\tflushIncrementBatch();\n\n\t\t\t\tif (op.kind === \"update\") {\n\t\t\t\t\tconst setEntries = Object.entries(op.set ?? {});\n\t\t\t\t\tfor (const [k] of setEntries) validateColumnName(k);\n\t\t\t\t\tconst setClauses = setEntries.map(\n\t\t\t\t\t\t([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n\t\t\t\t\t);\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t`UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n\t\t\t\t\t);\n\t\t\t\t} else if (op.kind === \"delete\") {\n\t\t\t\t\tconst { clause } = buildWhereClause(op.data);\n\t\t\t\t\tif (this.journal) {\n\t\t\t\t\t\tstatements.push(this.journalCaptureByWhereSQL(op.table, clause));\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Flush any remaining batches\n\t\tflushInsertBatch();\n\t\tflushIncrementBatch();\n\n\t\treturn statements;\n\t}\n\n\tprivate validateTable(table: string): void {\n\t\tif (!this.subgraphSchema[table]) {\n\t\t\tthrow new Error(\n\t\t\t\t`Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// --- Helpers ---\n\n/** Drop internal upsert control keys from an op's data. */\nfunction stripControlKeys(\n\tdata: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst {\n\t\t_upsert_keys: _a,\n\t\t_upsert_fallback_keys: _b,\n\t\t_upsert_fallback_set: _c,\n\t\t...clean\n\t} = data;\n\treturn clean;\n}\n\n/** Loose value equality across bigint/number/string representations. */\nfunction valEq(a: unknown, b: unknown): boolean {\n\tif (a === b) return true;\n\tif (a == null || b == null) return false;\n\treturn String(a) === String(b);\n}\n\n/** Does `row` satisfy every column constraint in `where`? */\nfunction rowMatches(\n\trow: Record<string, unknown>,\n\twhere: Record<string, unknown>,\n): boolean {\n\treturn Object.entries(where).every(([k, v]) => valEq(row[k], v));\n}\n\nfunction toBigIntOr0(v: unknown): bigint {\n\tif (typeof v === \"bigint\") return v;\n\tif (v == null) return 0n;\n\ttry {\n\t\treturn BigInt(String(v));\n\t} catch {\n\t\treturn 0n;\n\t}\n}\n\n/** Coerce a row for JSON serialization — bigints become strings. */\nfunction jsonSafe(row: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(row)) {\n\t\tout[k] = typeof v === \"bigint\" ? v.toString() : v;\n\t}\n\treturn out;\n}\n\nfunction escapeLiteral(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\tif (typeof value === \"object\")\n\t\treturn `'${JSON.stringify(value, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v)).replace(/'/g, \"''\")}'::jsonb`;\n\t// String — escape single quotes\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n\tclause: string;\n\tvalues: unknown[];\n} {\n\tconst entries = Object.entries(where);\n\tif (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n\tfor (const [k] of entries) validateColumnName(k);\n\tconst parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n\treturn { clause: parts.join(\" AND \"), values: [] };\n}\n",
6
6
  "import { createHash } from \"node:crypto\";\nimport type {\n\tColumnType,\n\tSubgraphDefinition,\n\tSubgraphTable,\n} from \"../types.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n\ttext: \"TEXT\",\n\tuint: \"NUMERIC\",\n\tint: \"NUMERIC\",\n\tprincipal: \"TEXT\",\n\tboolean: \"BOOLEAN\",\n\ttimestamp: \"TIMESTAMPTZ\",\n\tjsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n\tstatements: string[];\n\thash: string;\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/** True if any column on the table uses full-text `search` (needs the pg_trgm\n * extension before its GIN index can be created). */\nexport function tableNeedsTrgm(tableDef: SubgraphTable): boolean {\n\treturn Object.values(tableDef.columns).some((col) => col.search);\n}\n\n/**\n * All per-table DDL for ONE table — create + meta/user/composite indexes + UNIQUE\n * constraints (NOT foreign keys; see {@link emitForeignKeyDDL}, emitted in a\n * second pass once every referenced table exists). Single-sourced so the full\n * generator and the deployer's additive-create path can't drift — a missing\n * UNIQUE or DEFAULT here would make a handler `upsert ON CONFLICT` fail at runtime.\n */\nexport function emitTableDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\tconst qualifiedName = `${schemaName}.${tableName}`;\n\tconst statements: string[] = [];\n\n\tconst columnDefs: string[] = [\n\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t];\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tconst sqlType = TYPE_MAP[col.type];\n\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\tlet colDef = `${colName} ${sqlType}${nullable}`;\n\t\tif (col.default !== undefined) {\n\t\t\tcolDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n\t\t}\n\t\t// uint is unsigned by definition — fail loudly instead of silently\n\t\t// storing a negative (fix-f040 B4). Handlers run in chain order, so a\n\t\t// legitimate same-block receive-then-spend never trips this.\n\t\tif (col.type === \"uint\") {\n\t\t\tcolDef += ` CHECK (${colName} >= 0)`;\n\t\t}\n\t\tcolumnDefs.push(colDef);\n\t}\n\tstatements.push(\n\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n\t);\n\n\t// Auto-indexes on meta columns.\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n\t);\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n\t);\n\n\t// Single-column indexes.\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.indexed) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Trigram GIN indexes for search columns.\n\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\tif (col.search) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Composite indexes.\n\tif (tableDef.indexes) {\n\t\tfor (let i = 0; i < tableDef.indexes.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.indexes[i]!;\n\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Unique constraints (required for upsert ON CONFLICT).\n\tif (tableDef.uniqueKeys) {\n\t\tfor (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tconst cols = tableDef.uniqueKeys[i]!;\n\t\t\tconst constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn statements;\n}\n\n/**\n * Per-schema revert journal. Before every keyed mutation (upsert / increment /\n * update / delete) the flush records the row's prior state; a reorg restores\n * those states instead of deleting whole rows by `_block_height` — which is\n * only correct for append-only tables, not accumulators (fix-f040 B2).\n * `prev_row IS NULL` marks a row first created by the journaled op.\n */\nexport function emitJournalDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._journal (\n _jid BIGSERIAL PRIMARY KEY,\n block_height BIGINT NOT NULL,\n table_name TEXT NOT NULL,\n row_key JSONB NOT NULL,\n prev_row JSONB,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_journal_height ON ${schemaName}._journal (block_height)`,\n\t];\n}\n\n/**\n * Storage for factory-discovered addresses.\n *\n * `block_height` is what makes the set reorg-scoped: the reorg handler\n * deletes rows at or above the fork alongside the data tables, so an address\n * revealed on an orphaned chain does not linger in the matcher forever\n * (the failure mode a set kept outside the rollback model would have).\n */\nexport function emitFactoryDDL(schemaName: string): string[] {\n\treturn [\n\t\t`CREATE TABLE IF NOT EXISTS ${schemaName}._factory_addresses (\n source_name TEXT NOT NULL,\n address TEXT NOT NULL,\n block_height BIGINT NOT NULL,\n _created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n PRIMARY KEY (source_name, address)\n)`,\n\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_factory_height ON ${schemaName}._factory_addresses (block_height)`,\n\t];\n}\n\n/** Foreign-key DDL for one table's relations. Emit AFTER every referenced table\n * exists; references require the target columns to be a UNIQUE key. */\nexport function emitForeignKeyDDL(\n\tschemaName: string,\n\ttableName: string,\n\ttableDef: SubgraphTable,\n): string[] {\n\treturn (tableDef.relations ?? []).map((rel) => {\n\t\tconst constraintName = `fk_${schemaName}_${tableName}_${rel.name}`;\n\t\treturn (\n\t\t\t`ALTER TABLE ${schemaName}.${tableName} ADD CONSTRAINT ${constraintName} ` +\n\t\t\t`FOREIGN KEY (${rel.fields.join(\", \")}) ` +\n\t\t\t`REFERENCES ${schemaName}.${rel.references} (${rel.referencedColumns.join(\", \")})`\n\t\t);\n\t});\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(\n\tdef: SubgraphDefinition,\n\tschemaNameOverride?: string,\n): GeneratedSQL {\n\tconst schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n\tconst statements: string[] = [];\n\n\t// Check if any column uses search (trigram)\n\tconst needsTrgm = Object.values(def.schema).some((table) =>\n\t\tObject.values(table.columns).some((col) => col.search),\n\t);\n\n\tif (needsTrgm) {\n\t\tstatements.push(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\");\n\t}\n\n\t// Schema namespace\n\tstatements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n\t// One table per schema entry (single-sourced per-table DDL).\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitTableDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Revert journal (one per schema) — see emitJournalDDL.\n\tstatements.push(...emitJournalDDL(schemaName));\n\t// Only when a source actually uses a factory — no dead table otherwise.\n\tif (\n\t\tObject.values(def.sources ?? {}).some(\n\t\t\t(src) => (src as { factory?: unknown }).factory !== undefined,\n\t\t)\n\t) {\n\t\tstatements.push(...emitFactoryDDL(schemaName));\n\t}\n\n\t// Foreign keys are added in a second pass so every referenced table exists.\n\t// These mirror the ORM relations emitted by the codegen (no drift) and require\n\t// the referenced columns to be a UNIQUE key on the target table.\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tstatements.push(...emitForeignKeyDDL(schemaName, tableName, tableDef));\n\t}\n\n\t// Hash based on schema structure only — version intentionally excluded\n\t// so server-managed version bumps don't look like schema changes\n\tconst hashInput = JSON.stringify(\n\t\t{\n\t\t\tname: def.name,\n\t\t\tschema: def.schema,\n\t\t\tsources: def.sources,\n\t\t},\n\t\t(_key, value) => (typeof value === \"bigint\" ? value.toString() : value),\n\t);\n\t// node crypto (not Bun.hash) so the published node-runtime `sl` CLI can\n\t// compute schema hashes too (e.g. `sl subgraphs spec`).\n\tconst hash = createHash(\"sha256\").update(hashInput).digest(\"hex\");\n\n\treturn { statements, hash };\n}\n",
7
7
  "// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n",
8
+ "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Database } from \"@secondlayer/shared/db/schema\";\nimport { http, createPublicClient } from \"@secondlayer/stacks\";\nimport {\n\tContractResponseError,\n\ttype UnwrapResponse,\n\tbuildFunctionArgs,\n\tisResponseOutput,\n\treadContract,\n} from \"@secondlayer/stacks/actions\";\nimport type { ClarityValue } from \"@secondlayer/stacks/clarity\";\nimport type {\n\tAbiContract,\n\tAbiFunction,\n\tAbiType,\n\tExtractFunctionArgs,\n\tExtractFunctionOutput,\n\tExtractReadOnlyFunctions,\n\tToCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport {\n\tclarityValueToJSUntyped,\n\tdeserializeCV,\n\tnormalizeAbi,\n\tserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type { Kysely } from \"kysely\";\n\n/**\n * How long a read stays valid.\n *\n * - `per-block` (default): pinned to the block being processed, cached under\n * its `index_block_hash`. Sound for any read-only function — reindexing the\n * same block always returns the same value, and a reorg-replaced block has a\n * different id so it can't inherit the orphaned answer.\n * - `contract-constant`: the caller asserts the value cannot change for this\n * contract and these args (SIP-010 `get-decimals`/`get-symbol`), so it is\n * resolved ONCE instead of once per block. This is the mode that makes a\n * backfill affordable — under `per-block` every block is a distinct key and\n * therefore a distinct RPC. Declaring it on a value that does change pins the\n * first answer forever, so it is opt-in and never inferred.\n */\nexport type ChainReadCacheMode = \"per-block\" | \"contract-constant\";\n\nexport type ChainReadOptions = { cache?: ChainReadCacheMode };\n\n/**\n * The chain-read surface, fully typed by an ABI.\n *\n * Shaped like `getContract` from `@secondlayer/stacks` — the same ABI in, the\n * same camelCased read methods out — minus `call`/`buildCall`: a handler\n * indexes the chain, it never writes to it.\n *\n * Reached through {@link readContractAt} rather than off `ctx.client`\n * directly: an ABI-generic method living on the context interface makes every\n * structural comparison of a subgraph definition instantiate it, which exceeds\n * TS's depth budget. At a call site the ABI is already concrete and it costs\n * nothing.\n */\nexport interface ChainReadClient {\n\t/**\n\t * Read-only methods of a contract, evaluated against the exact block being\n\t * processed.\n\t *\n\t * Every call is pinned to the block's `index_block_hash`, so a handler is a\n\t * pure function of its block: reindexing a range produces byte-identical\n\t * rows. Reading at the node's tip instead would make the same reindex\n\t * return different values — that is the corruption this refuses to allow,\n\t * so a block whose id was never persisted throws rather than falling back.\n\t *\n\t * Results are memoized in Postgres, so a value is fetched once per block\n\t * rather than once per event (or once per contract with\n\t * `cache: \"contract-constant\"`).\n\t */\n\tcontract<const C extends AbiContract>(\n\t\tcontractId: string,\n\t\tabi: C,\n\t\toptions?: ChainReadOptions,\n\t): { read: ChainReadMethods<C> };\n}\n\n/**\n * The camelCased read methods of an ABI. Spelled out rather than reused from\n * `ContractInstance<C>[\"read\"]`: that type is a conditional over the codegen\n * brand, and evaluating it wherever a subgraph definition is structurally\n * compared pushes TS past its instantiation depth.\n */\nexport type ChainReadMethods<C extends AbiContract> = {\n\t[N in ExtractReadOnlyFunctions<C> as ToCamelCase<N>]: (\n\t\targs: ExtractFunctionArgs<C, N>,\n\t) => Promise<UnwrapResponse<ExtractFunctionOutput<C, N>>>;\n};\n\n/**\n * `ChainReadClient` with the ABI generic erased. Structurally cheap, so the\n * base `SubgraphContext` can carry it; `TypedSubgraphContext` uses the real\n * one and handlers get full inference.\n */\nexport interface ErasedChainReadClient {\n\t// `abi: unknown`, not `AbiContract`: naming the ABI type here drags its\n\t// (deeply recursive) definition into every structural comparison of a\n\t// subgraph definition. `readContractAt` constrains it properly.\n\tcontract(\n\t\tcontractId: string,\n\t\tabi: unknown,\n\t\toptions?: ChainReadOptions,\n\t): {\n\t\tread: Record<string, (args?: Record<string, unknown>) => Promise<unknown>>;\n\t};\n}\n\n/**\n * Typed read methods for one contract, from a handler.\n *\n * ```ts\n * const token = readContractAt(ctx, contractId, SIP010_ABI, {\n * cache: \"contract-constant\",\n * });\n * const decimals = await token.read.getDecimals({}); // bigint\n * ```\n */\nexport function readContractAt<const C extends AbiContract>(\n\tctx: { client: ErasedChainReadClient },\n\tcontractId: string,\n\tabi: C,\n\toptions?: ChainReadOptions,\n): { read: ChainReadMethods<C> } {\n\treturn ctx.client.contract(contractId, abi, options) as unknown as {\n\t\tread: ChainReadMethods<C>;\n\t};\n}\n\nexport class ChainReadError extends Error {\n\toverride name = \"ChainReadError\";\n}\n\n/**\n * Node transport for handler reads. Deliberately its own client rather than a\n * shared singleton: `retryCount: 0` keeps a slow node from multiplying into the\n * block's retry budget (`processBlockWithRetry` already owns retries), and the\n * concurrency gate below bounds how much of a backfill can hit the node at once.\n */\nfunction nodeClient(rpcUrl: string) {\n\treturn createPublicClient({\n\t\ttransport: http(rpcUrl, { retryCount: 0, timeout: 10_000 }),\n\t});\n}\n\n/**\n * Cap concurrent node reads across all handlers in this process. A handler that\n * reads on every event turns a 100-block batch into thousands of in-flight\n * requests otherwise — enough to knock over the node the indexer depends on.\n */\nclass ConcurrencyGate {\n\tprivate active = 0;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(private readonly limit: number) {}\n\n\tasync run<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (this.active >= this.limit) {\n\t\t\tawait new Promise<void>((resolve) => this.queue.push(resolve));\n\t\t}\n\t\tthis.active++;\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tthis.active--;\n\t\t\tthis.queue.shift()?.();\n\t\t}\n\t}\n}\n\nconst DEFAULT_MAX_CONCURRENT_READS = 4;\n\nfunction maxConcurrentReads(): number {\n\tconst raw = process.env.SUBGRAPH_CHAIN_READ_CONCURRENCY;\n\tconst parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;\n\treturn Number.isFinite(parsed) && parsed > 0\n\t\t? parsed\n\t\t: DEFAULT_MAX_CONCURRENT_READS;\n}\n\nconst gate = new ConcurrencyGate(maxConcurrentReads());\n\n/** Stable key for an arg set — property order must not fork a cache entry. */\nfunction hashArgs(args: readonly ClarityValue[]): string {\n\tconst serialized = args.map((arg) => serializeCV(arg)).join(\",\");\n\treturn Bun.hash(serialized).toString(16);\n}\n\nfunction findFunction(abi: AbiContract, name: string): AbiFunction {\n\tconst fn = abi.functions.find((f) => f.name === name) as\n\t\t| AbiFunction\n\t\t| undefined;\n\tif (!fn) {\n\t\tthrow new ChainReadError(`No function \"${name}\" in the supplied ABI.`);\n\t}\n\tif (fn.access !== \"read-only\") {\n\t\tthrow new ChainReadError(\n\t\t\t`\"${name}\" is ${fn.access}, not read-only — a handler cannot call it.`,\n\t\t);\n\t}\n\treturn fn;\n}\n\nexport type ChainReadContext = {\n\tblockHeight: number;\n\tindexBlockHash: string | null | undefined;\n\trpcUrl?: string;\n\tdb?: Kysely<Database>;\n};\n\n/**\n * Build the `ctx.client` surface for one block. Generic lives on the METHOD,\n * not here, so a handler's ABI narrows per call without infecting\n * `SubgraphContext` with a type parameter.\n */\n/**\n * Build the `ctx.client` surface for one block. The ABI generic lives on\n * `contract()`, not here, so a handler's types narrow per contract without\n * `SubgraphContext` carrying a type parameter.\n */\nexport function createChainReadClient(ctx: ChainReadContext): ChainReadClient {\n\t// The ABI generic is erased inside the implementation on purpose:\n\t// re-resolving `ExtractFunctionArgs` against an unfixed type parameter is\n\t// what pushes TS past its instantiation depth on a real-sized ABI.\n\tconst readValue = async (\n\t\tcontractId: string,\n\t\tabi: AbiContract,\n\t\tfunctionName: string,\n\t\targs: Record<string, unknown>,\n\t\toptions: ChainReadOptions,\n\t): Promise<unknown> => {\n\t\tconst rpcUrl = ctx.rpcUrl ?? process.env.STACKS_NODE_RPC_URL;\n\t\tif (!rpcUrl) {\n\t\t\tthrow new ChainReadError(\n\t\t\t\t\"ctx.client needs a Stacks node: set STACKS_NODE_RPC_URL on the subgraph processor.\",\n\t\t\t);\n\t\t}\n\n\t\tconst constant = options.cache === \"contract-constant\";\n\t\tif (!constant && !ctx.indexBlockHash) {\n\t\t\tthrow new ChainReadError(\n\t\t\t\t`Block ${ctx.blockHeight} has no index_block_hash, so a read cannot be pinned to it. Reading at the node's tip would make this handler non-deterministic (the same reindex would produce different rows). Re-ingest the block, or pass cache: \"contract-constant\" if the value genuinely cannot change.`,\n\t\t\t);\n\t\t}\n\n\t\tconst fn = findFunction(abi, functionName);\n\t\tconst clarityArgs = buildFunctionArgs(fn, args);\n\t\tconst db = ctx.db ?? getSourceDb();\n\t\tconst argsHash = hashArgs(clarityArgs);\n\t\tconst pinnedTo = constant ? null : (ctx.indexBlockHash as string);\n\n\t\tconst cached = await db\n\t\t\t.selectFrom(\"chain_read_cache\")\n\t\t\t.select(\"result_hex\")\n\t\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t\t.where(\"function_name\", \"=\", fn.name)\n\t\t\t.where(\"args_hash\", \"=\", argsHash)\n\t\t\t.where((eb) =>\n\t\t\t\tpinnedTo === null\n\t\t\t\t\t? eb(\"index_block_hash\", \"is\", null)\n\t\t\t\t\t: eb(\"index_block_hash\", \"=\", pinnedTo),\n\t\t\t)\n\t\t\t.executeTakeFirst();\n\n\t\tconst resultHex =\n\t\t\tcached?.result_hex ??\n\t\t\t(await gate.run(async () => {\n\t\t\t\tconst value = await readContract(nodeClient(rpcUrl), {\n\t\t\t\t\tcontract: contractId,\n\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\targs: clarityArgs,\n\t\t\t\t\t// A constant read still pins to this block: \"cannot change\"\n\t\t\t\t\t// is a claim about future blocks, not a license to read a\n\t\t\t\t\t// tip that may be ahead of the one being processed.\n\t\t\t\t\ttip: ctx.indexBlockHash ?? undefined,\n\t\t\t\t});\n\t\t\t\treturn serializeCV(value);\n\t\t\t}));\n\n\t\tif (!cached) {\n\t\t\tawait db\n\t\t\t\t.insertInto(\"chain_read_cache\")\n\t\t\t\t.values({\n\t\t\t\t\tcontract_id: contractId,\n\t\t\t\t\tfunction_name: fn.name,\n\t\t\t\t\targs_hash: argsHash,\n\t\t\t\t\tindex_block_hash: pinnedTo,\n\t\t\t\t\tblock_height: constant ? null : ctx.blockHeight,\n\t\t\t\t\tresult_hex: resultHex,\n\t\t\t\t})\n\t\t\t\t// Two handlers in the same batch can race to the same key; the\n\t\t\t\t// value is identical either way, so the loser keeps its own.\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst value = deserializeCV(resultHex);\n\t\tconst js = clarityValueToJSUntyped(fn.outputs as AbiType, value);\n\n\t\tif (isResponseOutput(fn.outputs as AbiType)) {\n\t\t\tconst response = js as { ok?: unknown; err?: unknown };\n\t\t\tif (\"ok\" in response) return response.ok;\n\t\t\tthrow new ContractResponseError(\n\t\t\t\t`${contractId}::${fn.name} returned an err response.`,\n\t\t\t\tresponse.err,\n\t\t\t);\n\t\t}\n\t\treturn js;\n\t};\n\n\treturn {\n\t\tcontract(contractId: string, rawAbi: AbiContract, options = {}) {\n\t\t\t// Accept a raw Hiro/Clarinet ABI as well as a normalized one — raw\n\t\t\t// ABIs wrap `outputs` as `{ type: … }`, which the JS bridge can't read.\n\t\t\tconst abi = normalizeAbi(rawAbi);\n\t\t\tconst camelToKebab = new Map<string, string>();\n\t\t\tfor (const fn of abi.functions) {\n\t\t\t\tcamelToKebab.set(toCamelCase(fn.name), fn.name);\n\t\t\t}\n\n\t\t\tconst read = new Proxy(\n\t\t\t\t{},\n\t\t\t\t{\n\t\t\t\t\tget(_target, prop: string) {\n\t\t\t\t\t\tconst fnName = camelToKebab.get(prop) ?? prop;\n\t\t\t\t\t\treturn (args: Record<string, unknown> = {}) =>\n\t\t\t\t\t\t\treadValue(contractId, abi, fnName, args, options);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn { read } as never;\n\t\t},\n\t};\n}\n",
8
9
  "import { cvToValue, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n\ttry {\n\t\tconst cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\tconst cv = deserializeCV(cleanHex);\n\t\treturn cvToValue(cv);\n\t} catch {\n\t\treturn hex;\n\t}\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n\tif (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n\t\treturn decodeClarityValue(data);\n\t}\n\n\tif (Array.isArray(data)) {\n\t\treturn data.map(decodeEventData);\n\t}\n\n\tif (typeof data === \"object\" && data !== null) {\n\t\tconst decoded: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tdecoded[key] = decodeEventData(value);\n\t\t}\n\t\treturn decoded;\n\t}\n\n\treturn data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n\treturn args.map(decodeClarityValue);\n}\n",
9
10
  "import { getErrorMessage } from \"@secondlayer/shared\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport {\n\tclarityValueToJS,\n\tdeserializeCV,\n\ttoCamelCase,\n} from \"@secondlayer/stacks/clarity\";\nimport type {\n\tContractCallFilter,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n} from \"../types.ts\";\nimport { decodeClarityValue, decodeEventData } from \"./clarity.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport { validatePrintPayload } from \"./print-validate.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n\tprocessed: number;\n\terrors: number;\n\t/** Print events skipped because their decoded payload did not match the\n\t * source's declared `prints` schema. Never an error: skipping keeps the\n\t * block committable, which the checkpoint model requires. */\n\tskipped?: number;\n}\n\n/** Convert kebab-case to camelCase: \"bitcoin-txid\" → \"bitcoinTxid\" */\nfunction camelCase(str: string): string {\n\treturn str.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());\n}\n\n/** Recursively camelize all object keys */\nfunction camelizeKeys(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj;\n\tif (typeof obj !== \"object\") return obj;\n\tif (Array.isArray(obj)) return obj.map(camelizeKeys);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n\t\tresult[camelCase(k)] = camelizeKeys(v);\n\t}\n\treturn result;\n}\n\n/**\n * Decode function_args (hex-encoded ClarityValues) to an array of JS values.\n * Returns decoded values via cvToValue.\n *\n * postgres.js returns JSONB columns as JSON strings rather than parsed objects —\n * parse the string first before checking Array.isArray.\n */\nfunction decodeFunctionArgs(args: unknown): unknown[] {\n\tlet parsed = args;\n\tif (typeof parsed === \"string\") {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.map((arg) => {\n\t\tif (typeof arg === \"string\") return decodeClarityValue(arg);\n\t\treturn arg;\n\t});\n}\n\n/**\n * Decode raw_result (hex-encoded Clarity return value) to JS value.\n */\nfunction decodeRawResult(raw: unknown): unknown {\n\tif (typeof raw === \"string\" && raw.length > 2) {\n\t\treturn decodeClarityValue(raw);\n\t}\n\treturn null;\n}\n\n/** Safely convert a value to BigInt. Handles string, number, bigint. Returns 0n on failure. */\nfunction safeBigInt(val: unknown): bigint {\n\tif (typeof val === \"bigint\") return val;\n\tif (typeof val === \"number\") return BigInt(val);\n\tif (typeof val === \"string\") {\n\t\ttry {\n\t\t\treturn BigInt(val);\n\t\t} catch {\n\t\t\treturn 0n;\n\t\t}\n\t}\n\treturn 0n;\n}\n\n/**\n * Build the named, ABI-decoded `event.input` for a contract_call source that\n * declares an `abi`. Each function arg is decoded via `clarityValueToJS` so the\n * values match the types `ExtractFunctionArgs` promises (Uint8Array buffers,\n * camelCase tuple keys, wrapped responses). Returns undefined when no abi /\n * function match, leaving handlers with the positional `args` only.\n */\nexport function buildContractCallInput(\n\tfilter: ContractCallFilter,\n\ttx: MatchedTx[\"tx\"],\n): Record<string, unknown> | undefined {\n\tconst abi = filter.abi;\n\tconst fnName = tx.function_name;\n\tif (!abi || !fnName) return undefined;\n\tconst fn = abi.functions?.find((f) => f.name === fnName);\n\tif (!fn || !Array.isArray(fn.args)) return undefined;\n\n\tlet rawArgs: unknown = tx.function_args;\n\tif (typeof rawArgs === \"string\") {\n\t\ttry {\n\t\t\trawArgs = JSON.parse(rawArgs);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (!Array.isArray(rawArgs)) return undefined;\n\n\t// Call through a non-generic cast: clarityValueToJS<T> instantiates the deep\n\t// AbiToTS<T> conditional (TS2589) at runtime call sites. The static types\n\t// come from ContractCallPayload; here we only need its runtime reshaping.\n\tconst decodeArg = clarityValueToJS as unknown as (\n\t\ttype: unknown,\n\t\tcv: unknown,\n\t) => unknown;\n\tconst input: Record<string, unknown> = {};\n\tfn.args.forEach((arg, i) => {\n\t\tconst hex = rawArgs[i];\n\t\tif (typeof hex !== \"string\") return;\n\t\ttry {\n\t\t\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\t\t\tinput[toCamelCase(arg.name)] = decodeArg(arg.type, deserializeCV(clean));\n\t\t} catch {\n\t\t\t// Skip args that fail to decode rather than dropping the whole event.\n\t\t}\n\t});\n\treturn input;\n}\n\n/**\n * Build a typed event payload based on the source filter type.\n * Returns the payload the handler will receive.\n */\nexport function buildEventPayload(\n\tfilter: SubgraphFilter,\n\ttx: MatchedTx[\"tx\"],\n\tevent: MatchedTx[\"events\"][0] | null,\n): Record<string, unknown> {\n\tconst txMeta = {\n\t\ttxId: tx.tx_id,\n\t\tsender: tx.sender,\n\t\ttype: tx.type,\n\t\tstatus: tx.status,\n\t\tcontractId: tx.contract_id ?? null,\n\t\tfunctionName: tx.function_name ?? null,\n\t};\n\n\t// Decoded function args + result for contract_call payloads\n\tconst decodedArgs = decodeFunctionArgs(tx.function_args);\n\tconst decodedResult = decodeRawResult(tx.raw_result);\n\n\t// No event — tx-level match (contract_call or contract_deploy)\n\tif (!event) {\n\t\tswitch (filter.type) {\n\t\t\tcase \"contract_call\": {\n\t\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"contract_call\",\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\targs: decodedArgs,\n\t\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\t\tresult: decodedResult,\n\t\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"contract_deploy\":\n\t\t\t\treturn {\n\t\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\t\tdeployer: tx.sender,\n\t\t\t\t\ttx: txMeta,\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn { tx: txMeta };\n\t\t}\n\t}\n\n\t// Decode event data (Clarity values auto-unwrapped via cvToValue)\n\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\n\tswitch (filter.type) {\n\t\t// ── FT events ──\n\t\tcase \"ft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"ft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── NFT events ──\n\t\t// tokenId decodes from the canonical hex (`raw_value`), not the node's\n\t\t// verbose serde-tagged `value` (`{UInt:223}`). The hex is source-\n\t\t// independent — present in both the DB tap and the Index API — so a\n\t\t// subgraph yields the same clean tokenId (e.g. 223n) on either source.\n\t\tcase \"nft_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"nft_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\ttokenId: decoded.raw_value ?? decoded.value,\n\t\t\t\tassetIdentifier: decoded.asset_identifier as string,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── STX events ──\n\t\tcase \"stx_transfer\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\tmemo: decoded.memo ?? \"\",\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_mint\":\n\t\t\treturn {\n\t\t\t\trecipient: decoded.recipient as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_burn\":\n\t\t\treturn {\n\t\t\t\tsender: decoded.sender as string,\n\t\t\t\tamount: safeBigInt(decoded.amount),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\tcase \"stx_lock\":\n\t\t\treturn {\n\t\t\t\tlockedAddress: decoded.locked_address as string,\n\t\t\t\tlockedAmount: safeBigInt(decoded.locked_amount),\n\t\t\t\tunlockHeight: safeBigInt(decoded.unlock_height),\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\t// ── Print event ──\n\t\tcase \"print_event\": {\n\t\t\t// Decode the print value from the canonical hex (`raw_value`) so it's\n\t\t\t// source-independent and clean — the node's verbose serde-tagged\n\t\t\t// `value` (e.g. `{Optional:{data:null}}`) is not reproducible from the\n\t\t\t// Index API and is no longer used (same rationale as nft tokenId).\n\t\t\t// decodeEventData skips hex ≤10 chars, so decode `raw_value` directly.\n\t\t\tconst rawHex = (event.data as Record<string, unknown> | null)?.raw_value;\n\t\t\tconst rawValue =\n\t\t\t\ttypeof rawHex === \"string\" && rawHex.startsWith(\"0x\")\n\t\t\t\t\t? decodeClarityValue(rawHex)\n\t\t\t\t\t: decoded.value;\n\t\t\t// Extract topic from decoded Clarity value (not raw event topic which is always \"print\")\n\t\t\tconst clarityObj =\n\t\t\t\trawValue && typeof rawValue === \"object\" && !Array.isArray(rawValue)\n\t\t\t\t\t? (rawValue as Record<string, unknown>)\n\t\t\t\t\t: null;\n\t\t\tconst topic = clarityObj?.topic\n\t\t\t\t? String(clarityObj.topic)\n\t\t\t\t: ((decoded.topic as string) ?? \"\");\n\t\t\t// Camelize remaining keys for developer convenience\n\t\t\tconst { topic: _, ...rest } = clarityObj ?? {};\n\t\t\tconst data =\n\t\t\t\tObject.keys(rest).length > 0\n\t\t\t\t\t? (camelizeKeys(rest) as Record<string, unknown>)\n\t\t\t\t\t: rawValue && typeof rawValue !== \"object\"\n\t\t\t\t\t\t? rawValue\n\t\t\t\t\t\t: {};\n\t\t\treturn {\n\t\t\t\tcontractId:\n\t\t\t\t\t(decoded.contract_identifier as string) ?? tx.contract_id ?? \"\",\n\t\t\t\ttopic,\n\t\t\t\tdata: data ?? {},\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract call (with events) ──\n\t\tcase \"contract_call\": {\n\t\t\t// Normalize the spread event Clarity `value` to the decoded canonical\n\t\t\t// (from `raw_value`), so it's identical whether the event came from the\n\t\t\t// DB tap or the Index API — the node's serde-tagged `value` is not\n\t\t\t// reproducible from Index (same rationale as nft tokenId / print).\n\t\t\tconst ccRawHex = (event.data as Record<string, unknown> | null)\n\t\t\t\t?.raw_value;\n\t\t\tconst normalized =\n\t\t\t\ttypeof ccRawHex === \"string\" && ccRawHex.startsWith(\"0x\")\n\t\t\t\t\t? { ...decoded, value: decodeClarityValue(ccRawHex) }\n\t\t\t\t\t: decoded;\n\t\t\tconst input = buildContractCallInput(filter, tx);\n\t\t\treturn {\n\t\t\t\t...normalized,\n\t\t\t\ttype: \"contract_call\",\n\t\t\t\t_eventType: event.type,\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tfunctionName: tx.function_name ?? \"\",\n\t\t\t\tsender: tx.sender,\n\t\t\t\targs: decodedArgs,\n\t\t\t\t...(input !== undefined ? { input } : {}),\n\t\t\t\tresult: decodedResult,\n\t\t\t\tresultHex: tx.raw_result ?? null,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t\t}\n\n\t\t// ── Contract deploy ──\n\t\tcase \"contract_deploy\":\n\t\t\treturn {\n\t\t\t\tcontractId: tx.contract_id ?? \"\",\n\t\t\t\tdeployer: tx.sender,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\n\t\tdefault:\n\t\t\t// Fallback: spread decoded data with tx metadata\n\t\t\treturn {\n\t\t\t\t...decoded,\n\t\t\t\t_eventType: event.type,\n\t\t\t\ttx: txMeta,\n\t\t\t};\n\t}\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceName from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n\tsubgraph: SubgraphDefinition,\n\tmatched: MatchedTx[],\n\tctx: SubgraphContext,\n\topts?: { errorThreshold?: number },\n): Promise<RunResult> {\n\tlet processed = 0;\n\tlet errors = 0;\n\tlet skipped = 0;\n\tconst threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n\t// Build filter lookup from sources (supports both array and named object)\n\tconst filterLookup = new Map<string, SubgraphFilter>();\n\tif (!Array.isArray(subgraph.sources)) {\n\t\tfor (const [name, filter] of Object.entries(\n\t\t\tsubgraph.sources as Record<string, SubgraphFilter>,\n\t\t)) {\n\t\t\tfilterLookup.set(name, filter);\n\t\t}\n\t}\n\n\t// Flatten matches to per-event dispatch units and sort into CHAIN order\n\t// (tx_index, then event_index; tx-level matches first within their tx).\n\t// The matcher groups results by source, so without this a block's mints\n\t// all run before (or after) its transfers — a debit could apply before\n\t// the same block's funding credit, which on-chain ordering forbids. Chain\n\t// order makes per-statement invariants (e.g. uint CHECK >= 0) sound.\n\ttype DispatchUnit = {\n\t\ttx: MatchedTx[\"tx\"];\n\t\tsourceName: string;\n\t\tevent: MatchedTx[\"events\"][0] | null;\n\t};\n\tconst units: DispatchUnit[] = [];\n\tfor (const { tx, events, sourceName } of matched) {\n\t\tif (events.length === 0) {\n\t\t\tunits.push({ tx, sourceName, event: null });\n\t\t} else {\n\t\t\tfor (const event of events) units.push({ tx, sourceName, event });\n\t\t}\n\t}\n\tunits.sort(\n\t\t(a, b) =>\n\t\t\t(a.tx.tx_index ?? 0) - (b.tx.tx_index ?? 0) ||\n\t\t\t(a.event?.event_index ?? -1) - (b.event?.event_index ?? -1),\n\t);\n\n\tfor (const { tx, event, sourceName } of units) {\n\t\tif (errors >= threshold) {\n\t\t\tlogger.error(\n\t\t\t\t\"Subgraph error threshold reached, skipping remaining events\",\n\t\t\t\t{\n\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\terrors,\n\t\t\t\t\tthreshold,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n\t\t}\n\n\t\tconst handler =\n\t\t\tsubgraph.handlers[sourceName] ?? subgraph.handlers[\"*\"] ?? null;\n\t\tif (!handler) {\n\t\t\tlogger.warn(\"No handler found for source\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tctx.setTx({\n\t\t\ttxId: tx.tx_id,\n\t\t\tsender: tx.sender,\n\t\t\ttype: tx.type,\n\t\t\tstatus: tx.status,\n\t\t\tcontractId: tx.contract_id ?? null,\n\t\t\tfunctionName: tx.function_name ?? null,\n\t\t});\n\n\t\tconst filter = filterLookup.get(sourceName);\n\n\t\t// Checkpoint the ops queue: a handler that throws mid-way must\n\t\t// contribute nothing — a partial flush (e.g. a debit without its\n\t\t// credit) silently corrupts accumulator tables (fix-f040 B6).\n\t\tconst checkpoint = ctx.opsCheckpoint();\n\t\ttry {\n\t\t\tlet payload: Record<string, unknown>;\n\t\t\tif (event === null) {\n\t\t\t\t// Tx-level match (contract_call / contract_deploy)\n\t\t\t\tpayload = filter\n\t\t\t\t\t? buildEventPayload(filter, tx, null)\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttx: {\n\t\t\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t} else if (filter) {\n\t\t\t\tpayload = buildEventPayload(filter, tx, event);\n\t\t\t} else {\n\t\t\t\tconst decoded = decodeEventData(event.data) as Record<string, unknown>;\n\t\t\t\tpayload = {\n\t\t\t\t\t...decoded,\n\t\t\t\t\t_eventId: event.id,\n\t\t\t\t\t_eventType: event.type,\n\t\t\t\t\t_eventIndex: event.event_index,\n\t\t\t\t\ttx: {\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\tsender: tx.sender,\n\t\t\t\t\t\ttype: tx.type,\n\t\t\t\t\t\tstatus: tx.status,\n\t\t\t\t\t\tcontractId: tx.contract_id,\n\t\t\t\t\t\tfunctionName: tx.function_name,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Post-decode topic filter for print_event — source-matcher defers this\n\t\t\t// because data.value is raw hex at match time; apply it now after decode.\n\t\t\tif (\n\t\t\t\tevent !== null &&\n\t\t\t\tfilter?.type === \"print_event\" &&\n\t\t\t\tfilter.topic &&\n\t\t\t\tpayload.topic !== filter.topic\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Declared `prints` is the developer's stated payload shape, so a\n\t\t\t// mismatch is a real defect (a contract upgrade, or a declaration\n\t\t\t// that never matched — the bns-names class, where every event\n\t\t\t// decoded to null for an entire deploy). Skip + log rather than\n\t\t\t// write nulls; never throw, which would wedge the block.\n\t\t\tif (event !== null && filter?.type === \"print_event\" && filter.prints) {\n\t\t\t\tconst printPayload = payload as {\n\t\t\t\t\ttopic?: string;\n\t\t\t\t\tdata?: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst verdict = validatePrintPayload(\n\t\t\t\t\tfilter.prints,\n\t\t\t\t\tprintPayload.topic ?? \"\",\n\t\t\t\t\tprintPayload.data ?? {},\n\t\t\t\t);\n\t\t\t\tif (!verdict.ok) {\n\t\t\t\t\tskipped++;\n\t\t\t\t\tlogger.warn(\"Print payload does not match declared prints schema\", {\n\t\t\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\t\t\tsourceName,\n\t\t\t\t\t\ttopic: printPayload.topic,\n\t\t\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t\t\treason: verdict.reason,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait handler(payload, ctx);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\tctx.rollbackTo(checkpoint);\n\t\t\terrors++;\n\t\t\tlogger.error(\"Subgraph handler error\", {\n\t\t\t\tsubgraph: subgraph.name,\n\t\t\t\tsourceName,\n\t\t\t\ttxId: tx.tx_id,\n\t\t\t\t...(event !== null ? { eventId: event.id, eventType: event.type } : {}),\n\t\t\t\terror: getErrorMessage(err),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { processed, errors, ...(skipped > 0 ? { skipped } : {}) };\n}\n",
10
11
  "import type { ColumnType, PrintField } from \"../types.ts\";\n\n/**\n * Runtime validation of a decoded print payload against a source's declared\n * `prints` schema.\n *\n * Declaring `prints` is the opt-in that makes strictness safe: the developer\n * has stated the shape, so a mismatch is a real defect (a contract upgrade,\n * or a hand-written declaration that never matched — the bns-names class of\n * bug, where a handler read flat `data.name` while BNS-V2 emitted a nested\n * tuple, and every event silently decoded to null for a whole deploy).\n *\n * Failure mode is SKIP + LOG, never throw: throwing would fail the block, and\n * a poisoned block that can never advance is incompatible with the\n * checkpoint model. One bad event is dropped and counted; the rest of the\n * block commits.\n */\n\nconst COLUMN_TYPES = new Set<string>([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nfunction isColumnType(field: PrintField): field is ColumnType {\n\treturn typeof field === \"string\" && COLUMN_TYPES.has(field);\n}\n\n/** Does a decoded value match one declared field? */\nfunction matchesField(field: PrintField, value: unknown): boolean {\n\tif (isColumnType(field)) {\n\t\tswitch (field) {\n\t\t\tcase \"uint\":\n\t\t\tcase \"int\":\n\t\t\t\treturn typeof value === \"bigint\" || typeof value === \"number\";\n\t\t\tcase \"boolean\":\n\t\t\t\treturn typeof value === \"boolean\";\n\t\t\tcase \"text\":\n\t\t\tcase \"principal\":\n\t\t\tcase \"timestamp\":\n\t\t\t\t// Buffers decode to strings; principals too. Accept any scalar the\n\t\t\t\t// decoder can render, but reject objects/arrays.\n\t\t\t\treturn (\n\t\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\t\ttypeof value === \"bigint\"\n\t\t\t\t);\n\t\t\tcase \"jsonb\":\n\t\t\t\t// Deliberately permissive: `jsonb` is the \"shape unknown\" escape.\n\t\t\t\treturn value !== undefined;\n\t\t}\n\t}\n\tif (typeof field !== \"object\" || field === null) return false;\n\tif (\"optional\" in field) {\n\t\treturn (\n\t\t\tvalue === undefined || value === null || matchesField(field.type, value)\n\t\t);\n\t}\n\tif (\"tuple\" in field) {\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn matchesTopic(field.tuple, value as Record<string, unknown>).ok;\n\t}\n\tif (\"list\" in field) {\n\t\treturn (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.every((item) => matchesField(field.list, item))\n\t\t);\n\t}\n\treturn false;\n}\n\nexport type PrintValidationResult =\n\t| { ok: true }\n\t| { ok: false; reason: string };\n\n/** Validate a decoded payload object against one topic's declared fields. */\nexport function matchesTopic(\n\tdeclared: Record<string, PrintField>,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tfor (const [name, field] of Object.entries(declared)) {\n\t\tconst present = name in data;\n\t\tconst optional =\n\t\t\ttypeof field === \"object\" && field !== null && \"optional\" in field;\n\t\tif (!present) {\n\t\t\tif (optional) continue;\n\t\t\treturn { ok: false, reason: `missing declared field \"${name}\"` };\n\t\t}\n\t\tif (!matchesField(field, data[name])) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: `field \"${name}\" does not match its declared type (got ${describe(data[name])})`,\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"array\";\n\treturn typeof value;\n}\n\n/**\n * Validate one decoded print event against a source's `prints` declaration.\n * Returns `{ ok: true }` when no declaration covers this topic (undeclared\n * topics are not the developer's stated contract, so they pass through).\n */\nexport function validatePrintPayload(\n\tprints: Record<string, Record<string, PrintField>> | undefined,\n\ttopic: string,\n\tdata: Record<string, unknown>,\n): PrintValidationResult {\n\tif (!prints) return { ok: true };\n\tconst declared = prints[topic];\n\tif (!declared) return { ok: true };\n\treturn matchesTopic(declared, data);\n}\n",
11
12
  "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\tevent_index: number;\n\tdata: unknown;\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// ── 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): { 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\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\t// Contract filter — events store the contract under either\n\t\t\t\t\t// `contract_identifier` (legacy smart_contract_event payload)\n\t\t\t\t\t// or `contract_id` (current contract_event payload). Mirror\n\t\t\t\t\t// the streams query which checks both shapes.\n\t\t\t\t\tconst printContractId =\n\t\t\t\t\t\t(data.contract_identifier as string | undefined) ??\n\t\t\t\t\t\t(data.contract_id as string | undefined);\n\t\t\t\t\tif (filter.contractId) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!printContractId ||\n\t\t\t\t\t\t\t!matchAny(printContractId, filter.contractId)\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 (!traitAllows(filter, printContractId, traitContracts))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (!factoryAllows(filter, printContractId, 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): MatchedTx[] {\n\t// Index events by txId\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\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);\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",
12
- "import { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport { advanceOperationCursor } from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\tisByoSubgraph,\n\trecordLiveProgress,\n\trecordSubgraphProcessed,\n\tresolveSubgraphDb,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport {\n\ttype BlockMeta,\n\tJOURNAL_RETENTION_BLOCKS,\n\tSubgraphContext,\n\ttype TxMeta,\n} from \"./context.ts\";\nimport { emitSubscriptionOutbox } from \"./outbox-emit.ts\";\nimport { buildEventPayload, runHandlers } from \"./runner.ts\";\nimport {\n\ttype EventRecord,\n\ttype TxRecord,\n\tmatchSources,\n\treadPath,\n} from \"./source-matcher.ts\";\nimport { matcher } from \"./subscription-state.ts\";\n\n/**\n * The data-plane route for a subgraph: which schema its tables live in, the DB\n * those writes/reads land on (the user's DB when BYO, else the managed target),\n * and whether it's BYO. Cached per subgraph to avoid a per-block lookup +\n * decrypt; invalidated on redeploy (the connection can change) via\n * {@link invalidateSubgraphRoute}.\n */\ninterface SubgraphRoute {\n\tschemaName: string;\n\tdataDb: Kysely<Database>;\n\tbyo: boolean;\n}\nconst routeCache = new Map<string, SubgraphRoute>();\n\nasync function resolveRoute(\n\tsubgraphName: string,\n\ttargetDb: Kysely<Database>,\n): Promise<SubgraphRoute> {\n\tconst cached = routeCache.get(subgraphName);\n\tif (cached) return cached;\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\tconst byo = row ? isByoSubgraph(row) : false;\n\tconst route: SubgraphRoute = {\n\t\tschemaName: row?.schema_name ?? pgSchemaName(subgraphName),\n\t\tdataDb: row && byo ? resolveSubgraphDb(row) : targetDb,\n\t\tbyo,\n\t};\n\trouteCache.set(subgraphName, route);\n\treturn route;\n}\n\n/** Drop a subgraph's cached route — call on redeploy/delete (conn may change). */\nexport function invalidateSubgraphRoute(subgraphName: string): void {\n\trouteCache.delete(subgraphName);\n}\n\n/**\n * Resolve each distinct trait used by a subgraph's sources to its conforming\n * contract-id set, as of `blockHeight`, from the contract registry. Empty map\n * when no source is trait-scoped (the common case → no DB work).\n */\n/**\n * Resolve each factory-scoped source's address set for this block.\n *\n * Two parts, and the ORDER is the guarantee:\n * 1. addresses persisted by earlier blocks (`block_height <= blockHeight`,\n * so a reindex sees exactly what the live walk saw), then\n * 2. addresses revealed by THIS block's events — computed before matching,\n * so a contract discovered in block N receives its own block-N events.\n * Without this pass the first event from every discovered contract is\n * silently lost.\n */\nasync function resolveFactoryContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\ttxs: TxRecord[],\n\tevts: EventRecord[],\n): Promise<{\n\tresolved: Map<string, ReadonlySet<string>>;\n\tdiscovered: Array<{ sourceName: string; address: string }>;\n}> {\n\t// Keyed by the DISCOVERING source (`factory.from`), not the consuming one:\n\t// several sources can share one factory, and this way the extraction runs\n\t// once per discovering source rather than once per consumer.\n\tconst factories = new Map<string, { from: string; field: string }>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst factory = (source as { factory?: { from: string; field: string } })\n\t\t\t.factory;\n\t\tif (factory) factories.set(factory.from, factory);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tconst discovered: Array<{ sourceName: string; address: string }> = [];\n\tif (factories.size === 0) return { resolved, discovered };\n\n\tfor (const [discoveringSource, factory] of factories) {\n\t\tconst known = new Set<string>();\n\t\t// 1. Everything revealed at or below this height.\n\t\ttry {\n\t\t\tconst rows = await sql<{ address: string }>`\n\t\t\t\tSELECT address FROM ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\tWHERE source_name = ${discoveringSource} AND block_height <= ${blockHeight}\n\t\t\t`.execute(db);\n\t\t\tfor (const row of rows.rows) known.add(row.address);\n\t\t} catch {\n\t\t\t// Table absent (first deploy before DDL, or a non-factory subgraph):\n\t\t\t// treat as an empty set rather than failing the block.\n\t\t}\n\n\t\t// 2. This block's own reveals — before matching, so same-block events\n\t\t// from a new contract are not dropped.\n\t\tconst discovering = subgraph.sources[factory.from];\n\t\tif (discovering) {\n\t\t\tconst matches = matchSources(\n\t\t\t\t{ [factory.from]: discovering },\n\t\t\t\ttxs,\n\t\t\t\tevts,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t);\n\t\t\tfor (const match of matches) {\n\t\t\t\tfor (const event of match.events ?? []) {\n\t\t\t\t\tconst payload = buildEventPayload(discovering, match.tx, event);\n\t\t\t\t\tconst value = readPath(payload, factory.field);\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\tvalue.length > 0 &&\n\t\t\t\t\t\t!known.has(value)\n\t\t\t\t\t) {\n\t\t\t\t\t\tknown.add(value);\n\t\t\t\t\t\tdiscovered.push({ sourceName: discoveringSource, address: value });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresolved.set(discoveringSource, known);\n\t}\n\treturn { resolved, discovered };\n}\n\n/** Persist this block's discoveries, stamped with the block that revealed\n * them so the reorg handler can roll them back. */\nasync function persistFactoryDiscoveries(\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\tdiscovered: Array<{ sourceName: string; address: string }>,\n): Promise<void> {\n\tif (discovered.length === 0) return;\n\tfor (const { sourceName, address } of discovered) {\n\t\tawait sql`\n\t\t\tINSERT INTO ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\t(source_name, address, block_height)\n\t\t\tVALUES (${sourceName}, ${address}, ${blockHeight})\n\t\t\tON CONFLICT (source_name, address) DO NOTHING\n\t\t`.execute(db);\n\t}\n}\n\nasync function resolveTraitContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tdb: Kysely<Database>,\n): Promise<Map<string, ReadonlySet<string>>> {\n\tconst traits = new Set<string>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst trait = (source as { trait?: string }).trait;\n\t\tif (trait) traits.add(trait);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tfor (const trait of traits) {\n\t\tconst ids = await resolveTraitContractIds(db, trait, blockHeight);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\nexport interface ProcessBlockTiming {\n\ttotalMs: number;\n\thandlerMs: number;\n\tflushMs: number;\n}\n\nexport interface ProcessBlockResult {\n\tblockHeight: number;\n\tmatched: number;\n\tprocessed: number;\n\terrors: number;\n\tskipped: boolean;\n\ttiming?: ProcessBlockTiming;\n}\n\n/**\n * Process a single block through a single subgraph's pipeline.\n *\n * Flow:\n * 1. Load block + txs + events from DB\n * 2. Run source matcher\n * 3. Run handlers with SubgraphContext\n * 4. Flush context (commit writes atomically)\n * 5. Update subgraph.last_processed_block\n */\nexport interface PreloadedBlockData {\n\tblock: import(\"@secondlayer/shared/db\").Block;\n\ttxs: import(\"@secondlayer/shared/db\").Transaction[];\n\tevents: import(\"@secondlayer/shared/db\").Event[];\n}\n\nexport interface ProcessBlockOptions {\n\t/** Skip updating last_processed_block in DB (reindex batches this externally). */\n\tskipProgressUpdate?: boolean;\n\t/** Pre-loaded block data — skips DB reads when provided (used by batch catch-up). */\n\tpreloaded?: PreloadedBlockData;\n\t/**\n\t * Crash-safe sequential processing. Two checkpoint scopes:\n\t * - `{ status }` (reindex): a written block commits\n\t * `subgraphs.last_processed_block = blockHeight` in the SAME transaction\n\t * as its writes; replays skip at/below the cursor. Only for strictly\n\t * ascending walks over the subgraph's own cursor.\n\t * - `{ operationId }` (backfill): same guarantee against the OPERATION's\n\t * own `cursor_block` — backfills legitimately revisit heights below the\n\t * live cursor, so they must never checkpoint (or read) the subgraph\n\t * cursor. The advance is a CONDITIONAL monotonic UPDATE: concurrent\n\t * writers serialize on it, and the loser's whole block tx rolls back\n\t * (surfaced as `skipped`, never an error/gap).\n\t * Either way: a crash can never leave committed deltas ahead of the\n\t * relevant checkpoint.\n\t */\n\tatomicProgress?: { status: string } | { operationId: string };\n}\n\n/** Thrown inside the block tx when a racing writer already covered this\n * height — rolls the tx back; processBlock converts it to `skipped`. The\n * winner committed the block, so this is success-shaped, never a gap. */\nclass CursorRaceLostError extends Error {\n\tconstructor(operationId: string, height: number) {\n\t\tsuper(`op ${operationId} lost cursor race at block ${height}`);\n\t\tthis.name = \"CursorRaceLostError\";\n\t}\n}\n\nfunction opCursorMode(\n\topts?: ProcessBlockOptions,\n): { operationId: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"operationId\" in ap ? ap : undefined;\n}\n\nfunction statusMode(\n\topts?: ProcessBlockOptions,\n): { status: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"status\" in ap ? ap : undefined;\n}\n\n/** Default per-block retry schedule before a failure counts as persistent. */\nexport const BLOCK_RETRY_DELAYS_MS: number[] = [500, 2_000, 5_000];\n\n/**\n * Journal pre-images on the live path only. Deep reindex/backfill heights\n * (skipProgressUpdate) are past finality — a reorg can't reach them, so\n * journaling would be pure churn for the pruner.\n */\nfunction journalEnabled(opts?: ProcessBlockOptions): boolean {\n\treturn !opts?.skipProgressUpdate;\n}\n\n/**\n * processBlock with bounded retries. Throws the last error once the schedule\n * is exhausted — callers decide whether that halts the walk (strict paths) or\n * records a gap (backfill). Never advances any cursor on failure.\n */\nexport async function processBlockWithRetry(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n\tretryDelaysMs: number[] = BLOCK_RETRY_DELAYS_MS,\n): Promise<ProcessBlockResult> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {\n\t\ttry {\n\t\t\treturn await processBlock(subgraph, subgraphName, blockHeight, opts);\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t\tconst delay = retryDelaysMs[attempt];\n\t\t\tif (delay === undefined) break;\n\t\t\tlogger.warn(\"Block processing failed, retrying\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t\tretryInMs: delay,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport async function processBlock(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n): Promise<ProcessBlockResult> {\n\tconst targetDb = getTargetDb();\n\tconst blockStart = performance.now();\n\tconst result: ProcessBlockResult = {\n\t\tblockHeight,\n\t\tmatched: 0,\n\t\tprocessed: 0,\n\t\terrors: 0,\n\t\tskipped: false,\n\t};\n\n\t// 1. Load block from source DB (shared indexer) — use pre-loaded data if available\n\tlet block: PreloadedBlockData[\"block\"] | undefined;\n\tlet txs: PreloadedBlockData[\"txs\"];\n\tlet evts: PreloadedBlockData[\"events\"];\n\tif (opts?.preloaded) {\n\t\tblock = opts.preloaded.block;\n\t\ttxs = opts.preloaded.txs;\n\t\tevts = opts.preloaded.events;\n\t} else {\n\t\t// The block source returns canonical blocks only, so a missing entry\n\t\t// means the block is absent or non-canonical — skip either way.\n\t\tconst data = (\n\t\t\tawait resolveBlockSource(subgraph).loadBlockRange(\n\t\t\t\tblockHeight,\n\t\t\t\tblockHeight,\n\t\t\t)\n\t\t).get(blockHeight);\n\t\tif (!data) {\n\t\t\tlogger.debug(\"Block not found or non-canonical for subgraph processing\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tblock = data.block;\n\t\ttxs = data.txs;\n\t\tevts = data.events;\n\t}\n\n\t// 3. Match source. Trait-scoped sources ({ trait: \"sip-010\" }) resolve to the\n\t// set of conforming contracts AS OF this block (deploy_height ≤ blockHeight),\n\t// so a reindex backfills a token's full history even if it was classified\n\t// after deploy. Resolution is done here (DB access) so the matcher stays pure.\n\t// Route first: the factory set lives in this subgraph's pg schema, and it\n\t// must resolve BEFORE matching. `resolveRoute` is cached per subgraph.\n\tconst route = await resolveRoute(subgraphName, targetDb);\n\tconst schemaName = route.schemaName;\n\n\tconst traitContracts = await resolveTraitContracts(\n\t\tsubgraph,\n\t\tblockHeight,\n\t\ttargetDb,\n\t);\n\t// Factory sets resolve BEFORE matching so a contract revealed in this\n\t// block receives its own block-N events (see resolveFactoryContracts).\n\tconst { resolved: factoryContracts, discovered } =\n\t\tawait resolveFactoryContracts(\n\t\t\tsubgraph,\n\t\t\tblockHeight,\n\t\t\tschemaName,\n\t\t\ttargetDb,\n\t\t\ttxs,\n\t\t\tevts,\n\t\t);\n\tconst matched = matchSources(\n\t\tsubgraph.sources,\n\t\ttxs,\n\t\tevts,\n\t\ttraitContracts,\n\t\tfactoryContracts,\n\t);\n\tresult.matched = matched.length;\n\n\tif (matched.length === 0) {\n\t\tif (!opts?.skipProgressUpdate) {\n\t\t\t// Promote-but-never-unpark: unconditional \"active\" stamping let the\n\t\t\t// live walk overwrite \"reindexing\" set by a queued reindex op,\n\t\t\t// flapping the subgraph back into catch-up (and into collision with\n\t\t\t// the op's schema drop).\n\t\t\tawait recordLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// 4. Data plane (managed target DB, or the user's DB when BYO) — resolved\n\t// above, since factory-set resolution needs the schema name.\n\tconst blockMeta: BlockMeta = {\n\t\theight: block.height,\n\t\thash: block.hash,\n\t\ttimestamp: block.timestamp,\n\t\tburnBlockHeight: block.burn_block_height,\n\t};\n\tconst initialTx: TxMeta = {\n\t\ttxId: \"\",\n\t\tsender: \"\",\n\t\ttype: \"\",\n\t\tstatus: \"\",\n\t};\n\n\tlet handlerMs = 0;\n\tlet flushMs = 0;\n\n\t// Progress + health writes — always on the managed DB, identical in both\n\t// modes (the subgraphs control-plane table lives in target).\n\tconst applyProgress = async (\n\t\ttx: Transaction<Database>,\n\t\trr: { processed: number; errors: number },\n\t) => {\n\t\tif (opts?.skipProgressUpdate) return;\n\t\tif (rr.errors > 0 && rr.processed === 0) {\n\t\t\tawait updateSubgraphStatus(tx, subgraphName, \"error\", blockHeight);\n\t\t} else {\n\t\t\t// Promote-but-never-unpark (see matched-0 note).\n\t\t\tawait recordLiveProgress(tx, subgraphName, blockHeight);\n\t\t}\n\t\tif (rr.processed > 0 || rr.errors > 0) {\n\t\t\tconst lastError =\n\t\t\t\trr.errors > 0\n\t\t\t\t\t? `${rr.errors} error(s) at block ${blockHeight}`\n\t\t\t\t\t: undefined;\n\t\t\tawait recordSubgraphProcessed(\n\t\t\t\ttx,\n\t\t\t\tsubgraphName,\n\t\t\t\trr.processed,\n\t\t\t\trr.errors,\n\t\t\t\tlastError,\n\t\t\t);\n\t\t}\n\t};\n\n\tif (route.byo) {\n\t\t// BYO: no cross-DB transaction possible. Phase A commits handler writes to\n\t\t// the user DB first (replace-per-height makes a replay idempotent); phase\n\t\t// B then records outbox + progress on the managed DB. If phase A throws,\n\t\t// progress never advances and the block replays — safe by construction.\n\t\t// atomicProgress: the checkpoint lands in phase B (post-commit), so it\n\t\t// can lag phase A but never lead it; the replay window that leaves is\n\t\t// covered by replace-per-height + the deploy-time handler restrictions.\n\t\t// Op-cursor mode is ADVISORY here for the same reason: phase-A user-DB\n\t\t// writes can never roll back on a lost race, so the guards\n\t\t// (BYO_NON_IDEMPOTENT_HANDLER) are the load-bearing protection.\n\t\tif (statusMode(opts)) {\n\t\t\tconst row = await targetDb\n\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} else if (opCursorMode(opts)) {\n\t\t\tconst om = opCursorMode(opts) as { operationId: string };\n\t\t\tconst row = await targetDb\n\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t.where(\"id\", \"=\", om.operationId)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (\n\t\t\t\trow?.cursor_block != null &&\n\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t) {\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tlet runResult = { processed: 0, errors: 0 };\n\t\tlet manifest: Awaited<ReturnType<SubgraphContext[\"flush\"]>> | undefined;\n\t\tawait route.dataDb\n\t\t\t.transaction()\n\t\t\t.execute(async (tx: Transaction<Database>) => {\n\t\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\t\ttx,\n\t\t\t\t\tschemaName,\n\t\t\t\t\tsubgraph.schema,\n\t\t\t\t\tblockMeta,\n\t\t\t\t\tinitialTx,\n\t\t\t\t\ttrue,\n\t\t\t\t\tjournalEnabled(opts),\n\t\t\t\t);\n\t\t\t\tconst handlerStart = performance.now();\n\t\t\t\trunResult = await runHandlers(subgraph, matched, ctx);\n\t\t\t\thandlerMs = performance.now() - handlerStart;\n\t\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\t\tconst flushStart = performance.now();\n\t\t\t\t\tmanifest = await ctx.flush();\n\t\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t\t}\n\t\t\t});\n\t\tresult.processed = runResult.processed;\n\t\tresult.errors = runResult.errors;\n\n\t\t// Persist factory discoveries only after the block's writes commit, so\n\t\t// a failed block doesn't leave addresses claimed for a block that\n\t\t// produced nothing. Stamped with this height, so the reorg handler\n\t\t// rolls them back with everything else.\n\t\tawait persistFactoryDiscoveries(\n\t\t\tschemaName,\n\t\t\troute.dataDb,\n\t\t\tblockHeight,\n\t\t\tdiscovered,\n\t\t);\n\n\t\t// Phase B (managed) — only reached after phase A commits.\n\t\tawait targetDb.transaction().execute(async (tx: Transaction<Database>) => {\n\t\t\tif (manifest && manifest.count > 0) {\n\t\t\t\tawait emitSubscriptionOutbox(\n\t\t\t\t\ttx,\n\t\t\t\t\tsubgraphName,\n\t\t\t\t\tmanifest,\n\t\t\t\t\tmatcher,\n\t\t\t\t\tblock.height,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst byoSm = statusMode(opts);\n\t\t\tconst byoOm = opCursorMode(opts);\n\t\t\tif (byoSm && manifest && manifest.count > 0) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, byoSm.status, blockHeight);\n\t\t\t} else if (byoOm && manifest && manifest.count > 0) {\n\t\t\t\t// Advisory: phase A already committed; a lost race here just means\n\t\t\t\t// the cursor was covered by another writer — nothing to undo.\n\t\t\t\tawait advanceOperationCursor(tx, byoOm.operationId, blockHeight);\n\t\t\t}\n\t\t\tawait applyProgress(tx, runResult);\n\t\t});\n\t} else {\n\t\t// Managed: a single atomic transaction on the target DB.\n\t\ttry {\n\t\t\tawait targetDb\n\t\t\t\t.transaction()\n\t\t\t\t.execute(async (tx: Transaction<Database>) => {\n\t\t\t\t\t// Replay guard (sequential walks only): committed writes always carry\n\t\t\t\t\t// their checkpoint (below), so a block at/below the cursor has already\n\t\t\t\t\t// been applied — running it again would double-apply deltas.\n\t\t\t\t\tconst opMode = opCursorMode(opts);\n\t\t\t\t\tif (statusMode(opts)) {\n\t\t\t\t\t\tconst row = await tx\n\t\t\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t\t\t.executeTakeFirst();\n\t\t\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (opMode) {\n\t\t\t\t\t\t// Fast path only — the conditional advance below is the guarantee.\n\t\t\t\t\t\tconst row = await tx\n\t\t\t\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t\t\t\t.where(\"id\", \"=\", opMode.operationId)\n\t\t\t\t\t\t\t.executeTakeFirst();\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow?.cursor_block != null &&\n\t\t\t\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\tsubgraph.schema,\n\t\t\t\t\t\tblockMeta,\n\t\t\t\t\t\tinitialTx,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tjournalEnabled(opts),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst handlerStart = performance.now();\n\t\t\t\t\tconst runResult = await runHandlers(subgraph, matched, ctx);\n\t\t\t\t\thandlerMs = performance.now() - handlerStart;\n\n\t\t\t\t\tresult.processed = runResult.processed;\n\t\t\t\t\tresult.errors = runResult.errors;\n\n\t\t\t\t\tlet flushedWrites = false;\n\t\t\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\t\t\tconst flushStart = performance.now();\n\t\t\t\t\t\tconst manifest = await ctx.flush();\n\t\t\t\t\t\tflushedWrites = manifest.count > 0;\n\t\t\t\t\t\tif (manifest.count > 0) {\n\t\t\t\t\t\t\tawait emitSubscriptionOutbox(\n\t\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\tmatcher,\n\t\t\t\t\t\t\t\tblock.height,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Checkpoint travels with the writes it covers — a crash can never\n\t\t\t\t\t// leave committed deltas ahead of the checkpoint (fix-f040 B3).\n\t\t\t\t\tconst sm = statusMode(opts);\n\t\t\t\t\tif (sm && flushedWrites) {\n\t\t\t\t\t\tawait updateSubgraphStatus(\n\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t\tsm.status,\n\t\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (opMode && flushedWrites) {\n\t\t\t\t\t\tconst advanced = await advanceOperationCursor(\n\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\topMode.operationId,\n\t\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!advanced) {\n\t\t\t\t\t\t\t// A racing writer (zombie/claimer) already covered this height —\n\t\t\t\t\t\t\t// abort OUR writes; the winner's commit stands.\n\t\t\t\t\t\t\tthrow new CursorRaceLostError(opMode.operationId, blockHeight);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tawait applyProgress(tx, runResult);\n\t\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof CursorRaceLostError) {\n\t\t\t\t// Success-shaped: the block IS committed (by the winner). Surfacing\n\t\t\t\t// this as an error would mint a false gap row and re-invite the\n\t\t\t\t// double-apply through gap repair.\n\t\t\t\tlogger.warn(\"cursor race lost — block already covered\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\terror: err.message,\n\t\t\t\t});\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst totalMs = performance.now() - blockStart;\n\tresult.timing = {\n\t\ttotalMs: Math.round(totalMs),\n\t\thandlerMs: Math.round(handlerMs),\n\t\tflushMs: Math.round(flushMs),\n\t};\n\n\t// 7. Row count warning — sample every 1000 blocks (uses pg_stat estimate, not COUNT(*))\n\tif (blockHeight % 1000 === 0) {\n\t\ttry {\n\t\t\tconst tables = Object.keys(subgraph.schema);\n\t\t\tfor (const table of tables) {\n\t\t\t\tconst { rows } = await sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(route.dataDb);\n\t\t\t\tconst count = Number((rows[0] as Record<string, unknown>)?.count ?? 0);\n\t\t\t\tif (count >= 10_000_000) {\n\t\t\t\t\tlogger.warn(\"Subgraph table exceeds 10M rows (estimate)\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tcount,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Expected: table may not exist yet (fresh subgraph, first few\n\t\t\t// blocks before DDL runs). Log at debug so real errors —\n\t\t\t// connection, permissions, query plan — aren't invisible.\n\t\t\tlogger.debug(\"Row count sample failed\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t}\n\n\t\t// Prune reorg-journal entries past finality (fix-f040 B2). Same cadence\n\t\t// as the row sample; retention is generous vs observed reorg depth.\n\t\tif (journalEnabled(opts)) {\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`DELETE FROM \"${schemaName}\".\"_journal\" WHERE \"block_height\" < ${blockHeight - JOURNAL_RETENTION_BLOCKS}`,\n\t\t\t\t)\n\t\t\t\t.execute(route.dataDb)\n\t\t\t\t.catch(() => {\n\t\t\t\t\t// Journal may not exist yet (pre-journal deploy, no writes since).\n\t\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n",
13
+ "import { type Database, getTargetDb } from \"@secondlayer/shared/db\";\nimport { resolveTraitContractIds } from \"@secondlayer/shared/db/queries/contracts\";\nimport { advanceOperationCursor } from \"@secondlayer/shared/db/queries/subgraph-operations\";\nimport {\n\tisByoSubgraph,\n\trecordLiveProgress,\n\trecordSubgraphProcessed,\n\tresolveSubgraphDb,\n\tupdateSubgraphStatus,\n} from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { type Kysely, type Transaction, sql } from \"kysely\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport {\n\ttype BlockMeta,\n\tJOURNAL_RETENTION_BLOCKS,\n\tSubgraphContext,\n\ttype TxMeta,\n} from \"./context.ts\";\nimport { emitSubscriptionOutbox } from \"./outbox-emit.ts\";\nimport { buildEventPayload, runHandlers } from \"./runner.ts\";\nimport {\n\ttype EventRecord,\n\ttype TxRecord,\n\tmatchSources,\n\treadPath,\n} from \"./source-matcher.ts\";\nimport { matcher } from \"./subscription-state.ts\";\n\n/**\n * The data-plane route for a subgraph: which schema its tables live in, the DB\n * those writes/reads land on (the user's DB when BYO, else the managed target),\n * and whether it's BYO. Cached per subgraph to avoid a per-block lookup +\n * decrypt; invalidated on redeploy (the connection can change) via\n * {@link invalidateSubgraphRoute}.\n */\ninterface SubgraphRoute {\n\tschemaName: string;\n\tdataDb: Kysely<Database>;\n\tbyo: boolean;\n}\nconst routeCache = new Map<string, SubgraphRoute>();\n\nasync function resolveRoute(\n\tsubgraphName: string,\n\ttargetDb: Kysely<Database>,\n): Promise<SubgraphRoute> {\n\tconst cached = routeCache.get(subgraphName);\n\tif (cached) return cached;\n\tconst row = await targetDb\n\t\t.selectFrom(\"subgraphs\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", subgraphName)\n\t\t.executeTakeFirst();\n\tconst byo = row ? isByoSubgraph(row) : false;\n\tconst route: SubgraphRoute = {\n\t\tschemaName: row?.schema_name ?? pgSchemaName(subgraphName),\n\t\tdataDb: row && byo ? resolveSubgraphDb(row) : targetDb,\n\t\tbyo,\n\t};\n\trouteCache.set(subgraphName, route);\n\treturn route;\n}\n\n/** Drop a subgraph's cached route — call on redeploy/delete (conn may change). */\nexport function invalidateSubgraphRoute(subgraphName: string): void {\n\trouteCache.delete(subgraphName);\n}\n\n/**\n * Resolve each distinct trait used by a subgraph's sources to its conforming\n * contract-id set, as of `blockHeight`, from the contract registry. Empty map\n * when no source is trait-scoped (the common case → no DB work).\n */\n/**\n * Resolve each factory-scoped source's address set for this block.\n *\n * Two parts, and the ORDER is the guarantee:\n * 1. addresses persisted by earlier blocks (`block_height <= blockHeight`,\n * so a reindex sees exactly what the live walk saw), then\n * 2. addresses revealed by THIS block's events — computed before matching,\n * so a contract discovered in block N receives its own block-N events.\n * Without this pass the first event from every discovered contract is\n * silently lost.\n */\nasync function resolveFactoryContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\ttxs: TxRecord[],\n\tevts: EventRecord[],\n): Promise<{\n\tresolved: Map<string, ReadonlySet<string>>;\n\tdiscovered: Array<{ sourceName: string; address: string }>;\n}> {\n\t// Keyed by the DISCOVERING source (`factory.from`), not the consuming one:\n\t// several sources can share one factory, and this way the extraction runs\n\t// once per discovering source rather than once per consumer.\n\tconst factories = new Map<string, { from: string; field: string }>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst factory = (source as { factory?: { from: string; field: string } })\n\t\t\t.factory;\n\t\tif (factory) factories.set(factory.from, factory);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tconst discovered: Array<{ sourceName: string; address: string }> = [];\n\tif (factories.size === 0) return { resolved, discovered };\n\n\tfor (const [discoveringSource, factory] of factories) {\n\t\tconst known = new Set<string>();\n\t\t// 1. Everything revealed at or below this height.\n\t\ttry {\n\t\t\tconst rows = await sql<{ address: string }>`\n\t\t\t\tSELECT address FROM ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\tWHERE source_name = ${discoveringSource} AND block_height <= ${blockHeight}\n\t\t\t`.execute(db);\n\t\t\tfor (const row of rows.rows) known.add(row.address);\n\t\t} catch {\n\t\t\t// Table absent (first deploy before DDL, or a non-factory subgraph):\n\t\t\t// treat as an empty set rather than failing the block.\n\t\t}\n\n\t\t// 2. This block's own reveals — before matching, so same-block events\n\t\t// from a new contract are not dropped.\n\t\tconst discovering = subgraph.sources[factory.from];\n\t\tif (discovering) {\n\t\t\tconst matches = matchSources(\n\t\t\t\t{ [factory.from]: discovering },\n\t\t\t\ttxs,\n\t\t\t\tevts,\n\t\t\t\tnew Map(),\n\t\t\t\tnew Map(),\n\t\t\t);\n\t\t\tfor (const match of matches) {\n\t\t\t\tfor (const event of match.events ?? []) {\n\t\t\t\t\tconst payload = buildEventPayload(discovering, match.tx, event);\n\t\t\t\t\tconst value = readPath(payload, factory.field);\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof value === \"string\" &&\n\t\t\t\t\t\tvalue.length > 0 &&\n\t\t\t\t\t\t!known.has(value)\n\t\t\t\t\t) {\n\t\t\t\t\t\tknown.add(value);\n\t\t\t\t\t\tdiscovered.push({ sourceName: discoveringSource, address: value });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresolved.set(discoveringSource, known);\n\t}\n\treturn { resolved, discovered };\n}\n\n/** Persist this block's discoveries, stamped with the block that revealed\n * them so the reorg handler can roll them back. */\nasync function persistFactoryDiscoveries(\n\tschemaName: string,\n\tdb: Kysely<Database>,\n\tblockHeight: number,\n\tdiscovered: Array<{ sourceName: string; address: string }>,\n): Promise<void> {\n\tif (discovered.length === 0) return;\n\tfor (const { sourceName, address } of discovered) {\n\t\tawait sql`\n\t\t\tINSERT INTO ${sql.raw(`\"${schemaName}\".\"_factory_addresses\"`)}\n\t\t\t\t(source_name, address, block_height)\n\t\t\tVALUES (${sourceName}, ${address}, ${blockHeight})\n\t\t\tON CONFLICT (source_name, address) DO NOTHING\n\t\t`.execute(db);\n\t}\n}\n\nasync function resolveTraitContracts(\n\tsubgraph: SubgraphDefinition,\n\tblockHeight: number,\n\tdb: Kysely<Database>,\n): Promise<Map<string, ReadonlySet<string>>> {\n\tconst traits = new Set<string>();\n\tfor (const source of Object.values(subgraph.sources)) {\n\t\tconst trait = (source as { trait?: string }).trait;\n\t\tif (trait) traits.add(trait);\n\t}\n\tconst resolved = new Map<string, ReadonlySet<string>>();\n\tfor (const trait of traits) {\n\t\tconst ids = await resolveTraitContractIds(db, trait, blockHeight);\n\t\tresolved.set(trait, new Set(ids));\n\t}\n\treturn resolved;\n}\n\nexport interface ProcessBlockTiming {\n\ttotalMs: number;\n\thandlerMs: number;\n\tflushMs: number;\n}\n\nexport interface ProcessBlockResult {\n\tblockHeight: number;\n\tmatched: number;\n\tprocessed: number;\n\terrors: number;\n\tskipped: boolean;\n\ttiming?: ProcessBlockTiming;\n}\n\n/**\n * Process a single block through a single subgraph's pipeline.\n *\n * Flow:\n * 1. Load block + txs + events from DB\n * 2. Run source matcher\n * 3. Run handlers with SubgraphContext\n * 4. Flush context (commit writes atomically)\n * 5. Update subgraph.last_processed_block\n */\nexport interface PreloadedBlockData {\n\tblock: import(\"@secondlayer/shared/db\").Block;\n\ttxs: import(\"@secondlayer/shared/db\").Transaction[];\n\tevents: import(\"@secondlayer/shared/db\").Event[];\n}\n\nexport interface ProcessBlockOptions {\n\t/** Skip updating last_processed_block in DB (reindex batches this externally). */\n\tskipProgressUpdate?: boolean;\n\t/** Pre-loaded block data — skips DB reads when provided (used by batch catch-up). */\n\tpreloaded?: PreloadedBlockData;\n\t/**\n\t * Crash-safe sequential processing. Two checkpoint scopes:\n\t * - `{ status }` (reindex): a written block commits\n\t * `subgraphs.last_processed_block = blockHeight` in the SAME transaction\n\t * as its writes; replays skip at/below the cursor. Only for strictly\n\t * ascending walks over the subgraph's own cursor.\n\t * - `{ operationId }` (backfill): same guarantee against the OPERATION's\n\t * own `cursor_block` — backfills legitimately revisit heights below the\n\t * live cursor, so they must never checkpoint (or read) the subgraph\n\t * cursor. The advance is a CONDITIONAL monotonic UPDATE: concurrent\n\t * writers serialize on it, and the loser's whole block tx rolls back\n\t * (surfaced as `skipped`, never an error/gap).\n\t * Either way: a crash can never leave committed deltas ahead of the\n\t * relevant checkpoint.\n\t */\n\tatomicProgress?: { status: string } | { operationId: string };\n}\n\n/** Thrown inside the block tx when a racing writer already covered this\n * height — rolls the tx back; processBlock converts it to `skipped`. The\n * winner committed the block, so this is success-shaped, never a gap. */\nclass CursorRaceLostError extends Error {\n\tconstructor(operationId: string, height: number) {\n\t\tsuper(`op ${operationId} lost cursor race at block ${height}`);\n\t\tthis.name = \"CursorRaceLostError\";\n\t}\n}\n\nfunction opCursorMode(\n\topts?: ProcessBlockOptions,\n): { operationId: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"operationId\" in ap ? ap : undefined;\n}\n\nfunction statusMode(\n\topts?: ProcessBlockOptions,\n): { status: string } | undefined {\n\tconst ap = opts?.atomicProgress;\n\treturn ap && \"status\" in ap ? ap : undefined;\n}\n\n/** Default per-block retry schedule before a failure counts as persistent. */\nexport const BLOCK_RETRY_DELAYS_MS: number[] = [500, 2_000, 5_000];\n\n/**\n * Journal pre-images on the live path only. Deep reindex/backfill heights\n * (skipProgressUpdate) are past finality — a reorg can't reach them, so\n * journaling would be pure churn for the pruner.\n */\nfunction journalEnabled(opts?: ProcessBlockOptions): boolean {\n\treturn !opts?.skipProgressUpdate;\n}\n\n/**\n * processBlock with bounded retries. Throws the last error once the schedule\n * is exhausted — callers decide whether that halts the walk (strict paths) or\n * records a gap (backfill). Never advances any cursor on failure.\n */\nexport async function processBlockWithRetry(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n\tretryDelaysMs: number[] = BLOCK_RETRY_DELAYS_MS,\n): Promise<ProcessBlockResult> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {\n\t\ttry {\n\t\t\treturn await processBlock(subgraph, subgraphName, blockHeight, opts);\n\t\t} catch (err) {\n\t\t\tlastError = err;\n\t\t\tconst delay = retryDelaysMs[attempt];\n\t\t\tif (delay === undefined) break;\n\t\t\tlogger.warn(\"Block processing failed, retrying\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t\tretryInMs: delay,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport async function processBlock(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n\tblockHeight: number,\n\topts?: ProcessBlockOptions,\n): Promise<ProcessBlockResult> {\n\tconst targetDb = getTargetDb();\n\tconst blockStart = performance.now();\n\tconst result: ProcessBlockResult = {\n\t\tblockHeight,\n\t\tmatched: 0,\n\t\tprocessed: 0,\n\t\terrors: 0,\n\t\tskipped: false,\n\t};\n\n\t// 1. Load block from source DB (shared indexer) — use pre-loaded data if available\n\tlet block: PreloadedBlockData[\"block\"] | undefined;\n\tlet txs: PreloadedBlockData[\"txs\"];\n\tlet evts: PreloadedBlockData[\"events\"];\n\tif (opts?.preloaded) {\n\t\tblock = opts.preloaded.block;\n\t\ttxs = opts.preloaded.txs;\n\t\tevts = opts.preloaded.events;\n\t} else {\n\t\t// The block source returns canonical blocks only, so a missing entry\n\t\t// means the block is absent or non-canonical — skip either way.\n\t\tconst data = (\n\t\t\tawait resolveBlockSource(subgraph).loadBlockRange(\n\t\t\t\tblockHeight,\n\t\t\t\tblockHeight,\n\t\t\t)\n\t\t).get(blockHeight);\n\t\tif (!data) {\n\t\t\tlogger.debug(\"Block not found or non-canonical for subgraph processing\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\tblockHeight,\n\t\t\t});\n\t\t\tresult.skipped = true;\n\t\t\treturn result;\n\t\t}\n\t\tblock = data.block;\n\t\ttxs = data.txs;\n\t\tevts = data.events;\n\t}\n\n\t// 3. Match source. Trait-scoped sources ({ trait: \"sip-010\" }) resolve to the\n\t// set of conforming contracts AS OF this block (deploy_height ≤ blockHeight),\n\t// so a reindex backfills a token's full history even if it was classified\n\t// after deploy. Resolution is done here (DB access) so the matcher stays pure.\n\t// Route first: the factory set lives in this subgraph's pg schema, and it\n\t// must resolve BEFORE matching. `resolveRoute` is cached per subgraph.\n\tconst route = await resolveRoute(subgraphName, targetDb);\n\tconst schemaName = route.schemaName;\n\n\tconst traitContracts = await resolveTraitContracts(\n\t\tsubgraph,\n\t\tblockHeight,\n\t\ttargetDb,\n\t);\n\t// Factory sets resolve BEFORE matching so a contract revealed in this\n\t// block receives its own block-N events (see resolveFactoryContracts).\n\tconst { resolved: factoryContracts, discovered } =\n\t\tawait resolveFactoryContracts(\n\t\t\tsubgraph,\n\t\t\tblockHeight,\n\t\t\tschemaName,\n\t\t\ttargetDb,\n\t\t\ttxs,\n\t\t\tevts,\n\t\t);\n\tconst matched = matchSources(\n\t\tsubgraph.sources,\n\t\ttxs,\n\t\tevts,\n\t\ttraitContracts,\n\t\tfactoryContracts,\n\t);\n\tresult.matched = matched.length;\n\n\tif (matched.length === 0) {\n\t\tif (!opts?.skipProgressUpdate) {\n\t\t\t// Promote-but-never-unpark: unconditional \"active\" stamping let the\n\t\t\t// live walk overwrite \"reindexing\" set by a queued reindex op,\n\t\t\t// flapping the subgraph back into catch-up (and into collision with\n\t\t\t// the op's schema drop).\n\t\t\tawait recordLiveProgress(targetDb, subgraphName, blockHeight);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// 4. Data plane (managed target DB, or the user's DB when BYO) — resolved\n\t// above, since factory-set resolution needs the schema name.\n\tconst blockMeta: BlockMeta = {\n\t\theight: block.height,\n\t\thash: block.hash,\n\t\ttimestamp: block.timestamp,\n\t\tburnBlockHeight: block.burn_block_height,\n\t\tindexBlockHash: block.index_block_hash,\n\t};\n\tconst initialTx: TxMeta = {\n\t\ttxId: \"\",\n\t\tsender: \"\",\n\t\ttype: \"\",\n\t\tstatus: \"\",\n\t};\n\n\tlet handlerMs = 0;\n\tlet flushMs = 0;\n\n\t// Progress + health writes — always on the managed DB, identical in both\n\t// modes (the subgraphs control-plane table lives in target).\n\tconst applyProgress = async (\n\t\ttx: Transaction<Database>,\n\t\trr: { processed: number; errors: number },\n\t) => {\n\t\tif (opts?.skipProgressUpdate) return;\n\t\tif (rr.errors > 0 && rr.processed === 0) {\n\t\t\tawait updateSubgraphStatus(tx, subgraphName, \"error\", blockHeight);\n\t\t} else {\n\t\t\t// Promote-but-never-unpark (see matched-0 note).\n\t\t\tawait recordLiveProgress(tx, subgraphName, blockHeight);\n\t\t}\n\t\tif (rr.processed > 0 || rr.errors > 0) {\n\t\t\tconst lastError =\n\t\t\t\trr.errors > 0\n\t\t\t\t\t? `${rr.errors} error(s) at block ${blockHeight}`\n\t\t\t\t\t: undefined;\n\t\t\tawait recordSubgraphProcessed(\n\t\t\t\ttx,\n\t\t\t\tsubgraphName,\n\t\t\t\trr.processed,\n\t\t\t\trr.errors,\n\t\t\t\tlastError,\n\t\t\t);\n\t\t}\n\t};\n\n\tif (route.byo) {\n\t\t// BYO: no cross-DB transaction possible. Phase A commits handler writes to\n\t\t// the user DB first (replace-per-height makes a replay idempotent); phase\n\t\t// B then records outbox + progress on the managed DB. If phase A throws,\n\t\t// progress never advances and the block replays — safe by construction.\n\t\t// atomicProgress: the checkpoint lands in phase B (post-commit), so it\n\t\t// can lag phase A but never lead it; the replay window that leaves is\n\t\t// covered by replace-per-height + the deploy-time handler restrictions.\n\t\t// Op-cursor mode is ADVISORY here for the same reason: phase-A user-DB\n\t\t// writes can never roll back on a lost race, so the guards\n\t\t// (BYO_NON_IDEMPOTENT_HANDLER) are the load-bearing protection.\n\t\tif (statusMode(opts)) {\n\t\t\tconst row = await targetDb\n\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} else if (opCursorMode(opts)) {\n\t\t\tconst om = opCursorMode(opts) as { operationId: string };\n\t\t\tconst row = await targetDb\n\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t.where(\"id\", \"=\", om.operationId)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (\n\t\t\t\trow?.cursor_block != null &&\n\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t) {\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\tlet runResult = { processed: 0, errors: 0 };\n\t\tlet manifest: Awaited<ReturnType<SubgraphContext[\"flush\"]>> | undefined;\n\t\tawait route.dataDb\n\t\t\t.transaction()\n\t\t\t.execute(async (tx: Transaction<Database>) => {\n\t\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\t\ttx,\n\t\t\t\t\tschemaName,\n\t\t\t\t\tsubgraph.schema,\n\t\t\t\t\tblockMeta,\n\t\t\t\t\tinitialTx,\n\t\t\t\t\ttrue,\n\t\t\t\t\tjournalEnabled(opts),\n\t\t\t\t);\n\t\t\t\tconst handlerStart = performance.now();\n\t\t\t\trunResult = await runHandlers(subgraph, matched, ctx);\n\t\t\t\thandlerMs = performance.now() - handlerStart;\n\t\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\t\tconst flushStart = performance.now();\n\t\t\t\t\tmanifest = await ctx.flush();\n\t\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t\t}\n\t\t\t});\n\t\tresult.processed = runResult.processed;\n\t\tresult.errors = runResult.errors;\n\n\t\t// Persist factory discoveries only after the block's writes commit, so\n\t\t// a failed block doesn't leave addresses claimed for a block that\n\t\t// produced nothing. Stamped with this height, so the reorg handler\n\t\t// rolls them back with everything else.\n\t\tawait persistFactoryDiscoveries(\n\t\t\tschemaName,\n\t\t\troute.dataDb,\n\t\t\tblockHeight,\n\t\t\tdiscovered,\n\t\t);\n\n\t\t// Phase B (managed) — only reached after phase A commits.\n\t\tawait targetDb.transaction().execute(async (tx: Transaction<Database>) => {\n\t\t\tif (manifest && manifest.count > 0) {\n\t\t\t\tawait emitSubscriptionOutbox(\n\t\t\t\t\ttx,\n\t\t\t\t\tsubgraphName,\n\t\t\t\t\tmanifest,\n\t\t\t\t\tmatcher,\n\t\t\t\t\tblock.height,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst byoSm = statusMode(opts);\n\t\t\tconst byoOm = opCursorMode(opts);\n\t\t\tif (byoSm && manifest && manifest.count > 0) {\n\t\t\t\tawait updateSubgraphStatus(tx, subgraphName, byoSm.status, blockHeight);\n\t\t\t} else if (byoOm && manifest && manifest.count > 0) {\n\t\t\t\t// Advisory: phase A already committed; a lost race here just means\n\t\t\t\t// the cursor was covered by another writer — nothing to undo.\n\t\t\t\tawait advanceOperationCursor(tx, byoOm.operationId, blockHeight);\n\t\t\t}\n\t\t\tawait applyProgress(tx, runResult);\n\t\t});\n\t} else {\n\t\t// Managed: a single atomic transaction on the target DB.\n\t\ttry {\n\t\t\tawait targetDb\n\t\t\t\t.transaction()\n\t\t\t\t.execute(async (tx: Transaction<Database>) => {\n\t\t\t\t\t// Replay guard (sequential walks only): committed writes always carry\n\t\t\t\t\t// their checkpoint (below), so a block at/below the cursor has already\n\t\t\t\t\t// been applied — running it again would double-apply deltas.\n\t\t\t\t\tconst opMode = opCursorMode(opts);\n\t\t\t\t\tif (statusMode(opts)) {\n\t\t\t\t\t\tconst row = await tx\n\t\t\t\t\t\t\t.selectFrom(\"subgraphs\")\n\t\t\t\t\t\t\t.select(\"last_processed_block\")\n\t\t\t\t\t\t\t.where(\"name\", \"=\", subgraphName)\n\t\t\t\t\t\t\t.executeTakeFirst();\n\t\t\t\t\t\tif (row && Number(row.last_processed_block) >= blockHeight) {\n\t\t\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (opMode) {\n\t\t\t\t\t\t// Fast path only — the conditional advance below is the guarantee.\n\t\t\t\t\t\tconst row = await tx\n\t\t\t\t\t\t\t.selectFrom(\"subgraph_operations\")\n\t\t\t\t\t\t\t.select(\"cursor_block\")\n\t\t\t\t\t\t\t.where(\"id\", \"=\", opMode.operationId)\n\t\t\t\t\t\t\t.executeTakeFirst();\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow?.cursor_block != null &&\n\t\t\t\t\t\t\tNumber(row.cursor_block) >= blockHeight\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tresult.skipped = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst ctx = new SubgraphContext(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tschemaName,\n\t\t\t\t\t\tsubgraph.schema,\n\t\t\t\t\t\tblockMeta,\n\t\t\t\t\t\tinitialTx,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tjournalEnabled(opts),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst handlerStart = performance.now();\n\t\t\t\t\tconst runResult = await runHandlers(subgraph, matched, ctx);\n\t\t\t\t\thandlerMs = performance.now() - handlerStart;\n\n\t\t\t\t\tresult.processed = runResult.processed;\n\t\t\t\t\tresult.errors = runResult.errors;\n\n\t\t\t\t\tlet flushedWrites = false;\n\t\t\t\t\tif (ctx.pendingOps > 0) {\n\t\t\t\t\t\tconst flushStart = performance.now();\n\t\t\t\t\t\tconst manifest = await ctx.flush();\n\t\t\t\t\t\tflushedWrites = manifest.count > 0;\n\t\t\t\t\t\tif (manifest.count > 0) {\n\t\t\t\t\t\t\tawait emitSubscriptionOutbox(\n\t\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\tmatcher,\n\t\t\t\t\t\t\t\tblock.height,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tflushMs = performance.now() - flushStart;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Checkpoint travels with the writes it covers — a crash can never\n\t\t\t\t\t// leave committed deltas ahead of the checkpoint (fix-f040 B3).\n\t\t\t\t\tconst sm = statusMode(opts);\n\t\t\t\t\tif (sm && flushedWrites) {\n\t\t\t\t\t\tawait updateSubgraphStatus(\n\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t\tsm.status,\n\t\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (opMode && flushedWrites) {\n\t\t\t\t\t\tconst advanced = await advanceOperationCursor(\n\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\topMode.operationId,\n\t\t\t\t\t\t\tblockHeight,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!advanced) {\n\t\t\t\t\t\t\t// A racing writer (zombie/claimer) already covered this height —\n\t\t\t\t\t\t\t// abort OUR writes; the winner's commit stands.\n\t\t\t\t\t\t\tthrow new CursorRaceLostError(opMode.operationId, blockHeight);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tawait applyProgress(tx, runResult);\n\t\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof CursorRaceLostError) {\n\t\t\t\t// Success-shaped: the block IS committed (by the winner). Surfacing\n\t\t\t\t// this as an error would mint a false gap row and re-invite the\n\t\t\t\t// double-apply through gap repair.\n\t\t\t\tlogger.warn(\"cursor race lost — block already covered\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tblockHeight,\n\t\t\t\t\terror: err.message,\n\t\t\t\t});\n\t\t\t\tresult.skipped = true;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst totalMs = performance.now() - blockStart;\n\tresult.timing = {\n\t\ttotalMs: Math.round(totalMs),\n\t\thandlerMs: Math.round(handlerMs),\n\t\tflushMs: Math.round(flushMs),\n\t};\n\n\t// 7. Row count warning — sample every 1000 blocks (uses pg_stat estimate, not COUNT(*))\n\tif (blockHeight % 1000 === 0) {\n\t\ttry {\n\t\t\tconst tables = Object.keys(subgraph.schema);\n\t\t\tfor (const table of tables) {\n\t\t\t\tconst { rows } = await sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(route.dataDb);\n\t\t\t\tconst count = Number((rows[0] as Record<string, unknown>)?.count ?? 0);\n\t\t\t\tif (count >= 10_000_000) {\n\t\t\t\t\tlogger.warn(\"Subgraph table exceeds 10M rows (estimate)\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tcount,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Expected: table may not exist yet (fresh subgraph, first few\n\t\t\t// blocks before DDL runs). Log at debug so real errors —\n\t\t\t// connection, permissions, query plan — aren't invisible.\n\t\t\tlogger.debug(\"Row count sample failed\", {\n\t\t\t\tsubgraph: subgraphName,\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t}\n\n\t\t// Prune reorg-journal entries past finality (fix-f040 B2). Same cadence\n\t\t// as the row sample; retention is generous vs observed reorg depth.\n\t\tif (journalEnabled(opts)) {\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`DELETE FROM \"${schemaName}\".\"_journal\" WHERE \"block_height\" < ${blockHeight - JOURNAL_RETENTION_BLOCKS}`,\n\t\t\t\t)\n\t\t\t\t.execute(route.dataDb)\n\t\t\t\t.catch(() => {\n\t\t\t\t\t// Journal may not exist yet (pre-journal deploy, no writes since).\n\t\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n",
13
14
  "import { getSourceDb } from \"@secondlayer/shared/db\";\nimport type { Transaction } from \"@secondlayer/shared/db\";\nimport {\n\ttype IndexEventRow,\n\tIndexHttpClient,\n\ttype IndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition, SubgraphFilter } from \"../types.ts\";\nimport { type BlockData, loadBlockRange } from \"./batch-loader.ts\";\nimport {\n\treconstructBlock,\n\treconstructEvent,\n\treconstructTransaction,\n\treconstructTxFromEventRow,\n} from \"./reconstruct.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/** Highest canonical block height available to process. */\n\tgetTip(): 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}\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/** Probe targets for a subgraph's filters: decoded type + contract scope when\n * the filter pins one (assetIdentifier \"SP….contract::asset\" or contractId). */\nexport function sparseProbeTargets(\n\tsubgraph: SubgraphDefinition,\n): SparseProbeTarget[] {\n\tconst targets = new Map<string, SparseProbeTarget>();\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 scoped = f as { assetIdentifier?: string; contractId?: string };\n\t\tconst contractId =\n\t\t\tscoped.contractId ?? scoped.assetIdentifier?.split(\"::\")[0];\n\t\tconst key = `${eventType}|${contractId ?? \"\"}`;\n\t\ttargets.set(key, { eventType, ...(contractId ? { contractId } : {}) });\n\t}\n\treturn [...targets.values()];\n}\n\n/** Reads directly from the shared indexer Postgres (the original behavior). */\nexport class PostgresBlockSource implements BlockSource {\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}\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};\n\n// Tx-level source types — matched against /v1/index/transactions, not events.\nconst TX_SOURCE_TYPES = new Set([\"contract_call\", \"contract_deploy\"]);\nconst ALL_INDEX_EVENT_TYPES = [\n\t...new Set(Object.values(EVENT_FILTER_TO_INDEX_TYPE)),\n];\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 event type (the\n * matched tx's events must be complete); otherwise just the referenced types.\n * Shared by the subgraph loader and the chain-trigger evaluator.\n */\nexport function indexEventTypesForFilterTypes(filterTypes: string[]): string[] {\n\tif (filterTypes.some((t) => TX_SOURCE_TYPES.has(t))) {\n\t\treturn ALL_INDEX_EVENT_TYPES;\n\t}\n\tconst types = new Set<string>();\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\nfunction referencedIndexEventTypes(subgraph: SubgraphDefinition): string[] {\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/** 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[],\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) {}\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(): Promise<number> {\n\t\t// Bound advancement to what the Index data plane can serve — never\n\t\t// process past it even if the Streams clock is ahead.\n\t\treturn this.http.getIndexTip();\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] = 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.eventTypes.map((t) =>\n\t\t\t\t\tthis.http.walkEvents(t, fromHeight, toHeight, withTx),\n\t\t\t\t),\n\t\t\t),\n\t\t]);\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(eventLists.flat());\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 list of eventLists) {\n\t\t\tfor (const e of list) {\n\t\t\t\tmap.get(e.block_height)?.events.push(reconstructEvent(e));\n\t\t\t}\n\t\t}\n\t\t// Canonical ordering — multi-type event walks merge here.\n\t\tfor (const bd of map.values()) {\n\t\t\tbd.txs.sort((a, b) => a.tx_index - b.tx_index);\n\t\t\tbd.events.sort((a, b) => a.event_index - b.event_index);\n\t\t}\n\t\treturn map;\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\tconstructor(\n\t\tprivate readonly primary: BlockSource,\n\t\tprivate readonly fallback: BlockSource,\n\t) {}\n\n\tasync getTip(): Promise<number> {\n\t\ttry {\n\t\t\treturn await this.primary.getTip();\n\t\t} catch (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\treturn this.fallback.getTip();\n\t\t}\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\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/**\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 */\nexport function buildChainBlockSource(eventTypes: string[]): BlockSource {\n\treturn new FallbackBlockSource(\n\t\tnew PublicApiBlockSource(buildHttpClient(), eventTypes),\n\t\tpostgresBlockSource,\n\t);\n}\n\nexport function buildHttpClient(): IndexHttpClient {\n\tconst baseUrl =\n\t\tprocess.env.SUBGRAPH_INDEX_API_URL ??\n\t\tprocess.env.STREAMS_API_URL ??\n\t\t\"http://api:3800\";\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tstreamsApiKey:\n\t\t\tprocess.env.STREAMS_INTERNAL_API_KEY ?? \"sk-sl_streams_decode_internal\",\n\t});\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; everything\n * else (and the default) stays on the Postgres tap.\n */\nexport function resolveBlockSource(subgraph?: SubgraphDefinition): BlockSource {\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\treturn new FallbackBlockSource(\n\t\t\tnew PublicApiBlockSource(\n\t\t\t\tbuildHttpClient(),\n\t\t\t\treferencedIndexEventTypes(subgraph),\n\t\t\t\tcanSparseScan(subgraph) ? sparseProbeTargets(subgraph) : undefined,\n\t\t\t\tneedsTransactionData(subgraph),\n\t\t\t),\n\t\t\tpostgresBlockSource,\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 postgresBlockSource;\n}\n",
14
15
  "import type {\n\tBlock,\n\tDatabase,\n\tEvent,\n\tTransaction,\n} from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\n\nexport interface BlockData {\n\tblock: Block;\n\ttxs: Transaction[];\n\tevents: Event[];\n}\n\n/**\n * Load a range of blocks with their transactions and events in 3 parallel queries.\n * Returns a Map keyed by block height. Non-canonical blocks are excluded.\n */\nexport async function loadBlockRange(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n\ttoHeight: number,\n): Promise<Map<number, BlockData>> {\n\tconst [blocks, txs, events] = 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]);\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 result = new Map<number, BlockData>();\n\tfor (const block of blocks) {\n\t\tconst h = Number(block.height);\n\t\tresult.set(h, {\n\t\t\tblock,\n\t\t\ttxs: txsByHeight.get(h) ?? [],\n\t\t\tevents: eventsByHeight.get(h) ?? [],\n\t\t});\n\t}\n\n\treturn result;\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",
15
- "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\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\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// Matcher + runner read `contract_identifier` (the raw node field).\n\t\t\t\t\tcontract_identifier: 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\t}\n}\n",
16
+ "import type { Block, Event, Transaction } from \"@secondlayer/shared/db\";\nimport type {\n\tIndexBlockRow,\n\tIndexEventRow,\n\tIndexTransactionRow,\n} from \"@secondlayer/shared/index-http\";\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// Matcher + runner read `contract_identifier` (the raw node field).\n\t\t\t\t\tcontract_identifier: 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\t}\n}\n",
16
17
  "import { createHash } from \"node:crypto\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { Transaction } from \"kysely\";\nimport type { FlushManifest } from \"./context.ts\";\nimport type { SubscriptionMatcher } from \"./emitter-matcher.ts\";\n\n/**\n * Emit subscription outbox rows for every flushed write that matches an\n * active subscription. Inserted inside the caller's transaction — the\n * outbox write commits (or rolls back) atomically with the subgraph row\n * writes. Zero outbox inserts if no subs match or the kill-switch is set.\n *\n * Set `SECONDLAYER_EMIT_OUTBOX=false` to bypass entirely — useful during\n * backfills or when a receiver is known-down and operators want to drain\n * tenant writes without producing dead outbox.\n */\n\nlet loggedKillSwitch = false;\n\n/** Flush op → event-type verb. A subscriber tracking a mutable row sees the\n * full lifecycle (created → updated → deleted), not just the initial insert. */\nconst OP_VERB = {\n\tinsert: \"created\",\n\tupdate: \"updated\",\n\tdelete: \"deleted\",\n} as const;\n\nexport function isEmitOutboxEnabled(): boolean {\n\treturn process.env.SECONDLAYER_EMIT_OUTBOX !== \"false\";\n}\n\nfunction dedupKey(\n\tsubgraphName: string,\n\ttableName: string,\n\tblockHeight: number,\n\ttxId: string,\n\trowIndex: number,\n\trow: Record<string, unknown>,\n): string {\n\t// Hash of row content + position → stable across replays of the same\n\t// block (unique constraint on (subscription_id, dedup_key) catches\n\t// duplicate emits if the block is reprocessed).\n\tconst canonical = `${subgraphName}:${tableName}:${blockHeight}:${txId}:${rowIndex}:${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 async function emitSubscriptionOutbox(\n\ttx: Transaction<Database>,\n\tsubgraphName: string,\n\tmanifest: FlushManifest,\n\tmatcher: SubscriptionMatcher,\n\tblockHeight: number,\n): Promise<number> {\n\tif (!isEmitOutboxEnabled()) {\n\t\tif (!loggedKillSwitch) {\n\t\t\tlogger.warn(\"SECONDLAYER_EMIT_OUTBOX=false — outbox emission bypassed\");\n\t\t\tloggedKillSwitch = true;\n\t\t}\n\t\treturn 0;\n\t}\n\tloggedKillSwitch = false;\n\n\tif (manifest.count === 0 || matcher.size() === 0) return 0;\n\n\ttype OutboxInsert = {\n\t\tsubscription_id: string;\n\t\tsubgraph_name: string;\n\t\ttable_name: string;\n\t\tblock_height: number;\n\t\ttx_id: string | null;\n\t\trow_pk: Record<string, unknown>;\n\t\tevent_type: string;\n\t\tpayload: Record<string, unknown>;\n\t\tdedup_key: string;\n\t};\n\n\tconst rows: OutboxInsert[] = [];\n\tfor (const write of manifest.writes) {\n\t\tconst subs = matcher.match(subgraphName, write.table, write.row);\n\t\tif (subs.length === 0) continue;\n\n\t\tconst eventType = `${subgraphName}.${write.table}.${OP_VERB[write.op]}`;\n\t\tfor (const s of subs) {\n\t\t\trows.push({\n\t\t\t\tsubscription_id: s.id,\n\t\t\t\tsubgraph_name: subgraphName,\n\t\t\t\ttable_name: write.table,\n\t\t\t\tblock_height: blockHeight,\n\t\t\t\t// Nullish-only — an empty-string txId is still a value (block-level\n\t\t\t\t// write with no specific tx), not \"no tx\".\n\t\t\t\ttx_id: write.pk.txId ?? null,\n\t\t\t\trow_pk: write.pk,\n\t\t\t\tevent_type: eventType,\n\t\t\t\tpayload: write.row,\n\t\t\t\tdedup_key: dedupKey(\n\t\t\t\t\tsubgraphName,\n\t\t\t\t\twrite.table,\n\t\t\t\t\twrite.pk.blockHeight,\n\t\t\t\t\twrite.pk.txId,\n\t\t\t\t\twrite.pk.rowIndex,\n\t\t\t\t\twrite.row,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\t}\n\n\tif (rows.length === 0) return 0;\n\n\t// Bulk INSERT with ON CONFLICT DO NOTHING on (subscription_id, dedup_key)\n\t// so a replayed block is a no-op instead of an error.\n\tawait tx\n\t\t.insertInto(\"subscription_outbox\")\n\t\t.values(rows)\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"subscription_id\", \"dedup_key\"]).doNothing(),\n\t\t)\n\t\t.execute();\n\n\treturn rows.length;\n}\n",
17
18
  "import type { Database, Subscription } from \"@secondlayer/shared/db\";\nimport { listSubscriptions } from \"@secondlayer/shared/db/queries/subscriptions\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport { SubscriptionMatcher } from \"./emitter-matcher.ts\";\n\n/**\n * Singleton matcher populated at processor startup and hot-reloaded via\n * `pg_notify('subscriptions:changed')`. The block-processor reads from it\n * to decide which outbox rows to emit for each flushed write.\n *\n * Per-account listing: in oss/dedicated mode the tenant DB holds all subs\n * for the single account; the matcher loads every row. In platform mode\n * the emitter doesn't run at all (control plane only), so this module is\n * dedicated/oss-only.\n */\n\nexport const matcher = new SubscriptionMatcher();\n\nexport async function refreshMatcher(db: Kysely<Database>): Promise<number> {\n\t// listSubscriptions is account-scoped; the emitter wants every active\n\t// sub so we do a raw query.\n\tconst rows = await sql<Subscription>`\n\t\tSELECT * FROM subscriptions WHERE status = 'active'\n\t`.execute(db);\n\tmatcher.setAll(rows.rows);\n\treturn matcher.size();\n}\n\n// Per-account helper used by tests so the DATABASE_URL-based code path is\n// exercised through listSubscriptions (keeps the query helper in the\n// integration surface).\nexport async function refreshMatcherForAccount(\n\tdb: Kysely<Database>,\n\taccountId: string,\n): Promise<number> {\n\tconst rows = await listSubscriptions(db, accountId);\n\tmatcher.setAll(rows.filter((r: Subscription) => r.status === \"active\"));\n\treturn matcher.size();\n}\n",
18
19
  "import type { Subscription } from \"@secondlayer/shared/db\";\n\n/**\n * Subscription matcher — holds the active-subscriptions cache keyed by\n * `(subgraph_name, table_name)` and evaluates each sub's scalar-only\n * JSONB filter against a row.\n *\n * Filter DSL (v1): scalar operators over string/number/boolean columns.\n * { column: value } → column === value\n * { column: { eq: value } } → column === value\n * { column: { neq: value } } → column !== value\n * { column: { gt|gte|lt|lte: N } } → numeric compare\n * { column: { in: [a, b, c] } } → column ∈ set\n * { } → match all\n *\n * Nested objects, arrays, and non-scalar values are rejected with `false`\n * (never match) — subscribers get logged warnings at sub create time.\n *\n * Multiple conditions AND together. OR is deliberately absent in v1.\n */\n\nexport type FilterPrimitive = string | number | boolean;\nexport type FilterOperator =\n\t| { eq: FilterPrimitive }\n\t| { neq: FilterPrimitive }\n\t| { gt: number | string }\n\t| { gte: number | string }\n\t| { lt: number | string }\n\t| { lte: number | string }\n\t| { in: FilterPrimitive[] };\n\nexport type FilterClause = FilterPrimitive | FilterOperator;\nexport type SubscriptionFilter = Record<string, FilterClause>;\n\nfunction isPrimitive(v: unknown): v is FilterPrimitive {\n\tconst t = typeof v;\n\treturn t === \"string\" || t === \"number\" || t === \"boolean\";\n}\n\n/**\n * Coerce a value to BigInt for arbitrary-precision compare — avoids the\n * silent precision loss of `Number()` on integers past 2^53. Returns\n * `null` for non-integer numerics, which is fine because the filter DSL\n * is documented as scalar-only + integer-amount-aware (Stacks uses\n * uint128 bigint columns everywhere).\n */\nfunction coerceBigInt(v: unknown): bigint | null {\n\tif (typeof v === \"bigint\") return v;\n\tif (typeof v === \"number\") {\n\t\tif (!Number.isFinite(v)) return null;\n\t\tif (!Number.isInteger(v)) return null;\n\t\treturn BigInt(v);\n\t}\n\tif (typeof v === \"string\" && /^-?\\d+$/.test(v)) {\n\t\ttry {\n\t\t\treturn BigInt(v);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Float compare fallback — used when a value isn't a clean integer\n * (rare in subgraph columns but defensible for user-supplied filters).\n */\nfunction coerceFloat(v: unknown): number | null {\n\tif (typeof v === \"number\" && Number.isFinite(v)) return v;\n\tif (typeof v === \"bigint\") return Number(v);\n\tif (typeof v === \"string\" && v !== \"\" && !Number.isNaN(Number(v))) {\n\t\treturn Number(v);\n\t}\n\treturn null;\n}\n\nfunction compareNumeric(a: unknown, b: unknown): 0 | 1 | -1 | null {\n\tconst ba = coerceBigInt(a);\n\tconst bb = coerceBigInt(b);\n\tif (ba !== null && bb !== null) {\n\t\tif (ba === bb) return 0;\n\t\treturn ba > bb ? 1 : -1;\n\t}\n\tconst fa = coerceFloat(a);\n\tconst fb = coerceFloat(b);\n\tif (fa === null || fb === null) return null;\n\tif (fa === fb) return 0;\n\treturn fa > fb ? 1 : -1;\n}\n\nfunction matchClause(rowValue: unknown, clause: FilterClause): boolean {\n\t// Reject non-primitive row values — `{ value: {...} }` should not\n\t// match `filter: { value: \"[object Object]\" }` via loose stringify.\n\t// Bigints are not primitives in the JSON sense but are supported\n\t// scalar inputs from subgraph rows.\n\tconst rowIsPrimitive = isPrimitive(rowValue) || typeof rowValue === \"bigint\";\n\n\tif (isPrimitive(clause)) {\n\t\tif (!rowIsPrimitive) return false;\n\t\tif (\n\t\t\ttypeof clause === \"number\" ||\n\t\t\ttypeof rowValue === \"number\" ||\n\t\t\ttypeof rowValue === \"bigint\"\n\t\t) {\n\t\t\tconst cmp = compareNumeric(rowValue, clause);\n\t\t\tif (cmp !== null) return cmp === 0;\n\t\t}\n\t\treturn rowValue === clause || String(rowValue) === String(clause);\n\t}\n\n\tif (clause === null || typeof clause !== \"object\" || Array.isArray(clause)) {\n\t\treturn false;\n\t}\n\n\tconst keys = Object.keys(clause);\n\tif (keys.length !== 1) return false;\n\tconst op = keys[0];\n\n\tconst c = clause as Record<string, unknown>;\n\tswitch (op) {\n\t\tcase \"eq\":\n\t\t\treturn matchClause(rowValue, c.eq as FilterPrimitive);\n\t\tcase \"neq\":\n\t\t\treturn !matchClause(rowValue, c.neq as FilterPrimitive);\n\t\tcase \"gt\":\n\t\tcase \"gte\":\n\t\tcase \"lt\":\n\t\tcase \"lte\": {\n\t\t\tif (!rowIsPrimitive) return false;\n\t\t\tconst cmp = compareNumeric(rowValue, c[op]);\n\t\t\tif (cmp === null) return false;\n\t\t\tif (op === \"gt\") return cmp > 0;\n\t\t\tif (op === \"gte\") return cmp >= 0;\n\t\t\tif (op === \"lt\") return cmp < 0;\n\t\t\treturn cmp <= 0;\n\t\t}\n\t\tcase \"in\": {\n\t\t\tconst list = c.in;\n\t\t\tif (!Array.isArray(list)) return false;\n\t\t\tif (!rowIsPrimitive) return false;\n\t\t\treturn list.some(\n\t\t\t\t(item) => isPrimitive(item) && matchClause(rowValue, item),\n\t\t\t);\n\t\t}\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nexport function matchesFilter(\n\tfilter: SubscriptionFilter | null | undefined,\n\trow: Record<string, unknown>,\n): boolean {\n\tif (!filter || Object.keys(filter).length === 0) return true;\n\tfor (const [col, clause] of Object.entries(filter)) {\n\t\tif (!matchClause(row[col], clause)) return false;\n\t}\n\treturn true;\n}\n\n// ── Cache keyed by (subgraph_name, table_name) ──────────────────────────\n\ntype MatcherKey = string;\n\nfunction key(subgraphName: string, tableName: string): MatcherKey {\n\treturn `${subgraphName}\u0000${tableName}`;\n}\n\nexport class SubscriptionMatcher {\n\tprivate readonly byKey = new Map<MatcherKey, Subscription[]>();\n\tprivate readonly byId = new Map<string, Subscription>();\n\n\t/** Replace the entire cache with a fresh snapshot. */\n\tsetAll(subs: Subscription[]): void {\n\t\tthis.byKey.clear();\n\t\tthis.byId.clear();\n\t\tfor (const sub of subs) {\n\t\t\tif (sub.status !== \"active\") continue;\n\t\t\t// This matcher keys on (subgraph, table) row writes; chain\n\t\t\t// subscriptions react to raw chain events and never flow through it.\n\t\t\tif (sub.kind !== \"subgraph\" || !sub.subgraph_name || !sub.table_name)\n\t\t\t\tcontinue;\n\t\t\tthis.byId.set(sub.id, sub);\n\t\t\tconst k = key(sub.subgraph_name, sub.table_name);\n\t\t\tconst arr = this.byKey.get(k);\n\t\t\tif (arr) arr.push(sub);\n\t\t\telse this.byKey.set(k, [sub]);\n\t\t}\n\t}\n\n\t/** Returns active subs for a (subgraph, table) whose filter matches the row. */\n\tmatch(\n\t\tsubgraphName: string,\n\t\ttableName: string,\n\t\trow: Record<string, unknown>,\n\t): Subscription[] {\n\t\tconst bucket = this.byKey.get(key(subgraphName, tableName));\n\t\tif (!bucket) return [];\n\t\tconst hits: Subscription[] = [];\n\t\tfor (const sub of bucket) {\n\t\t\tif (matchesFilter(sub.filter as SubscriptionFilter, row)) hits.push(sub);\n\t\t}\n\t\treturn hits;\n\t}\n\n\thas(subgraphName: string, tableName: string): boolean {\n\t\treturn this.byKey.has(key(subgraphName, tableName));\n\t}\n\n\tsize(): number {\n\t\treturn this.byId.size;\n\t}\n\n\tget(id: string): Subscription | undefined {\n\t\treturn this.byId.get(id);\n\t}\n}\n",
19
20
  "import type { Database } from \"@secondlayer/shared/db\";\nimport type { Kysely } from \"kysely\";\nimport type { ProcessBlockTiming } from \"./block-processor.ts\";\n\ninterface StatsEntry {\n\tsubgraphName: string;\n\tbucketStart: Date;\n\tblocksProcessed: number;\n\ttotalTimeMs: number;\n\thandlerTimeMs: number;\n\tflushTimeMs: number;\n\tmaxBlockTimeMs: number;\n\tmaxHandlerTimeMs: number;\n\ttotalOps: number;\n\tisCatchup: boolean;\n}\n\nconst FLUSH_INTERVAL_BLOCKS = 100;\nconst FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Accumulates per-block timing stats and flushes to DB periodically.\n * One instance per subgraph during catchup/reindex/live processing.\n */\nexport class StatsAccumulator {\n\tprivate current: StatsEntry;\n\tprivate lastFlush = Date.now();\n\n\tconstructor(\n\t\tprivate subgraphName: string,\n\t\tprivate isCatchup: boolean,\n\t) {\n\t\tthis.current = this.newEntry();\n\t}\n\n\trecord(timing: ProcessBlockTiming, opsCount: number): void {\n\t\tthis.current.blocksProcessed++;\n\t\tthis.current.totalTimeMs += timing.totalMs;\n\t\tthis.current.handlerTimeMs += timing.handlerMs;\n\t\tthis.current.flushTimeMs += timing.flushMs;\n\t\tthis.current.maxBlockTimeMs = Math.max(\n\t\t\tthis.current.maxBlockTimeMs,\n\t\t\ttiming.totalMs,\n\t\t);\n\t\tthis.current.maxHandlerTimeMs = Math.max(\n\t\t\tthis.current.maxHandlerTimeMs,\n\t\t\ttiming.handlerMs,\n\t\t);\n\t\tthis.current.totalOps += opsCount;\n\t}\n\n\tshouldFlush(): boolean {\n\t\treturn (\n\t\t\tthis.current.blocksProcessed >= FLUSH_INTERVAL_BLOCKS ||\n\t\t\tDate.now() - this.lastFlush >= FLUSH_INTERVAL_MS\n\t\t);\n\t}\n\n\tasync flush(db: Kysely<Database>): Promise<void> {\n\t\tif (this.current.blocksProcessed === 0) return;\n\n\t\tconst entry = this.current;\n\t\tthis.current = this.newEntry();\n\t\tthis.lastFlush = Date.now();\n\n\t\tconst avgOpsPerBlock =\n\t\t\tentry.blocksProcessed > 0 ? entry.totalOps / entry.blocksProcessed : 0;\n\n\t\tawait db\n\t\t\t.insertInto(\"subgraph_processing_stats\")\n\t\t\t.values({\n\t\t\t\tsubgraph_name: entry.subgraphName,\n\t\t\t\tbucket_start: entry.bucketStart,\n\t\t\t\tbucket_end: new Date(),\n\t\t\t\tblocks_processed: entry.blocksProcessed,\n\t\t\t\ttotal_time_ms: Math.round(entry.totalTimeMs),\n\t\t\t\thandler_time_ms: Math.round(entry.handlerTimeMs),\n\t\t\t\tflush_time_ms: Math.round(entry.flushTimeMs),\n\t\t\t\tmax_block_time_ms: Math.round(entry.maxBlockTimeMs),\n\t\t\t\tmax_handler_time_ms: Math.round(entry.maxHandlerTimeMs),\n\t\t\t\tavg_ops_per_block: Number.parseFloat(avgOpsPerBlock.toFixed(2)),\n\t\t\t\tis_catchup: entry.isCatchup,\n\t\t\t})\n\t\t\t.execute();\n\t}\n\n\tprivate newEntry(): StatsEntry {\n\t\treturn {\n\t\t\tsubgraphName: this.subgraphName,\n\t\t\tbucketStart: new Date(),\n\t\t\tblocksProcessed: 0,\n\t\t\ttotalTimeMs: 0,\n\t\t\thandlerTimeMs: 0,\n\t\t\tflushTimeMs: 0,\n\t\t\tmaxBlockTimeMs: 0,\n\t\t\tmaxHandlerTimeMs: 0,\n\t\t\ttotalOps: 0,\n\t\t\tisCatchup: this.isCatchup,\n\t\t};\n\t}\n}\n",
20
21
  "import { getTargetDb } from \"@secondlayer/shared/db\";\nimport { getSubgraph } from \"@secondlayer/shared/db/queries/subgraphs\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { type BlockData, avgEventsPerBlock } from \"./batch-loader.ts\";\nimport {\n\ttype ProcessBlockResult,\n\tprocessBlockWithRetry,\n} from \"./block-processor.ts\";\nimport { resolveBlockSource } from \"./block-source.ts\";\nimport { StatsAccumulator } from \"./stats.ts\";\n\nconst LOG_INTERVAL = 1000;\nconst STANDARD_CATCHUP_BATCH_CONFIG = {\n\tdefaultBatchSize: 500,\n\tminBatchSize: 100,\n\tmaxBatchSize: 1000,\n\tprefetch: true,\n};\n\nconst catchingUp = new Set<string>();\n\n/**\n * f057 guard: `recordLiveProgress` (subgraphs.ts) writes `last_processed_block`\n * unconditionally — no monotonic guard — because the reorg rewind MUST be able\n * to move the cursor backward. That means a catch-up walk's forward writes and\n * a reorg's backward rewind must never interleave for the same subgraph, or\n * whichever commits last wins regardless of correctness. `catchingUp` (above)\n * only excludes concurrent catch-ups; it does nothing against a reorg.\n *\n * Both writers can only ever race within the SAME process: catch-up only ever\n * runs on the catch-up leader (processor.ts `runCatchUp`), and the reorg\n * NOTIFY listener runs on every process including that leader — so an\n * in-process guard is sufficient; no cross-process DB lock is needed.\n *\n * Two pieces, used together by catchUpSubgraph (below) and handleSubgraphReorg\n * (reorg.ts):\n *\n * - `withSubgraphBlockLock` is a per-subgraph mutex held for the duration of\n * ONE block's write — catch-up acquires it around each individual block it\n * commits (not around the whole walk), and the reorg handler acquires it\n * around its entire delete+reprocess+rewind sequence for a subgraph. So a\n * reorg only ever waits out a single in-flight block commit, never an\n * entire remaining catch-up walk — and since the lock is per-subgraph name,\n * a slow catch-up on one subgraph never stalls reorg handling for another\n * (handleSubgraphReorg processes subgraphs sequentially).\n * - `reorgEpoch` is a monotonic per-subgraph counter, bumped by\n * handleSubgraphReorg BEFORE it acquires the lock (so the bump is visible\n * immediately, independent of how long the lock wait takes, and is never\n * \"cleared\" — there's no race in un-setting a flag too early). catchUpSubgraph\n * snapshots the epoch once at the start of its walk and, after acquiring the\n * lock for each block, checks it again: a changed epoch means a reorg\n * touched this subgraph's cursor at some point during the walk, so the\n * walk's local progress state can no longer be trusted — it aborts the\n * whole tick without writing anything further. The next catch-up tick\n * re-reads `last_processed_block` fresh from the DB (line ~108) and resumes\n * correctly from the post-reorg cursor.\n */\nconst subgraphBlockLockHeld = new Set<string>();\nconst subgraphBlockLockWaiters = new Map<string, Array<() => void>>();\nconst reorgEpoch = new Map<string, number>();\n\nasync function acquireSubgraphBlockLock(name: string): Promise<() => void> {\n\tif (!subgraphBlockLockHeld.has(name)) {\n\t\tsubgraphBlockLockHeld.add(name);\n\t\treturn () => releaseSubgraphBlockLock(name);\n\t}\n\treturn new Promise<() => void>((resolve) => {\n\t\tconst waiters = subgraphBlockLockWaiters.get(name) ?? [];\n\t\twaiters.push(() => resolve(() => releaseSubgraphBlockLock(name)));\n\t\tsubgraphBlockLockWaiters.set(name, waiters);\n\t});\n}\n\nfunction releaseSubgraphBlockLock(name: string): void {\n\tconst waiters = subgraphBlockLockWaiters.get(name);\n\tif (waiters && waiters.length > 0) {\n\t\tconst next = waiters.shift() as () => void;\n\t\tif (waiters.length === 0) subgraphBlockLockWaiters.delete(name);\n\t\tnext(); // hand the lock straight to the next waiter (FIFO), stays held\n\t\treturn;\n\t}\n\tsubgraphBlockLockHeld.delete(name);\n}\n\n/** Run `fn` (a single block's write, or a reorg's whole rewind) holding the\n * per-subgraph block lock. Exported for reorg.ts. */\nexport async function withSubgraphBlockLock<T>(\n\tname: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst release = await acquireSubgraphBlockLock(name);\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/** Bump a subgraph's reorg epoch. Call BEFORE acquiring the block lock so the\n * bump is visible to any concurrent catch-up immediately. Exported for\n * reorg.ts. */\nexport function bumpReorgEpoch(name: string): void {\n\treorgEpoch.set(name, (reorgEpoch.get(name) ?? 0) + 1);\n}\n\nfunction getReorgEpoch(name: string): number {\n\treturn reorgEpoch.get(name) ?? 0;\n}\n\n/** Thrown inside the lock to unwind a catch-up walk when a reorg's epoch bump\n * is observed mid-walk — distinct from a real processing failure so the\n * caller aborts silently instead of marking the subgraph \"error\". */\nclass ReorgEpochChangedError extends Error {\n\tconstructor(name: string) {\n\t\tsuper(`reorg epoch changed for ${name} mid catch-up`);\n\t\tthis.name = \"ReorgEpochChangedError\";\n\t}\n}\n\ntype CatchupBatchConfig = {\n\tdefaultBatchSize: number;\n\tminBatchSize: number;\n\tmaxBatchSize: number;\n\tprefetch: boolean;\n};\n\ntype CatchupBatchEnv = {\n\tSUBGRAPH_CATCHUP_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_MIN_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_MAX_BATCH_SIZE?: string;\n\tSUBGRAPH_CATCHUP_PREFETCH?: string;\n};\n\nfunction parsePositiveInt(value: string | undefined): number | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst parsed = Number.parseInt(value, 10);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction parseBoolean(value: string | undefined): boolean | undefined {\n\tif (value == null || value.trim() === \"\") return undefined;\n\tconst normalized = value.trim().toLowerCase();\n\tif (normalized === \"true\") return true;\n\tif (normalized === \"false\") return false;\n\treturn undefined;\n}\n\nexport function resolveCatchupBatchConfig(\n\tenv: CatchupBatchEnv = process.env as CatchupBatchEnv,\n): CatchupBatchConfig {\n\tconst base = STANDARD_CATCHUP_BATCH_CONFIG;\n\tconst minBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_MIN_BATCH_SIZE) ?? base.minBatchSize;\n\tconst maxBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_MAX_BATCH_SIZE) ?? base.maxBatchSize;\n\tconst defaultBatchSize =\n\t\tparsePositiveInt(env.SUBGRAPH_CATCHUP_BATCH_SIZE) ?? base.defaultBatchSize;\n\n\treturn {\n\t\tminBatchSize,\n\t\tmaxBatchSize,\n\t\tdefaultBatchSize: Math.min(\n\t\t\tMath.max(defaultBatchSize, minBatchSize),\n\t\t\tmaxBatchSize,\n\t\t),\n\t\tprefetch: parseBoolean(env.SUBGRAPH_CATCHUP_PREFETCH) ?? base.prefetch,\n\t};\n}\n\n/**\n * Adjust batch size based on event density.\n * Sparse blocks (early chain) → larger batches. Dense blocks → smaller batches.\n */\nfunction adjustBatchSize(\n\tcurrent: number,\n\tavgEvents: number,\n\tconfig: CatchupBatchConfig,\n): number {\n\tif (avgEvents > 50)\n\t\treturn Math.max(Math.round(current * 0.5), config.minBatchSize);\n\tif (avgEvents < 10)\n\t\treturn Math.min(Math.round(current * 1.5), config.maxBatchSize);\n\treturn current;\n}\n\n/**\n * Catch a subgraph up from its last_processed_block to the chain tip.\n * Uses batch loading (3 queries per batch instead of 3 per block) and\n * plan-aware pipeline prefetching.\n */\nexport async function catchUpSubgraph(\n\tsubgraph: SubgraphDefinition,\n\tsubgraphName: string,\n): Promise<number> {\n\tif (catchingUp.has(subgraphName)) return 0;\n\tcatchingUp.add(subgraphName);\n\n\ttry {\n\t\tconst source = resolveBlockSource(subgraph);\n\t\tconst targetDb = getTargetDb();\n\n\t\t// Re-read from DB to avoid stale lastProcessedBlock\n\t\tconst subgraphRow = await getSubgraph(targetDb, subgraphName);\n\t\tif (!subgraphRow) return 0;\n\t\tconst lastProcessedBlock = Number(subgraphRow.last_processed_block);\n\n\t\t// Chain tip comes from the block source (indexer DB today; Streams clock\n\t\t// once re-pointed).\n\t\tconst chainTip = await source.getTip();\n\t\tif (chainTip <= 0 || lastProcessedBlock >= chainTip) return 0;\n\n\t\tconst subgraphStart = Number(subgraphRow.start_block) || 1;\n\t\tconst startBlock = Math.max(lastProcessedBlock + 1, subgraphStart);\n\t\tconst totalBlocks = chainTip - lastProcessedBlock;\n\n\t\tlogger.info(\"Subgraph catch-up starting\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tfrom: startBlock,\n\t\t\tto: chainTip,\n\t\t\tblocks: totalBlocks,\n\t\t});\n\n\t\tconst stats = new StatsAccumulator(subgraphName, true);\n\t\tlet processed = 0;\n\t\tconst batchConfig = resolveCatchupBatchConfig();\n\t\tlet batchSize = batchConfig.defaultBatchSize;\n\t\tlet currentHeight = startBlock;\n\t\t// f057: snapshot the epoch once — see the guard comment above\n\t\t// `subgraphBlockLockHeld` for the invariant this protects.\n\t\tconst walkEpoch = getReorgEpoch(subgraphName);\n\n\t\t// Pipeline: start loading first batch and track the prefetched range.\n\t\t// batchEnd must match what was actually loaded — not recalculated from a\n\t\t// potentially resized batchSize (adaptive sizing can change it between iterations).\n\t\tlet prefetchedBatchEnd = Math.min(currentHeight + batchSize - 1, chainTip);\n\t\tlet nextBatchPromise = batchConfig.prefetch\n\t\t\t? source.loadBlockRange(currentHeight, prefetchedBatchEnd)\n\t\t\t: undefined;\n\n\t\twhile (currentHeight <= chainTip) {\n\t\t\t// Check if subgraph status changed (e.g. reindex started) — bail if so\n\t\t\tconst currentRow = await getSubgraph(targetDb, subgraphName);\n\t\t\tif (!currentRow || currentRow.status !== \"active\") {\n\t\t\t\tlogger.info(\"Subgraph status changed, stopping catch-up\", {\n\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\tstatus: currentRow?.status ?? \"deleted\",\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet batchEnd: number;\n\t\t\tlet batch: Map<number, BlockData>;\n\t\t\tif (nextBatchPromise) {\n\t\t\t\tbatch = await nextBatchPromise;\n\t\t\t\tbatchEnd = prefetchedBatchEnd;\n\n\t\t\t\t// Start prefetching next batch while we process this one.\n\t\t\t\tconst nextStart = batchEnd + 1;\n\t\t\t\tif (nextStart <= chainTip) {\n\t\t\t\t\tprefetchedBatchEnd = Math.min(nextStart + batchSize - 1, chainTip);\n\t\t\t\t\tnextBatchPromise = source.loadBlockRange(\n\t\t\t\t\t\tnextStart,\n\t\t\t\t\t\tprefetchedBatchEnd,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tnextBatchPromise = undefined;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Low-memory mode: load only the current batch, process it, then size\n\t\t\t\t// and load the next batch after this iteration completes.\n\t\t\t\tbatchEnd = Math.min(currentHeight + batchSize - 1, chainTip);\n\t\t\t\tbatch = await source.loadBlockRange(currentHeight, batchEnd);\n\t\t\t}\n\n\t\t\t// Process each block from pre-loaded data\n\t\t\tlet stopCatchup = false;\n\n\t\t\tfor (let height = currentHeight; height <= batchEnd; height++) {\n\t\t\t\tlet blockData = batch.get(height);\n\t\t\t\tif (!blockData) {\n\t\t\t\t\t// Refetch once — distinguishes a transient source hiccup from a\n\t\t\t\t\t// genuinely absent block.\n\t\t\t\t\tblockData = (await source.loadBlockRange(height, height)).get(height);\n\t\t\t\t}\n\t\t\t\tif (!blockData) {\n\t\t\t\t\t// Near the tip this is usually a reorg race (the height briefly\n\t\t\t\t\t// has no canonical block). Stop the tick with the cursor BEFORE\n\t\t\t\t\t// this height — the next catch-up re-attempts it. Skipping it\n\t\t\t\t\t// instead would silently drop its events (fix-f040 B5).\n\t\t\t\t\tlogger.warn(\"Block missing during catch-up, deferring to next tick\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tblockHeight: height,\n\t\t\t\t\t});\n\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst preloaded = blockData;\n\n\t\t\t\tlet result: ProcessBlockResult;\n\t\t\t\ttry {\n\t\t\t\t\t// f057: hold the per-subgraph block lock for this one block's\n\t\t\t\t\t// write, and bail without writing if a reorg's epoch bump landed\n\t\t\t\t\t// mid-walk — see the guard comment near subgraphBlockLockHeld.\n\t\t\t\t\tresult = await withSubgraphBlockLock(subgraphName, async () => {\n\t\t\t\t\t\tif (getReorgEpoch(subgraphName) !== walkEpoch) {\n\t\t\t\t\t\t\tthrow new ReorgEpochChangedError(subgraphName);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn processBlockWithRetry(subgraph, subgraphName, height, {\n\t\t\t\t\t\t\tpreloaded,\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof ReorgEpochChangedError) {\n\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\"Reorg detected mid catch-up, aborting walk without writing further progress\",\n\t\t\t\t\t\t\t{ subgraph: subgraphName, blockHeight: height },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// Persistent failure: halt with the cursor before this block.\n\t\t\t\t\t// Advancing past it would bake the missing events into every\n\t\t\t\t\t// downstream row (fix-f040 B5).\n\t\t\t\t\tconst errorMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tlogger.error(\"Block processing failed persistently during catch-up\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tblockHeight: height,\n\t\t\t\t\t\terror: errorMsg,\n\t\t\t\t\t});\n\t\t\t\t\tconst { updateSubgraphStatus, recordSubgraphProcessed } =\n\t\t\t\t\t\tawait import(\"@secondlayer/shared/db/queries/subgraphs\");\n\t\t\t\t\tawait recordSubgraphProcessed(\n\t\t\t\t\t\ttargetDb,\n\t\t\t\t\t\tsubgraphName,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\t`catch-up halted at block ${height}: ${errorMsg}`,\n\t\t\t\t\t).catch(() => {});\n\t\t\t\t\tawait updateSubgraphStatus(targetDb, subgraphName, \"error\").catch(\n\t\t\t\t\t\t() => {},\n\t\t\t\t\t);\n\t\t\t\t\tstopCatchup = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprocessed++;\n\n\t\t\t\tif (result.timing) {\n\t\t\t\t\tstats.record(result.timing, result.processed);\n\t\t\t\t\tif (stats.shouldFlush()) {\n\t\t\t\t\t\tawait stats.flush(targetDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (processed % LOG_INTERVAL === 0) {\n\t\t\t\t\tlogger.info(\"Subgraph catch-up progress\", {\n\t\t\t\t\t\tsubgraph: subgraphName,\n\t\t\t\t\t\tprocessed,\n\t\t\t\t\t\ttotal: totalBlocks,\n\t\t\t\t\t\tcurrentBlock: height,\n\t\t\t\t\t\tpct: Math.round((processed / totalBlocks) * 100),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// A missing block or persistent failure stops the walk with the\n\t\t\t// cursor before the problem height — never record-and-skip.\n\t\t\tif (stopCatchup) break;\n\n\t\t\t// Adaptive batch sizing based on event density\n\t\t\tconst avg = avgEventsPerBlock(batch);\n\t\t\tbatchSize = adjustBatchSize(batchSize, avg, batchConfig);\n\n\t\t\tcurrentHeight = batchEnd + 1;\n\t\t}\n\n\t\t// Flush remaining stats\n\t\tawait stats.flush(targetDb);\n\n\t\tlogger.info(\"Subgraph catch-up complete\", {\n\t\t\tsubgraph: subgraphName,\n\t\t\tprocessed,\n\t\t});\n\n\t\treturn processed;\n\t} finally {\n\t\tcatchingUp.delete(subgraphName);\n\t}\n}\n"
21
22
  ],
22
- "mappings": ";;;;AACA;AACA;AACA;;;ACHA;;;ACCA;;;ADOO,IAAM,WAAuC;AAAA,EACnD,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AAAA,EACL,WAAW;AAAA,EACX,SAAS;AAAA,EACT,WAAW;AAAA,EACX,OAAO;AACR;AAOA,SAAS,oBAAoB,CAAC,OAAwB;AAAA,EACrD,IAAI,UAAU,QAAQ,UAAU;AAAA,IAAW,OAAO;AAAA,EAClD,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU;AAAA,IACjD,OAAO,OAAO,KAAK;AAAA,EACpB,IAAI,OAAO,UAAU;AAAA,IAAW,OAAO,QAAQ,SAAS;AAAA,EACxD,OAAO,I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