@secondlayer/shared 15.6.1 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/src/archive/range-digest.d.ts +2 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +2 -0
  3. package/dist/src/coverage/index.d.ts +2 -0
  4. package/dist/src/db/index.d.ts +7 -1
  5. package/dist/src/db/index.js +3 -1
  6. package/dist/src/db/index.js.map +4 -4
  7. package/dist/src/db/queries/chain-reorgs.d.ts +2 -0
  8. package/dist/src/db/queries/chain-reorgs.js +3 -1
  9. package/dist/src/db/queries/chain-reorgs.js.map +4 -4
  10. package/dist/src/db/queries/contracts.d.ts +2 -0
  11. package/dist/src/db/queries/contracts.js.map +2 -2
  12. package/dist/src/db/queries/instance.d.ts +2 -0
  13. package/dist/src/db/queries/integrity.d.ts +2 -0
  14. package/dist/src/db/queries/subgraph-gaps.d.ts +2 -0
  15. package/dist/src/db/queries/subgraph-operations.d.ts +2 -0
  16. package/dist/src/db/queries/subgraphs.d.ts +2 -0
  17. package/dist/src/db/queries/sync-scope.d.ts +2 -0
  18. package/dist/src/db/queries/webhook-replays.d.ts +2 -0
  19. package/dist/src/db/queries/webhooks.d.ts +2 -0
  20. package/dist/src/db/schema.d.ts +2 -0
  21. package/dist/src/db/schema.js.map +2 -2
  22. package/dist/src/index-http.d.ts +1 -0
  23. package/dist/src/index-http.js.map +2 -2
  24. package/dist/src/index.d.ts +11 -6
  25. package/dist/src/index.js +6 -11
  26. package/dist/src/index.js.map +6 -6
  27. package/dist/src/insights/index.d.ts +2 -0
  28. package/dist/src/leader.js +3 -1
  29. package/dist/src/leader.js.map +4 -4
  30. package/dist/src/node/local-client.d.ts +2 -0
  31. package/dist/src/queue/listener.js +3 -1
  32. package/dist/src/queue/listener.js.map +4 -4
  33. package/dist/src/schemas/chain-triggers.js +2 -8
  34. package/dist/src/schemas/chain-triggers.js.map +3 -3
  35. package/dist/src/schemas/index.d.ts +1 -2
  36. package/dist/src/schemas/index.js +4 -11
  37. package/dist/src/schemas/index.js.map +4 -4
  38. package/dist/src/schemas/webhooks.d.ts +1 -2
  39. package/dist/src/schemas/webhooks.js +4 -11
  40. package/dist/src/schemas/webhooks.js.map +4 -4
  41. package/migrations/0205_sbtc_deposit_recipient.ts +75 -0
  42. package/package.json +2 -2
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/types.ts"],
4
4
  "sourcesContent": [
5
- "import type {\n\tColumnType,\n\tGenerated,\n\tInsertable,\n\tSelectable,\n\tUpdateable,\n} from \"kysely\";\nimport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\nimport type { BootstrapSource } from \"../coverage/evaluate.ts\";\nimport type {\n\tSubgraphStatus,\n\tSubgraphVerification,\n} from \"../schemas/subgraphs.ts\";\nimport type { WebhookPauseReason } from \"../webhooks/health.ts\";\n\nexport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\n\n// ── Table interfaces ──────────────────────────────────────────────────\n\nexport interface BlocksTable {\n\theight: number;\n\thash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\t/** Nakamoto StacksBlockId. Null on rows ingested before it was persisted. */\n\tindex_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\ttimestamp: number;\n\tcanonical: Generated<boolean>;\n\t/** Tx count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\ttx_count: ColumnType<number | null, number | null | undefined, number | null>;\n\t/** Event count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\tevent_count: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface TransactionsTable {\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: Generated<number>;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: Generated<unknown | null>;\n\traw_result: Generated<string | null>;\n\traw_tx: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface EventsTable {\n\tid: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\n// Reorg archive (see migration 0084): orphaned transactions/events copied here\n// before a reused height is replaced, preserving the raw log instead of\n// deleting it.\nexport interface TransactionsArchiveTable {\n\tarchive_id: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: number;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\traw_result: string | null;\n\traw_tx: string;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\nexport interface EventsArchiveTable {\n\tarchive_id: Generated<string>;\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in VM traces (migration 0131). Second clock: `ordinal` (array position\n// in `/new_block.vm_events`). Never mixed into `events.event_index`. Primary\n// key `(block_height, ordinal)` (migration 0153).\nexport interface VmEventsTable {\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface VmEventsArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`; rows archived before migration 0153 hold the old uuid. */\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in node storage-layer writes (migration 0154): the exact MARF writes a\n// block committed, in node order. `tx_index` is null for block-level writes.\n// Primary key `(block_height, ordinal)`.\nexport interface StateWritesTable {\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n}\n\nexport interface StateWritesArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`. */\n\tid: string;\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Dead-letter log (see migration 0085): events whose decoded payload failed\n// schema validation on ingest. Append-only diagnostic; the event still lands in\n// `events`, so chain data is never lost.\nexport interface DeadLetterEventsTable {\n\tid: Generated<string>;\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tevent_type: string;\n\tdata: unknown;\n\treason: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Pending (unconfirmed) transactions (see migration 0086). Pre-chain, so no\n// block_height/tx_index/result/events and never canonical. tx_id is derived\n// from raw_tx; function_args holds hex-encoded ClarityValues (jsonb), like\n// `transactions`.\nexport interface MempoolTransactionsTable {\n\tseq: Generated<string>;\n\ttx_id: string;\n\traw_tx: string;\n\ttype: string;\n\tsender: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\treceived_at: Generated<Date>;\n}\n\nexport interface IndexProgressTable {\n\tnetwork: string;\n\tlast_indexed_block: Generated<number>;\n\tlast_contiguous_block: Generated<number>;\n\thighest_seen_block: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface SubgraphsTable {\n\tid: Generated<string>;\n\tname: string;\n\tversion: Generated<string>;\n\tstatus: Generated<SubgraphStatus>;\n\tdefinition: Record<string, unknown>;\n\tschema_hash: string;\n\thandler_path: string;\n\tschema_name: string | null;\n\tstart_block: Generated<number>;\n\tlast_processed_block: Generated<number>;\n\t/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */\n\tlast_processed_block_hash: Generated<string | null>;\n\treindex_from_block: number | null;\n\treindex_to_block: number | null;\n\tlast_error: string | null;\n\tlast_error_at: Date | null;\n\ttotal_processed: Generated<number>;\n\ttotal_errors: Generated<number>;\n\taccount_id: string;\n\thandler_code: string | null;\n\tsource_code: string | null;\n\tproject_id: string | null;\n\t/** Set while the account's metered reads are refused (spend cap, credits).\n\t * Both columns are set or both null; `last_error` stays for real errors. */\n\tbilling_paused_at: Date | null;\n\tbilling_paused_code: string | null;\n\t/** (event type, contract) probe pairs persisted at deploy for weight classification. */\n\tsparse_probe_targets: unknown | null;\n\t/** sha256 over everything that shapes rows (schema, handler bundle,\n\t * startBlock, network, runtime). NULL for unbundled or older deploys. */\n\tpin: string | null;\n\t/** The canonical JSON `pin` hashes, so a client can recompute it. NULL\n\t * wherever `pin` is, and for deploys before migration 0158. */\n\tpin_preimage: string | null;\n\t/** Level derived at deploy. NULL (older deploys) = not verifiable. */\n\tverification: SubgraphVerification | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `contracts.abi_status`. */\nexport const ABI_STATUSES = [\n\t\"pending\",\n\t\"fetched\",\n\t\"unparseable\",\n\t\"failed\",\n] as const;\nexport type AbiStatus = (typeof ABI_STATUSES)[number];\n\nexport interface ContractsTable {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tcanonical: Generated<boolean>;\n\tabi: unknown | null;\n\tdeclared_traits: Generated<string[]>;\n\tinferred_standards: Generated<string[]>;\n\tabi_status: Generated<AbiStatus>;\n\tabi_fetched_at: Date | null;\n\t/** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */\n\tabi_attempts: Generated<number>;\n\t/** When a `failed` row is next due; NULL once attempts are exhausted. */\n\tabi_next_attempt_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */\nexport type GapReason = \"block_missing\" | \"processing_error\";\n\nexport interface SubgraphGapsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tgap_start: number;\n\tgap_end: number;\n\treason: GapReason;\n\tdetected_at: Generated<Date>;\n\tresolved_at: Date | null;\n}\n\n/** Print-validate skips persisted for the authed violations GET. Cap 100/subgraph. */\nexport interface SubgraphViolationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tsource_name: string;\n\tblock_height: number;\n\ttx_id: string;\n\treason: string;\n\tsample_payload: Record<string, unknown>;\n\tseen_at: Generated<Date>;\n}\n\nexport type SubgraphOperationKind = \"reindex\" | \"backfill\";\nexport type SubgraphOperationStatus =\n\t| \"queued\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"cancelled\";\n\nexport interface SubgraphOperationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\taccount_id: string | null;\n\tkind: ColumnType<\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind\n\t>;\n\tstatus: ColumnType<\n\t\tSubgraphOperationStatus,\n\t\tSubgraphOperationStatus | undefined,\n\t\tSubgraphOperationStatus\n\t>;\n\tfrom_block: number | null;\n\tto_block: number | null;\n\tcancel_requested: Generated<boolean>;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\tstarted_at: Date | null;\n\tfinished_at: Date | null;\n\tprocessed_blocks: number | null;\n\terror: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n\t/** 'light' (contract-scoped sparse) | 'heavy' (broad). Claim budgets heavy. */\n\tweight: Generated<string>;\n\t/** Candidate-event denominator computed at enqueue (sparse ops only). */\n\testimated_events: string | number | bigint | null;\n\t/** Events processed so far — written by the progress flush. */\n\tprocessed_events: string | number | bigint | null;\n\t/** Backfill ops' own crash checkpoint — advanced conditionally in-tx with\n\t * each written block; replays skip at/below it. NULL for reindex ops\n\t * (those checkpoint on subgraphs.last_processed_block). */\n\tcursor_block: string | number | bigint | null;\n}\n\nexport type ApiKeyStatus = \"active\" | \"revoked\";\n\nexport interface ApiKeysTable {\n\tid: Generated<string>;\n\tkey_hash: string;\n\tkey_prefix: string;\n\tname: string | null;\n\tstatus: Generated<ApiKeyStatus>;\n\trate_limit: Generated<number>;\n\tip_address: string;\n\taccount_id: string;\n\tproduct: Generated<\n\t\t\"account\" | \"streams\" | \"index\" | \"sentinel\" | \"docs\" | \"tenant\"\n\t>;\n\t/** Sentinel permission areas; set only on `product = 'sentinel'` keys. */\n\tareas: unknown | null;\n\ttier: \"free\" | \"internal\" | null;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n\t/** Set only on `docs` keys (24h). A key past this instant never authenticates. */\n\texpires_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Singleton self-host / publisher identity. Network is immutable. */\nexport interface InstancesTable {\n\tid: Generated<string>;\n\tnetwork: string;\n\t/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */\n\tsecrets_key_canary: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface AccountsTable {\n\tid: Generated<string>;\n\t/** NULL for unclaimed ghost accounts (anonymous self-serve keys). */\n\temail: string | null;\n\t/** True for anonymous self-serve accounts until claimed via magic link. */\n\tghost: Generated<boolean>;\n\t/** First-party service account: usage priced at $0, never gated on\n\t * credits. Set by ops only. */\n\tinternal: Generated<boolean>;\n\t/** Stacks principal owning a wallet-ghost account. */\n\twallet_principal: string | null;\n\tdisplay_name: string | null;\n\tbio: string | null;\n\tavatar_url: string | null;\n\tstripe_customer_id: string | null;\n\t/** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */\n\tnotify_reindex_complete: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SessionsTable {\n\tid: Generated<string>;\n\ttoken_hash: string;\n\ttoken_prefix: string;\n\taccount_id: string;\n\tip_address: string;\n\texpires_at: Generated<Date>;\n\trevoked_at: Date | null;\n\tlast_used_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface MagicLinksTable {\n\tid: Generated<string>;\n\temail: string;\n\ttoken: string;\n\tcode: string | null;\n\texpires_at: Date;\n\tused_at: Date | null;\n\tfailed_attempts: Generated<number>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphProcessingStatsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tapi_key_id: string | null;\n\tbucket_start: Date | null;\n\tbucket_end: Date | null;\n\tblocks_processed: number | null;\n\ttotal_time_ms: number | null;\n\thandler_time_ms: number | null;\n\tflush_time_ms: number | null;\n\tmax_block_time_ms: number | null;\n\tmax_handler_time_ms: number | null;\n\tavg_ops_per_block: number | null;\n\tis_catchup: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphHealthSnapshotsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\ttotal_processed: number;\n\ttotal_errors: number;\n\tlast_processed_block: number | null;\n\tchain_tip: string | number | null;\n\trows_written_total: string | number | null;\n\tstorage_bytes: string | number | null;\n\tcaptured_at: Generated<Date>;\n}\n\n/** Handler errors grouped by fingerprint. Cap 50/subgraph. */\nexport interface SubgraphErrorGroupsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tfingerprint: string;\n\tsource_name: string;\n\tevent_type: string | null;\n\tmessage: string;\n\tframe: string | null;\n\tcount: Generated<string | number>;\n\tsample_tx_id: string | null;\n\tsample_block_height: string | number | null;\n\tfirst_seen: Generated<Date>;\n\tlast_seen: Generated<Date>;\n}\n\n/**\n * One ranked dashboard insight. `account_id` is NULL on tenant and self-host\n * databases. `severity` is never \"recovered\": that is derived on read from\n * `resolved_at`.\n */\nexport interface InsightsTable {\n\tid: Generated<string>;\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tseverity: string;\n\timpact: Generated<number>;\n\t/** resource, line, meta, lead, body, evidence, handoff, how. */\n\tpayload: unknown;\n\tfirst_seen_at: Generated<Date>;\n\tlast_seen_at: Generated<Date>;\n\tclear_streak: Generated<number>;\n\tresolved_at: Date | null;\n\tdismissed_at: Date | null;\n\tsnoozed_until: Date | null;\n}\n\n/** \"Expected\": mutes one rule for one resource until removed. */\nexport interface InsightMutesTable {\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface ProcessedStripeEventsTable {\n\tevent_id: string;\n\tevent_type: string;\n\tprocessed_at: Generated<Date>;\n}\n\nexport interface DecodedEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: string;\n\tmicroblock_hash: string | null;\n\tcanonical: Generated<boolean>;\n\tcontract_id: string | null;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string | null;\n\tasset_identifier: string | null;\n\tvalue: string | null;\n\tmemo: string | null;\n\t/** Decoded payload for event types that don't fit the flat columns\n\t * (e.g. `print`: { topic, value, raw_value }). Null for transfer types. */\n\tpayload: unknown | null;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface DecoderCheckpointsTable {\n\tdecoder_name: string;\n\tlast_cursor: string | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface ChainReorgsTable {\n\tid: Generated<string>;\n\tdetected_at: Generated<Date>;\n\tfork_point_height: number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_from_height: number;\n\torphaned_from_event_index: number;\n\torphaned_to_height: number;\n\torphaned_to_event_index: number;\n\tnew_canonical_height: number;\n\tnew_canonical_event_index: number;\n\tcreated_at: Generated<Date>;\n}\n\n// ── L2 decoded tables: PoX-4 / sBTC / BNS ────────────────────────────\n\nexport type Pox4FunctionName =\n\t| \"stack-stx\"\n\t| \"delegate-stx\"\n\t| \"stack-extend\"\n\t| \"stack-increase\"\n\t| \"revoke-delegate-stx\"\n\t| \"delegate-stack-stx\"\n\t| \"delegate-stack-extend\"\n\t| \"delegate-stack-increase\"\n\t| \"stack-aggregation-commit\"\n\t| \"stack-aggregation-commit-indexed\"\n\t| \"stack-aggregation-increase\"\n\t| \"set-signer-key-authorization\";\n\nexport interface Pox4CallsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\tburn_block_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tfunction_name: Pox4FunctionName;\n\tcaller: string;\n\tstacker: string | null;\n\tdelegate_to: string | null;\n\tamount_ustx: string | null;\n\tlock_period: number | null;\n\tpox_addr_version: number | null;\n\tpox_addr_hashbytes: string | null;\n\tpox_addr_btc: string | null;\n\tstart_cycle: number | null;\n\tend_cycle: number | null;\n\tsigner_key: string | null;\n\tsigner_signature: string | null;\n\tauth_id: string | null;\n\tmax_amount: string | null;\n\treward_cycle: number | null;\n\taggregated_amount_ustx: string | null;\n\taggregated_signer_index: number | null;\n\tauth_period: number | null;\n\tauth_topic: string | null;\n\tauth_allowed: boolean | null;\n\tresult_ok: boolean;\n\tresult_raw: string;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type Pox5EventTopic =\n\t| \"set-bond-admin\"\n\t| \"set-pause-admin\"\n\t| \"pause-rewards\"\n\t| \"setup-bond\"\n\t| \"add-to-allowlist\"\n\t| \"register-for-bond\"\n\t| \"update-bond-registration\"\n\t| \"register-signer\"\n\t| \"stake\"\n\t| \"stake-update\"\n\t| \"announce-l1-early-exit\"\n\t| \"unstake-sbtc\"\n\t| \"unstake\"\n\t| \"calculate-rewards\"\n\t| \"bond-distribution\"\n\t| \"claim-rewards\"\n\t| \"claim-staker-rewards-for-signer\"\n\t| \"grant-signer-key\"\n\t| \"revoke-signer-grant\";\n\n// PoX-5 print events (SIP-045). Promoted columns cover hot query paths; the\n// full decoded tuple always lands in `data` (nested shapes: btc-lockup,\n// bond-rewards lists, bond-periods).\nexport interface Pox5EventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: Pox5EventTopic;\n\tstaker: string | null;\n\tsigner: string | null;\n\tsigner_manager: string | null;\n\tbond_index: number | null;\n\tamount_ustx: string | null;\n\tamount_sats: string | null;\n\treward_cycle: number | null;\n\tfirst_reward_cycle: number | null;\n\tunlock_cycle: number | null;\n\tunlock_burn_height: number | null;\n\tis_l1_lock: boolean | null;\n\tsigner_key: string | null;\n\tdata: unknown;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Materialized per-cycle PoX-5 rollup (`rollupPox5Cycles`), maintained after\n// every committed pox5 decoder batch and after a pox5 reorg. Fully\n// rebuildable from `pox5_events` via `rebuild-pox5-cycles.ts --apply`.\nexport interface Pox5CyclesTable {\n\treward_cycle: number;\n\tstart_burn_height: number;\n\tprepare_start_burn_height: number;\n\tend_burn_height: number;\n\ttotal_stacked_ustx: string;\n\treward_eligible_ustx: string;\n\tstakers: number;\n\tsigners_in_set: number;\n\t/** bond index (as string) -> sats staked for this cycle. */\n\tbond_sats: unknown;\n\tbond_total_sats: string;\n\tsbtc_custodied_sats: string;\n\trewards_allocated_stx: string;\n\trewards_allocated_bond: string;\n\treserve_deposit: string;\n\trewards_per_token_stx: string | null;\n\t/** bond index (as string) -> cumulative rewards-per-sat for this cycle. */\n\trewards_per_token_bond: unknown;\n\tdistributions: number;\n\trewards_claimed: string;\n\tcomputed_through_height: number;\n\tupdated_at: Generated<Date>;\n}\n\n// Per-signer half of the pox-5 cycle rollup.\nexport interface Pox5CycleSignersTable {\n\treward_cycle: number;\n\tsigner: string;\n\tdelegated_ustx: string;\n\tstx_only_ustx: string;\n\treward_shares_ustx: string;\n\tin_set: boolean;\n\trewards_claimed: string;\n}\n\n// Actual BTC PoX payout — one row per reward slot (≤2 per burn block), from the\n// /new_burn_block reward_recipients array. `amount_sats`/`burn_amount` are sats.\nexport interface BurnBlockRewardsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\treward_index: number;\n\trecipient_btc: string;\n\t// sats; TEXT to match the dataset amount convention (BIGINT returns as string).\n\tamount_sats: string;\n\tburn_amount: Generated<string>;\n\tcreated_at: Generated<Date>;\n}\n\n// Reward-set membership per burn block, from /new_burn_block reward_slot_holders.\nexport interface BurnBlockRewardSlotsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\tslot_index: number;\n\tholder_btc: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcEventTopic =\n\t| \"completed-deposit\"\n\t| \"withdrawal-create\"\n\t| \"withdrawal-accept\"\n\t| \"withdrawal-reject\"\n\t| \"key-rotation\"\n\t| \"update-protocol-contract\";\n\nexport interface SbtcEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: SbtcEventTopic;\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\tblock_height_at_request: number | 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\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcTokenEventType = \"transfer\" | \"mint\" | \"burn\";\n\nexport interface SbtcTokenEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: SbtcTokenEventType;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string;\n\tmemo: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * BTC L1 settlement status for sBTC withdrawal sweeps. Filled by the indexer's\n * settlement-confirmer worker, which polls our own bitcoind for confirmations of\n * each `withdrawal-accept`'s `sweep_txid` and surfaces real settlement on the\n * withdrawal lifecycle (the API's `settlement.{btc_confirmations,\n * settlement_confirmed}` placeholder). Keyed on `sweep_txid` (not `request_id`):\n * a request can produce more than one sweep over its life (RBF/rebroadcast), so\n * each broadcast keeps its own confirmation history.\n */\nexport interface SbtcSettlementsTable {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: Generated<number>;\n\tsettlement_confirmed: Generated<boolean>;\n\t/** Confirming Bitcoin block — null while the sweep is unconfirmed. */\n\tblock_hash: string | null;\n\tblock_height: number | null;\n\tfirst_seen_at: Generated<Date>;\n\tlast_checked_at: Generated<Date>;\n\t/** Set once, when `settlement_confirmed` first flips true. */\n\tconfirmed_at: Date | null;\n\t/** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep\n\t * becomes confirmed. The webhook scan's watermark. BIGINT: a string at\n\t * runtime. */\n\tseq: Generated<number | string>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type BnsNameEventTopic =\n\t| \"new-name\"\n\t| \"transfer-name\"\n\t| \"renew-name\"\n\t| \"burn-name\"\n\t| \"new-airdrop\";\n\nexport interface BnsNameEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: BnsNameEventTopic;\n\tnamespace: string;\n\tname: string;\n\tfqn: string;\n\towner: string | null;\n\tbns_id: string;\n\tregistered_at: number | null;\n\timported_at: number | null;\n\trenewal_height: number | null;\n\tstx_burn: string | null;\n\tpreordered_by: string | null;\n\thashed_salted_fqn_preorder: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsNamespaceEventStatus =\n\t| \"launch\"\n\t| \"transfer-manager\"\n\t| \"freeze-manager\"\n\t| \"update-price-manager\"\n\t| \"freeze-price-manager\"\n\t| \"turn-off-manager-transfers\";\n\nexport interface BnsNamespaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tstatus: BnsNamespaceEventStatus;\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: boolean | null;\n\tmanager_transfers_disabled: boolean | null;\n\tprice_function: string | null;\n\tprice_frozen: boolean | null;\n\tlifetime: number | null;\n\trevealed_at: number | null;\n\tlaunched_at: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsMarketplaceAction =\n\t| \"list-in-ustx\"\n\t| \"unlist-in-ustx\"\n\t| \"buy-in-ustx\";\n\nexport interface BnsMarketplaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\taction: BnsMarketplaceAction;\n\tbns_id: string;\n\tprice_ustx: string | null;\n\tcommission: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface BnsNamesTable {\n\tfqn: string;\n\tnamespace: string;\n\tname: string;\n\towner: string;\n\tbns_id: string;\n\tregistered_at: number | null;\n\trenewal_height: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface BnsNamespacesTable {\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: Generated<boolean>;\n\tprice_frozen: Generated<boolean>;\n\tlifetime: number | null;\n\tlaunched_at: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tname_count: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\n// ── Database interface ────────────────────────────────────────────────\n\n/**\n * Memoized `ctx.client.readOnly()` results. Keyed on `index_block_hash` so a\n * reorg-replaced block never inherits the orphaned fork's answer; a NULL\n * `index_block_hash` marks a caller-declared contract-constant value, cached\n * once per contract+args instead of once per block.\n */\nexport interface ChainReadCacheTable {\n\tid: Generated<number>;\n\tcontract_id: string;\n\tfunction_name: string;\n\targs_hash: string;\n\tindex_block_hash: string | null;\n\tblock_height: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tresult_hex: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A block that arrived for a height we already hold, staged until a later\n * block's `parent_hash` says which of the two the chain kept. See migration\n * 0112 — adopting on first sight picked the losing fork twice.\n */\nexport interface PendingForkBlocksTable {\n\theight: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\t/** The canonical hash we held at this height when the contender arrived. */\n\tincumbent_hash: string;\n\t/** The raw observer payload, replayed verbatim if this fork wins. */\n\tpayload: ColumnType<unknown, unknown, unknown>;\n\treceived_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `observer_journal.status`. */\nexport const OBSERVER_JOURNAL_STATUSES = [\n\t\"received\",\n\t\"processed\",\n\t\"failed\",\n\t\"retried\",\n\t\"poisoned\",\n\t\"skipped\",\n] as const;\nexport type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];\n\n/**\n * Exact observer callback receipt. `raw_body` is immutable evidence; the\n * processing columns are updated only after the current derived-state write\n * succeeds or fails.\n */\nexport interface ObserverJournalTable {\n\tsequence: Generated<string>;\n\tnetwork: string;\n\tpath: string;\n\tsource: string | null;\n\treceived_at: Generated<Date>;\n\traw_body: ColumnType<Buffer, Buffer, Buffer>;\n\traw_body_sha256: string;\n\tstatus: ColumnType<\n\t\tObserverJournalStatus,\n\t\tObserverJournalStatus | undefined,\n\t\tObserverJournalStatus\n\t>;\n\tsemantic_sha256: string | null;\n\tblock_height: number | null;\n\tblock_hash: string | null;\n\tburn_block_height: number | null;\n\tburn_block_hash: string | null;\n\tresult: unknown | null;\n\terror: string | null;\n\tprocessed_at: Date | null;\n}\n\n/** Declared coverage stage. Identity is the `id` string (`raw`, `decode:stx`, …). */\nexport interface StageRegistryTable {\n\tid: string;\n\tkind: StageKind;\n\tdepends_on: string | null;\n\tnative_clock: NativeClock;\n\tproducer_version: string;\n\trepair_mode: RepairMode;\n\tenabled: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\n/** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */\nexport interface StageRunsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tcode_hash: string;\n\tconfig_hash: string;\n\thandler_hash: string | null;\n\ttarget_height: number | null;\n\ttarget_cursor: string | null;\n\tstatus: RunStatus;\n\tcomplete_through: number | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\n\n/** Per-block acknowledgement. Unique on (stage, height, hash). */\nexport interface StageBlockReceiptsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tblock_height: number;\n\tblock_hash: string;\n\tinput_count: number;\n\tinput_digest: string;\n\teffect_digest: string;\n\tfinalized: Generated<boolean>;\n\tcompacted_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Compacted finalized range. Only sealed after receipts in the range finalize. */\nexport interface CoverageSegmentsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tfrom_height: number;\n\tto_height: number;\n\tchain_digest: string;\n\tinput_digest: string;\n\toutput_digest: string;\n\tsealed_at: Generated<Date>;\n}\n\n/** Exact unit or range that failed, plus retry/retention state. */\nexport interface StageFailuresTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tunit_kind: FailureUnit;\n\tfrom_height: number | null;\n\tto_height: number | null;\n\tclass: FailureClass;\n\tretry_state: RetryState;\n\tretry_count: Generated<number>;\n\tlast_error: string | null;\n\tcreated_at: Generated<Date>;\n\tresolved_at: Date | null;\n\tretain_until: Generated<Date>;\n}\n\n/**\n * The instance's declared scope — one row per network. `start_height` is what\n * makes missing history below it deliberate rather than a gap.\n */\nexport interface SyncScopesTable {\n\tnetwork: string;\n\tstart_height: number;\n\ttarget_height: number | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface Database {\n\tblocks: BlocksTable;\n\ttransactions: TransactionsTable;\n\tevents: EventsTable;\n\tvm_events: VmEventsTable;\n\tstate_writes: StateWritesTable;\n\ttransactions_archive: TransactionsArchiveTable;\n\tevents_archive: EventsArchiveTable;\n\tvm_events_archive: VmEventsArchiveTable;\n\tstate_writes_archive: StateWritesArchiveTable;\n\tdead_letter_events: DeadLetterEventsTable;\n\tmempool_transactions: MempoolTransactionsTable;\n\tindex_progress: IndexProgressTable;\n\tcontracts: ContractsTable;\n\tsubgraphs: SubgraphsTable;\n\tapi_keys: ApiKeysTable;\n\tinstances: InstancesTable;\n\taccounts: AccountsTable;\n\tsessions: SessionsTable;\n\tmagic_links: MagicLinksTable;\n\tsubgraph_health_snapshots: SubgraphHealthSnapshotsTable;\n\tsubgraph_processing_stats: SubgraphProcessingStatsTable;\n\tsubgraph_gaps: SubgraphGapsTable;\n\tsubgraph_violations: SubgraphViolationsTable;\n\tsubgraph_error_groups: SubgraphErrorGroupsTable;\n\tsubgraph_operations: SubgraphOperationsTable;\n\tprocessed_stripe_events: ProcessedStripeEventsTable;\n\taccount_spend_caps: AccountSpendCapsTable;\n\taccount_credits: AccountCreditsTable;\n\twebhooks: WebhooksTable;\n\twebhook_outbox: WebhookOutboxTable;\n\twebhook_deliveries: WebhookDeliveriesTable;\n\twebhook_delivery_hours: WebhookDeliveryHoursTable;\n\twebhook_replays: WebhookReplaysTable;\n\ttrigger_evaluator_state: TriggerEvaluatorStateTable;\n\tdecoded_events: DecodedEventsTable;\n\tdecoder_checkpoints: DecoderCheckpointsTable;\n\tchain_reorgs: ChainReorgsTable;\n\tpox4_calls: Pox4CallsTable;\n\tpox5_events: Pox5EventsTable;\n\tpox5_cycles: Pox5CyclesTable;\n\tpox5_cycle_signers: Pox5CycleSignersTable;\n\tburn_block_rewards: BurnBlockRewardsTable;\n\tburn_block_reward_slots: BurnBlockRewardSlotsTable;\n\tsbtc_events: SbtcEventsTable;\n\tsbtc_token_events: SbtcTokenEventsTable;\n\tsbtc_settlements: SbtcSettlementsTable;\n\tbns_name_events: BnsNameEventsTable;\n\tbns_namespace_events: BnsNamespaceEventsTable;\n\tbns_marketplace_events: BnsMarketplaceEventsTable;\n\tbns_names: BnsNamesTable;\n\tbns_namespaces: BnsNamespacesTable;\n\tservice_heartbeats: ServiceHeartbeatsTable;\n\tchain_read_cache: ChainReadCacheTable;\n\tpending_fork_blocks: PendingForkBlocksTable;\n\tobserver_journal: ObserverJournalTable;\n\tsync_scopes: SyncScopesTable;\n\tstage_registry: StageRegistryTable;\n\tstage_runs: StageRunsTable;\n\tstage_block_receipts: StageBlockReceiptsTable;\n\tcoverage_segments: CoverageSegmentsTable;\n\tstage_failures: StageFailuresTable;\n\tarchive_fetches: ArchiveFetchesTable;\n\tusage_ledger: UsageLedgerTable;\n\taccount_balance_alerts: AccountBalanceAlertsTable;\n\thosted_stack_state: HostedStackStateTable;\n\twebhook_incident_alerts: WebhookIncidentAlertsTable;\n\tcli_device_logins: CliDeviceLoginsTable;\n\toauth_clients: OauthClientsTable;\n\toauth_requests: OauthRequestsTable;\n\toauth_codes: OauthCodesTable;\n\toauth_grants: OauthGrantsTable;\n\toauth_tokens: OauthTokensTable;\n\toauth_refresh_retired: OauthRefreshRetiredTable;\n\tsentinel_accounts: SentinelAccountsTable;\n\twaitlists: WaitlistsTable;\n\twaitlist_signups: WaitlistSignupsTable;\n\tcontact_requests: ContactRequestsTable;\n\tupdate_subscribers: UpdateSubscribersTable;\n\tupdate_sends: UpdateSendsTable;\n\tapi_failed_requests: ApiFailedRequestsTable;\n\tapi_request_log: ApiRequestLogTable;\n\tinsights: InsightsTable;\n\tinsight_mutes: InsightMutesTable;\n\tfeedback_tickets: FeedbackTicketsTable;\n\tpush_subscriptions: PushSubscriptionsTable;\n\tpush_prefs: PushPrefsTable;\n\tpush_sent: PushSentTable;\n}\n\nexport interface ServiceHeartbeatsTable {\n\tname: string;\n\tupdated_at: Generated<Date>;\n}\n\n// --- Account spend caps (soft cap + threshold alerts) ---\n//\n// One row per account. Null caps = \"no cap\" for that dimension.\n// `monthly_cap_cents` caps this calendar month's pay-as-you-go credit spend.\n// The hard stop is enforced in real time on the read path (read-credits.ts);\n// `frozen_at` is a display/alert mirror set by the daily cron when the cap is\n// hit, and cleared on month rollover, on invoice.paid, or when the cap is raised.\n\nexport interface AccountSpendCapsTable {\n\taccount_id: string;\n\tmonthly_cap_cents: number | null;\n\tcompute_cap_cents: number | null;\n\tstorage_cap_cents: number | null;\n\talert_threshold_pct: Generated<number>;\n\talert_sent_at: Date | null;\n\tfrozen_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountSpendCap = Selectable<AccountSpendCapsTable>;\nexport type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;\nexport type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;\n\n/** Prepaid dev credits — card-funded balance per account. */\nexport interface AccountCreditsTable {\n\taccount_id: string;\n\tbalance_usd_micros: Generated<string | number | bigint>;\n\t/** Month bucket (\"YYYY-MM\") the spend counter applies to. */\n\tspent_month: string | null;\n\tspent_month_usd_micros: Generated<string | number | bigint>;\n\t/** Null = auto-refill off. */\n\trefill_below_usd_micros: string | number | bigint | null;\n\trefill_pack_usd: number | null;\n\trefill_last_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountCredits = Selectable<AccountCreditsTable>;\nexport type InsertAccountCredits = Insertable<AccountCreditsTable>;\nexport type UpdateAccountCredits = Updateable<AccountCreditsTable>;\n\n/**\n * Archive fetch charge log. Append-only: one row per\n * priced attempt to fetch a partition object. `usd_micros` is 0 for\n * free rows (24h re-issue, monthly repair allowance).\n */\nexport interface ArchiveFetchesTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tpath: string;\n\tdataset: string;\n\tusd_micros: string | number | bigint;\n\tvia_allowance: Generated<boolean>;\n\tcharged_at: Generated<Date>;\n}\n\nexport type ArchiveFetch = Selectable<ArchiveFetchesTable>;\nexport type InsertArchiveFetch = Insertable<ArchiveFetchesTable>;\nexport type UpdateArchiveFetch = Updateable<ArchiveFetchesTable>;\n\n/**\n * One metered ledger for every billable unit (archive partitions, hosted\n * Index/Streams rows, and future hosted-stack meters). Append-only, written\n * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission\n * no-ops instead of double-charging. `debited` is false when the balance\n * (or a spend cap) refused the charge — the row still exists so the gap is\n * visible, never silently dropped. `usd_micros` is negative for a Stripe\n * top-up (`unit: \"topup\"`).\n */\nexport interface UsageLedgerTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tunit: string;\n\tquantity: string | number | bigint;\n\t/** Raw sampled quantity before any floor (e.g. `memory.gb_hour`'s actual\n\t * RAM, before the 0.5 GB minimum). NULL for every unit that has no\n\t * floor to observe past. */\n\tobserved_quantity: string | number | null;\n\tusd_micros: string | number | bigint;\n\t/** True when the whole price was taken; derived from `debited_usd_micros`. */\n\tdebited: Generated<boolean>;\n\t/** Amount actually taken from the balance, `0..usd_micros` (bounded the\n\t * other way for a negative top-up/grant row). Unpaid = price - this. */\n\tdebited_usd_micros: Generated<string | number | bigint>;\n\tsource: string;\n\t/** API key behind a metered read; null for non-read units and older rows. */\n\tapi_key_id: string | null;\n\tidempotency_key: string;\n\toccurred_at: Generated<Date>;\n\trecorded_at: Generated<Date>;\n}\n\nexport type UsageLedgerRow = Selectable<UsageLedgerTable>;\nexport type InsertUsageLedgerRow = Insertable<UsageLedgerTable>;\nexport type UpdateUsageLedgerRow = Updateable<UsageLedgerTable>;\n\n/** Preferences + debounce state for the balance-runway email alerts. One\n * row per account; a missing row means both alerts are on (defaults). */\nexport interface AccountBalanceAlertsTable {\n\taccount_id: string;\n\tnotify_7d: Generated<boolean>;\n\tnotify_2d: Generated<boolean>;\n\tsent_7d_at: Date | null;\n\tsent_2d_at: Date | null;\n\tsent_stopped_at: Date | null;\n}\n\n/** The workload host's report of one account's hosted stack. Written only by\n * `POST /internal/stack-state`; `reported_at` is the host's observation time. */\nexport interface HostedStackStateTable {\n\taccount_id: string;\n\tstate: \"provisioning\" | \"running\" | \"stopped\" | \"destroyed\";\n\tstop_reason: \"credits\" | \"cap\" | \"idle\" | null;\n\treported_at: Date;\n}\n\n/** Debounce state for the webhook-down email: one row per incident, open\n * while `resolved_at` is null. No preference columns by design. */\nexport interface WebhookIncidentAlertsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\twebhook_id: string;\n\twebhook_name: string;\n\tfailing_since: Date;\n\topened_at: Generated<Date>;\n\temailed_at: Date | null;\n\temail_attempts: Generated<number>;\n\tresolved_at: Date | null;\n}\n\nexport type WebhookIncidentAlert = Selectable<WebhookIncidentAlertsTable>;\n\n/** One browser/device push subscription; the endpoint is unique. */\nexport interface PushSubscriptionsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tendpoint: string;\n\tp256dh: string;\n\tauth: string;\n\tuser_agent: string | null;\n\tcreated_at: Generated<Date>;\n\tlast_success_at: Date | null;\n\tfailed_count: Generated<number>;\n}\n\nexport type PushSubscription = Selectable<PushSubscriptionsTable>;\n\n/** Per-account push toggles. A missing row means the column defaults. */\nexport interface PushPrefsTable {\n\taccount_id: string;\n\twebhook_failing: Generated<boolean>;\n\tsubgraph_stopped: Generated<boolean>;\n\tsubgraph_not_serving: Generated<boolean>;\n\treplay_done: Generated<boolean>;\n\tspend_cap: Generated<boolean>;\n\tkey_repeat: Generated<boolean>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type PushPrefs = Selectable<PushPrefsTable>;\n\n/** A push already sent, keyed by what it was about; debounces repeat signals. */\nexport interface PushSentTable {\n\taccount_id: string;\n\tkey: string;\n\tkind: string;\n\tsent_at: Generated<Date>;\n}\n\nexport type CliDeviceLoginStatus =\n\t| \"pending\"\n\t| \"approved\"\n\t| \"denied\"\n\t| \"consumed\";\n\n/** The product that started a CLI sign-in; null is `sl login`. */\nexport type CliDeviceProduct = \"sentinel\";\n\n/** One browser sign-in attempt from `sl login` (or `sentinel login`). Only the\n * hash of the CLI's device code is stored; the session is opened when the CLI\n * polls after approval. */\nexport interface CliDeviceLoginsTable {\n\tid: Generated<string>;\n\tdevice_code_hash: string;\n\tuser_code: string;\n\tclient_name: string;\n\tproduct: CliDeviceProduct | null;\n\tstatus: Generated<CliDeviceLoginStatus>;\n\taccount_id: string | null;\n\tkey_name: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tapproved_at: Date | null;\n\tconsumed_at: Date | null;\n}\n\nexport type CliDeviceLogin = Selectable<CliDeviceLoginsTable>;\n\n// --- OAuth for the hosted MCP endpoint ---\n//\n// Codes and tokens are stored as SHA-256 hashes only. See migration\n// `0177_oauth_mcp` and `@secondlayer/platform/db/queries/oauth`.\n\n/** An app that registered itself (RFC 7591). Public clients only: no secret. */\nexport interface OauthClientsTable {\n\tid: string;\n\t/** The app's own claim, validated at registration; shown quoted. */\n\tname: string;\n\tredirect_uris: string[];\n\tcreated_ip: string | null;\n\tcreated_at: Generated<Date>;\n\t/** Set when it first gets tokens; never-used clients are purged. */\n\tlast_used_at: Date | null;\n}\n\nexport type OauthRequestStatus = \"pending\" | \"approved\" | \"denied\";\n\n/** One authorize request waiting for (or answered on) the consent page. */\nexport interface OauthRequestsTable {\n\tid: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tstate: string | null;\n\tcode_challenge: string;\n\tresource: string;\n\tstatus: Generated<OauthRequestStatus>;\n\taccount_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tanswered_at: Date | null;\n}\n\n/** A one-time authorization code, bound to its client, redirect, PKCE\n * challenge, resource and account. */\nexport interface OauthCodesTable {\n\tcode_hash: string;\n\tclient_id: string;\n\taccount_id: string;\n\tredirect_uri: string;\n\tcode_challenge: string;\n\tresource: string;\n\t/** The grant its one use made, so a replay can revoke it. */\n\tgrant_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tused_at: Date | null;\n}\n\n/** What a person allowed one app to do: use the hosted MCP as them. */\nexport interface OauthGrantsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tclient_id: string;\n\tscope: Generated<string>;\n\tresource: string;\n\tcreated_at: Generated<Date>;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n}\n\nexport type OauthTokenKind = \"access\" | \"refresh\";\n\nexport interface OauthTokensTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tkind: OauthTokenKind;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n}\n\n/** A refresh token a rotation replaced: presented again, it revokes the grant. */\nexport interface OauthRefreshRetiredTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tretired_at: Generated<Date>;\n}\n\nexport type OauthClient = Selectable<OauthClientsTable>;\nexport type OauthGrant = Selectable<OauthGrantsTable>;\n\n/** Accounts Sentinel's service key may touch: created by Sentinel, or the\n * owner opted in. */\nexport interface SentinelAccountsTable {\n\taccount_id: string;\n\tlinked_at: Generated<Date>;\n\tvia: \"created\" | \"consent\";\n}\n\nexport type SentinelAccount = Selectable<SentinelAccountsTable>;\n\nexport type AccountBalanceAlerts = Selectable<AccountBalanceAlertsTable>;\nexport type InsertAccountBalanceAlerts = Insertable<AccountBalanceAlertsTable>;\nexport type UpdateAccountBalanceAlerts = Updateable<AccountBalanceAlertsTable>;\n\n// ── Convenience types ─────────────────────────────────────────────────\n\nexport type Block = Selectable<BlocksTable>;\nexport type InsertBlock = Insertable<BlocksTable>;\nexport type UpdateBlock = Updateable<BlocksTable>;\n\nexport type Transaction = Selectable<TransactionsTable>;\nexport type InsertTransaction = Insertable<TransactionsTable>;\nexport type UpdateTransaction = Updateable<TransactionsTable>;\n\nexport type MempoolTransaction = Selectable<MempoolTransactionsTable>;\nexport type InsertMempoolTransaction = Insertable<MempoolTransactionsTable>;\n\nexport type Event = Selectable<EventsTable>;\nexport type InsertEvent = Insertable<EventsTable>;\nexport type UpdateEvent = Updateable<EventsTable>;\n\nexport type VmEvent = Selectable<VmEventsTable>;\nexport type InsertVmEvent = Insertable<VmEventsTable>;\nexport type UpdateVmEvent = Updateable<VmEventsTable>;\nexport type StateWrite = Selectable<StateWritesTable>;\nexport type InsertStateWrite = Insertable<StateWritesTable>;\n\nexport type IndexProgress = Selectable<IndexProgressTable>;\nexport type InsertIndexProgress = Insertable<IndexProgressTable>;\nexport type UpdateIndexProgress = Updateable<IndexProgressTable>;\n\nexport type Subgraph = Selectable<SubgraphsTable>;\nexport type InsertSubgraph = Insertable<SubgraphsTable>;\nexport type UpdateSubgraph = Updateable<SubgraphsTable>;\n\nexport type Contract = Selectable<ContractsTable>;\nexport type InsertContract = Insertable<ContractsTable>;\nexport type UpdateContract = Updateable<ContractsTable>;\n\nexport type SubgraphOperation = Selectable<SubgraphOperationsTable>;\nexport type InsertSubgraphOperation = Insertable<SubgraphOperationsTable>;\nexport type UpdateSubgraphOperation = Updateable<SubgraphOperationsTable>;\n\nexport type ApiKey = Selectable<ApiKeysTable>;\nexport type InsertApiKey = Insertable<ApiKeysTable>;\nexport type UpdateApiKey = Updateable<ApiKeysTable>;\n\nexport type Account = Selectable<AccountsTable>;\nexport type InsertAccount = Insertable<AccountsTable>;\n\nexport type MagicLink = Selectable<MagicLinksTable>;\nexport type InsertMagicLink = Insertable<MagicLinksTable>;\n\nexport type Session = Selectable<SessionsTable>;\nexport type InsertSession = Insertable<SessionsTable>;\n\nexport type SubgraphHealthSnapshot = Selectable<SubgraphHealthSnapshotsTable>;\nexport type InsertSubgraphHealthSnapshot =\n\tInsertable<SubgraphHealthSnapshotsTable>;\n\nexport type SubgraphGap = Selectable<SubgraphGapsTable>;\nexport type InsertSubgraphGap = Insertable<SubgraphGapsTable>;\n\n// ── Webhooks (chain event webhooks) ─────────────────────\n\nexport type WebhookStatus = \"active\" | \"paused\";\nexport type { WebhookPauseReason };\n\n/** Webhooks react to raw chain events matched directly off the Index/Streams\n * clock. `chain` is the only kind since migration 0159 removed subgraph-row\n * webhooks; the column stays as the discriminator. */\nexport type WebhookKind = \"chain\";\nexport type WebhookFormat =\n\t| \"standard-webhooks\"\n\t| \"inngest\"\n\t| \"trigger\"\n\t| \"cloudflare\"\n\t| \"cloudevents\"\n\t| \"raw\";\n\nexport interface WebhooksTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tproject_id: string | null;\n\tname: string;\n\tstatus: ColumnType<WebhookStatus, WebhookStatus | undefined, WebhookStatus>;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\t/** Chain-trigger filter array (the `SubgraphFilter` shape, JSON). Typed\n\t * loosely here to avoid a shared→subgraphs import cycle; the Zod schema in\n\t * schemas/webhooks.ts owns the shape. */\n\ttriggers: unknown;\n\tformat: ColumnType<WebhookFormat, WebhookFormat | undefined, WebhookFormat>;\n\turl: string;\n\tsigning_secret_enc: Buffer;\n\tauth_config: Generated<unknown>;\n\tmax_retries: Generated<number>;\n\ttimeout_ms: Generated<number>;\n\tconcurrency: Generated<number>;\n\tcircuit_failures: Generated<number>;\n\tcircuit_opened_at: Date | null;\n\t/** Why a paused webhook is paused. Set exactly while `status` is `paused`. */\n\tpause_reason: WebhookPauseReason | null;\n\tlast_delivery_at: Date | null;\n\tlast_success_at: Date | null;\n\tlast_error: string | null;\n\t/** Receiver TLS leaf certificate expiry, from the emitter's periodic probe. */\n\treceiver_cert_expires_at: Date | null;\n\treceiver_cert_checked_at: Date | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type Webhook = Selectable<WebhooksTable>;\nexport type InsertWebhook = Insertable<WebhooksTable>;\nexport type UpdateWebhook = Updateable<WebhooksTable>;\n\nexport type OutboxStatus = \"pending\" | \"delivered\" | \"dead\";\n/** Why a row is dead: retries ran out, or a reorg removed its event. An\n * orphaned row stays dead; requeueing it would resend an event the chain no\n * longer contains. */\nexport type DeadReason = \"exhausted\" | \"orphaned\";\n\nexport interface WebhookOutboxTable {\n\tid: Generated<string>;\n\twebhook_id: string;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\tblock_height: number | bigint;\n\ttx_id: string | null;\n\trow_pk: unknown;\n\tevent_type: string;\n\tpayload: unknown;\n\tdedup_key: string;\n\tattempt: Generated<number>;\n\tnext_attempt_at: Generated<Date>;\n\tstatus: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;\n\tis_replay: Generated<boolean>;\n\t/** The replay that created this row; null for live rows. */\n\treplay_id: string | null;\n\t/** The chain block_time of the matched event/tx. Null for rows written\n\t * before this column existed, and for the settlement scan path (not yet\n\t * wired). Lets `delivered_at - block_time` measure end-to-end webhook\n\t * latency without a join to SOURCE-plane `blocks`. */\n\tblock_time: Date | null;\n\tdelivered_at: Date | null;\n\tfailed_at: Date | null;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\t/** Set when a reorg marks an in-flight row `dead` instead of retrying it\n\t * into an orphaned fork. Null otherwise — delivery failures track their\n\t * history on `webhooks.last_error`, not per-row. */\n\tlast_error: string | null;\n\t/** Set exactly while `status` is `dead`. */\n\tdead_reason: DeadReason | null;\n\t/** Hash of the block a chain apply row was emitted for. Null on rows\n\t * written before the column existed (the payload carries it too). */\n\tblock_hash: string | null;\n\t/** Set when a reorg rollback recalled this delivered apply row, so a\n\t * later rollback for the same reorg skips it. */\n\trolled_back_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type WebhookReplayStatus = \"scanning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface WebhookReplaysTable {\n\tid: string;\n\twebhook_id: string;\n\tfrom_block: number | bigint;\n\tto_block: number | bigint;\n\tstatus: WebhookReplayStatus;\n\tscanned_count: Generated<number>;\n\tenqueued_count: Generated<number>;\n\ttotal: number | null;\n\tdelivered: number | null;\n\tgave_up: number | null;\n\terror: string | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\nexport type WebhookReplay = Selectable<WebhookReplaysTable>;\n\n/** `replay_id` is optional on the row type so hand-built rows (the test\n * delivery, fixtures) need not carry it; reads still return it. */\nexport type WebhookOutbox = Omit<\n\tSelectable<WebhookOutboxTable>,\n\t\"replay_id\"\n> & {\n\treplay_id?: string | null;\n};\nexport type InsertWebhookOutbox = Insertable<WebhookOutboxTable>;\nexport type UpdateWebhookOutbox = Updateable<WebhookOutboxTable>;\n\nexport interface WebhookDeliveriesTable {\n\tid: Generated<string>;\n\t/** Nullable after migration 0077 — outbox row may be cleaned up while\n\t * delivery telemetry is retained. */\n\toutbox_id: string | null;\n\twebhook_id: string;\n\tattempt: number;\n\tstatus_code: number | null;\n\tresponse_headers: unknown | null;\n\tresponse_body: string | null;\n\terror_message: string | null;\n\tduration_ms: number | null;\n\tdispatched_at: Generated<Date>;\n}\n\n/** Attempts per UTC hour, counted by a trigger on `webhook_deliveries`. */\nexport interface WebhookDeliveryHoursTable {\n\twebhook_id: string;\n\thour: Date;\n\t/** 2xx attempts. */\n\tdelivered: Generated<number>;\n\t/** Every other attempt. */\n\tfailed: Generated<number>;\n}\n\nexport type WebhookDelivery = Selectable<WebhookDeliveriesTable>;\nexport type InsertWebhookDelivery = Insertable<WebhookDeliveriesTable>;\n\n/** Single-row (id always TRUE) high-water mark for the chain-trigger evaluator.\n * One loop serves all chain webhooks, so the cursor is global. */\nexport interface TriggerEvaluatorStateTable {\n\tid: Generated<boolean>;\n\tlast_processed_block: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Watermark for the async sBTC settlement-confirmed webhook scan; null until\n\t * the evaluator fast-forwards it on first run. */\n\tlast_settlement_scan_at: ColumnType<\n\t\tDate | null,\n\t\tDate | null | undefined,\n\t\tDate | null\n\t>;\n\t/** `sbtc_settlements.seq` watermark. Null until the first settlement row is\n\t * scanned; `last_settlement_scan_at` is the forward-only floor until then. */\n\tlast_settlement_scan_seq: ColumnType<\n\t\tbigint | null,\n\t\tbigint | number | null | undefined,\n\t\tbigint | number | null\n\t>;\n\t/** Counts reorg rewinds. The evaluator checks it under the row lock in the\n\t * transaction that emits a batch and advances the cursor, so a reorg that\n\t * lands mid-tick rolls the batch back. */\n\treorg_generation: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)\n\t * chain-trigger evaluator (plan 060) — a separate clock from\n\t * `last_processed_block` (Stacks). Null until the evaluator fast-forwards\n\t * it to the Bitcoin Streams tip on first run. */\n\tbitcoin_last_cursor: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type TriggerEvaluatorState = Selectable<TriggerEvaluatorStateTable>;\n\n/** A public waitlist page: what it is for and whether it takes signups. */\nexport interface WaitlistsTable {\n\tslug: string;\n\ttitle: string;\n\tdescription: string;\n\turl: string;\n\topened_at: Generated<Date>;\n\t/** Null while the list is open. */\n\tclosed_at: Date | null;\n}\n\n/**\n * One signup per (list, contact, token). `answers` holds the list's own\n * questions, validated per list by the API before insert.\n */\nexport interface WaitlistSignupsTable {\n\tid: Generated<string>;\n\tlist: string;\n\tcontact: string;\n\tanswers: Record<string, unknown>;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A \"Talk to us\" message. Stored before the operator is emailed;\n * `notified_at` stays null until the email goes out.\n */\nexport interface ContactRequestsTable {\n\tid: Generated<string>;\n\tname: string;\n\temail: string;\n\tcompany: string | null;\n\tvolume: \"lt10m\" | \"10m-100m\" | \"100m-1b\" | \"gt1b\" | \"unsure\" | null;\n\tmessage: string;\n\tsource_page: string | null;\n\taccount_id: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tnotified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A member of the email updates list. `pending` until the emailed link is\n * confirmed (`confirm_sent_at` starts the 7-day window), `confirmed` while\n * subscribed, `unsubscribed` after an opt-out. `token` is the secret in\n * confirm and unsubscribe links.\n */\nexport interface UpdateSubscribersTable {\n\tid: Generated<string>;\n\temail: string;\n\tstatus: Generated<\"pending\" | \"confirmed\" | \"unsubscribed\">;\n\ttoken: string;\n\tsource_page: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tconfirm_sent_at: Date | null;\n\tconfirmed_at: Date | null;\n\tunsubscribed_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** One broadcast (`send_key`) delivered to one subscriber. */\nexport interface UpdateSendsTable {\n\tsend_key: string;\n\tsubscriber_id: string;\n\tsent_at: Generated<Date>;\n}\n\n/**\n * 24h hosted record of a failed API request, keyed by `request_id` and\n * scoped to the account that made it. `query` is redacted before insert.\n */\nexport interface ApiFailedRequestsTable {\n\trequest_id: string;\n\taccount_id: string;\n\tmethod: string;\n\tpath: string;\n\tstatus: number;\n\tcode: string;\n\tmessage: Generated<string>;\n\tquery: Record<string, unknown>;\n\torigin: string | null;\n\t/** Revoked account key the request presented (`KEY_REVOKED` only). */\n\tapi_key_id: string | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiFailedRequest = Selectable<ApiFailedRequestsTable>;\nexport type InsertApiFailedRequest = Insertable<ApiFailedRequestsTable>;\n\n/**\n * 7-day hosted log of account-attributed Index/Streams reads. Query values\n * are stored only as hashes; never bodies, headers or tokens.\n */\nexport interface ApiRequestLogTable {\n\tid: Generated<string>;\n\trequest_id: string | null;\n\taccount_id: string;\n\tapi_key_id: string | null;\n\tmethod: string;\n\tpath: string;\n\tpath_template: string;\n\tparams_hash: string | null;\n\tcursor_hash: string | null;\n\tpage_size: number | null;\n\trows: number | null;\n\tstatus: number;\n\tduration_ms: number;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiRequestLogRow = Selectable<ApiRequestLogTable>;\nexport type InsertApiRequestLogRow = Insertable<ApiRequestLogTable>;\n\n/**\n * Hosted problem report. `attempted` is the server's own copy of the failed\n * request (never caller-supplied); `status` starts `new` until classified.\n */\nexport interface FeedbackTicketsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tidempotency_key: string | null;\n\trequest_id: string | null;\n\tintent: string;\n\t/** Any JSON value the caller sent: a sentence or a shape. */\n\texpected: unknown;\n\tkind_hint: string | null;\n\tevidence: Record<string, unknown> | null;\n\tattempted: Record<string, unknown> | null;\n\torigin: string;\n\tstatus: Generated<\"new\" | \"classified\">;\n\troute: string | null;\n\tclassification: Record<string, unknown> | null;\n\tclassified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type FeedbackTicket = Selectable<FeedbackTicketsTable>;\nexport type InsertFeedbackTicket = Insertable<FeedbackTicketsTable>;\n\nexport type Waitlist = Selectable<WaitlistsTable>;\nexport type WaitlistSignup = Selectable<WaitlistSignupsTable>;\nexport type InsertWaitlistSignup = Insertable<WaitlistSignupsTable>;\n\nexport type ContactRequest = Selectable<ContactRequestsTable>;\nexport type InsertContactRequest = Insertable<ContactRequestsTable>;\n\nexport type UpdateSubscriber = Selectable<UpdateSubscribersTable>;\nexport type InsertUpdateSubscriber = Insertable<UpdateSubscribersTable>;\n"
5
+ "import type {\n\tColumnType,\n\tGenerated,\n\tInsertable,\n\tSelectable,\n\tUpdateable,\n} from \"kysely\";\nimport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\nimport type { BootstrapSource } from \"../coverage/evaluate.ts\";\nimport type {\n\tSubgraphStatus,\n\tSubgraphVerification,\n} from \"../schemas/subgraphs.ts\";\nimport type { WebhookPauseReason } from \"../webhooks/health.ts\";\n\nexport type {\n\tFailureClass,\n\tFailureUnit,\n\tNativeClock,\n\tRepairMode,\n\tRetryState,\n\tRunStatus,\n\tStageKind,\n} from \"../coverage/constraints.ts\";\n\n// ── Table interfaces ──────────────────────────────────────────────────\n\nexport interface BlocksTable {\n\theight: number;\n\thash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\t/** Nakamoto StacksBlockId. Null on rows ingested before it was persisted. */\n\tindex_block_hash: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\ttimestamp: number;\n\tcanonical: Generated<boolean>;\n\t/** Tx count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\ttx_count: ColumnType<number | null, number | null | undefined, number | null>;\n\t/** Event count `persistBlock` was handed for this height. Null on rows\n\t * ingested before this column existed. */\n\tevent_count: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface TransactionsTable {\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: Generated<number>;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: Generated<unknown | null>;\n\traw_result: Generated<string | null>;\n\traw_tx: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface EventsTable {\n\tid: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\n// Reorg archive (see migration 0084): orphaned transactions/events copied here\n// before a reused height is replaced, preserving the raw log instead of\n// deleting it.\nexport interface TransactionsArchiveTable {\n\tarchive_id: Generated<string>;\n\ttx_id: string;\n\tblock_height: number;\n\ttx_index: number;\n\ttype: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\traw_result: string | null;\n\traw_tx: string;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\nexport interface EventsArchiveTable {\n\tarchive_id: Generated<string>;\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tevent_index: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in VM traces (migration 0131). Second clock: `ordinal` (array position\n// in `/new_block.vm_events`). Never mixed into `events.event_index`. Primary\n// key `(block_height, ordinal)` (migration 0153).\nexport interface VmEventsTable {\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface VmEventsArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`; rows archived before migration 0153 hold the old uuid. */\n\tid: string;\n\ttx_id: string;\n\tblock_height: number;\n\tordinal: number;\n\ttype: string;\n\tdata: unknown;\n\tcreated_at: Date;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Opt-in node storage-layer writes (migration 0154): the exact MARF writes a\n// block committed, in node order. `tx_index` is null for block-level writes.\n// Primary key `(block_height, ordinal)`.\nexport interface StateWritesTable {\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n}\n\nexport interface StateWritesArchiveTable {\n\tarchive_id: Generated<string>;\n\t/** `block_height:ordinal`. */\n\tid: string;\n\tblock_height: number;\n\tordinal: number;\n\ttx_index: number | null;\n\tkey: string;\n\tvalue_hex: string;\n\torphaned_block_hash: string | null;\n\tarchived_at: Generated<Date>;\n}\n\n// Dead-letter log (see migration 0085): events whose decoded payload failed\n// schema validation on ingest. Append-only diagnostic; the event still lands in\n// `events`, so chain data is never lost.\nexport interface DeadLetterEventsTable {\n\tid: Generated<string>;\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tevent_type: string;\n\tdata: unknown;\n\treason: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Pending (unconfirmed) transactions (see migration 0086). Pre-chain, so no\n// block_height/tx_index/result/events and never canonical. tx_id is derived\n// from raw_tx; function_args holds hex-encoded ClarityValues (jsonb), like\n// `transactions`.\nexport interface MempoolTransactionsTable {\n\tseq: Generated<string>;\n\ttx_id: string;\n\traw_tx: string;\n\ttype: string;\n\tsender: string;\n\tcontract_id: string | null;\n\tfunction_name: string | null;\n\tfunction_args: unknown | null;\n\treceived_at: Generated<Date>;\n}\n\nexport interface IndexProgressTable {\n\tnetwork: string;\n\tlast_indexed_block: Generated<number>;\n\tlast_contiguous_block: Generated<number>;\n\thighest_seen_block: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface SubgraphsTable {\n\tid: Generated<string>;\n\tname: string;\n\tversion: Generated<string>;\n\tstatus: Generated<SubgraphStatus>;\n\tdefinition: Record<string, unknown>;\n\tschema_hash: string;\n\thandler_path: string;\n\tschema_name: string | null;\n\tstart_block: Generated<number>;\n\tlast_processed_block: Generated<number>;\n\t/** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */\n\tlast_processed_block_hash: Generated<string | null>;\n\treindex_from_block: number | null;\n\treindex_to_block: number | null;\n\tlast_error: string | null;\n\tlast_error_at: Date | null;\n\ttotal_processed: Generated<number>;\n\ttotal_errors: Generated<number>;\n\taccount_id: string;\n\thandler_code: string | null;\n\tsource_code: string | null;\n\tproject_id: string | null;\n\t/** Set while the account's metered reads are refused (spend cap, credits).\n\t * Both columns are set or both null; `last_error` stays for real errors. */\n\tbilling_paused_at: Date | null;\n\tbilling_paused_code: string | null;\n\t/** (event type, contract) probe pairs persisted at deploy for weight classification. */\n\tsparse_probe_targets: unknown | null;\n\t/** sha256 over everything that shapes rows (schema, handler bundle,\n\t * startBlock, network, runtime). NULL for unbundled or older deploys. */\n\tpin: string | null;\n\t/** The canonical JSON `pin` hashes, so a client can recompute it. NULL\n\t * wherever `pin` is, and for deploys before migration 0158. */\n\tpin_preimage: string | null;\n\t/** Level derived at deploy. NULL (older deploys) = not verifiable. */\n\tverification: SubgraphVerification | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `contracts.abi_status`. */\nexport const ABI_STATUSES = [\n\t\"pending\",\n\t\"fetched\",\n\t\"unparseable\",\n\t\"failed\",\n] as const;\nexport type AbiStatus = (typeof ABI_STATUSES)[number];\n\nexport interface ContractsTable {\n\tcontract_id: string;\n\tdeployer: string;\n\tblock_height: number;\n\tcanonical: Generated<boolean>;\n\tabi: unknown | null;\n\tdeclared_traits: Generated<string[]>;\n\tinferred_standards: Generated<string[]>;\n\tabi_status: Generated<AbiStatus>;\n\tabi_fetched_at: Date | null;\n\t/** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */\n\tabi_attempts: Generated<number>;\n\t/** When a `failed` row is next due; NULL once attempts are exhausted. */\n\tabi_next_attempt_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */\nexport type GapReason = \"block_missing\" | \"processing_error\";\n\nexport interface SubgraphGapsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tgap_start: number;\n\tgap_end: number;\n\treason: GapReason;\n\tdetected_at: Generated<Date>;\n\tresolved_at: Date | null;\n}\n\n/** Print-validate skips persisted for the authed violations GET. Cap 100/subgraph. */\nexport interface SubgraphViolationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tsource_name: string;\n\tblock_height: number;\n\ttx_id: string;\n\treason: string;\n\tsample_payload: Record<string, unknown>;\n\tseen_at: Generated<Date>;\n}\n\nexport type SubgraphOperationKind = \"reindex\" | \"backfill\";\nexport type SubgraphOperationStatus =\n\t| \"queued\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"cancelled\";\n\nexport interface SubgraphOperationsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\taccount_id: string | null;\n\tkind: ColumnType<\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind,\n\t\tSubgraphOperationKind\n\t>;\n\tstatus: ColumnType<\n\t\tSubgraphOperationStatus,\n\t\tSubgraphOperationStatus | undefined,\n\t\tSubgraphOperationStatus\n\t>;\n\tfrom_block: number | null;\n\tto_block: number | null;\n\tcancel_requested: Generated<boolean>;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\tstarted_at: Date | null;\n\tfinished_at: Date | null;\n\tprocessed_blocks: number | null;\n\terror: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n\t/** 'light' (contract-scoped sparse) | 'heavy' (broad). Claim budgets heavy. */\n\tweight: Generated<string>;\n\t/** Candidate-event denominator computed at enqueue (sparse ops only). */\n\testimated_events: string | number | bigint | null;\n\t/** Events processed so far — written by the progress flush. */\n\tprocessed_events: string | number | bigint | null;\n\t/** Backfill ops' own crash checkpoint — advanced conditionally in-tx with\n\t * each written block; replays skip at/below it. NULL for reindex ops\n\t * (those checkpoint on subgraphs.last_processed_block). */\n\tcursor_block: string | number | bigint | null;\n}\n\nexport type ApiKeyStatus = \"active\" | \"revoked\";\n\nexport interface ApiKeysTable {\n\tid: Generated<string>;\n\tkey_hash: string;\n\tkey_prefix: string;\n\tname: string | null;\n\tstatus: Generated<ApiKeyStatus>;\n\trate_limit: Generated<number>;\n\tip_address: string;\n\taccount_id: string;\n\tproduct: Generated<\n\t\t\"account\" | \"streams\" | \"index\" | \"sentinel\" | \"docs\" | \"tenant\"\n\t>;\n\t/** Sentinel permission areas; set only on `product = 'sentinel'` keys. */\n\tareas: unknown | null;\n\ttier: \"free\" | \"internal\" | null;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n\t/** Set only on `docs` keys (24h). A key past this instant never authenticates. */\n\texpires_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Singleton self-host / publisher identity. Network is immutable. */\nexport interface InstancesTable {\n\tid: Generated<string>;\n\tnetwork: string;\n\t/** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */\n\tsecrets_key_canary: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface AccountsTable {\n\tid: Generated<string>;\n\t/** NULL for unclaimed ghost accounts (anonymous self-serve keys). */\n\temail: string | null;\n\t/** True for anonymous self-serve accounts until claimed via magic link. */\n\tghost: Generated<boolean>;\n\t/** First-party service account: usage priced at $0, never gated on\n\t * credits. Set by ops only. */\n\tinternal: Generated<boolean>;\n\t/** Stacks principal owning a wallet-ghost account. */\n\twallet_principal: string | null;\n\tdisplay_name: string | null;\n\tbio: string | null;\n\tavatar_url: string | null;\n\tstripe_customer_id: string | null;\n\t/** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */\n\tnotify_reindex_complete: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SessionsTable {\n\tid: Generated<string>;\n\ttoken_hash: string;\n\ttoken_prefix: string;\n\taccount_id: string;\n\tip_address: string;\n\texpires_at: Generated<Date>;\n\trevoked_at: Date | null;\n\tlast_used_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface MagicLinksTable {\n\tid: Generated<string>;\n\temail: string;\n\ttoken: string;\n\tcode: string | null;\n\texpires_at: Date;\n\tused_at: Date | null;\n\tfailed_attempts: Generated<number>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphProcessingStatsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tapi_key_id: string | null;\n\tbucket_start: Date | null;\n\tbucket_end: Date | null;\n\tblocks_processed: number | null;\n\ttotal_time_ms: number | null;\n\thandler_time_ms: number | null;\n\tflush_time_ms: number | null;\n\tmax_block_time_ms: number | null;\n\tmax_handler_time_ms: number | null;\n\tavg_ops_per_block: number | null;\n\tis_catchup: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface SubgraphHealthSnapshotsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\ttotal_processed: number;\n\ttotal_errors: number;\n\tlast_processed_block: number | null;\n\tchain_tip: string | number | null;\n\trows_written_total: string | number | null;\n\tstorage_bytes: string | number | null;\n\tcaptured_at: Generated<Date>;\n}\n\n/** Handler errors grouped by fingerprint. Cap 50/subgraph. */\nexport interface SubgraphErrorGroupsTable {\n\tid: Generated<string>;\n\tsubgraph_id: string;\n\tsubgraph_name: string;\n\tfingerprint: string;\n\tsource_name: string;\n\tevent_type: string | null;\n\tmessage: string;\n\tframe: string | null;\n\tcount: Generated<string | number>;\n\tsample_tx_id: string | null;\n\tsample_block_height: string | number | null;\n\tfirst_seen: Generated<Date>;\n\tlast_seen: Generated<Date>;\n}\n\n/**\n * One ranked dashboard insight. `account_id` is NULL on tenant and self-host\n * databases. `severity` is never \"recovered\": that is derived on read from\n * `resolved_at`.\n */\nexport interface InsightsTable {\n\tid: Generated<string>;\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tseverity: string;\n\timpact: Generated<number>;\n\t/** resource, line, meta, lead, body, evidence, handoff, how. */\n\tpayload: unknown;\n\tfirst_seen_at: Generated<Date>;\n\tlast_seen_at: Generated<Date>;\n\tclear_streak: Generated<number>;\n\tresolved_at: Date | null;\n\tdismissed_at: Date | null;\n\tsnoozed_until: Date | null;\n}\n\n/** \"Expected\": mutes one rule for one resource until removed. */\nexport interface InsightMutesTable {\n\taccount_id: string | null;\n\tresource_kind: string;\n\tresource_id: string;\n\trule: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface ProcessedStripeEventsTable {\n\tevent_id: string;\n\tevent_type: string;\n\tprocessed_at: Generated<Date>;\n}\n\nexport interface DecodedEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: string;\n\tmicroblock_hash: string | null;\n\tcanonical: Generated<boolean>;\n\tcontract_id: string | null;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string | null;\n\tasset_identifier: string | null;\n\tvalue: string | null;\n\tmemo: string | null;\n\t/** Decoded payload for event types that don't fit the flat columns\n\t * (e.g. `print`: { topic, value, raw_value }). Null for transfer types. */\n\tpayload: unknown | null;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface DecoderCheckpointsTable {\n\tdecoder_name: string;\n\tlast_cursor: string | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface ChainReorgsTable {\n\tid: Generated<string>;\n\tdetected_at: Generated<Date>;\n\tfork_point_height: number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_from_height: number;\n\torphaned_from_event_index: number;\n\torphaned_to_height: number;\n\torphaned_to_event_index: number;\n\tnew_canonical_height: number;\n\tnew_canonical_event_index: number;\n\tcreated_at: Generated<Date>;\n}\n\n// ── L2 decoded tables: PoX-4 / sBTC / BNS ────────────────────────────\n\nexport type Pox4FunctionName =\n\t| \"stack-stx\"\n\t| \"delegate-stx\"\n\t| \"stack-extend\"\n\t| \"stack-increase\"\n\t| \"revoke-delegate-stx\"\n\t| \"delegate-stack-stx\"\n\t| \"delegate-stack-extend\"\n\t| \"delegate-stack-increase\"\n\t| \"stack-aggregation-commit\"\n\t| \"stack-aggregation-commit-indexed\"\n\t| \"stack-aggregation-increase\"\n\t| \"set-signer-key-authorization\";\n\nexport interface Pox4CallsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\tburn_block_height: number;\n\ttx_id: string;\n\ttx_index: number;\n\tfunction_name: Pox4FunctionName;\n\tcaller: string;\n\tstacker: string | null;\n\tdelegate_to: string | null;\n\tamount_ustx: string | null;\n\tlock_period: number | null;\n\tpox_addr_version: number | null;\n\tpox_addr_hashbytes: string | null;\n\tpox_addr_btc: string | null;\n\tstart_cycle: number | null;\n\tend_cycle: number | null;\n\tsigner_key: string | null;\n\tsigner_signature: string | null;\n\tauth_id: string | null;\n\tmax_amount: string | null;\n\treward_cycle: number | null;\n\taggregated_amount_ustx: string | null;\n\taggregated_signer_index: number | null;\n\tauth_period: number | null;\n\tauth_topic: string | null;\n\tauth_allowed: boolean | null;\n\tresult_ok: boolean;\n\tresult_raw: string;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type Pox5EventTopic =\n\t| \"set-bond-admin\"\n\t| \"set-pause-admin\"\n\t| \"pause-rewards\"\n\t| \"setup-bond\"\n\t| \"add-to-allowlist\"\n\t| \"register-for-bond\"\n\t| \"update-bond-registration\"\n\t| \"register-signer\"\n\t| \"stake\"\n\t| \"stake-update\"\n\t| \"announce-l1-early-exit\"\n\t| \"unstake-sbtc\"\n\t| \"unstake\"\n\t| \"calculate-rewards\"\n\t| \"bond-distribution\"\n\t| \"claim-rewards\"\n\t| \"claim-staker-rewards-for-signer\"\n\t| \"grant-signer-key\"\n\t| \"revoke-signer-grant\";\n\n// PoX-5 print events (SIP-045). Promoted columns cover hot query paths; the\n// full decoded tuple always lands in `data` (nested shapes: btc-lockup,\n// bond-rewards lists, bond-periods).\nexport interface Pox5EventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: Pox5EventTopic;\n\tstaker: string | null;\n\tsigner: string | null;\n\tsigner_manager: string | null;\n\tbond_index: number | null;\n\tamount_ustx: string | null;\n\tamount_sats: string | null;\n\treward_cycle: number | null;\n\tfirst_reward_cycle: number | null;\n\tunlock_cycle: number | null;\n\tunlock_burn_height: number | null;\n\tis_l1_lock: boolean | null;\n\tsigner_key: string | null;\n\tdata: unknown;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n// Materialized per-cycle PoX-5 rollup (`rollupPox5Cycles`), maintained after\n// every committed pox5 decoder batch and after a pox5 reorg. Fully\n// rebuildable from `pox5_events` via `rebuild-pox5-cycles.ts --apply`.\nexport interface Pox5CyclesTable {\n\treward_cycle: number;\n\tstart_burn_height: number;\n\tprepare_start_burn_height: number;\n\tend_burn_height: number;\n\ttotal_stacked_ustx: string;\n\treward_eligible_ustx: string;\n\tstakers: number;\n\tsigners_in_set: number;\n\t/** bond index (as string) -> sats staked for this cycle. */\n\tbond_sats: unknown;\n\tbond_total_sats: string;\n\tsbtc_custodied_sats: string;\n\trewards_allocated_stx: string;\n\trewards_allocated_bond: string;\n\treserve_deposit: string;\n\trewards_per_token_stx: string | null;\n\t/** bond index (as string) -> cumulative rewards-per-sat for this cycle. */\n\trewards_per_token_bond: unknown;\n\tdistributions: number;\n\trewards_claimed: string;\n\tcomputed_through_height: number;\n\tupdated_at: Generated<Date>;\n}\n\n// Per-signer half of the pox-5 cycle rollup.\nexport interface Pox5CycleSignersTable {\n\treward_cycle: number;\n\tsigner: string;\n\tdelegated_ustx: string;\n\tstx_only_ustx: string;\n\treward_shares_ustx: string;\n\tin_set: boolean;\n\trewards_claimed: string;\n}\n\n// Actual BTC PoX payout — one row per reward slot (≤2 per burn block), from the\n// /new_burn_block reward_recipients array. `amount_sats`/`burn_amount` are sats.\nexport interface BurnBlockRewardsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\treward_index: number;\n\trecipient_btc: string;\n\t// sats; TEXT to match the dataset amount convention (BIGINT returns as string).\n\tamount_sats: string;\n\tburn_amount: Generated<string>;\n\tcreated_at: Generated<Date>;\n}\n\n// Reward-set membership per burn block, from /new_burn_block reward_slot_holders.\nexport interface BurnBlockRewardSlotsTable {\n\tcursor: string;\n\tburn_block_height: number;\n\tburn_block_hash: string;\n\tslot_index: number;\n\tholder_btc: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcEventTopic =\n\t| \"completed-deposit\"\n\t| \"withdrawal-create\"\n\t| \"withdrawal-accept\"\n\t| \"withdrawal-reject\"\n\t| \"key-rotation\"\n\t| \"update-protocol-contract\";\n\nexport interface SbtcEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: SbtcEventTopic;\n\trequest_id: number | null;\n\tamount: string | null;\n\tsender: string | null;\n\t/** Stacks principal a `completed-deposit` minted sBTC to. */\n\trecipient: 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\tblock_height_at_request: number | 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\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type SbtcTokenEventType = \"transfer\" | \"mint\" | \"burn\";\n\nexport interface SbtcTokenEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tevent_type: SbtcTokenEventType;\n\tsender: string | null;\n\trecipient: string | null;\n\tamount: string;\n\tmemo: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * BTC L1 settlement status for sBTC withdrawal sweeps. Filled by the indexer's\n * settlement-confirmer worker, which polls our own bitcoind for confirmations of\n * each `withdrawal-accept`'s `sweep_txid` and surfaces real settlement on the\n * withdrawal lifecycle (the API's `settlement.{btc_confirmations,\n * settlement_confirmed}` placeholder). Keyed on `sweep_txid` (not `request_id`):\n * a request can produce more than one sweep over its life (RBF/rebroadcast), so\n * each broadcast keeps its own confirmation history.\n */\nexport interface SbtcSettlementsTable {\n\tsweep_txid: string;\n\trequest_id: number;\n\tbtc_confirmations: Generated<number>;\n\tsettlement_confirmed: Generated<boolean>;\n\t/** Confirming Bitcoin block — null while the sweep is unconfirmed. */\n\tblock_hash: string | null;\n\tblock_height: number | null;\n\tfirst_seen_at: Generated<Date>;\n\tlast_checked_at: Generated<Date>;\n\t/** Set once, when `settlement_confirmed` first flips true. */\n\tconfirmed_at: Date | null;\n\t/** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep\n\t * becomes confirmed. The webhook scan's watermark. BIGINT: a string at\n\t * runtime. */\n\tseq: Generated<number | string>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type BnsNameEventTopic =\n\t| \"new-name\"\n\t| \"transfer-name\"\n\t| \"renew-name\"\n\t| \"burn-name\"\n\t| \"new-airdrop\";\n\nexport interface BnsNameEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\ttopic: BnsNameEventTopic;\n\tnamespace: string;\n\tname: string;\n\tfqn: string;\n\towner: string | null;\n\tbns_id: string;\n\tregistered_at: number | null;\n\timported_at: number | null;\n\trenewal_height: number | null;\n\tstx_burn: string | null;\n\tpreordered_by: string | null;\n\thashed_salted_fqn_preorder: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsNamespaceEventStatus =\n\t| \"launch\"\n\t| \"transfer-manager\"\n\t| \"freeze-manager\"\n\t| \"update-price-manager\"\n\t| \"freeze-price-manager\"\n\t| \"turn-off-manager-transfers\";\n\nexport interface BnsNamespaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\tstatus: BnsNamespaceEventStatus;\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: boolean | null;\n\tmanager_transfers_disabled: boolean | null;\n\tprice_function: string | null;\n\tprice_frozen: boolean | null;\n\tlifetime: number | null;\n\trevealed_at: number | null;\n\tlaunched_at: number | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport type BnsMarketplaceAction =\n\t| \"list-in-ustx\"\n\t| \"unlist-in-ustx\"\n\t| \"buy-in-ustx\";\n\nexport interface BnsMarketplaceEventsTable {\n\tcursor: string;\n\tblock_height: number;\n\tblock_time: Date;\n\ttx_id: string;\n\ttx_index: number;\n\tevent_index: number;\n\taction: BnsMarketplaceAction;\n\tbns_id: string;\n\tprice_ustx: string | null;\n\tcommission: string | null;\n\tcanonical: Generated<boolean>;\n\tsource_cursor: string;\n\tcreated_at: Generated<Date>;\n}\n\nexport interface BnsNamesTable {\n\tfqn: string;\n\tnamespace: string;\n\tname: string;\n\towner: string;\n\tbns_id: string;\n\tregistered_at: number | null;\n\trenewal_height: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface BnsNamespacesTable {\n\tnamespace: string;\n\tmanager: string | null;\n\tmanager_frozen: Generated<boolean>;\n\tprice_frozen: Generated<boolean>;\n\tlifetime: number | null;\n\tlaunched_at: number | null;\n\tlast_event_cursor: string;\n\tlast_event_at: Date;\n\tname_count: Generated<number>;\n\tupdated_at: Generated<Date>;\n}\n\n// ── Database interface ────────────────────────────────────────────────\n\n/**\n * Memoized `ctx.client.readOnly()` results. Keyed on `index_block_hash` so a\n * reorg-replaced block never inherits the orphaned fork's answer; a NULL\n * `index_block_hash` marks a caller-declared contract-constant value, cached\n * once per contract+args instead of once per block.\n */\nexport interface ChainReadCacheTable {\n\tid: Generated<number>;\n\tcontract_id: string;\n\tfunction_name: string;\n\targs_hash: string;\n\tindex_block_hash: string | null;\n\tblock_height: ColumnType<\n\t\tnumber | null,\n\t\tnumber | null | undefined,\n\t\tnumber | null\n\t>;\n\tresult_hex: string;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A block that arrived for a height we already hold, staged until a later\n * block's `parent_hash` says which of the two the chain kept. See migration\n * 0112 — adopting on first sight picked the losing fork twice.\n */\nexport interface PendingForkBlocksTable {\n\theight: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\t/** The canonical hash we held at this height when the contender arrived. */\n\tincumbent_hash: string;\n\t/** The raw observer payload, replayed verbatim if this fork wins. */\n\tpayload: ColumnType<unknown, unknown, unknown>;\n\treceived_at: Generated<Date>;\n}\n\n/** Mirrored by the CHECK on `observer_journal.status`. */\nexport const OBSERVER_JOURNAL_STATUSES = [\n\t\"received\",\n\t\"processed\",\n\t\"failed\",\n\t\"retried\",\n\t\"poisoned\",\n\t\"skipped\",\n] as const;\nexport type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];\n\n/**\n * Exact observer callback receipt. `raw_body` is immutable evidence; the\n * processing columns are updated only after the current derived-state write\n * succeeds or fails.\n */\nexport interface ObserverJournalTable {\n\tsequence: Generated<string>;\n\tnetwork: string;\n\tpath: string;\n\tsource: string | null;\n\treceived_at: Generated<Date>;\n\traw_body: ColumnType<Buffer, Buffer, Buffer>;\n\traw_body_sha256: string;\n\tstatus: ColumnType<\n\t\tObserverJournalStatus,\n\t\tObserverJournalStatus | undefined,\n\t\tObserverJournalStatus\n\t>;\n\tsemantic_sha256: string | null;\n\tblock_height: number | null;\n\tblock_hash: string | null;\n\tburn_block_height: number | null;\n\tburn_block_hash: string | null;\n\tresult: unknown | null;\n\terror: string | null;\n\tprocessed_at: Date | null;\n}\n\n/** Declared coverage stage. Identity is the `id` string (`raw`, `decode:stx`, …). */\nexport interface StageRegistryTable {\n\tid: string;\n\tkind: StageKind;\n\tdepends_on: string | null;\n\tnative_clock: NativeClock;\n\tproducer_version: string;\n\trepair_mode: RepairMode;\n\tenabled: Generated<boolean>;\n\tcreated_at: Generated<Date>;\n}\n\n/** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */\nexport interface StageRunsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tcode_hash: string;\n\tconfig_hash: string;\n\thandler_hash: string | null;\n\ttarget_height: number | null;\n\ttarget_cursor: string | null;\n\tstatus: RunStatus;\n\tcomplete_through: number | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\n\n/** Per-block acknowledgement. Unique on (stage, height, hash). */\nexport interface StageBlockReceiptsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tblock_height: number;\n\tblock_hash: string;\n\tinput_count: number;\n\tinput_digest: string;\n\teffect_digest: string;\n\tfinalized: Generated<boolean>;\n\tcompacted_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** Compacted finalized range. Only sealed after receipts in the range finalize. */\nexport interface CoverageSegmentsTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\tfrom_height: number;\n\tto_height: number;\n\tchain_digest: string;\n\tinput_digest: string;\n\toutput_digest: string;\n\tsealed_at: Generated<Date>;\n}\n\n/** Exact unit or range that failed, plus retry/retention state. */\nexport interface StageFailuresTable {\n\tid: Generated<string>;\n\tstage_id: string;\n\trun_id: string | null;\n\tunit_kind: FailureUnit;\n\tfrom_height: number | null;\n\tto_height: number | null;\n\tclass: FailureClass;\n\tretry_state: RetryState;\n\tretry_count: Generated<number>;\n\tlast_error: string | null;\n\tcreated_at: Generated<Date>;\n\tresolved_at: Date | null;\n\tretain_until: Generated<Date>;\n}\n\n/**\n * The instance's declared scope — one row per network. `start_height` is what\n * makes missing history below it deliberate rather than a gap.\n */\nexport interface SyncScopesTable {\n\tnetwork: string;\n\tstart_height: number;\n\ttarget_height: number | null;\n\tbootstrap_source: BootstrapSource;\n\tbootstrap_manifest_digest: string | null;\n\tgenesis_hash: string | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport interface Database {\n\tblocks: BlocksTable;\n\ttransactions: TransactionsTable;\n\tevents: EventsTable;\n\tvm_events: VmEventsTable;\n\tstate_writes: StateWritesTable;\n\ttransactions_archive: TransactionsArchiveTable;\n\tevents_archive: EventsArchiveTable;\n\tvm_events_archive: VmEventsArchiveTable;\n\tstate_writes_archive: StateWritesArchiveTable;\n\tdead_letter_events: DeadLetterEventsTable;\n\tmempool_transactions: MempoolTransactionsTable;\n\tindex_progress: IndexProgressTable;\n\tcontracts: ContractsTable;\n\tsubgraphs: SubgraphsTable;\n\tapi_keys: ApiKeysTable;\n\tinstances: InstancesTable;\n\taccounts: AccountsTable;\n\tsessions: SessionsTable;\n\tmagic_links: MagicLinksTable;\n\tsubgraph_health_snapshots: SubgraphHealthSnapshotsTable;\n\tsubgraph_processing_stats: SubgraphProcessingStatsTable;\n\tsubgraph_gaps: SubgraphGapsTable;\n\tsubgraph_violations: SubgraphViolationsTable;\n\tsubgraph_error_groups: SubgraphErrorGroupsTable;\n\tsubgraph_operations: SubgraphOperationsTable;\n\tprocessed_stripe_events: ProcessedStripeEventsTable;\n\taccount_spend_caps: AccountSpendCapsTable;\n\taccount_credits: AccountCreditsTable;\n\twebhooks: WebhooksTable;\n\twebhook_outbox: WebhookOutboxTable;\n\twebhook_deliveries: WebhookDeliveriesTable;\n\twebhook_delivery_hours: WebhookDeliveryHoursTable;\n\twebhook_replays: WebhookReplaysTable;\n\ttrigger_evaluator_state: TriggerEvaluatorStateTable;\n\tdecoded_events: DecodedEventsTable;\n\tdecoder_checkpoints: DecoderCheckpointsTable;\n\tchain_reorgs: ChainReorgsTable;\n\tpox4_calls: Pox4CallsTable;\n\tpox5_events: Pox5EventsTable;\n\tpox5_cycles: Pox5CyclesTable;\n\tpox5_cycle_signers: Pox5CycleSignersTable;\n\tburn_block_rewards: BurnBlockRewardsTable;\n\tburn_block_reward_slots: BurnBlockRewardSlotsTable;\n\tsbtc_events: SbtcEventsTable;\n\tsbtc_token_events: SbtcTokenEventsTable;\n\tsbtc_settlements: SbtcSettlementsTable;\n\tbns_name_events: BnsNameEventsTable;\n\tbns_namespace_events: BnsNamespaceEventsTable;\n\tbns_marketplace_events: BnsMarketplaceEventsTable;\n\tbns_names: BnsNamesTable;\n\tbns_namespaces: BnsNamespacesTable;\n\tservice_heartbeats: ServiceHeartbeatsTable;\n\tchain_read_cache: ChainReadCacheTable;\n\tpending_fork_blocks: PendingForkBlocksTable;\n\tobserver_journal: ObserverJournalTable;\n\tsync_scopes: SyncScopesTable;\n\tstage_registry: StageRegistryTable;\n\tstage_runs: StageRunsTable;\n\tstage_block_receipts: StageBlockReceiptsTable;\n\tcoverage_segments: CoverageSegmentsTable;\n\tstage_failures: StageFailuresTable;\n\tarchive_fetches: ArchiveFetchesTable;\n\tusage_ledger: UsageLedgerTable;\n\taccount_balance_alerts: AccountBalanceAlertsTable;\n\thosted_stack_state: HostedStackStateTable;\n\twebhook_incident_alerts: WebhookIncidentAlertsTable;\n\tcli_device_logins: CliDeviceLoginsTable;\n\toauth_clients: OauthClientsTable;\n\toauth_requests: OauthRequestsTable;\n\toauth_codes: OauthCodesTable;\n\toauth_grants: OauthGrantsTable;\n\toauth_tokens: OauthTokensTable;\n\toauth_refresh_retired: OauthRefreshRetiredTable;\n\tsentinel_accounts: SentinelAccountsTable;\n\twaitlists: WaitlistsTable;\n\twaitlist_signups: WaitlistSignupsTable;\n\tcontact_requests: ContactRequestsTable;\n\tupdate_subscribers: UpdateSubscribersTable;\n\tupdate_sends: UpdateSendsTable;\n\tapi_failed_requests: ApiFailedRequestsTable;\n\tapi_request_log: ApiRequestLogTable;\n\tinsights: InsightsTable;\n\tinsight_mutes: InsightMutesTable;\n\tfeedback_tickets: FeedbackTicketsTable;\n\tpush_subscriptions: PushSubscriptionsTable;\n\tpush_prefs: PushPrefsTable;\n\tpush_sent: PushSentTable;\n}\n\nexport interface ServiceHeartbeatsTable {\n\tname: string;\n\tupdated_at: Generated<Date>;\n}\n\n// --- Account spend caps (soft cap + threshold alerts) ---\n//\n// One row per account. Null caps = \"no cap\" for that dimension.\n// `monthly_cap_cents` caps this calendar month's pay-as-you-go credit spend.\n// The hard stop is enforced in real time on the read path (read-credits.ts);\n// `frozen_at` is a display/alert mirror set by the daily cron when the cap is\n// hit, and cleared on month rollover, on invoice.paid, or when the cap is raised.\n\nexport interface AccountSpendCapsTable {\n\taccount_id: string;\n\tmonthly_cap_cents: number | null;\n\tcompute_cap_cents: number | null;\n\tstorage_cap_cents: number | null;\n\talert_threshold_pct: Generated<number>;\n\talert_sent_at: Date | null;\n\tfrozen_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountSpendCap = Selectable<AccountSpendCapsTable>;\nexport type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;\nexport type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;\n\n/** Prepaid dev credits — card-funded balance per account. */\nexport interface AccountCreditsTable {\n\taccount_id: string;\n\tbalance_usd_micros: Generated<string | number | bigint>;\n\t/** Month bucket (\"YYYY-MM\") the spend counter applies to. */\n\tspent_month: string | null;\n\tspent_month_usd_micros: Generated<string | number | bigint>;\n\t/** Null = auto-refill off. */\n\trefill_below_usd_micros: string | number | bigint | null;\n\trefill_pack_usd: number | null;\n\trefill_last_at: Date | null;\n\tupdated_at: Generated<Date>;\n}\n\nexport type AccountCredits = Selectable<AccountCreditsTable>;\nexport type InsertAccountCredits = Insertable<AccountCreditsTable>;\nexport type UpdateAccountCredits = Updateable<AccountCreditsTable>;\n\n/**\n * Archive fetch charge log. Append-only: one row per\n * priced attempt to fetch a partition object. `usd_micros` is 0 for\n * free rows (24h re-issue, monthly repair allowance).\n */\nexport interface ArchiveFetchesTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tpath: string;\n\tdataset: string;\n\tusd_micros: string | number | bigint;\n\tvia_allowance: Generated<boolean>;\n\tcharged_at: Generated<Date>;\n}\n\nexport type ArchiveFetch = Selectable<ArchiveFetchesTable>;\nexport type InsertArchiveFetch = Insertable<ArchiveFetchesTable>;\nexport type UpdateArchiveFetch = Updateable<ArchiveFetchesTable>;\n\n/**\n * One metered ledger for every billable unit (archive partitions, hosted\n * Index/Streams rows, and future hosted-stack meters). Append-only, written\n * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission\n * no-ops instead of double-charging. `debited` is false when the balance\n * (or a spend cap) refused the charge — the row still exists so the gap is\n * visible, never silently dropped. `usd_micros` is negative for a Stripe\n * top-up (`unit: \"topup\"`).\n */\nexport interface UsageLedgerTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tunit: string;\n\tquantity: string | number | bigint;\n\t/** Raw sampled quantity before any floor (e.g. `memory.gb_hour`'s actual\n\t * RAM, before the 0.5 GB minimum). NULL for every unit that has no\n\t * floor to observe past. */\n\tobserved_quantity: string | number | null;\n\tusd_micros: string | number | bigint;\n\t/** True when the whole price was taken; derived from `debited_usd_micros`. */\n\tdebited: Generated<boolean>;\n\t/** Amount actually taken from the balance, `0..usd_micros` (bounded the\n\t * other way for a negative top-up/grant row). Unpaid = price - this. */\n\tdebited_usd_micros: Generated<string | number | bigint>;\n\tsource: string;\n\t/** API key behind a metered read; null for non-read units and older rows. */\n\tapi_key_id: string | null;\n\tidempotency_key: string;\n\toccurred_at: Generated<Date>;\n\trecorded_at: Generated<Date>;\n}\n\nexport type UsageLedgerRow = Selectable<UsageLedgerTable>;\nexport type InsertUsageLedgerRow = Insertable<UsageLedgerTable>;\nexport type UpdateUsageLedgerRow = Updateable<UsageLedgerTable>;\n\n/** Preferences + debounce state for the balance-runway email alerts. One\n * row per account; a missing row means both alerts are on (defaults). */\nexport interface AccountBalanceAlertsTable {\n\taccount_id: string;\n\tnotify_7d: Generated<boolean>;\n\tnotify_2d: Generated<boolean>;\n\tsent_7d_at: Date | null;\n\tsent_2d_at: Date | null;\n\tsent_stopped_at: Date | null;\n}\n\n/** The workload host's report of one account's hosted stack. Written only by\n * `POST /internal/stack-state`; `reported_at` is the host's observation time. */\nexport interface HostedStackStateTable {\n\taccount_id: string;\n\tstate: \"provisioning\" | \"running\" | \"stopped\" | \"destroyed\";\n\tstop_reason: \"credits\" | \"cap\" | \"idle\" | null;\n\treported_at: Date;\n}\n\n/** Debounce state for the webhook-down email: one row per incident, open\n * while `resolved_at` is null. No preference columns by design. */\nexport interface WebhookIncidentAlertsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\twebhook_id: string;\n\twebhook_name: string;\n\tfailing_since: Date;\n\topened_at: Generated<Date>;\n\temailed_at: Date | null;\n\temail_attempts: Generated<number>;\n\tresolved_at: Date | null;\n}\n\nexport type WebhookIncidentAlert = Selectable<WebhookIncidentAlertsTable>;\n\n/** One browser/device push subscription; the endpoint is unique. */\nexport interface PushSubscriptionsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tendpoint: string;\n\tp256dh: string;\n\tauth: string;\n\tuser_agent: string | null;\n\tcreated_at: Generated<Date>;\n\tlast_success_at: Date | null;\n\tfailed_count: Generated<number>;\n}\n\nexport type PushSubscription = Selectable<PushSubscriptionsTable>;\n\n/** Per-account push toggles. A missing row means the column defaults. */\nexport interface PushPrefsTable {\n\taccount_id: string;\n\twebhook_failing: Generated<boolean>;\n\tsubgraph_stopped: Generated<boolean>;\n\tsubgraph_not_serving: Generated<boolean>;\n\treplay_done: Generated<boolean>;\n\tspend_cap: Generated<boolean>;\n\tkey_repeat: Generated<boolean>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type PushPrefs = Selectable<PushPrefsTable>;\n\n/** A push already sent, keyed by what it was about; debounces repeat signals. */\nexport interface PushSentTable {\n\taccount_id: string;\n\tkey: string;\n\tkind: string;\n\tsent_at: Generated<Date>;\n}\n\nexport type CliDeviceLoginStatus =\n\t| \"pending\"\n\t| \"approved\"\n\t| \"denied\"\n\t| \"consumed\";\n\n/** The product that started a CLI sign-in; null is `sl login`. */\nexport type CliDeviceProduct = \"sentinel\";\n\n/** One browser sign-in attempt from `sl login` (or `sentinel login`). Only the\n * hash of the CLI's device code is stored; the session is opened when the CLI\n * polls after approval. */\nexport interface CliDeviceLoginsTable {\n\tid: Generated<string>;\n\tdevice_code_hash: string;\n\tuser_code: string;\n\tclient_name: string;\n\tproduct: CliDeviceProduct | null;\n\tstatus: Generated<CliDeviceLoginStatus>;\n\taccount_id: string | null;\n\tkey_name: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tapproved_at: Date | null;\n\tconsumed_at: Date | null;\n}\n\nexport type CliDeviceLogin = Selectable<CliDeviceLoginsTable>;\n\n// --- OAuth for the hosted MCP endpoint ---\n//\n// Codes and tokens are stored as SHA-256 hashes only. See migration\n// `0177_oauth_mcp` and `@secondlayer/platform/db/queries/oauth`.\n\n/** An app that registered itself (RFC 7591). Public clients only: no secret. */\nexport interface OauthClientsTable {\n\tid: string;\n\t/** The app's own claim, validated at registration; shown quoted. */\n\tname: string;\n\tredirect_uris: string[];\n\tcreated_ip: string | null;\n\tcreated_at: Generated<Date>;\n\t/** Set when it first gets tokens; never-used clients are purged. */\n\tlast_used_at: Date | null;\n}\n\nexport type OauthRequestStatus = \"pending\" | \"approved\" | \"denied\";\n\n/** One authorize request waiting for (or answered on) the consent page. */\nexport interface OauthRequestsTable {\n\tid: string;\n\tclient_id: string;\n\tredirect_uri: string;\n\tstate: string | null;\n\tcode_challenge: string;\n\tresource: string;\n\tstatus: Generated<OauthRequestStatus>;\n\taccount_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tanswered_at: Date | null;\n}\n\n/** A one-time authorization code, bound to its client, redirect, PKCE\n * challenge, resource and account. */\nexport interface OauthCodesTable {\n\tcode_hash: string;\n\tclient_id: string;\n\taccount_id: string;\n\tredirect_uri: string;\n\tcode_challenge: string;\n\tresource: string;\n\t/** The grant its one use made, so a replay can revoke it. */\n\tgrant_id: string | null;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n\tused_at: Date | null;\n}\n\n/** What a person allowed one app to do: use the hosted MCP as them. */\nexport interface OauthGrantsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tclient_id: string;\n\tscope: Generated<string>;\n\tresource: string;\n\tcreated_at: Generated<Date>;\n\tlast_used_at: Date | null;\n\trevoked_at: Date | null;\n}\n\nexport type OauthTokenKind = \"access\" | \"refresh\";\n\nexport interface OauthTokensTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tkind: OauthTokenKind;\n\tcreated_at: Generated<Date>;\n\texpires_at: Date;\n}\n\n/** A refresh token a rotation replaced: presented again, it revokes the grant. */\nexport interface OauthRefreshRetiredTable {\n\ttoken_hash: string;\n\tgrant_id: string;\n\tretired_at: Generated<Date>;\n}\n\nexport type OauthClient = Selectable<OauthClientsTable>;\nexport type OauthGrant = Selectable<OauthGrantsTable>;\n\n/** Accounts Sentinel's service key may touch: created by Sentinel, or the\n * owner opted in. */\nexport interface SentinelAccountsTable {\n\taccount_id: string;\n\tlinked_at: Generated<Date>;\n\tvia: \"created\" | \"consent\";\n}\n\nexport type SentinelAccount = Selectable<SentinelAccountsTable>;\n\nexport type AccountBalanceAlerts = Selectable<AccountBalanceAlertsTable>;\nexport type InsertAccountBalanceAlerts = Insertable<AccountBalanceAlertsTable>;\nexport type UpdateAccountBalanceAlerts = Updateable<AccountBalanceAlertsTable>;\n\n// ── Convenience types ─────────────────────────────────────────────────\n\nexport type Block = Selectable<BlocksTable>;\nexport type InsertBlock = Insertable<BlocksTable>;\nexport type UpdateBlock = Updateable<BlocksTable>;\n\nexport type Transaction = Selectable<TransactionsTable>;\nexport type InsertTransaction = Insertable<TransactionsTable>;\nexport type UpdateTransaction = Updateable<TransactionsTable>;\n\nexport type MempoolTransaction = Selectable<MempoolTransactionsTable>;\nexport type InsertMempoolTransaction = Insertable<MempoolTransactionsTable>;\n\nexport type Event = Selectable<EventsTable>;\nexport type InsertEvent = Insertable<EventsTable>;\nexport type UpdateEvent = Updateable<EventsTable>;\n\nexport type VmEvent = Selectable<VmEventsTable>;\nexport type InsertVmEvent = Insertable<VmEventsTable>;\nexport type UpdateVmEvent = Updateable<VmEventsTable>;\nexport type StateWrite = Selectable<StateWritesTable>;\nexport type InsertStateWrite = Insertable<StateWritesTable>;\n\nexport type IndexProgress = Selectable<IndexProgressTable>;\nexport type InsertIndexProgress = Insertable<IndexProgressTable>;\nexport type UpdateIndexProgress = Updateable<IndexProgressTable>;\n\nexport type Subgraph = Selectable<SubgraphsTable>;\nexport type InsertSubgraph = Insertable<SubgraphsTable>;\nexport type UpdateSubgraph = Updateable<SubgraphsTable>;\n\nexport type Contract = Selectable<ContractsTable>;\nexport type InsertContract = Insertable<ContractsTable>;\nexport type UpdateContract = Updateable<ContractsTable>;\n\nexport type SubgraphOperation = Selectable<SubgraphOperationsTable>;\nexport type InsertSubgraphOperation = Insertable<SubgraphOperationsTable>;\nexport type UpdateSubgraphOperation = Updateable<SubgraphOperationsTable>;\n\nexport type ApiKey = Selectable<ApiKeysTable>;\nexport type InsertApiKey = Insertable<ApiKeysTable>;\nexport type UpdateApiKey = Updateable<ApiKeysTable>;\n\nexport type Account = Selectable<AccountsTable>;\nexport type InsertAccount = Insertable<AccountsTable>;\n\nexport type MagicLink = Selectable<MagicLinksTable>;\nexport type InsertMagicLink = Insertable<MagicLinksTable>;\n\nexport type Session = Selectable<SessionsTable>;\nexport type InsertSession = Insertable<SessionsTable>;\n\nexport type SubgraphHealthSnapshot = Selectable<SubgraphHealthSnapshotsTable>;\nexport type InsertSubgraphHealthSnapshot =\n\tInsertable<SubgraphHealthSnapshotsTable>;\n\nexport type SubgraphGap = Selectable<SubgraphGapsTable>;\nexport type InsertSubgraphGap = Insertable<SubgraphGapsTable>;\n\n// ── Webhooks (chain event webhooks) ─────────────────────\n\nexport type WebhookStatus = \"active\" | \"paused\";\nexport type { WebhookPauseReason };\n\n/** Webhooks react to raw chain events matched directly off the Index/Streams\n * clock. `chain` is the only kind since migration 0159 removed subgraph-row\n * webhooks; the column stays as the discriminator. */\nexport type WebhookKind = \"chain\";\nexport type WebhookFormat =\n\t| \"standard-webhooks\"\n\t| \"inngest\"\n\t| \"trigger\"\n\t| \"cloudflare\"\n\t| \"cloudevents\"\n\t| \"raw\";\n\nexport interface WebhooksTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tproject_id: string | null;\n\tname: string;\n\tstatus: ColumnType<WebhookStatus, WebhookStatus | undefined, WebhookStatus>;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\t/** Chain-trigger filter array (the `SubgraphFilter` shape, JSON). Typed\n\t * loosely here to avoid a shared→subgraphs import cycle; the Zod schema in\n\t * schemas/webhooks.ts owns the shape. */\n\ttriggers: unknown;\n\tformat: ColumnType<WebhookFormat, WebhookFormat | undefined, WebhookFormat>;\n\turl: string;\n\tsigning_secret_enc: Buffer;\n\tauth_config: Generated<unknown>;\n\tmax_retries: Generated<number>;\n\ttimeout_ms: Generated<number>;\n\tconcurrency: Generated<number>;\n\tcircuit_failures: Generated<number>;\n\tcircuit_opened_at: Date | null;\n\t/** Why a paused webhook is paused. Set exactly while `status` is `paused`. */\n\tpause_reason: WebhookPauseReason | null;\n\tlast_delivery_at: Date | null;\n\tlast_success_at: Date | null;\n\tlast_error: string | null;\n\t/** Receiver TLS leaf certificate expiry, from the emitter's periodic probe. */\n\treceiver_cert_expires_at: Date | null;\n\treceiver_cert_checked_at: Date | null;\n\tcreated_at: Generated<Date>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type Webhook = Selectable<WebhooksTable>;\nexport type InsertWebhook = Insertable<WebhooksTable>;\nexport type UpdateWebhook = Updateable<WebhooksTable>;\n\nexport type OutboxStatus = \"pending\" | \"delivered\" | \"dead\";\n/** Why a row is dead: retries ran out, or a reorg removed its event. An\n * orphaned row stays dead; requeueing it would resend an event the chain no\n * longer contains. */\nexport type DeadReason = \"exhausted\" | \"orphaned\";\n\nexport interface WebhookOutboxTable {\n\tid: Generated<string>;\n\twebhook_id: string;\n\tkind: ColumnType<WebhookKind, WebhookKind | undefined, WebhookKind>;\n\tblock_height: number | bigint;\n\ttx_id: string | null;\n\trow_pk: unknown;\n\tevent_type: string;\n\tpayload: unknown;\n\tdedup_key: string;\n\tattempt: Generated<number>;\n\tnext_attempt_at: Generated<Date>;\n\tstatus: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;\n\tis_replay: Generated<boolean>;\n\t/** The replay that created this row; null for live rows. */\n\treplay_id: string | null;\n\t/** The chain block_time of the matched event/tx. Null for rows written\n\t * before this column existed, and for the settlement scan path (not yet\n\t * wired). Lets `delivered_at - block_time` measure end-to-end webhook\n\t * latency without a join to SOURCE-plane `blocks`. */\n\tblock_time: Date | null;\n\tdelivered_at: Date | null;\n\tfailed_at: Date | null;\n\tlocked_by: string | null;\n\tlocked_until: Date | null;\n\t/** Set when a reorg marks an in-flight row `dead` instead of retrying it\n\t * into an orphaned fork. Null otherwise — delivery failures track their\n\t * history on `webhooks.last_error`, not per-row. */\n\tlast_error: string | null;\n\t/** Set exactly while `status` is `dead`. */\n\tdead_reason: DeadReason | null;\n\t/** Hash of the block a chain apply row was emitted for. Null on rows\n\t * written before the column existed (the payload carries it too). */\n\tblock_hash: string | null;\n\t/** Set when a reorg rollback recalled this delivered apply row, so a\n\t * later rollback for the same reorg skips it. */\n\trolled_back_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type WebhookReplayStatus = \"scanning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface WebhookReplaysTable {\n\tid: string;\n\twebhook_id: string;\n\tfrom_block: number | bigint;\n\tto_block: number | bigint;\n\tstatus: WebhookReplayStatus;\n\tscanned_count: Generated<number>;\n\tenqueued_count: Generated<number>;\n\ttotal: number | null;\n\tdelivered: number | null;\n\tgave_up: number | null;\n\terror: string | null;\n\tstarted_at: Generated<Date>;\n\tfinished_at: Date | null;\n}\nexport type WebhookReplay = Selectable<WebhookReplaysTable>;\n\n/** `replay_id` is optional on the row type so hand-built rows (the test\n * delivery, fixtures) need not carry it; reads still return it. */\nexport type WebhookOutbox = Omit<\n\tSelectable<WebhookOutboxTable>,\n\t\"replay_id\"\n> & {\n\treplay_id?: string | null;\n};\nexport type InsertWebhookOutbox = Insertable<WebhookOutboxTable>;\nexport type UpdateWebhookOutbox = Updateable<WebhookOutboxTable>;\n\nexport interface WebhookDeliveriesTable {\n\tid: Generated<string>;\n\t/** Nullable after migration 0077 — outbox row may be cleaned up while\n\t * delivery telemetry is retained. */\n\toutbox_id: string | null;\n\twebhook_id: string;\n\tattempt: number;\n\tstatus_code: number | null;\n\tresponse_headers: unknown | null;\n\tresponse_body: string | null;\n\terror_message: string | null;\n\tduration_ms: number | null;\n\tdispatched_at: Generated<Date>;\n}\n\n/** Attempts per UTC hour, counted by a trigger on `webhook_deliveries`. */\nexport interface WebhookDeliveryHoursTable {\n\twebhook_id: string;\n\thour: Date;\n\t/** 2xx attempts. */\n\tdelivered: Generated<number>;\n\t/** Every other attempt. */\n\tfailed: Generated<number>;\n}\n\nexport type WebhookDelivery = Selectable<WebhookDeliveriesTable>;\nexport type InsertWebhookDelivery = Insertable<WebhookDeliveriesTable>;\n\n/** Single-row (id always TRUE) high-water mark for the chain-trigger evaluator.\n * One loop serves all chain webhooks, so the cursor is global. */\nexport interface TriggerEvaluatorStateTable {\n\tid: Generated<boolean>;\n\tlast_processed_block: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Watermark for the async sBTC settlement-confirmed webhook scan; null until\n\t * the evaluator fast-forwards it on first run. */\n\tlast_settlement_scan_at: ColumnType<\n\t\tDate | null,\n\t\tDate | null | undefined,\n\t\tDate | null\n\t>;\n\t/** `sbtc_settlements.seq` watermark. Null until the first settlement row is\n\t * scanned; `last_settlement_scan_at` is the forward-only floor until then. */\n\tlast_settlement_scan_seq: ColumnType<\n\t\tbigint | null,\n\t\tbigint | number | null | undefined,\n\t\tbigint | number | null\n\t>;\n\t/** Counts reorg rewinds. The evaluator checks it under the row lock in the\n\t * transaction that emits a batch and advances the cursor, so a reorg that\n\t * lands mid-tick rolls the batch back. */\n\treorg_generation: ColumnType<\n\t\tbigint,\n\t\tbigint | number | undefined,\n\t\tbigint | number\n\t>;\n\t/** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)\n\t * chain-trigger evaluator (plan 060) — a separate clock from\n\t * `last_processed_block` (Stacks). Null until the evaluator fast-forwards\n\t * it to the Bitcoin Streams tip on first run. */\n\tbitcoin_last_cursor: ColumnType<\n\t\tstring | null,\n\t\tstring | null | undefined,\n\t\tstring | null\n\t>;\n\tupdated_at: Generated<Date>;\n}\n\nexport type TriggerEvaluatorState = Selectable<TriggerEvaluatorStateTable>;\n\n/** A public waitlist page: what it is for and whether it takes signups. */\nexport interface WaitlistsTable {\n\tslug: string;\n\ttitle: string;\n\tdescription: string;\n\turl: string;\n\topened_at: Generated<Date>;\n\t/** Null while the list is open. */\n\tclosed_at: Date | null;\n}\n\n/**\n * One signup per (list, contact, token). `answers` holds the list's own\n * questions, validated per list by the API before insert.\n */\nexport interface WaitlistSignupsTable {\n\tid: Generated<string>;\n\tlist: string;\n\tcontact: string;\n\tanswers: Record<string, unknown>;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A \"Talk to us\" message. Stored before the operator is emailed;\n * `notified_at` stays null until the email goes out.\n */\nexport interface ContactRequestsTable {\n\tid: Generated<string>;\n\tname: string;\n\temail: string;\n\tcompany: string | null;\n\tvolume: \"lt10m\" | \"10m-100m\" | \"100m-1b\" | \"gt1b\" | \"unsure\" | null;\n\tmessage: string;\n\tsource_page: string | null;\n\taccount_id: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tnotified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/**\n * A member of the email updates list. `pending` until the emailed link is\n * confirmed (`confirm_sent_at` starts the 7-day window), `confirmed` while\n * subscribed, `unsubscribed` after an opt-out. `token` is the secret in\n * confirm and unsubscribe links.\n */\nexport interface UpdateSubscribersTable {\n\tid: Generated<string>;\n\temail: string;\n\tstatus: Generated<\"pending\" | \"confirmed\" | \"unsubscribed\">;\n\ttoken: string;\n\tsource_page: string | null;\n\t/** Hex sha256 of the client IP, never the address. */\n\tip_hash: string | null;\n\tconfirm_sent_at: Date | null;\n\tconfirmed_at: Date | null;\n\tunsubscribed_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\n/** One broadcast (`send_key`) delivered to one subscriber. */\nexport interface UpdateSendsTable {\n\tsend_key: string;\n\tsubscriber_id: string;\n\tsent_at: Generated<Date>;\n}\n\n/**\n * 24h hosted record of a failed API request, keyed by `request_id` and\n * scoped to the account that made it. `query` is redacted before insert.\n */\nexport interface ApiFailedRequestsTable {\n\trequest_id: string;\n\taccount_id: string;\n\tmethod: string;\n\tpath: string;\n\tstatus: number;\n\tcode: string;\n\tmessage: Generated<string>;\n\tquery: Record<string, unknown>;\n\torigin: string | null;\n\t/** Revoked account key the request presented (`KEY_REVOKED` only). */\n\tapi_key_id: string | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiFailedRequest = Selectable<ApiFailedRequestsTable>;\nexport type InsertApiFailedRequest = Insertable<ApiFailedRequestsTable>;\n\n/**\n * 7-day hosted log of account-attributed Index/Streams reads. Query values\n * are stored only as hashes; never bodies, headers or tokens.\n */\nexport interface ApiRequestLogTable {\n\tid: Generated<string>;\n\trequest_id: string | null;\n\taccount_id: string;\n\tapi_key_id: string | null;\n\tmethod: string;\n\tpath: string;\n\tpath_template: string;\n\tparams_hash: string | null;\n\tcursor_hash: string | null;\n\tpage_size: number | null;\n\trows: number | null;\n\tstatus: number;\n\tduration_ms: number;\n\tcreated_at: Generated<Date>;\n}\n\nexport type ApiRequestLogRow = Selectable<ApiRequestLogTable>;\nexport type InsertApiRequestLogRow = Insertable<ApiRequestLogTable>;\n\n/**\n * Hosted problem report. `attempted` is the server's own copy of the failed\n * request (never caller-supplied); `status` starts `new` until classified.\n */\nexport interface FeedbackTicketsTable {\n\tid: Generated<string>;\n\taccount_id: string;\n\tidempotency_key: string | null;\n\trequest_id: string | null;\n\tintent: string;\n\t/** Any JSON value the caller sent: a sentence or a shape. */\n\texpected: unknown;\n\tkind_hint: string | null;\n\tevidence: Record<string, unknown> | null;\n\tattempted: Record<string, unknown> | null;\n\torigin: string;\n\tstatus: Generated<\"new\" | \"classified\">;\n\troute: string | null;\n\tclassification: Record<string, unknown> | null;\n\tclassified_at: Date | null;\n\tcreated_at: Generated<Date>;\n}\n\nexport type FeedbackTicket = Selectable<FeedbackTicketsTable>;\nexport type InsertFeedbackTicket = Insertable<FeedbackTicketsTable>;\n\nexport type Waitlist = Selectable<WaitlistsTable>;\nexport type WaitlistSignup = Selectable<WaitlistSignupsTable>;\nexport type InsertWaitlistSignup = Insertable<WaitlistSignupsTable>;\n\nexport type ContactRequest = Selectable<ContactRequestsTable>;\nexport type InsertContactRequest = Insertable<ContactRequestsTable>;\n\nexport type UpdateSubscriber = Selectable<UpdateSubscribersTable>;\nexport type InsertUpdateSubscriber = Insertable<UpdateSubscribersTable>;\n"
6
6
  ],
7
- "mappings": ";AA+PO,IAAM,eAAe;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AA8rBO,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;",
7
+ "mappings": ";AA+PO,IAAM,eAAe;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAgsBO,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;",
8
8
  "debugId": "6E76A79D8A25C17E64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -216,6 +216,7 @@ type IndexSbtcEventRow = {
216
216
  request_id: number | null
217
217
  amount: string | null
218
218
  sender: string | null
219
+ recipient: string | null
219
220
  recipient_btc_version: number | null
220
221
  recipient_btc_hashbytes: string | null
221
222
  bitcoin_txid: string | null
@@ -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\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"
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: 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,EACpD,IAAI;AAAA,IAAU,OAAO;AAAA,EACrB,MAAM,WAAW,IAAI,gBAAgB,KAAK;AAAA,EAC1C,IAAI;A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