@secondlayer/shared 15.4.0 → 15.4.2
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.
- package/dist/src/db/queries/contracts.d.ts +26 -1
- package/dist/src/db/queries/contracts.js +47 -1
- package/dist/src/db/queries/contracts.js.map +3 -3
- package/dist/src/db/queries/integrity.d.ts +13 -1
- package/dist/src/db/queries/integrity.js +24 -1
- package/dist/src/db/queries/integrity.js.map +3 -3
- package/dist/src/index-http.d.ts +14 -0
- package/dist/src/index-http.js +4 -1
- package/dist/src/index-http.js.map +3 -3
- package/dist/src/index.d.ts +9 -0
- package/dist/src/index.js.map +2 -2
- package/package.json +1 -1
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/db/queries/integrity.ts", "../src/env.ts", "../src/logger.ts", "../src/runtime/backup.ts", "../src/db/queries/instance.ts", "../src/db/queries/sync-scope.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\nimport { stacksNetworkFromEnv } from \"./instance.ts\";\nimport { getSyncScope, upsertSyncScope } from \"./sync-scope.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\n/**\n * The three honest answers to \"what is the chain tip\", so no reader derives its\n * own:\n *\n * seen highest block height the indexer has received (`index_progress`)\n * canonical highest block currently canonical in `blocks`\n * contiguous highest height with no gap below it (`index_progress`)\n *\n * `null` when nothing is recorded yet. The node's own tip is a different\n * question (it needs RPC) and is not answered here.\n */\nexport type ChainTipKind = \"seen\" | \"canonical\" | \"contiguous\";\n\nexport async function resolveChainTip(\n\tdb: Kysely<Database>,\n\tkind: ChainTipKind,\n\topts: { network?: string } = {},\n): Promise<number | null> {\n\tif (kind === \"canonical\") {\n\t\tconst row = await db\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.select(\"height\")\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.orderBy(\"height\", \"desc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? Number(row.height) : null;\n\t}\n\tconst column =\n\t\tkind === \"seen\" ? \"highest_seen_block\" : \"last_contiguous_block\";\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(column)\n\t\t.where(\"network\", \"=\", opts.network ?? stacksNetworkFromEnv())\n\t\t.executeTakeFirst();\n\treturn row ? Number(row[column]) : null;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nasync function lowestCanonicalHeight(\n\tdb: Kysely<Database>,\n\tabove: number,\n): Promise<number | null> {\n\tconst { rows } = await sql<{ min: string | null }>`\n\t\tSELECT MIN(height) AS min FROM blocks\n\t\tWHERE canonical = true AND height > ${above}\n\t`.execute(db);\n\tconst min = rows[0]?.min;\n\treturn min === null || min === undefined ? null : Number(min);\n}\n\n/**\n * The height contiguity is measured from: where this instance's canonical\n * history begins, never an assumed 1. A recorded sync scope above the lowest\n * stored block wins (an operator or the indexer declared that history below it\n * is deliberately absent); otherwise it is the lowest canonical block.\n *\n * `null` when no canonical block is stored yet.\n */\nexport async function resolveContiguousFloor(\n\tdb: Kysely<Database>,\n\tnetwork: string = stacksNetworkFromEnv(),\n): Promise<number | null> {\n\tconst lowest = await lowestCanonicalHeight(db, -1);\n\tif (lowest === null) return null;\n\tconst scope = await getSyncScope(db, network);\n\treturn Math.max(lowest, scope?.start_height ?? 0);\n}\n\n/**\n * First block above genesis lands on an instance whose cursor is still 0.\n *\n * A node on a cached chain (a Clarinet devnet) announces its genesis block at\n * boot and then first shows the chain at its real height; the heights between\n * are never delivered. Counting from that lone genesis row leaves the cursor\n * pinned below a hole nobody can fill, so declare the lowest block above\n * genesis as the instance's start (the same declaration a forward-only archive\n * restore makes) and return the floor contiguity now counts from. A scope that\n * already exists is never overwritten.\n */\nexport async function seedContiguousFloor(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<number | null> {\n\tconst lowest = await lowestCanonicalHeight(db, -1);\n\tconst aboveGenesis = await lowestCanonicalHeight(db, 0);\n\tif (\n\t\tlowest === 0 &&\n\t\taboveGenesis !== null &&\n\t\taboveGenesis > 1 &&\n\t\t(await getSyncScope(db, network)) === null\n\t) {\n\t\tawait upsertSyncScope(db, {\n\t\t\tnetwork,\n\t\t\tstart_height: aboveGenesis,\n\t\t\ttarget_height: null,\n\t\t\tbootstrap: {\n\t\t\t\tsource: \"import\",\n\t\t\t\tmanifest_digest: null,\n\t\t\t\tgenesis_hash: null,\n\t\t\t},\n\t\t});\n\t}\n\treturn resolveContiguousFloor(db, network);\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type ShortBlock = {\n\theight: number;\n\texpectedTxCount: number;\n\tactualTxCount: number;\n};\n\n/**\n * Canonical heights where `transactions` holds fewer (or more) rows than the\n * block was supposed to. `blocks.tx_count` is set by `persistBlock` from the\n * incoming block, so a mismatch means a later write silently moved or dropped\n * a tx after that block was persisted — a reorg replaying the wrong height, a\n * same-height tx_id collision, or a bug in the persist path itself. Ingest\n * used to report the *parsed* count, not the inserted count, so this kind of\n * short block was invisible; a skipped insert looked identical to success.\n *\n * Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this\n * column existed have no baseline to check against. Also scoped to a recent\n * window by default (like `findBrokenLinks`): every new block sets\n * `tx_count`, so the eligible range only grows, and a short block is an\n * active-repair concern, not something worth a full-table scan every cycle.\n */\nexport async function findShortBlocks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<ShortBlock[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\ttx_count: number;\n\t\tactual_count: string | number;\n\t}>`\n\t\tSELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count\n\t\t FROM blocks b\n\t\t LEFT JOIN transactions t ON t.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.tx_count IS NOT NULL\n\t\t ${windowClause}\n\t\t GROUP BY b.height, b.tx_count\n\t\tHAVING COUNT(t.tx_id) <> b.tx_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedTxCount: Number(r.tx_count),\n\t\tactualTxCount: Number(r.actual_count),\n\t}));\n}\n\nfunction recentWindow(\n\twindowSize: number | null,\n\tcolumn: ReturnType<typeof sql.ref>,\n) {\n\treturn windowSize === null\n\t\t? sql``\n\t\t: sql`AND ${column} > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n}\n\nexport type DuplicateTxIndex = {\n\theight: number;\n\ttxIndex: number;\n\tcount: number;\n};\n\n/**\n * `(block_height, tx_index)` pairs held by more than one transaction on a\n * canonical block. A transaction's index is its position in the block, so each\n * pair is unique; two rows sharing one make Streams and Index order that block\n * ambiguously. Windowed by default; the daily canonical audit passes its own\n * window.\n */\nexport async function findDuplicateTxIndexes(\n\tdb: Kysely<Database>,\n\topts: {\n\t\twindow?: number | null;\n\t\t/** Absolute lower bound: only heights above it. */\n\t\tfloorHeight?: number;\n\t\tlimit?: number;\n\t} = {},\n): Promise<DuplicateTxIndex[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst floorClause =\n\t\topts.floorHeight === undefined\n\t\t\t? sql``\n\t\t\t: sql`AND t.block_height > ${opts.floorHeight}`;\n\tconst { rows } = await sql<{\n\t\tblock_height: string | number;\n\t\ttx_index: string | number;\n\t\tn: string | number;\n\t}>`\n\t\tSELECT t.block_height, t.tx_index, COUNT(*) AS n\n\t\t FROM transactions t\n\t\t JOIN blocks b ON b.height = t.block_height AND b.canonical = true\n\t\t WHERE true\n\t\t ${recentWindow(windowSize, sql.ref(\"t.block_height\"))}\n\t\t ${floorClause}\n\t\t GROUP BY t.block_height, t.tx_index\n\t\tHAVING COUNT(*) > 1\n\t\t ORDER BY t.block_height, t.tx_index\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.block_height),\n\t\ttxIndex: Number(r.tx_index),\n\t\tcount: Number(r.n),\n\t}));\n}\n\nexport type BurnHeightRegression = {\n\theight: number;\n\tburnBlockHeight: number;\n\tpreviousBurnBlockHeight: number;\n};\n\n/**\n * Canonical blocks whose `burn_block_height` is lower than the canonical block\n * below them. Stacks blocks are anchored to Bitcoin blocks in order, so the\n * burn height never decreases as the Stacks height rises; a regression means\n * a block from another fork, or a wrongly stored anchor, sits on the chain.\n */\nexport async function findBurnHeightRegressions(\n\tdb: Kysely<Database>,\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BurnHeightRegression[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\tburn_block_height: string | number;\n\t\tprevious: string | number;\n\t}>`\n\t\tSELECT height, burn_block_height, previous\n\t\t FROM (\n\t\t\tSELECT height, burn_block_height,\n\t\t\t LAG(burn_block_height) OVER (ORDER BY height) AS previous\n\t\t\t FROM blocks\n\t\t\t WHERE canonical = true\n\t\t\t ${recentWindow(windowSize, sql.ref(\"height\"))}\n\t\t ) s\n\t\t WHERE burn_block_height < previous\n\t\t ORDER BY height\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\tburnBlockHeight: Number(r.burn_block_height),\n\t\tpreviousBurnBlockHeight: Number(r.previous),\n\t}));\n}\n\nexport type EventCountMismatch = {\n\theight: number;\n\texpectedEventCount: number;\n\tactualEventCount: number;\n};\n\n/**\n * Canonical blocks whose `events` rows disagree with the `event_count`\n * `persistBlock` recorded, the events counterpart of `findShortBlocks`.\n * Heights without a recorded count (written before the column existed) have no\n * baseline and are skipped.\n */\nexport async function findEventCountMismatches(\n\tdb: Kysely<Database>,\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<EventCountMismatch[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\tevent_count: number;\n\t\tactual: string | number;\n\t}>`\n\t\tSELECT b.height, b.event_count, COUNT(e.block_height) AS actual\n\t\t FROM blocks b\n\t\t LEFT JOIN events e ON e.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.event_count IS NOT NULL\n\t\t ${recentWindow(windowSize, sql.ref(\"b.height\"))}\n\t\t GROUP BY b.height, b.event_count\n\t\tHAVING COUNT(e.block_height) <> b.event_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedEventCount: Number(r.event_count),\n\t\tactualEventCount: Number(r.actual),\n\t}));\n}\n\nexport type EventsLogicalIndexState = \"valid\" | \"invalid\" | \"missing\";\n\n/**\n * Whether `events_logical_id_uniq` (migration 0101) protects the table.\n * The migration skips it on a large table, so a database can run without it\n * and the persist path's bare `ON CONFLICT DO NOTHING` then dedupes nothing.\n */\nexport async function eventsLogicalIndexState(\n\tdb: Kysely<Database>,\n): Promise<EventsLogicalIndexState> {\n\tconst { rows } = await sql<{ indisvalid: boolean }>`\n\t\tSELECT i.indisvalid\n\t\t FROM pg_index i\n\t\t JOIN pg_class c ON c.oid = i.indexrelid\n\t\t WHERE c.relname = 'events_logical_id_uniq'\n\t\t AND i.indisunique\n\t`.execute(db);\n\tif (rows.length === 0) return \"missing\";\n\treturn rows.every((r) => r.indisvalid) ? \"valid\" : \"invalid\";\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n\t}));\n}\n",
|
|
5
|
+
"import { type Kysely, sql } from \"kysely\";\nimport type { Database } from \"../types.ts\";\nimport { stacksNetworkFromEnv } from \"./instance.ts\";\nimport { getSyncScope, upsertSyncScope } from \"./sync-scope.ts\";\n\nexport interface Gap {\n\tgapStart: number;\n\tgapEnd: number;\n\tsize: number;\n}\n\n/**\n * The three honest answers to \"what is the chain tip\", so no reader derives its\n * own:\n *\n * seen highest block height the indexer has received (`index_progress`)\n * canonical highest block currently canonical in `blocks`\n * contiguous highest height with no gap below it (`index_progress`)\n *\n * `null` when nothing is recorded yet. The node's own tip is a different\n * question (it needs RPC) and is not answered here.\n */\nexport type ChainTipKind = \"seen\" | \"canonical\" | \"contiguous\";\n\nexport async function resolveChainTip(\n\tdb: Kysely<Database>,\n\tkind: ChainTipKind,\n\topts: { network?: string } = {},\n): Promise<number | null> {\n\tif (kind === \"canonical\") {\n\t\tconst row = await db\n\t\t\t.selectFrom(\"blocks\")\n\t\t\t.select(\"height\")\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.orderBy(\"height\", \"desc\")\n\t\t\t.limit(1)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? Number(row.height) : null;\n\t}\n\tconst column =\n\t\tkind === \"seen\" ? \"highest_seen_block\" : \"last_contiguous_block\";\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(column)\n\t\t.where(\"network\", \"=\", opts.network ?? stacksNetworkFromEnv())\n\t\t.executeTakeFirst();\n\treturn row ? Number(row[column]) : null;\n}\n\nexport async function findGaps(\n\tdb: Kysely<Database>,\n\tlimit?: number,\n): Promise<Gap[]> {\n\tconst limitClause = limit ? sql`LIMIT ${limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\tgap_start: string;\n\t\tgap_end: string;\n\t\tsize: string;\n\t}>`\n SELECT gap_start, gap_end, gap_end - gap_start + 1 AS size\n FROM (\n SELECT height + 1 AS gap_start, next_height - 1 AS gap_end\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n ) gaps\n ORDER BY gap_start\n ${limitClause}\n `.execute(db);\n\n\treturn rows.map((r) => ({\n\t\tgapStart: Number(r.gap_start),\n\t\tgapEnd: Number(r.gap_end),\n\t\tsize: Number(r.size),\n\t}));\n}\n\nexport async function countMissingBlocks(\n\tdb: Kysely<Database>,\n): Promise<number> {\n\tconst { rows } = await sql<{ total: string }>`\n SELECT COALESCE(SUM(next_height - height - 1), 0) AS total\n FROM (\n SELECT height, LEAD(height) OVER (ORDER BY height) AS next_height\n FROM blocks WHERE canonical = true\n ) sub\n WHERE next_height - height > 1\n `.execute(db);\n\n\treturn Number(rows[0]?.total ?? 0);\n}\n\nexport interface ChainDataIntegrity {\n\tok: boolean;\n\tmaxHeight: number;\n\tsampleHeight: number | null;\n\tsampleBlocks: number;\n\treason: string | null;\n}\n\n/**\n * Cheap sanity check that the `blocks` table actually holds the history its tip\n * implies. Catches a wrong/empty Postgres volume — e.g. a container recreated\n * against a fresh volume — being silently served: if the tip is high but a\n * window of blocks well below it is missing, the data isn't what the tip claims.\n *\n * Below `checkFloor` we can't distinguish a fresh install from an empty volume,\n * so we report ok — a genuinely new DB legitimately has little history. Two\n * indexed lookups, safe to run on every startup / health poll.\n */\nexport async function checkChainDataIntegrity(\n\tdb: Kysely<Database>,\n\topts?: { checkFloor?: number; lookback?: number },\n): Promise<ChainDataIntegrity> {\n\tconst checkFloor = opts?.checkFloor ?? 1_000_000;\n\tconst lookback = opts?.lookback ?? 500_000;\n\n\tconst { rows: tipRows } = await sql<{ max: string | null }>`\n\t\tSELECT MAX(height) AS max FROM blocks WHERE canonical = true\n\t`.execute(db);\n\tconst maxHeight = Number(tipRows[0]?.max ?? 0);\n\n\tif (maxHeight < checkFloor) {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmaxHeight,\n\t\t\tsampleHeight: null,\n\t\t\tsampleBlocks: 0,\n\t\t\treason: null,\n\t\t};\n\t}\n\n\tconst sampleHeight = maxHeight - lookback;\n\tconst { rows: sampleRows } = await sql<{ n: string }>`\n\t\tSELECT count(*) AS n FROM blocks\n\t\tWHERE canonical = true AND height >= ${sampleHeight} AND height < ${sampleHeight + 1000}\n\t`.execute(db);\n\tconst sampleBlocks = Number(sampleRows[0]?.n ?? 0);\n\n\treturn {\n\t\tok: sampleBlocks > 0,\n\t\tmaxHeight,\n\t\tsampleHeight,\n\t\tsampleBlocks,\n\t\treason:\n\t\t\tsampleBlocks > 0\n\t\t\t\t? null\n\t\t\t\t: `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`,\n\t};\n}\n\nasync function lowestCanonicalHeight(\n\tdb: Kysely<Database>,\n\tabove: number,\n): Promise<number | null> {\n\tconst { rows } = await sql<{ min: string | null }>`\n\t\tSELECT MIN(height) AS min FROM blocks\n\t\tWHERE canonical = true AND height > ${above}\n\t`.execute(db);\n\tconst min = rows[0]?.min;\n\treturn min === null || min === undefined ? null : Number(min);\n}\n\n/**\n * The height contiguity is measured from: where this instance's canonical\n * history begins, never an assumed 1. A recorded sync scope above the lowest\n * stored block wins (an operator or the indexer declared that history below it\n * is deliberately absent); otherwise it is the lowest canonical block.\n *\n * `null` when no canonical block is stored yet.\n */\nexport async function resolveContiguousFloor(\n\tdb: Kysely<Database>,\n\tnetwork: string = stacksNetworkFromEnv(),\n): Promise<number | null> {\n\tconst lowest = await lowestCanonicalHeight(db, -1);\n\tif (lowest === null) return null;\n\tconst scope = await getSyncScope(db, network);\n\treturn Math.max(lowest, scope?.start_height ?? 0);\n}\n\n/**\n * First block above genesis lands on an instance whose cursor is still 0.\n *\n * A node on a cached chain (a Clarinet devnet) announces its genesis block at\n * boot and then first shows the chain at its real height; the heights between\n * are never delivered. Counting from that lone genesis row leaves the cursor\n * pinned below a hole nobody can fill, so declare the lowest block above\n * genesis as the instance's start (the same declaration a forward-only archive\n * restore makes) and return the floor contiguity now counts from. A scope that\n * already exists is never overwritten.\n */\nexport async function seedContiguousFloor(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<number | null> {\n\tconst lowest = await lowestCanonicalHeight(db, -1);\n\tconst aboveGenesis = await lowestCanonicalHeight(db, 0);\n\tif (\n\t\tlowest === 0 &&\n\t\taboveGenesis !== null &&\n\t\taboveGenesis > 1 &&\n\t\t(await getSyncScope(db, network)) === null\n\t) {\n\t\tawait upsertSyncScope(db, {\n\t\t\tnetwork,\n\t\t\tstart_height: aboveGenesis,\n\t\t\ttarget_height: null,\n\t\t\tbootstrap: {\n\t\t\t\tsource: \"import\",\n\t\t\t\tmanifest_digest: null,\n\t\t\t\tgenesis_hash: null,\n\t\t\t},\n\t\t});\n\t}\n\treturn resolveContiguousFloor(db, network);\n}\n\nexport async function computeContiguousTip(\n\tdb: Kysely<Database>,\n\tfromHeight: number,\n): Promise<number> {\n\tconst { rows } = await sql<{ tip: string }>`\n SELECT COALESCE(MAX(height), ${fromHeight}) AS tip\n FROM (\n SELECT height, height - ROW_NUMBER() OVER (ORDER BY height) AS grp\n FROM blocks WHERE canonical = true AND height >= ${fromHeight}\n ) sub\n WHERE grp = (\n SELECT height - ROW_NUMBER() OVER (ORDER BY height)\n FROM blocks WHERE canonical = true AND height = ${fromHeight}\n )\n `.execute(db);\n\n\treturn Number(rows[0]?.tip ?? fromHeight);\n}\n\nexport type ShortBlock = {\n\theight: number;\n\texpectedTxCount: number;\n\tactualTxCount: number;\n};\n\n/**\n * Canonical heights where `transactions` holds fewer (or more) rows than the\n * block was supposed to. `blocks.tx_count` is set by `persistBlock` from the\n * incoming block, so a mismatch means a later write silently moved or dropped\n * a tx after that block was persisted — a reorg replaying the wrong height, a\n * same-height tx_id collision, or a bug in the persist path itself. Ingest\n * used to report the *parsed* count, not the inserted count, so this kind of\n * short block was invisible; a skipped insert looked identical to success.\n *\n * Scoped to heights with `tx_count IS NOT NULL` — rows ingested before this\n * column existed have no baseline to check against. Also scoped to a recent\n * window by default (like `findBrokenLinks`): every new block sets\n * `tx_count`, so the eligible range only grows, and a short block is an\n * active-repair concern, not something worth a full-table scan every cycle.\n */\nexport async function findShortBlocks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<ShortBlock[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND b.height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\ttx_count: number;\n\t\tactual_count: string | number;\n\t}>`\n\t\tSELECT b.height, b.tx_count, COUNT(t.tx_id) AS actual_count\n\t\t FROM blocks b\n\t\t LEFT JOIN transactions t ON t.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.tx_count IS NOT NULL\n\t\t ${windowClause}\n\t\t GROUP BY b.height, b.tx_count\n\t\tHAVING COUNT(t.tx_id) <> b.tx_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedTxCount: Number(r.tx_count),\n\t\tactualTxCount: Number(r.actual_count),\n\t}));\n}\n\nfunction recentWindow(\n\twindowSize: number | null,\n\tcolumn: ReturnType<typeof sql.ref>,\n) {\n\treturn windowSize === null\n\t\t? sql``\n\t\t: sql`AND ${column} > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n}\n\nexport type DuplicateTxIndex = {\n\theight: number;\n\ttxIndex: number;\n\tcount: number;\n};\n\n/**\n * `(block_height, tx_index)` pairs held by more than one transaction on a\n * canonical block. A transaction's index is its position in the block, so each\n * pair is unique; two rows sharing one make Streams and Index order that block\n * ambiguously. Windowed by default; the daily canonical audit passes its own\n * window.\n */\nexport async function findDuplicateTxIndexes(\n\tdb: Kysely<Database>,\n\topts: {\n\t\twindow?: number | null;\n\t\t/** Absolute lower bound: only heights above it. */\n\t\tfloorHeight?: number;\n\t\tlimit?: number;\n\t} = {},\n): Promise<DuplicateTxIndex[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst floorClause =\n\t\topts.floorHeight === undefined\n\t\t\t? sql``\n\t\t\t: sql`AND t.block_height > ${opts.floorHeight}`;\n\tconst { rows } = await sql<{\n\t\tblock_height: string | number;\n\t\ttx_index: string | number;\n\t\tn: string | number;\n\t}>`\n\t\tSELECT t.block_height, t.tx_index, COUNT(*) AS n\n\t\t FROM transactions t\n\t\t JOIN blocks b ON b.height = t.block_height AND b.canonical = true\n\t\t WHERE true\n\t\t ${recentWindow(windowSize, sql.ref(\"t.block_height\"))}\n\t\t ${floorClause}\n\t\t GROUP BY t.block_height, t.tx_index\n\t\tHAVING COUNT(*) > 1\n\t\t ORDER BY t.block_height, t.tx_index\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.block_height),\n\t\ttxIndex: Number(r.tx_index),\n\t\tcount: Number(r.n),\n\t}));\n}\n\nexport type BurnHeightRegression = {\n\theight: number;\n\tburnBlockHeight: number;\n\tpreviousBurnBlockHeight: number;\n};\n\n/**\n * Canonical blocks whose `burn_block_height` is lower than the canonical block\n * below them. Stacks blocks are anchored to Bitcoin blocks in order, so the\n * burn height never decreases as the Stacks height rises; a regression means\n * a block from another fork, or a wrongly stored anchor, sits on the chain.\n */\nexport async function findBurnHeightRegressions(\n\tdb: Kysely<Database>,\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BurnHeightRegression[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\tburn_block_height: string | number;\n\t\tprevious: string | number;\n\t}>`\n\t\tSELECT height, burn_block_height, previous\n\t\t FROM (\n\t\t\tSELECT height, burn_block_height,\n\t\t\t LAG(burn_block_height) OVER (ORDER BY height) AS previous\n\t\t\t FROM blocks\n\t\t\t WHERE canonical = true\n\t\t\t ${recentWindow(windowSize, sql.ref(\"height\"))}\n\t\t ) s\n\t\t WHERE burn_block_height < previous\n\t\t ORDER BY height\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\tburnBlockHeight: Number(r.burn_block_height),\n\t\tpreviousBurnBlockHeight: Number(r.previous),\n\t}));\n}\n\nexport type EventCountMismatch = {\n\theight: number;\n\texpectedEventCount: number;\n\tactualEventCount: number;\n};\n\n/**\n * Canonical blocks whose `events` rows disagree with the `event_count`\n * `persistBlock` recorded, the events counterpart of `findShortBlocks`.\n * Heights without a recorded count (written before the column existed) have no\n * baseline and are skipped.\n */\nexport async function findEventCountMismatches(\n\tdb: Kysely<Database>,\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<EventCountMismatch[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\tevent_count: number;\n\t\tactual: string | number;\n\t}>`\n\t\tSELECT b.height, b.event_count, COUNT(e.block_height) AS actual\n\t\t FROM blocks b\n\t\t LEFT JOIN events e ON e.block_height = b.height\n\t\t WHERE b.canonical = true\n\t\t AND b.event_count IS NOT NULL\n\t\t ${recentWindow(windowSize, sql.ref(\"b.height\"))}\n\t\t GROUP BY b.height, b.event_count\n\t\tHAVING COUNT(e.block_height) <> b.event_count\n\t\t ORDER BY b.height\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\texpectedEventCount: Number(r.event_count),\n\t\tactualEventCount: Number(r.actual),\n\t}));\n}\n\n/**\n * Canonical heights in `[fromHeight, toHeight]` where a raw `events.event_index`\n * is not its 0-based position in the block, ordered by `(tx_index, event_index)`.\n * That position is what `event_index` means everywhere else (see\n * `STREAMS_CURSOR_VERSION`), so a mismatch means subgraph event ids built from\n * raw rows would differ from ones built from Streams.\n */\nexport async function findEventIndexMismatches(\n\tdb: Kysely<Database>,\n\topts: { fromHeight: number; toHeight: number; limit?: number },\n): Promise<number[]> {\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst { rows } = await sql<{ height: string | number }>`\n\t\tSELECT DISTINCT height\n\t\t FROM (\n\t\t SELECT e.block_height AS height,\n\t\t e.event_index,\n\t\t ROW_NUMBER() OVER (\n\t\t PARTITION BY e.block_height\n\t\t ORDER BY t.tx_index ASC, e.event_index ASC\n\t\t ) - 1 AS position\n\t\t FROM events e\n\t\t JOIN transactions t ON t.tx_id = e.tx_id\n\t\t JOIN blocks b ON b.height = e.block_height AND b.canonical = true\n\t\t WHERE e.block_height BETWEEN ${opts.fromHeight} AND ${opts.toHeight}\n\t\t ) ranked\n\t\t WHERE event_index <> position\n\t\t ORDER BY height\n\t\t ${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => Number(r.height));\n}\n\nexport type EventsLogicalIndexState = \"valid\" | \"invalid\" | \"missing\";\n\n/**\n * Whether `events_logical_id_uniq` (migration 0101) protects the table.\n * The migration skips it on a large table, so a database can run without it\n * and the persist path's bare `ON CONFLICT DO NOTHING` then dedupes nothing.\n */\nexport async function eventsLogicalIndexState(\n\tdb: Kysely<Database>,\n): Promise<EventsLogicalIndexState> {\n\tconst { rows } = await sql<{ indisvalid: boolean }>`\n\t\tSELECT i.indisvalid\n\t\t FROM pg_index i\n\t\t JOIN pg_class c ON c.oid = i.indexrelid\n\t\t WHERE c.relname = 'events_logical_id_uniq'\n\t\t AND i.indisunique\n\t`.execute(db);\n\tif (rows.length === 0) return \"missing\";\n\treturn rows.every((r) => r.indisvalid) ? \"valid\" : \"invalid\";\n}\n\nexport type BrokenLink = {\n\theight: number;\n\thash: string;\n\texpectedParent: string;\n\tstoredParent: string;\n};\n\n/**\n * Canonical heights whose block does not descend from the canonical block\n * below it.\n *\n * `findGaps` asks \"is every height present?\", which a chain sitting on a losing\n * fork answers yes to. On 2026-07-30 a reorg at 8,663,166 was resolved the\n * wrong way: we adopted a block that mainnet orphaned, its true successors were\n * swept non-canonical, and later blocks were inserted canonical on top. Every\n * height existed. Nothing was \"missing\". The chain simply did not join up, and\n * no check asked that question — so we served a broken chain for seventeen\n * hours and only noticed because subgraphs stopped moving.\n *\n * Scoped to a recent window by default: an unlinked height is an active-repair\n * concern, and scanning eight million rows every cycle is not.\n */\nexport async function findBrokenLinks(\n\tdb: Kysely<Database>,\n\t/** Heights below the tip to scan; `null` scans the whole chain. */\n\topts: { window?: number | null; limit?: number } = {},\n): Promise<BrokenLink[]> {\n\tconst windowSize = opts.window === undefined ? 10_000 : opts.window;\n\tconst limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;\n\tconst windowClause =\n\t\twindowSize === null\n\t\t\t? sql``\n\t\t\t: sql`AND height > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;\n\tconst { rows } = await sql<{\n\t\theight: string | number;\n\t\thash: string;\n\t\texpected_parent: string;\n\t\tstored_parent: string;\n\t}>`\n\t\tWITH recent AS (\n\t\t\tSELECT height, hash, parent_hash\n\t\t\tFROM blocks\n\t\t\tWHERE canonical = true\n\t\t\t\t${windowClause}\n\t\t)\n\t\tSELECT b.height, b.hash, p.hash AS expected_parent, b.parent_hash AS stored_parent\n\t\tFROM recent b\n\t\tJOIN recent p ON p.height = b.height - 1\n\t\tWHERE b.parent_hash <> p.hash\n\t\tORDER BY b.height\n\t\t${limitClause}\n\t`.execute(db);\n\treturn rows.map((r) => ({\n\t\theight: Number(r.height),\n\t\thash: r.hash,\n\t\texpectedParent: r.expected_parent,\n\t\tstoredParent: r.stored_parent,\n\t}));\n}\n",
|
|
6
6
|
"import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tconst named = stacksNetwork();\n\t\tenabledNetworks = named === \"testnet\" ? [\"testnet\"] : [\"mainnet\"];\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The Stacks network this process serves, and the only place that decides it:\n * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment\n * that only sets it is not silently re-keyed), else mainnet. Not validated;\n * `instanceNetworkFromEnv` is the strict form.\n */\nexport function stacksNetwork(env: NodeJS.ProcessEnv = process.env): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tconsole.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
|
|
7
7
|
"import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
|
|
8
8
|
"/**\n * Backup bundle — the index, the operator's keys, and the scope they cover.\n *\n * This file holds the pure parts: manifest shape, validation, bundle\n * encryption, and the key canary. The IO (pg_dump, pg_restore, reading and\n * writing bundle files) lives in the CLI command, so everything here stays\n * testable without a database or a filesystem.\n *\n * ## Why there is a canary\n *\n * `SECONDLAYER_SECRETS_KEY` encrypts columns in the database — subgraph\n * connection strings, webhook signing secrets. In OSS mode, if that key is\n * missing when something first needs it, the runtime GENERATES A NEW ONE and\n * persists it (see `crypto/secrets.ts`). That behaviour is right for a fresh\n * install and catastrophic for a restore: bring the database back without its\n * original key and the runtime quietly mints a different one, leaving every\n * encrypted column permanently unreadable. Nothing errors. You find out later.\n *\n * So a backup seals a known plaintext under the live key and stores the\n * ciphertext in the manifest. Restore opens it with the key it is about to\n * install, and refuses if it does not match. That converts a silent, permanent\n * data loss into a loud failure before anything is written.\n */\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\trandomBytes,\n\tscryptSync,\n\ttimingSafeEqual,\n} from \"node:crypto\";\n\nexport const BACKUP_MANIFEST_VERSION = 1;\n\nexport const BACKUP_PARTS = [\n\t\"db\",\n\t\"config\",\n\t\"keys\",\n\t\"handlers\",\n\t\"scope\",\n] as const;\nexport type BackupPart = (typeof BACKUP_PARTS)[number];\n\n/**\n * Sealed under the secrets key at backup time and opened at restore time. The\n * value is arbitrary; only the round-trip matters.\n */\nconst CANARY_PLAINTEXT = \"secondlayer-secrets-key-canary-v1\";\n\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\nconst SALT_LEN = 16;\n/** Deliberately expensive: bundle passphrases are chosen by humans. */\nconst SCRYPT_COST = 2 ** 15;\n/**\n * scrypt needs ~128 * N * r bytes (r defaults to 8), which is just over Node's\n * 32 MB default cap at this cost. Raising the ceiling rather than weakening the\n * KDF — the whole point of the cost is that it is uncomfortable.\n */\nconst SCRYPT_MAXMEM = 64 * 1024 * 1024;\nconst SCRYPT_OPTS = { N: SCRYPT_COST, maxmem: SCRYPT_MAXMEM } as const;\n\nexport type BackupManifest = {\n\tschema_version: number;\n\tcreated_at: string;\n\tnetwork: string;\n\tparts: BackupPart[];\n\tencrypted: boolean;\n\tscope: { from_height: number; to_height: number | null };\n\tdb: {\n\t\tfile: string;\n\t\tsha256: string;\n\t\tbytes: number;\n\t\tformat: string;\n\t} | null;\n\t/** Never the secrets themselves — only how to check them. */\n\tsecrets: {\n\t\tfile: string;\n\t\tencrypted: boolean;\n\t\tcanary: string;\n\t} | null;\n\tsignature?: string;\n\tkey_id?: string;\n};\n\nexport type BackupPlan =\n\t| { ok: true; manifest: BackupManifest }\n\t| { ok: false; reason: string };\n\n/**\n * Validate a backup before any bytes are written. Refusing early is the whole\n * point: a bundle that omits the keys looks like a backup and is not one.\n */\nexport function planBackup(input: {\n\tnetwork: string;\n\tfromHeight: number;\n\ttoHeight?: number | null;\n\tincludeSecrets: boolean;\n\tsecretsEncrypted: boolean;\n\tcanary?: string;\n\tnow?: string;\n}): BackupPlan {\n\tif (input.fromHeight < 0) {\n\t\treturn { ok: false, reason: \"scope from_height must be >= 0\" };\n\t}\n\tif (\n\t\tinput.toHeight !== null &&\n\t\tinput.toHeight !== undefined &&\n\t\tinput.toHeight < input.fromHeight\n\t) {\n\t\treturn { ok: false, reason: \"scope to_height is below from_height\" };\n\t}\n\tif (input.includeSecrets && !input.secretsEncrypted) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\treason:\n\t\t\t\t\"refusing to write plaintext secrets; supply a passphrase or pass the explicit plaintext override\",\n\t\t};\n\t}\n\tif (input.includeSecrets && !input.canary) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\treason:\n\t\t\t\t\"secrets bundle requires a key canary so a restore can prove the key matches\",\n\t\t};\n\t}\n\n\tconst parts: BackupPart[] = input.includeSecrets\n\t\t? [...BACKUP_PARTS]\n\t\t: BACKUP_PARTS.filter((p) => p !== \"keys\");\n\n\treturn {\n\t\tok: true,\n\t\tmanifest: {\n\t\t\tschema_version: BACKUP_MANIFEST_VERSION,\n\t\t\tcreated_at: input.now ?? new Date().toISOString(),\n\t\t\tnetwork: input.network,\n\t\t\tparts,\n\t\t\tencrypted: input.secretsEncrypted,\n\t\t\tscope: {\n\t\t\t\tfrom_height: input.fromHeight,\n\t\t\t\tto_height: input.toHeight ?? null,\n\t\t\t},\n\t\t\tdb: null,\n\t\t\tsecrets: null,\n\t\t},\n\t};\n}\n\nfunction secretsKeyBuffer(hexKey: string): Buffer {\n\tconst key = Buffer.from(hexKey.trim(), \"hex\");\n\tif (key.length !== 32) {\n\t\tthrow new Error(\"SECONDLAYER_SECRETS_KEY must be 32 bytes hex\");\n\t}\n\treturn key;\n}\n\n/**\n * Seal the canary under an EXPLICIT key.\n *\n * Deliberately not reusing `crypto/secrets.ts`: that module resolves the key\n * from the ambient environment and, in OSS mode, generates and persists one as\n * a side effect when it is missing. Calling it here would mean a backup could\n * mint the very key it is supposed to be preserving.\n */\nexport function sealKeyCanary(secretsKeyHex: string): string {\n\tconst key = secretsKeyBuffer(secretsKeyHex);\n\tconst iv = randomBytes(IV_LEN);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(CANARY_PLAINTEXT, \"utf8\"),\n\t\tcipher.final(),\n\t]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), ciphertext]).toString(\n\t\t\"base64\",\n\t);\n}\n\n/** True only when `secretsKeyHex` is the key the canary was sealed with. */\nexport function keyMatchesCanary(\n\tcanaryBase64: string,\n\tsecretsKeyHex: string,\n): boolean {\n\ttry {\n\t\tconst key = secretsKeyBuffer(secretsKeyHex);\n\t\tconst envelope = Buffer.from(canaryBase64, \"base64\");\n\t\tconst iv = envelope.subarray(0, IV_LEN);\n\t\tconst tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);\n\t\tconst ciphertext = envelope.subarray(IV_LEN + TAG_LEN);\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n\t\tdecipher.setAuthTag(tag);\n\t\tconst plaintext = Buffer.concat([\n\t\t\tdecipher.update(ciphertext),\n\t\t\tdecipher.final(),\n\t\t]);\n\t\tconst expected = Buffer.from(CANARY_PLAINTEXT, \"utf8\");\n\t\treturn (\n\t\t\tplaintext.length === expected.length &&\n\t\t\ttimingSafeEqual(plaintext, expected)\n\t\t);\n\t} catch {\n\t\t// A wrong key fails the GCM auth tag, which throws. That is a mismatch,\n\t\t// not an error to propagate.\n\t\treturn false;\n\t}\n}\n\n/**\n * Encrypt the secrets bundle under an operator passphrase.\n * Layout: `salt(16) || iv(12) || authTag(16) || ciphertext`.\n */\nexport function encryptBundle(plaintext: string, passphrase: string): Buffer {\n\tif (!passphrase) throw new Error(\"passphrase is required\");\n\tconst salt = randomBytes(SALT_LEN);\n\tconst key = scryptSync(passphrase, salt, 32, SCRYPT_OPTS);\n\tconst iv = randomBytes(IV_LEN);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, \"utf8\"),\n\t\tcipher.final(),\n\t]);\n\treturn Buffer.concat([salt, iv, cipher.getAuthTag(), ciphertext]);\n}\n\nexport function decryptBundle(envelope: Buffer, passphrase: string): string {\n\tconst salt = envelope.subarray(0, SALT_LEN);\n\tconst iv = envelope.subarray(SALT_LEN, SALT_LEN + IV_LEN);\n\tconst tag = envelope.subarray(SALT_LEN + IV_LEN, SALT_LEN + IV_LEN + TAG_LEN);\n\tconst ciphertext = envelope.subarray(SALT_LEN + IV_LEN + TAG_LEN);\n\tconst key = scryptSync(passphrase, salt, 32, SCRYPT_OPTS);\n\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n\tdecipher.setAuthTag(tag);\n\treturn decipher.update(ciphertext).toString(\"utf8\") + decipher.final(\"utf8\");\n}\n\nexport type RestorePrecheck =\n\t| { ok: true }\n\t| { ok: false; reason: string; fatal: boolean };\n\n/**\n * Everything that must hold before a restore writes anything.\n *\n * `fatal` distinguishes \"this bundle can never restore here\" from \"this needs\n * an explicit override\" — the caller surfaces them differently.\n */\nexport function precheckRestore(input: {\n\tmanifest: BackupManifest;\n\ttargetNetwork: string;\n\ttargetIsEmpty: boolean;\n\tforce: boolean;\n\tsecretsKeyHex?: string;\n}): RestorePrecheck {\n\tif (input.manifest.schema_version !== BACKUP_MANIFEST_VERSION) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfatal: true,\n\t\t\treason: `bundle schema_version ${input.manifest.schema_version} is not supported (expected ${BACKUP_MANIFEST_VERSION})`,\n\t\t};\n\t}\n\tif (input.manifest.network !== input.targetNetwork) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfatal: true,\n\t\t\treason: `bundle is ${input.manifest.network}; this instance is ${input.targetNetwork}`,\n\t\t};\n\t}\n\tif (!input.targetIsEmpty && !input.force) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tfatal: false,\n\t\t\treason:\n\t\t\t\t\"target database already holds chain data; restoring would overwrite it\",\n\t\t};\n\t}\n\tconst secrets = input.manifest.secrets;\n\tif (secrets) {\n\t\tif (!input.secretsKeyHex) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tfatal: false,\n\t\t\t\treason:\n\t\t\t\t\t\"bundle carries encrypted columns but no secrets key was supplied; restoring now would leave them unreadable\",\n\t\t\t};\n\t\t}\n\t\tif (!keyMatchesCanary(secrets.canary, input.secretsKeyHex)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tfatal: true,\n\t\t\t\treason:\n\t\t\t\t\t\"the supplied SECONDLAYER_SECRETS_KEY does not match the one this backup was taken with; encrypted columns would be permanently unreadable\",\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true };\n}\n",
|
|
9
9
|
"import type { Kysely } from \"kysely\";\nimport { stacksNetwork } from \"../../env.ts\";\nimport { logger } from \"../../logger.ts\";\nimport { keyMatchesCanary, sealKeyCanary } from \"../../runtime/backup.ts\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\n/**\n * The network key `index_progress` is written under; see `stacksNetwork`.\n * Kept under this name for the callers that already import it from here.\n */\nexport function stacksNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\treturn stacksNetwork(env);\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(stacksNetwork(env));\n}\n\nexport type InstanceNetworkCheck = \"match\" | \"mismatch\" | \"unpinned\";\n\n/**\n * Compare the network this process is configured for with the one pinned in\n * `instances`, and log loudly on a disagreement. It only reports: a process\n * pointed at the wrong database should be seen immediately, but a stack whose\n * pin is stale must not be taken down by a check, so this never throws. A\n * missing row, a missing table or an unreachable database is \"unpinned\".\n */\nexport async function checkInstanceNetwork(\n\tdb: Kysely<Database>,\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<InstanceNetworkCheck> {\n\tconst configured = stacksNetwork(env);\n\tlet pinned: string | undefined;\n\ttry {\n\t\tpinned = (\n\t\t\tawait db.selectFrom(\"instances\").select(\"network\").executeTakeFirst()\n\t\t)?.network;\n\t} catch {\n\t\treturn \"unpinned\";\n\t}\n\tif (pinned === undefined) return \"unpinned\";\n\tif (pinned === configured) return \"match\";\n\tlogger.error(\n\t\t\"STACKS_NETWORK disagrees with the network this database is pinned to; this process may be pointed at the wrong database\",\n\t\t{ configured, pinned },\n\t);\n\treturn \"mismatch\";\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nexport class SecretsKeyMismatchError extends Error {\n\treadonly name = \"SecretsKeyMismatchError\";\n\tconstructor() {\n\t\tsuper(\n\t\t\t\"SECONDLAYER_SECRETS_KEY is not the key this database's secrets were sealed with. Refusing to start: running on a different key leaves every webhook signing secret unreadable. Restore the original key (the DATA_DIR volume's secrets.env, or your SECONDLAYER_SECRETS_KEY), or clear instances.secrets_key_canary only if you mean to abandon those secrets.\",\n\t\t);\n\t}\n}\n\n/**\n * Pin the secrets key to this database. The first boot with a key seals a\n * canary into the instance row; every later boot must open it with the key it\n * was handed, or it refuses to start. Without this, a lost key is replaced by\n * a freshly generated one and every encrypted column quietly stops decrypting.\n */\nexport async function ensureSecretsKeyCanary(\n\tdb: Kysely<Database>,\n\tinput: { keyHex: string; network: InstanceNetwork },\n): Promise<void> {\n\tconst read = () =>\n\t\tdb\n\t\t\t.selectFrom(\"instances\")\n\t\t\t.select([\"id\", \"secrets_key_canary\"])\n\t\t\t.executeTakeFirst();\n\n\tlet row = await read();\n\tif (!row) {\n\t\tawait db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tsecrets_key_canary: sealKeyCanary(input.keyHex),\n\t\t\t})\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\trow = await read();\n\t\tif (!row) throw new Error(\"failed to create instance\");\n\t}\n\tif (row.secrets_key_canary === null) {\n\t\t// Only the first writer's canary counts: a concurrent boot with another\n\t\t// key loses the race and is then checked against the winner's.\n\t\tawait db\n\t\t\t.updateTable(\"instances\")\n\t\t\t.set({ secrets_key_canary: sealKeyCanary(input.keyHex) })\n\t\t\t.where(\"id\", \"=\", row.id)\n\t\t\t.where(\"secrets_key_canary\", \"is\", null)\n\t\t\t.execute();\n\t\trow = await read();\n\t}\n\tif (\n\t\t!row?.secrets_key_canary ||\n\t\t!keyMatchesCanary(row.secrets_key_canary, input.keyHex)\n\t) {\n\t\tthrow new SecretsKeyMismatchError();\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n\n/**\n * A stack with no local chain: it reads chain data from a hosted Index/Streams\n * API (`SUBGRAPH_INDEX_API_URL` set) and its own `index_progress` has no row\n * for this network (a hosted tenant). Derived, not configured: a self-hoster\n * running a local indexer has the row and keeps reading its own tables, even\n * with its processors pointed at its own api over HTTP.\n */\nexport async function hasNoLocalChain(\n\tdb: Kysely<Database>,\n\topts: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\thasProgressRow?: (network: string) => Promise<boolean>;\n\t} = {},\n): Promise<boolean> {\n\tconst env = opts.env ?? process.env;\n\tif (!env.SUBGRAPH_INDEX_API_URL) return false;\n\tconst network = stacksNetworkFromEnv(env);\n\tconst hasRow =\n\t\topts.hasProgressRow ?? ((n: string) => hasLocalProgressRow(db, n));\n\treturn !(await hasRow(network));\n}\n\nasync function hasLocalProgressRow(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(\"network\")\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst()\n\t\t.catch(() => undefined);\n\treturn row !== undefined;\n}\n",
|
|
10
10
|
"import type { Kysely } from \"kysely\";\nimport type { BootstrapSource, SyncScope } from \"../../coverage/evaluate.ts\";\nimport type { Database } from \"../types.ts\";\n\n/**\n * The instance's declared sync scope.\n *\n * An instance that starts at height N is not an instance missing the first N\n * blocks — but nothing in the schema said so, so every consumer had to guess\n * from `MIN(height)`. `sync_scopes` records the declaration; this module is the\n * only place that reads it, and it always answers in the `SyncScope` shape the\n * coverage evaluator consumes.\n *\n * `resolveSyncScope` never fails on an instance that predates the table: with\n * no row it derives a scope from what the database already shows, so an\n * existing install keeps working without a backfill dance.\n */\n\n/**\n * Declares a forward-only instance: history below this height is deliberately\n * absent, not lost. Read only when no `sync_scopes` row exists — a recorded\n * scope always wins, because it is the one an operator committed to.\n */\nexport const SYNC_START_HEIGHT_ENV = \"SECONDLAYER_SYNC_START_HEIGHT\";\n\nexport class InvalidSyncStartHeightError extends Error {\n\treadonly name = \"InvalidSyncStartHeightError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`${SYNC_START_HEIGHT_ENV} must be a non-negative integer (got ${value})`,\n\t\t);\n\t}\n}\n\n/**\n * Throws rather than ignoring a malformed value: a typo'd start height that\n * silently falls back to genesis would report a real forward-only instance as\n * an 8M-block gap, which is the exact confusion this table exists to end.\n */\nexport function syncStartHeightFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): number | null {\n\tconst raw = env[SYNC_START_HEIGHT_ENV];\n\tif (raw === undefined || raw.trim() === \"\") return null;\n\tconst height = Number(raw.trim());\n\tif (!Number.isInteger(height) || height < 0) {\n\t\tthrow new InvalidSyncStartHeightError(raw);\n\t}\n\treturn height;\n}\n\nfunction toScope(row: {\n\tnetwork: string;\n\tstart_height: number | string;\n\ttarget_height: number | string | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n}): SyncScope {\n\treturn {\n\t\tnetwork: row.network,\n\t\tstart_height: Number(row.start_height),\n\t\ttarget_height:\n\t\t\trow.target_height === null ? null : Number(row.target_height),\n\t\tbootstrap: {\n\t\t\tsource: row.bootstrap_source,\n\t\t\tmanifest_digest: row.bootstrap_manifest_digest,\n\t\t\tgenesis_hash: row.genesis_hash,\n\t\t},\n\t};\n}\n\nexport async function getSyncScope(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<SyncScope | null> {\n\tconst row = await db\n\t\t.selectFrom(\"sync_scopes\")\n\t\t.select([\n\t\t\t\"network\",\n\t\t\t\"start_height\",\n\t\t\t\"target_height\",\n\t\t\t\"bootstrap_source\",\n\t\t\t\"bootstrap_manifest_digest\",\n\t\t\t\"genesis_hash\",\n\t\t])\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst();\n\treturn row ? toScope(row) : null;\n}\n\n/**\n * Record (or restate) the scope for a network. Bootstrap and re-bootstrap are\n * the writers; the upsert is idempotent so re-running a restore over the same\n * archive does not fork the declaration.\n */\nexport async function upsertSyncScope(\n\tdb: Kysely<Database>,\n\tscope: SyncScope,\n): Promise<SyncScope> {\n\tconst row = await db\n\t\t.insertInto(\"sync_scopes\")\n\t\t.values({\n\t\t\tnetwork: scope.network,\n\t\t\tstart_height: scope.start_height,\n\t\t\ttarget_height: scope.target_height,\n\t\t\tbootstrap_source: scope.bootstrap.source,\n\t\t\tbootstrap_manifest_digest: scope.bootstrap.manifest_digest,\n\t\t\tgenesis_hash: scope.bootstrap.genesis_hash,\n\t\t})\n\t\t.onConflict((oc) =>\n\t\t\toc.column(\"network\").doUpdateSet({\n\t\t\t\tstart_height: scope.start_height,\n\t\t\t\ttarget_height: scope.target_height,\n\t\t\t\tbootstrap_source: scope.bootstrap.source,\n\t\t\t\tbootstrap_manifest_digest: scope.bootstrap.manifest_digest,\n\t\t\t\tgenesis_hash: scope.bootstrap.genesis_hash,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t}),\n\t\t)\n\t\t.returning([\n\t\t\t\"network\",\n\t\t\t\"start_height\",\n\t\t\t\"target_height\",\n\t\t\t\"bootstrap_source\",\n\t\t\t\"bootstrap_manifest_digest\",\n\t\t\t\"genesis_hash\",\n\t\t])\n\t\t.executeTakeFirstOrThrow();\n\treturn toScope(row);\n}\n\n/**\n * The persisted scope, or one derived from the database when none was ever\n * recorded.\n *\n * The derivation is deliberately conservative: it claims only what the data\n * already shows (the lowest canonical block, the genesis hash if genesis is\n * present) and never invents provenance — an instance whose history starts\n * above genesis with no recorded bootstrap is an `import`, not an archive\n * restore we can vouch for.\n */\nexport async function resolveSyncScope(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<SyncScope> {\n\tconst persisted = await getSyncScope(db, network);\n\tif (persisted) return persisted;\n\n\tconst declaredStart = syncStartHeightFromEnv();\n\tconst lowest = await db\n\t\t.selectFrom(\"blocks\")\n\t\t.select(({ fn }) => fn.min(\"height\").as(\"min\"))\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.executeTakeFirst();\n\tconst lowestStored =\n\t\tlowest?.min === null || lowest?.min === undefined\n\t\t\t? null\n\t\t\t: Number(lowest.min);\n\tconst startHeight = declaredStart ?? lowestStored ?? 0;\n\n\tconst genesis =\n\t\tstartHeight === 0\n\t\t\t? await db\n\t\t\t\t\t.selectFrom(\"blocks\")\n\t\t\t\t\t.select(\"hash\")\n\t\t\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t\t\t.where(\"height\", \"=\", 0)\n\t\t\t\t\t.executeTakeFirst()\n\t\t\t: undefined;\n\n\treturn {\n\t\tnetwork,\n\t\tstart_height: startHeight,\n\t\ttarget_height: null,\n\t\tbootstrap: {\n\t\t\tsource: startHeight === 0 ? \"genesis\" : \"import\",\n\t\t\tmanifest_digest: null,\n\t\t\tgenesis_hash: genesis?.hash ??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Y,KAAK,UAAU;AAAA,EAC5D,MAAM,eACL,eAAe,OACZ,QACA,yCAAyC;AAAA,EAC7C,QAAQ,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,MAUlB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOF;AAAA,GACD,QAAQ,EAAE;AAAA,EACZ,OAAO,KAAK,IAAI,CAAC,OAAO;AAAA,IACvB,QAAQ,OAAO,EAAE,MAAM;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,gBAAgB,EAAE;AAAA,IAClB,cAAc,EAAE;AAAA,EACjB,EAAE;AAAA;",
|
|
13
|
+
"debugId": "E081DBBD08BE0DEF64756E2164756E21",
|
|
14
14
|
"names": []
|
|
15
15
|
}
|
package/dist/src/index-http.d.ts
CHANGED
|
@@ -300,6 +300,12 @@ type IndexTipEnvelope = {
|
|
|
300
300
|
* before this field was added.
|
|
301
301
|
*/
|
|
302
302
|
decoded_heights?: Record<string, number | null>
|
|
303
|
+
/**
|
|
304
|
+
* Highest height at which the contract registry has classified every
|
|
305
|
+
* deploy. `null` means the server cannot tell; absent means an older
|
|
306
|
+
* server that doesn't send the field.
|
|
307
|
+
*/
|
|
308
|
+
registry_classified_through?: number | null
|
|
303
309
|
}
|
|
304
310
|
};
|
|
305
311
|
declare class IndexHttpClient {
|
|
@@ -416,6 +422,14 @@ declare class IndexHttpClient {
|
|
|
416
422
|
* the conservative cross-decoder floor `block_height` itself carries.
|
|
417
423
|
*/
|
|
418
424
|
getDecodedHeights(): Record<string, number | null> | undefined;
|
|
425
|
+
/**
|
|
426
|
+
* The contract registry's classified-through height from the last tip
|
|
427
|
+
* envelope fetched by `getIndexTip()`/`getIndexSourceTip()` — reads the
|
|
428
|
+
* cached response, no extra request. `undefined` before either has been
|
|
429
|
+
* called, or against an older server that doesn't send the field; `null`
|
|
430
|
+
* when the server cannot tell.
|
|
431
|
+
*/
|
|
432
|
+
getRegistryClassifiedThrough(): number | null | undefined;
|
|
419
433
|
/** False once a `wait`/`tip_only` request has 400'd on THIS client instance
|
|
420
434
|
* (see the catch in `getIndexTipEnvelope`) — an older server that doesn't
|
|
421
435
|
* recognize these params. A caller that reuses one client across many
|
package/dist/src/index-http.js
CHANGED
|
@@ -249,6 +249,9 @@ class IndexHttpClient {
|
|
|
249
249
|
getDecodedHeights() {
|
|
250
250
|
return this.lastTipEnvelope?.tip.decoded_heights;
|
|
251
251
|
}
|
|
252
|
+
getRegistryClassifiedThrough() {
|
|
253
|
+
return this.lastTipEnvelope?.tip.registry_classified_through;
|
|
254
|
+
}
|
|
252
255
|
waitIsSupported() {
|
|
253
256
|
return this.waitSupported;
|
|
254
257
|
}
|
|
@@ -321,5 +324,5 @@ export {
|
|
|
321
324
|
createInternalIndexHttpClient
|
|
322
325
|
};
|
|
323
326
|
|
|
324
|
-
//# debugId=
|
|
327
|
+
//# debugId=2DEA5C26CE126E5564756E2164756E21
|
|
325
328
|
//# sourceMappingURL=index-http.js.map
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../src/index-internal-auth.ts", "../src/index-http.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"// Internal service credentials for first-party consumers of /v1/index and\n// /v1/streams over HTTP (decoder, subgraph processor PublicApiBlockSource).\n// Seeded as internal tenants with NO account_id, so these reads are\n// unmetered (metering gates on account_id). Lives in shared so the API (seed)\n// and the consumers import it without a cycle.\n//\n// Resolution: STREAMS_INTERNAL_API_KEY / INDEX_INTERNAL_API_KEY, then\n// INSTANCE_TOKEN (OSS). No committed fallback. Empty-string env values fall\n// through (`trim()`, then empty): compose interpolates\n// `${STREAMS_INTERNAL_API_KEY:-}` which is \"\" when unset.\n//\n// Archive keys must not use the `sk-sl_` prefix; generate with `sl-int_`.\n// OSS compose should omit the internal env and send INSTANCE_TOKEN.\nexport const INDEX_INTERNAL_TENANT_ID = \"tenant_index_internal\";\nexport const INTERNAL_STREAMS_TENANT_ID = \"tenant_streams_decode_internal\";\n\nconst DEFAULT_INTERNAL_INDEX_BASE_URL = \"http://api:3800\";\n\nconst MISSING_INTERNAL_STREAMS_API_KEY =\n\t\"Set STREAMS_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Empty env no longer falls back to a committed secret.\";\n\nconst MISSING_INTERNAL_INDEX_API_KEY =\n\t\"Set INDEX_INTERNAL_API_KEY (archive; prefix sl-int_) or INSTANCE_TOKEN (OSS). Without one, Index reads carry no credential and platform mode 401s every one of them.\";\n\nexport function defaultInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.INDEX_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\nexport function defaultInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\tconst internal = env.STREAMS_INTERNAL_API_KEY?.trim();\n\tif (internal) return internal;\n\tconst instance = env.INSTANCE_TOKEN?.trim();\n\tif (instance) return instance;\n\treturn undefined;\n}\n\n/**\n * Platform-mode Index consumer: refuse to run with neither credential.\n *\n * Platform mode requires a credential on every Index read (a keyless read\n * 401s, `api/src/index/auth.ts`) — a first-party consumer with no internal\n * key would fail every request at call time. Fail here at startup instead.\n *\n * Self-hosted (oss/dedicated) instances are not gated, so they must NOT call\n * this — `defaultInternalIndexApiKey()` returning undefined is correct there.\n */\nexport function requireInternalIndexApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalIndexApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_INDEX_API_KEY);\n\treturn key;\n}\n\n/** Decoder startup: refuse to run with neither credential. */\nexport function requireInternalStreamsApiKey(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tconst key = defaultInternalStreamsApiKey(env);\n\tif (!key) throw new Error(MISSING_INTERNAL_STREAMS_API_KEY);\n\treturn key;\n}\n\n/** Shared env contract for decoder + subgraph HTTP dogfood. */\nexport function defaultInternalIndexBaseUrl(): string {\n\treturn (\n\t\tprocess.env.SUBGRAPH_INDEX_API_URL ||\n\t\tprocess.env.STREAMS_API_URL ||\n\t\tDEFAULT_INTERNAL_INDEX_BASE_URL\n\t);\n}\n",
|
|
6
|
-
"import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\n/** The refusals a metered read can get once an account is past what it may\n * read (`checkRowsAllowance`): its free allowance with no credits or past its\n * spend cap, or a signed-out docs key's 100k rows. All are deliberate billing\n * states, not outages: retrying them in a storm only burns the request budget. */\nexport type BillingPausedCode =\n\t| \"spend_cap_reached\"\n\t| \"insufficient_credits\"\n\t| \"rows_limit_reached\";\n\nconst BILLING_PAUSED_CODES: ReadonlySet<string> = new Set<BillingPausedCode>([\n\t\"spend_cap_reached\",\n\t\"insufficient_credits\",\n\t\"rows_limit_reached\",\n]);\n\n/** A read refused with `402` and `{ error: BillingPausedCode }`. Raised only\n * on an exact body match, so an unmetered (self-host) server never produces\n * it. */\nexport class BillingPausedError extends IndexHttpStatusError {\n\tconstructor(\n\t\treadonly code: BillingPausedCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(402, message);\n\t\tthis.name = \"BillingPausedError\";\n\t}\n}\n\n/** `BillingPausedError` when `status`/`body` is exactly a billing refusal. */\nfunction billingPausedFrom(\n\tstatus: number,\n\tbody: string,\n\tmessage: string,\n): BillingPausedError | null {\n\tif (status !== 402) return null;\n\ttry {\n\t\tconst code = (JSON.parse(body) as { error?: unknown } | null)?.error;\n\t\tif (typeof code === \"string\" && BILLING_PAUSED_CODES.has(code)) {\n\t\t\treturn new BillingPausedError(code as BillingPausedCode, message);\n\t\t}\n\t} catch {\n\t\t// Not JSON: not a billing refusal.\n\t}\n\treturn null;\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\n/** A `/v1/index/state-writes` row read with `tx_context=true`. */\nexport type IndexStateWriteRow = {\n\tblock_height: number;\n\tordinal: number;\n\t/** Null for block-level writes. */\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\ttx_id?: string | null;\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\n/** A `/v1/index/sbtc/events` row: one decoded sBTC protocol event. Numeric\n * columns are JSON numbers here (the API normalizes them). */\nexport type IndexSbtcEventRow = {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: string;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tbitcoin_txid: string | null;\n\toutput_index: number | null;\n\tsweep_txid: string | null;\n\tburn_hash: string | null;\n\tburn_height: number | null;\n\tsigner_bitmap: string | null;\n\tmax_fee: string | null;\n\tfee: string | null;\n\tgovernance_contract_type: number | null;\n\tgovernance_new_contract: string | null;\n\tsigner_aggregate_pubkey: string | null;\n\tsigner_threshold: number | null;\n\tsigner_address: string | null;\n\tsigner_keys_count: number | null;\n};\n\n/** A `/v1/contracts?trait=` row (ABI omitted). */\nexport type IndexContractRow = {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tdeclared_traits: string[] | null;\n\tinferred_standards: string[] | null;\n\tabi_status: string;\n\t/** When the contract's traits were last set (server clock). */\n\tclassified_at: string | null;\n};\n\n/** A `/v1/index/sbtc/withdrawals` row: one peg-out rolled up per request. */\nexport type IndexSbtcWithdrawalRow = {\n\tcursor: string;\n\trequest_id: number;\n\tstatus: \"REQUESTED\" | \"ACCEPTED\" | \"REJECTED\";\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tsweep_txid: string | null;\n\tsettlement_confirmed: boolean | null;\n\tbtc_confirmations: number | null;\n\tbtc_block_height: number | null;\n\tconfirmed_at: string | null;\n\t/** Monotonic stamp of the sweep's confirmation; the settlement scan's\n\t * watermark. Null while unsettled. */\n\tsettlement_seq?: number | null;\n\trequested_at?: string | null;\n\tresolved_at?: string | null;\n};\n\n/** Page size for `/v1/contracts`, its server-side maximum. */\nconst CONTRACTS_PAGE_LIMIT = 500;\n\n/** `to_height` meaning \"through the tip\": the server clamps it to its tip. */\nconst THROUGH_TIP = Number.MAX_SAFE_INTEGER;\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n\t/** Hash of the block orphaned at `fork_point_height`. */\n\told_index_block_hash?: string | null;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst body = await res.text();\n\t\t\t\tconst message = `GET ${url} → ${res.status} ${body}`;\n\t\t\t\tthrow (\n\t\t\t\t\tbillingPausedFrom(res.status, body, message) ??\n\t\t\t\t\tnew IndexHttpStatusError(res.status, message)\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t\t/** Scope the walk to one contract (what a filter pins), so the Index\n\t\t * returns, and meters, only that contract's rows. */\n\t\tcontractId?: string,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Every node storage write over the range, each with its writing tx\n\t * (`tx_context=true`); scoped to one contract's keys when given. */\n\twalkStateWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<IndexStateWriteRow[]> {\n\t\treturn this.walk<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\ttx_context: \"true\",\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Lowest height the Index serves `state_writes` for, or null when it has\n\t * none (its node does not deliver them). One row. */\n\tasync firstStateWriteHeight(): Promise<number | null> {\n\t\tconst { items } = await this.getPage<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tnew URLSearchParams({ from_height: \"0\", limit: \"1\" }),\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\t/**\n\t * Canonical sBTC protocol events over [fromHeight, toHeight] for `topics`,\n\t * ordered by (block_height, event_index). One drained walk per topic (the\n\t * endpoint filters on a single topic); `requestId` narrows each walk.\n\t */\n\tasync fetchSbtcEvents(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\ttopics: readonly string[],\n\t\topts?: { requestId?: number },\n\t): Promise<IndexSbtcEventRow[]> {\n\t\tconst out: IndexSbtcEventRow[] = [];\n\t\tfor (const topic of topics) {\n\t\t\tout.push(\n\t\t\t\t...(await this.walk<\"events\", IndexSbtcEventRow>(\n\t\t\t\t\t\"/v1/index/sbtc/events\",\n\t\t\t\t\t\"events\",\n\t\t\t\t\tfromHeight,\n\t\t\t\t\ttoHeight,\n\t\t\t\t\t{\n\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t...(opts?.requestId !== undefined\n\t\t\t\t\t\t\t? { request_id: String(opts.requestId) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t)),\n\t\t\t);\n\t\t}\n\t\treturn out.sort(\n\t\t\t(a, b) =>\n\t\t\t\ta.block_height - b.block_height || a.event_index - b.event_index,\n\t\t);\n\t}\n\n\t/** Every canonical contract conforming to `trait` (declared or inferred),\n\t * draining `/v1/contracts`'s `next_cursor`. `classifiedAfter` limits it to\n\t * contracts classified at or after that time. */\n\tasync listContractsByTrait(\n\t\ttrait: string,\n\t\topts: { classifiedAfter?: Date } = {},\n\t): Promise<IndexContractRow[]> {\n\t\tconst out: IndexContractRow[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\ttrait,\n\t\t\t\tlimit: String(CONTRACTS_PAGE_LIMIT),\n\t\t\t});\n\t\t\tif (opts.classifiedAfter) {\n\t\t\t\tparams.set(\"classified_after\", opts.classifiedAfter.toISOString());\n\t\t\t}\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\t\"contracts\",\n\t\t\t\tIndexContractRow\n\t\t\t>(\"/v1/contracts\", \"contracts\", params);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/** Withdrawals whose BTC sweep crossed the confirmation threshold past\n\t * `scan`, across all history: stamped after `afterSeq`, or confirmed\n\t * strictly after `confirmedAfter`. */\n\tfetchSettledWithdrawals(\n\t\tscan: { afterSeq: number } | { confirmedAfter: Date },\n\t): Promise<IndexSbtcWithdrawalRow[]> {\n\t\treturn this.walk<\"withdrawals\", IndexSbtcWithdrawalRow>(\n\t\t\t\"/v1/index/sbtc/withdrawals\",\n\t\t\t\"withdrawals\",\n\t\t\t0,\n\t\t\tTHROUGH_TIP,\n\t\t\t{\n\t\t\t\tsettlement_confirmed: \"true\",\n\t\t\t\t...(\"afterSeq\" in scan\n\t\t\t\t\t? { confirmed_after_seq: String(scan.afterSeq) }\n\t\t\t\t\t: { confirmed_after: scan.confirmedAfter.toISOString() }),\n\t\t\t},\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
|
|
6
|
+
"import {\n\tdefaultInternalIndexApiKey,\n\tdefaultInternalIndexBaseUrl,\n\tdefaultInternalStreamsApiKey,\n} from \"./index-internal-auth.ts\";\nimport type { RuneStreamsEvent } from \"./streams-rows/events.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n/** Ceiling on the Index long-poll `wait` param (seconds), shared by client and\n * server so neither drifts from the other. Kept comfortably under app-server\n * Caddy's `reverse_proxy` (no read/write timeout override, so this is a\n * self-imposed ceiling, not one it's protecting against) and Bun's own\n * 90s idleTimeout on the api listener. */\nexport const MAX_INDEX_WAIT_SECONDS = 25;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\n/** A non-2xx Index/Streams response, carrying the status so a caller can\n * distinguish \"the server rejected this request\" (e.g. a `wait`/`from_height`\n * param an older server's `validateQueryParams` doesn't recognize, HTTP 400)\n * from a transient outage — see `getIndexTipEnvelope`'s wait fallback. */\nexport class IndexHttpStatusError extends Error {\n\tconstructor(\n\t\treadonly status: number,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"IndexHttpStatusError\";\n\t}\n}\n\n/** The refusals a metered read can get once an account is past what it may\n * read (`checkRowsAllowance`): its free allowance with no credits or past its\n * spend cap, or a signed-out docs key's 100k rows. All are deliberate billing\n * states, not outages: retrying them in a storm only burns the request budget. */\nexport type BillingPausedCode =\n\t| \"spend_cap_reached\"\n\t| \"insufficient_credits\"\n\t| \"rows_limit_reached\";\n\nconst BILLING_PAUSED_CODES: ReadonlySet<string> = new Set<BillingPausedCode>([\n\t\"spend_cap_reached\",\n\t\"insufficient_credits\",\n\t\"rows_limit_reached\",\n]);\n\n/** A read refused with `402` and `{ error: BillingPausedCode }`. Raised only\n * on an exact body match, so an unmetered (self-host) server never produces\n * it. */\nexport class BillingPausedError extends IndexHttpStatusError {\n\tconstructor(\n\t\treadonly code: BillingPausedCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(402, message);\n\t\tthis.name = \"BillingPausedError\";\n\t}\n}\n\n/** `BillingPausedError` when `status`/`body` is exactly a billing refusal. */\nfunction billingPausedFrom(\n\tstatus: number,\n\tbody: string,\n\tmessage: string,\n): BillingPausedError | null {\n\tif (status !== 402) return null;\n\ttry {\n\t\tconst code = (JSON.parse(body) as { error?: unknown } | null)?.error;\n\t\tif (typeof code === \"string\" && BILLING_PAUSED_CODES.has(code)) {\n\t\t\treturn new BillingPausedError(code as BillingPausedCode, message);\n\t\t}\n\t} catch {\n\t\t// Not JSON: not a billing refusal.\n\t}\n\treturn null;\n}\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\t/** Nakamoto StacksBlockId. Absent from pre-2026-07 API deployments. */\n\tindex_block_hash?: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index?: number;\n\tevent_index: number;\n\tcontract_id: string | null;\n\t/** Submitting-tx context — present only when the read passed `tx_context=true`.\n\t * Lets a consumer build the tx for `ctx.tx` without a separate\n\t * walkTransactions (the ~37x reindex over-fetch; see indexing-speed plan). */\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nested_contract_call\";\n\t\t\t\tsender?: string | null;\n\t\t\t\tcaller: string;\n\t\t\t\tfunction_name: string;\n\t\t\t\tfunction_args?: unknown;\n\t\t\t\traw_result?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"var_set\";\n\t\t\t\tvar_name: string;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_set\" | \"map_insert\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t\t\traw_value?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"map_delete\";\n\t\t\t\tmap: string;\n\t\t\t\traw_key?: string | null;\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\n/** A `/v1/index/state-writes` row read with `tx_context=true`. */\nexport type IndexStateWriteRow = {\n\tblock_height: number;\n\tordinal: number;\n\t/** Null for block-level writes. */\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\ttx_id?: string | null;\n\ttx_sender?: string | null;\n\ttx_type?: string | null;\n\ttx_status?: string | null;\n\ttx_contract_id?: string | null;\n\ttx_function_name?: string | null;\n};\n\n/** A `/v1/index/sbtc/events` row: one decoded sBTC protocol event. Numeric\n * columns are JSON numbers here (the API normalizes them). */\nexport type IndexSbtcEventRow = {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: string;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tbitcoin_txid: string | null;\n\toutput_index: number | null;\n\tsweep_txid: string | null;\n\tburn_hash: string | null;\n\tburn_height: number | null;\n\tsigner_bitmap: string | null;\n\tmax_fee: string | null;\n\tfee: string | null;\n\tgovernance_contract_type: number | null;\n\tgovernance_new_contract: string | null;\n\tsigner_aggregate_pubkey: string | null;\n\tsigner_threshold: number | null;\n\tsigner_address: string | null;\n\tsigner_keys_count: number | null;\n};\n\n/** A `/v1/contracts?trait=` row (ABI omitted). */\nexport type IndexContractRow = {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tdeclared_traits: string[] | null;\n\tinferred_standards: string[] | null;\n\tabi_status: string;\n\t/** When the contract's traits were last set (server clock). */\n\tclassified_at: string | null;\n};\n\n/** A `/v1/index/sbtc/withdrawals` row: one peg-out rolled up per request. */\nexport type IndexSbtcWithdrawalRow = {\n\tcursor: string;\n\trequest_id: number;\n\tstatus: \"REQUESTED\" | \"ACCEPTED\" | \"REJECTED\";\n\tamount: string | null;\n\tsender: string | null;\n\trecipient_btc_version: number | null;\n\trecipient_btc_hashbytes: string | null;\n\tsweep_txid: string | null;\n\tsettlement_confirmed: boolean | null;\n\tbtc_confirmations: number | null;\n\tbtc_block_height: number | null;\n\tconfirmed_at: string | null;\n\t/** Monotonic stamp of the sweep's confirmation; the settlement scan's\n\t * watermark. Null while unsettled. */\n\tsettlement_seq?: number | null;\n\trequested_at?: string | null;\n\tresolved_at?: string | null;\n};\n\n/** Page size for `/v1/contracts`, its server-side maximum. */\nconst CONTRACTS_PAGE_LIMIT = 500;\n\n/** `to_height` meaning \"through the tip\": the server clamps it to its tip. */\nconst THROUGH_TIP = Number.MAX_SAFE_INTEGER;\n\nexport type StreamsReorgRow = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n\t/** Hash of the block orphaned at `fork_point_height`. */\n\told_index_block_hash?: string | null;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Empty/unset omits the header. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams. Empty/unset omits the header. */\n\tstreamsApiKey?: string;\n};\n\n/** `/v1/index/blocks?limit=1`'s envelope — read for its `tip`, not its rows. */\nexport type IndexTipEnvelope = {\n\ttip: {\n\t\tblock_height: number;\n\t\tsource_block_height?: number;\n\t\t/**\n\t\t * Committed height per classic decoded event_type, e.g.\n\t\t * `{ ft_transfer: 950, stx_transfer: 940 }`. `null` means that decoder\n\t\t * has no checkpoint yet (fail-closed for a caller that references it,\n\t\t * not \"committed to height 0\"); a missing key means an older server\n\t\t * that doesn't send this field at all. Absent on an instance built\n\t\t * before this field was added.\n\t\t */\n\t\tdecoded_heights?: Record<string, number | null>;\n\t\t/**\n\t\t * Highest height at which the contract registry has classified every\n\t\t * deploy. `null` means the server cannot tell; absent means an older\n\t\t * server that doesn't send the field.\n\t\t */\n\t\tregistry_classified_through?: number | null;\n\t};\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string | undefined;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string | undefined;\n\t/** Populated by the last `getIndexTipEnvelope()` call (via `getIndexTip`/\n\t * `getIndexSourceTip`) so `getDecodedHeights()` can read the SAME response\n\t * synchronously instead of making a second request. */\n\tprivate lastTipEnvelope: IndexTipEnvelope | undefined;\n\t/** Flips false the first time a `wait` request 400s — see\n\t * `getIndexTipEnvelope`'s catch. Per-instance, not global: a fresh client\n\t * (e.g. against a different/upgraded server) always tries wait again. */\n\tprivate waitSupported = true;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string | undefined): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst body = await res.text();\n\t\t\t\tconst message = `GET ${url} → ${res.status} ${body}`;\n\t\t\t\tthrow (\n\t\t\t\t\tbillingPausedFrom(res.status, body, message) ??\n\t\t\t\t\tnew IndexHttpStatusError(res.status, message)\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Lowest block height in [fromHeight, toHeight] with a matching event, or\n\t * null. One page, limit 1 — built for sparse-scan probes. */\n\tasync firstEventHeight(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<number | null> {\n\t\tconst params = new URLSearchParams({\n\t\t\tevent_type: eventType,\n\t\t\tfrom_height: String(fromHeight),\n\t\t\tto_height: String(toHeight),\n\t\t\tlimit: \"1\",\n\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t});\n\t\tconst { items } = await this.getPage<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tparams,\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\t/** Join the submitting tx so each row carries `tx_*` — lets an event-only\n\t\t * subgraph skip walkTransactions and build `ctx.tx` from the event. */\n\t\twithTx = false,\n\t\t/** Scope the walk to one contract (what a filter pins), so the Index\n\t\t * returns, and meters, only that contract's rows. */\n\t\tcontractId?: string,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\tevent_type: eventType,\n\t\t\t\t...(withTx ? { tx_context: \"true\" } : {}),\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Every node storage write over the range, each with its writing tx\n\t * (`tx_context=true`); scoped to one contract's keys when given. */\n\twalkStateWrites(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\tcontractId?: string,\n\t): Promise<IndexStateWriteRow[]> {\n\t\treturn this.walk<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{\n\t\t\t\ttx_context: \"true\",\n\t\t\t\t...(contractId ? { contract_id: contractId } : {}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Lowest height the Index serves `state_writes` for, or null when it has\n\t * none (its node does not deliver them). One row. */\n\tasync firstStateWriteHeight(): Promise<number | null> {\n\t\tconst { items } = await this.getPage<\"state_writes\", IndexStateWriteRow>(\n\t\t\t\"/v1/index/state-writes\",\n\t\t\t\"state_writes\",\n\t\t\tnew URLSearchParams({ from_height: \"0\", limit: \"1\" }),\n\t\t);\n\t\treturn items[0]?.block_height ?? null;\n\t}\n\n\t/**\n\t * Canonical sBTC protocol events over [fromHeight, toHeight] for `topics`,\n\t * ordered by (block_height, event_index). One drained walk per topic (the\n\t * endpoint filters on a single topic); `requestId` narrows each walk.\n\t */\n\tasync fetchSbtcEvents(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\ttopics: readonly string[],\n\t\topts?: { requestId?: number },\n\t): Promise<IndexSbtcEventRow[]> {\n\t\tconst out: IndexSbtcEventRow[] = [];\n\t\tfor (const topic of topics) {\n\t\t\tout.push(\n\t\t\t\t...(await this.walk<\"events\", IndexSbtcEventRow>(\n\t\t\t\t\t\"/v1/index/sbtc/events\",\n\t\t\t\t\t\"events\",\n\t\t\t\t\tfromHeight,\n\t\t\t\t\ttoHeight,\n\t\t\t\t\t{\n\t\t\t\t\t\ttopic,\n\t\t\t\t\t\t...(opts?.requestId !== undefined\n\t\t\t\t\t\t\t? { request_id: String(opts.requestId) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t)),\n\t\t\t);\n\t\t}\n\t\treturn out.sort(\n\t\t\t(a, b) =>\n\t\t\t\ta.block_height - b.block_height || a.event_index - b.event_index,\n\t\t);\n\t}\n\n\t/** Every canonical contract conforming to `trait` (declared or inferred),\n\t * draining `/v1/contracts`'s `next_cursor`. `classifiedAfter` limits it to\n\t * contracts classified at or after that time. */\n\tasync listContractsByTrait(\n\t\ttrait: string,\n\t\topts: { classifiedAfter?: Date } = {},\n\t): Promise<IndexContractRow[]> {\n\t\tconst out: IndexContractRow[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\ttrait,\n\t\t\t\tlimit: String(CONTRACTS_PAGE_LIMIT),\n\t\t\t});\n\t\t\tif (opts.classifiedAfter) {\n\t\t\t\tparams.set(\"classified_after\", opts.classifiedAfter.toISOString());\n\t\t\t}\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\t\"contracts\",\n\t\t\t\tIndexContractRow\n\t\t\t>(\"/v1/contracts\", \"contracts\", params);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/** Withdrawals whose BTC sweep crossed the confirmation threshold past\n\t * `scan`, across all history: stamped after `afterSeq`, or confirmed\n\t * strictly after `confirmedAfter`. */\n\tfetchSettledWithdrawals(\n\t\tscan: { afterSeq: number } | { confirmedAfter: Date },\n\t): Promise<IndexSbtcWithdrawalRow[]> {\n\t\treturn this.walk<\"withdrawals\", IndexSbtcWithdrawalRow>(\n\t\t\t\"/v1/index/sbtc/withdrawals\",\n\t\t\t\"withdrawals\",\n\t\t\t0,\n\t\t\tTHROUGH_TIP,\n\t\t\t{\n\t\t\t\tsettlement_confirmed: \"true\",\n\t\t\t\t...(\"afterSeq\" in scan\n\t\t\t\t\t? { confirmed_after_seq: String(scan.afterSeq) }\n\t\t\t\t\t: { confirmed_after: scan.confirmedAfter.toISOString() }),\n\t\t\t},\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t *\n\t * `opts.wait` (seconds, clamped to `MAX_INDEX_WAIT_SECONDS`) long-polls:\n\t * the server holds the request until a fresher tip than `opts.knownHeight`\n\t * is available or `wait` elapses. Pass `knownHeight` —\n\t * the last tip THIS caller observed — or `wait` is a no-op (nothing to\n\t * compare against). A caller that only wants the plain tip omits both.\n\t */\n\tasync getIndexTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\t/**\n\t\t * Event types this caller actually reads (e.g. a chain evaluator's\n\t\t * `referencedEventTypes`). Narrows the returned tip — and, together with\n\t\t * `wait`, what counts as \"nothing new\" — to the MIN committed height\n\t\t * over just these types, instead of the global floor over EVERY classic\n\t\t * decoder. Without it, an unrelated decoder committing (any of ~15,\n\t\t * several times a block) moves the global floor and makes an unrelated\n\t\t * `wait` return early — the exact busy-idle pattern this fixes. Omit\n\t\t * when there's no meaningful subset (falls back to the global floor,\n\t\t * unchanged from before this option existed).\n\t\t */\n\t\teventTypes?: readonly string[];\n\t}): Promise<number> {\n\t\t// `tip_only`: this method never reads `blocks[]`, only `tip`, so the\n\t\t// server can skip the row query. It ALSO fixes what `tip_only` exists\n\t\t// for: `blocks.length` is governed by the SOURCE tip (`/blocks` windows\n\t\t// to it), but `knownHeight` here is the DECODED tip this method itself\n\t\t// returns — comparing against raw rows made an idle `wait` return\n\t\t// almost instantly whenever ingest ran even slightly ahead of decode\n\t\t// (routes/index.ts's /blocks handler judges emptiness against\n\t\t// `tip.block_height` directly when `tip_only` is set, sidestepping the\n\t\t// mismatch). Do NOT set this on `getIndexSourceTip` below — its\n\t\t// `knownHeight` baseline is the source tip already, so the row-based\n\t\t// check is the CORRECT one there, not a bug to route around.\n\t\tconst env = await this.getIndexTipEnvelope({\n\t\t\t...opts,\n\t\t\ttipOnly: true,\n\t\t\teventTypes: opts?.eventTypes,\n\t\t});\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Ingest tip. VM rows land with the block; decoded `block_height` can lag.\n\t * Same `wait`/`knownHeight` long-poll contract as {@link getIndexTip}. */\n\tasync getIndexSourceTip(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t}): Promise<number> {\n\t\tconst env = await this.getIndexTipEnvelope(opts);\n\t\treturn Number(env.tip?.source_block_height ?? env.tip?.block_height) || 0;\n\t}\n\n\t/**\n\t * Per-decoder committed heights from the last tip envelope fetched by\n\t * `getIndexTip()`/`getIndexSourceTip()` — reads the cached response, no\n\t * extra request. `undefined` before either has been called, or against an\n\t * older server that doesn't send the field. A caller (the chain evaluator)\n\t * uses this to bound itself by the decoders it actually reads instead of\n\t * the conservative cross-decoder floor `block_height` itself carries.\n\t */\n\tgetDecodedHeights(): Record<string, number | null> | undefined {\n\t\treturn this.lastTipEnvelope?.tip.decoded_heights;\n\t}\n\n\t/**\n\t * The contract registry's classified-through height from the last tip\n\t * envelope fetched by `getIndexTip()`/`getIndexSourceTip()` — reads the\n\t * cached response, no extra request. `undefined` before either has been\n\t * called, or against an older server that doesn't send the field; `null`\n\t * when the server cannot tell.\n\t */\n\tgetRegistryClassifiedThrough(): number | null | undefined {\n\t\treturn this.lastTipEnvelope?.tip.registry_classified_through;\n\t}\n\n\t/** False once a `wait`/`tip_only` request has 400'd on THIS client instance\n\t * (see the catch in `getIndexTipEnvelope`) — an older server that doesn't\n\t * recognize these params. A caller that reuses one client across many\n\t * calls (the chain evaluator) uses this to stop scheduling\n\t * itself as if `wait` actually blocked, instead of re-discovering the 400\n\t * on every single call. */\n\twaitIsSupported(): boolean {\n\t\treturn this.waitSupported;\n\t}\n\n\tprivate async getIndexTipEnvelope(opts?: {\n\t\twait?: number;\n\t\tknownHeight?: number;\n\t\ttipOnly?: boolean;\n\t\teventTypes?: readonly string[];\n\t}): Promise<IndexTipEnvelope> {\n\t\tconst wantsWait = this.waitSupported && (opts?.wait ?? 0) > 0;\n\t\tconst wantsTipOnly = this.waitSupported && Boolean(opts?.tipOnly);\n\t\tconst wantsEventTypes =\n\t\t\tthis.waitSupported && wantsTipOnly && Boolean(opts?.eventTypes?.length);\n\t\tconst params = new URLSearchParams({ limit: \"1\" });\n\t\tif (wantsTipOnly) params.set(\"tip_only\", \"true\");\n\t\t// Only meaningful alongside tip_only — it narrows what the returned\n\t\t// (and wait-compared) tip means, and tip_only is what makes the server\n\t\t// return a tip at all instead of a page of rows.\n\t\tif (wantsEventTypes && opts?.eventTypes) {\n\t\t\tparams.set(\"event_types\", opts.eventTypes.join(\",\"));\n\t\t}\n\t\tif (wantsWait) {\n\t\t\tparams.set(\n\t\t\t\t\"wait\",\n\t\t\t\tString(Math.min(MAX_INDEX_WAIT_SECONDS, Math.max(0, opts?.wait ?? 0))),\n\t\t\t);\n\t\t\t// `from_height` is what makes the wait meaningful here: with no cursor,\n\t\t\t// `/v1/index/blocks?limit=1` always returns a row (the default window's\n\t\t\t// oldest block), so the server would never see \"nothing new\" to wait\n\t\t\t// on. Anchoring one past the last height THIS caller saw makes the page\n\t\t\t// empty until a fresher block lands — the same signal the endpoint\n\t\t\t// already uses for a normal forward walk.\n\t\t\tif (opts?.knownHeight !== undefined) {\n\t\t\t\tparams.set(\"from_height\", String(opts.knownHeight + 1));\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst env = await this.get<IndexTipEnvelope>(\n\t\t\t\t`${this.indexBaseUrl}/v1/index/blocks?${params}`,\n\t\t\t\tthis.indexApiKey,\n\t\t\t);\n\t\t\tthis.lastTipEnvelope = env;\n\t\t\treturn env;\n\t\t} catch (err) {\n\t\t\t// An older server's `validateQueryParams` 400s on `wait`/`from_height`/\n\t\t\t// `tip_only`/`event_types` it doesn't recognize. Treat that ONE status\n\t\t\t// as \"this server predates long-poll\", not an outage: disable every\n\t\t\t// extension for the rest of this client's life (event_types is only\n\t\t\t// ever sent alongside tip_only, so gating on `wantsTipOnly` already\n\t\t\t// covers a server that knows `wait`/`tip_only` but not `event_types`\n\t\t\t// yet) and retry plainly, so `FallbackBlockSource` never mistakes a\n\t\t\t// version-skew 400 for the api being down and routes to the DB tap.\n\t\t\t// Gating on `wantsWait || wantsTipOnly` (not `wantsWait` alone)\n\t\t\t// matters mid-rollout: a server already upgraded for `wait` but not\n\t\t\t// yet for `tip_only` still 400s on the one it doesn't know, even on a\n\t\t\t// plain, non-waiting `getIndexTip()` call.\n\t\t\tif (\n\t\t\t\t(wantsWait || wantsTipOnly) &&\n\t\t\t\terr instanceof IndexHttpStatusError &&\n\t\t\t\terr.status === 400\n\t\t\t) {\n\t\t\t\tthis.waitSupported = false;\n\t\t\t\treturn this.getIndexTipEnvelope(opts);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). `chain`\n\t * defaults to `\"stacks\"` (unchanged); `\"bitcoin\"` reads Runes reorgs\n\t * (`btc_reorgs`, plan 060) instead — a separate feed, own resume tokens. */\n\tasync listReorgs(\n\t\tsince: string,\n\t\tchain: \"stacks\" | \"bitcoin\" = \"stacks\",\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\tif (chain === \"bitcoin\") params.set(\"chain\", \"bitcoin\");\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n\n\t/** Bitcoin (Runes) Streams tip height — `chain=bitcoin`'s own clock,\n\t * unrelated to the Stacks tip (plan 060). */\n\tasync getBitcoinStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip?chain=bitcoin`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * One page of `chain=bitcoin` Streams events (Runes activity, plan 060's\n\t * evaluator source). Unlike `walkEvents`, this does NOT drain — the caller\n\t * pages by feeding back `next_cursor` — so a tick bounds its own work\n\t * instead of draining an unbounded backlog in one call. `afterCursor`\n\t * (exclusive) takes precedence over `fromHeight` when both are given,\n\t * mirroring the REST endpoint's own `cursor`/`from_height` exclusivity.\n\t */\n\tasync getBitcoinStreamsEventsPage(opts: {\n\t\ttypes: readonly string[];\n\t\ttoHeight: number;\n\t\tafterCursor?: string;\n\t\tfromHeight?: number;\n\t\tlimit?: number;\n\t}): Promise<{ events: RuneStreamsEvent[]; next_cursor: string | null }> {\n\t\tconst params = new URLSearchParams({\n\t\t\tchain: \"bitcoin\",\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\ttypes: opts.types.join(\",\"),\n\t\t});\n\t\tif (opts.afterCursor) params.set(\"from_cursor\", opts.afterCursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/events?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n\n/** Decoder + subgraph processor client. One env contract; omits bearer when no key. */\nexport function createInternalIndexHttpClient(): IndexHttpClient {\n\tconst baseUrl = defaultInternalIndexBaseUrl();\n\treturn new IndexHttpClient({\n\t\tindexBaseUrl: baseUrl,\n\t\tstreamsBaseUrl: baseUrl,\n\t\tindexApiKey: defaultInternalIndexApiKey(),\n\t\tstreamsApiKey: defaultInternalStreamsApiKey(),\n\t});\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";AAaO,IAAM,2BAA2B;AACjC,IAAM,6BAA6B;AAE1C,IAAM,kCAAkC;AAExC,IAAM,mCACL;AAED,IAAM,iCACL;AAEM,SAAS,0BAA0B,CACzC,MAAyB,QAAQ,KACZ;AAAA,EACrB,MAAM,WAAW,IAAI,wBAAwB,KAAK;AAAA,EAClD,IAAI;AAAA,IAAU,OAAO;AAAA,EACrB,MAAM,WAAW,IAAI,gBAAgB,KAAK;AAAA,EAC1C,IAAI;AAAA,IAAU,OAAO;AAAA,EACrB;AAAA;AAGM,SAAS,4BAA4B,CAC3C,MAAyB,QAAQ,KACZ;AAAA,EACrB,MAAM,WAAW,IAAI,0BAA0B,KAAK;AAAA,EAC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AAAA,IAChB,aAAa,2BAA2B;AAAA,IACxC,eAAe,6BAA6B;AAAA,EAC7C,CAAC;AAAA;",
|
|
9
|
+
"debugId": "2DEA5C26CE126E5564756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1875,6 +1875,15 @@ type RuneEventType = (typeof RUNE_EVENT_TYPES)[number];
|
|
|
1875
1875
|
* removing or reordering a type shifts the ordinal of every later event in any
|
|
1876
1876
|
* block that holds one, silently invalidating saved cursors. Change the list
|
|
1877
1877
|
* only together with a bump of this number; `db-event-types.test.ts` pins both.
|
|
1878
|
+
*
|
|
1879
|
+
* `event_index` means one thing everywhere it is exposed: the event's 0-based
|
|
1880
|
+
* position within its block, counted in `(tx_index, event_index)` order of the
|
|
1881
|
+
* raw `events` rows. Streams, the decoded tables and subgraph event ids
|
|
1882
|
+
* (`${tx_id}#${event_index}`) all rely on it, so ids built from raw rows
|
|
1883
|
+
* (`PostgresBlockSource`) match ids built from the Index API
|
|
1884
|
+
* (`PublicApiBlockSource`) only while the raw column equals that position.
|
|
1885
|
+
* `findEventIndexMismatches` (db/queries/integrity.ts) checks it; the indexer
|
|
1886
|
+
* reports it on `/health/integrity` and `audit-event-index.ts` walks history.
|
|
1878
1887
|
*/
|
|
1879
1888
|
declare const STREAMS_CURSOR_VERSION = 1;
|
|
1880
1889
|
declare const STREAMS_DB_EVENT_TYPES: readonly ["stx_transfer_event", "stx_mint_event", "stx_burn_event", "stx_lock_event", "ft_transfer_event", "ft_mint_event", "ft_burn_event", "nft_transfer_event", "nft_mint_event", "nft_burn_event", "smart_contract_event", "contract_event"];
|