@secondlayer/shared 15.2.1 → 15.3.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 (84) hide show
  1. package/dist/src/archive/range-digest.d.ts +61 -9
  2. package/dist/src/archive/semantic-digest-builder.d.ts +61 -9
  3. package/dist/src/coverage/index.d.ts +64 -9
  4. package/dist/src/coverage/index.js.map +2 -2
  5. package/dist/src/db/index.d.ts +63 -10
  6. package/dist/src/db/index.js +19 -1
  7. package/dist/src/db/index.js.map +5 -4
  8. package/dist/src/db/queries/chain-reorgs.d.ts +61 -9
  9. package/dist/src/db/queries/chain-reorgs.js +17 -1
  10. package/dist/src/db/queries/chain-reorgs.js.map +5 -4
  11. package/dist/src/db/queries/contracts.d.ts +108 -28
  12. package/dist/src/db/queries/contracts.js +115 -15
  13. package/dist/src/db/queries/contracts.js.map +7 -5
  14. package/dist/src/db/queries/instance.d.ts +69 -10
  15. package/dist/src/db/queries/instance.js +147 -3
  16. package/dist/src/db/queries/instance.js.map +6 -4
  17. package/dist/src/db/queries/integrity.d.ts +77 -10
  18. package/dist/src/db/queries/integrity.js +236 -2
  19. package/dist/src/db/queries/integrity.js.map +7 -4
  20. package/dist/src/db/queries/subgraph-gaps.d.ts +69 -12
  21. package/dist/src/db/queries/subgraph-gaps.js +7 -3
  22. package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
  23. package/dist/src/db/queries/subgraph-operations.d.ts +61 -9
  24. package/dist/src/db/queries/subgraphs.d.ts +122 -42
  25. package/dist/src/db/queries/subgraphs.js +85 -27
  26. package/dist/src/db/queries/subgraphs.js.map +7 -6
  27. package/dist/src/db/queries/sync-scope.d.ts +61 -9
  28. package/dist/src/db/queries/webhook-replays.d.ts +73 -13
  29. package/dist/src/db/queries/webhook-replays.js +468 -19
  30. package/dist/src/db/queries/webhook-replays.js.map +9 -4
  31. package/dist/src/db/queries/webhooks.d.ts +96 -21
  32. package/dist/src/db/queries/webhooks.js +72 -17
  33. package/dist/src/db/queries/webhooks.js.map +6 -5
  34. package/dist/src/db/schema.d.ts +62 -10
  35. package/dist/src/db/schema.js +20 -1
  36. package/dist/src/db/schema.js.map +4 -3
  37. package/dist/src/db/transition.d.ts +46 -0
  38. package/dist/src/db/transition.js +38 -0
  39. package/dist/src/db/transition.js.map +10 -0
  40. package/dist/src/email/index.d.ts +16 -1
  41. package/dist/src/email/index.js +186 -130
  42. package/dist/src/email/index.js.map +5 -4
  43. package/dist/src/errors.d.ts +7 -1
  44. package/dist/src/errors.js +12 -1
  45. package/dist/src/errors.js.map +3 -3
  46. package/dist/src/index-http.d.ts +11 -3
  47. package/dist/src/index-http.js +3 -3
  48. package/dist/src/index-http.js.map +3 -3
  49. package/dist/src/index.d.ts +98 -19
  50. package/dist/src/index.js +41 -8
  51. package/dist/src/index.js.map +8 -7
  52. package/dist/src/insights/index.d.ts +62 -9
  53. package/dist/src/insights/index.js +55 -5
  54. package/dist/src/insights/index.js.map +7 -6
  55. package/dist/src/node/local-client.d.ts +61 -9
  56. package/dist/src/queue/listener.js +17 -1
  57. package/dist/src/queue/listener.js.map +5 -4
  58. package/dist/src/runtime/index.d.ts +0 -4
  59. package/dist/src/runtime/index.js +54 -4
  60. package/dist/src/runtime/index.js.map +6 -5
  61. package/dist/src/schemas/index.d.ts +36 -10
  62. package/dist/src/schemas/index.js +12 -8
  63. package/dist/src/schemas/index.js.map +4 -4
  64. package/dist/src/schemas/subgraphs.d.ts +22 -9
  65. package/dist/src/schemas/subgraphs.js +10 -6
  66. package/dist/src/schemas/subgraphs.js.map +3 -3
  67. package/dist/src/schemas/webhooks.d.ts +15 -2
  68. package/dist/src/schemas/webhooks.js +2 -2
  69. package/dist/src/schemas/webhooks.js.map +3 -3
  70. package/dist/src/subgraphs/spec.d.ts +5 -1
  71. package/dist/src/webhooks/health.d.ts +27 -0
  72. package/dist/src/webhooks/health.js +84 -0
  73. package/dist/src/webhooks/health.js.map +11 -0
  74. package/migrations/0184_status_checks.ts +92 -0
  75. package/migrations/0185_reorg_generation_settlement_seq.ts +89 -0
  76. package/migrations/0186_api_keys_one_active_tenant_per_name.ts +43 -0
  77. package/migrations/0187_accounts_email_lower_unique.ts +27 -0
  78. package/migrations/0188_webhook_reasons.ts +124 -0
  79. package/migrations/0189_subgraph_lifecycle.ts +83 -0
  80. package/migrations/0190_usage_ledger_debited_usd_micros.ts +59 -0
  81. package/migrations/0191_indexer_state_machines.ts +83 -0
  82. package/migrations/0192_hosted_stack_state.ts +37 -0
  83. package/migrations/0193_accounts_ghost_has_no_email.ts +34 -0
  84. package/package.json +9 -1
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/db/queries/instance.ts"],
3
+ "sources": ["../src/env.ts", "../src/logger.ts", "../src/db/queries/instance.ts"],
4
4
  "sourcesContent": [
5
- "import type { Kysely } from \"kysely\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? \"mainnet\");\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n\n/**\n * A stack with no local chain: it reads chain data from a hosted Index/Streams\n * API (`SUBGRAPH_INDEX_API_URL` set) and its own `index_progress` has no row\n * for this network (a hosted tenant). Derived, not configured: a self-hoster\n * running a local indexer has the row and keeps reading its own tables, even\n * with its processors pointed at its own api over HTTP.\n */\nexport async function hasNoLocalChain(\n\tdb: Kysely<Database>,\n\topts: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\thasProgressRow?: (network: string) => Promise<boolean>;\n\t} = {},\n): Promise<boolean> {\n\tconst env = opts.env ?? process.env;\n\tif (!env.SUBGRAPH_INDEX_API_URL) return false;\n\tconst network = env.NETWORK ?? \"mainnet\";\n\tconst hasRow =\n\t\topts.hasProgressRow ?? ((n: string) => hasLocalProgressRow(db, n));\n\treturn !(await hasRow(network));\n}\n\nasync function hasLocalProgressRow(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(\"network\")\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst()\n\t\t.catch(() => undefined);\n\treturn row !== undefined;\n}\n"
5
+ "import { z } from \"zod\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
+ "import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
7
+ "import type { Kysely } from \"kysely\";\nimport { logger } from \"../../logger.ts\";\nimport type { Database } from \"../types.ts\";\n\nexport const INSTANCE_NETWORKS = [\"mainnet\", \"testnet\", \"devnet\"] as const;\nexport type InstanceNetwork = (typeof INSTANCE_NETWORKS)[number];\n\nexport type InstanceRow = {\n\tid: string;\n\tnetwork: InstanceNetwork;\n\tcreated_at: Date;\n};\n\nexport class InstanceNetworkMismatchError extends Error {\n\treadonly name = \"InstanceNetworkMismatchError\";\n\tconstructor(\n\t\treadonly existing: InstanceNetwork,\n\t\treadonly requested: InstanceNetwork,\n\t) {\n\t\tsuper(`instance network is ${existing}; cannot change to ${requested}`);\n\t}\n}\n\nexport class InvalidInstanceNetworkError extends Error {\n\treadonly name = \"InvalidInstanceNetworkError\";\n\tconstructor(readonly value: string) {\n\t\tsuper(\n\t\t\t`instance network must be mainnet, testnet, or devnet (got ${value})`,\n\t\t);\n\t}\n}\n\nexport function parseInstanceNetwork(value: string): InstanceNetwork {\n\tconst network = value.trim().toLowerCase();\n\tif ((INSTANCE_NETWORKS as readonly string[]).includes(network)) {\n\t\treturn network as InstanceNetwork;\n\t}\n\tthrow new InvalidInstanceNetworkError(value);\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The network key `index_progress` is written under: `STACKS_NETWORK`, else\n * the deprecated `NETWORK` (logged once so a deployment that only sets it is\n * not silently re-keyed), else mainnet. Not validated; see\n * {@link instanceNetworkFromEnv} for the strict form.\n */\nexport function stacksNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tlogger.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\n}\n\n/** STACKS_NETWORK, then NETWORK, then mainnet. */\nexport function instanceNetworkFromEnv(\n\tenv: NodeJS.ProcessEnv = process.env,\n): InstanceNetwork {\n\treturn parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? \"mainnet\");\n}\n\nexport async function getInstance(\n\tdb: Kysely<Database>,\n): Promise<InstanceRow | null> {\n\tconst row = await db\n\t\t.selectFrom(\"instances\")\n\t\t.select([\"id\", \"network\", \"created_at\"])\n\t\t.executeTakeFirst();\n\treturn row ? toInstance(row) : null;\n}\n\n/**\n * Return the singleton instance, creating it on first call.\n * A second call with a different network is refused — the network is\n * immutable for the life of the database.\n */\nexport async function ensureInstance(\n\tdb: Kysely<Database>,\n\tinput: { network: InstanceNetwork },\n): Promise<InstanceRow> {\n\tconst existing = await getInstance(db);\n\tif (existing) {\n\t\tif (existing.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(existing.network, input.network);\n\t\t}\n\t\treturn existing;\n\t}\n\ttry {\n\t\tconst inserted = await db\n\t\t\t.insertInto(\"instances\")\n\t\t\t.values({ network: input.network })\n\t\t\t.returning([\"id\", \"network\", \"created_at\"])\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn toInstance(inserted);\n\t} catch {\n\t\t// Lost the singleton race — the other writer won.\n\t\tconst raced = await getInstance(db);\n\t\tif (!raced) throw new Error(\"failed to create instance\");\n\t\tif (raced.network !== input.network) {\n\t\t\tthrow new InstanceNetworkMismatchError(raced.network, input.network);\n\t\t}\n\t\treturn raced;\n\t}\n}\n\nfunction toInstance(row: {\n\tid: string;\n\tnetwork: string;\n\tcreated_at: Date;\n}): InstanceRow {\n\treturn {\n\t\tid: row.id,\n\t\tnetwork: parseInstanceNetwork(row.network),\n\t\tcreated_at: row.created_at,\n\t};\n}\n\n/**\n * A stack with no local chain: it reads chain data from a hosted Index/Streams\n * API (`SUBGRAPH_INDEX_API_URL` set) and its own `index_progress` has no row\n * for this network (a hosted tenant). Derived, not configured: a self-hoster\n * running a local indexer has the row and keeps reading its own tables, even\n * with its processors pointed at its own api over HTTP.\n */\nexport async function hasNoLocalChain(\n\tdb: Kysely<Database>,\n\topts: {\n\t\tenv?: NodeJS.ProcessEnv;\n\t\thasProgressRow?: (network: string) => Promise<boolean>;\n\t} = {},\n): Promise<boolean> {\n\tconst env = opts.env ?? process.env;\n\tif (!env.SUBGRAPH_INDEX_API_URL) return false;\n\tconst network = stacksNetworkFromEnv(env);\n\tconst hasRow =\n\t\topts.hasProgressRow ?? ((n: string) => hasLocalProgressRow(db, n));\n\treturn !(await hasRow(network));\n}\n\nasync function hasLocalProgressRow(\n\tdb: Kysely<Database>,\n\tnetwork: string,\n): Promise<boolean> {\n\tconst row = await db\n\t\t.selectFrom(\"index_progress\")\n\t\t.select(\"network\")\n\t\t.where(\"network\", \"=\", network)\n\t\t.executeTakeFirst()\n\t\t.catch(() => undefined);\n\treturn row !== undefined;\n}\n"
6
8
  ],
7
- "mappings": ";AAGO,IAAM,oBAAoB,CAAC,WAAW,WAAW,QAAQ;AAAA;AASzD,MAAM,qCAAqC,MAAM;AAAA,EAG7C;AAAA,EACA;AAAA,EAHD,OAAO;AAAA,EAChB,WAAW,CACD,UACA,WACR;AAAA,IACD,MAAM,uBAAuB,8BAA8B,WAAW;AAAA,IAH7D;AAAA,IACA;AAAA;AAIX;AAAA;AAEO,MAAM,oCAAoC,MAAM;AAAA,EAEjC;AAAA,EADZ,OAAO;AAAA,EAChB,WAAW,CAAU,OAAe;AAAA,IACnC,MACC,6DAA6D,QAC9D;AAAA,IAHoB;AAAA;AAKtB;AAEO,SAAS,oBAAoB,CAAC,OAAgC;AAAA,EACpE,MAAM,UAAU,MAAM,KAAK,EAAE,YAAY;AAAA,EACzC,IAAK,kBAAwC,SAAS,OAAO,GAAG;AAAA,IAC/D,OAAO;AAAA,EACR;AAAA,EACA,MAAM,IAAI,4BAA4B,KAAK;AAAA;AAIrC,SAAS,sBAAsB,CACrC,MAAyB,QAAQ,KACf;AAAA,EAClB,OAAO,qBAAqB,IAAI,kBAAkB,IAAI,WAAW,SAAS;AAAA;AAG3E,eAAsB,WAAW,CAChC,IAC8B;AAAA,EAC9B,MAAM,MAAM,MAAM,GAChB,WAAW,WAAW,EACtB,OAAO,CAAC,MAAM,WAAW,YAAY,CAAC,EACtC,iBAAiB;AAAA,EACnB,OAAO,MAAM,WAAW,GAAG,IAAI;AAAA;AAQhC,eAAsB,cAAc,CACnC,IACA,OACuB;AAAA,EACvB,MAAM,WAAW,MAAM,YAAY,EAAE;AAAA,EACrC,IAAI,U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;AAAA,EACxC,MAAM,UAAU,qBAAqB,GAAG;AAAA,EACxC,MAAM,SACL,KAAK,mBAAmB,CAAC,MAAc,oBAAoB,IAAI,CAAC;AAAA,EACjE,OAAO,CAAE,MAAM,OAAO,OAAO;AAAA;AAG9B,eAAe,mBAAmB,CACjC,IACA,SACmB;AAAA,EACnB,MAAM,MAAM,MAAM,GAChB,WAAW,gBAAgB,EAC3B,OAAO,SAAS,EAChB,MAAM,WAAW,KAAK,OAAO,EAC7B,iBAAiB,EACjB,MAAM,MAAG;AAAA,IAAG;AAAA,GAAS;AAAA,EACvB,OAAO,QAAQ;AAAA;",
10
+ "debugId": "9B63D2E16C669F9764756E2164756E21",
9
11
  "names": []
10
12
  }
@@ -40,6 +40,12 @@ interface SubgraphVerification {
40
40
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
41
41
  unproven: string[];
42
42
  }
43
+ /** Every state `subgraphs.status` can hold; mirrored by the
44
+ * `subgraphs_status_check` CHECK (migration 0189). */
45
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
46
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
47
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
48
+ type WebhookPauseReason = "user" | "circuit";
43
49
  interface BlocksTable {
44
50
  height: number;
45
51
  hash: string;
@@ -179,7 +185,7 @@ interface SubgraphsTable {
179
185
  id: Generated<string>;
180
186
  name: string;
181
187
  version: Generated<string>;
182
- status: Generated<string>;
188
+ status: Generated<SubgraphStatus>;
183
189
  definition: Record<string, unknown>;
184
190
  schema_hash: string;
185
191
  handler_path: string;
@@ -196,8 +202,10 @@ interface SubgraphsTable {
196
202
  handler_code: string | null;
197
203
  source_code: string | null;
198
204
  project_id: string | null;
199
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
200
- expires_at: Date | null;
205
+ /** Set while the account's metered reads are refused (spend cap, credits).
206
+ * Both columns are set or both null; `last_error` stays for real errors. */
207
+ billing_paused_at: Date | null;
208
+ billing_paused_code: string | null;
201
209
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
202
210
  sparse_probe_targets: unknown | null;
203
211
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -211,6 +219,9 @@ interface SubgraphsTable {
211
219
  created_at: Generated<Date>;
212
220
  updated_at: Generated<Date>;
213
221
  }
222
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
223
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
224
+ type AbiStatus = (typeof ABI_STATUSES)[number];
214
225
  interface ContractsTable {
215
226
  contract_id: string;
216
227
  deployer: string;
@@ -219,17 +230,23 @@ interface ContractsTable {
219
230
  abi: unknown | null;
220
231
  declared_traits: Generated<string[]>;
221
232
  inferred_standards: Generated<string[]>;
222
- abi_status: Generated<string>;
233
+ abi_status: Generated<AbiStatus>;
223
234
  abi_fetched_at: Date | null;
235
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
236
+ abi_attempts: Generated<number>;
237
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
238
+ abi_next_attempt_at: Date | null;
224
239
  created_at: Generated<Date>;
225
240
  }
241
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
242
+ type GapReason = "block_missing" | "processing_error";
226
243
  interface SubgraphGapsTable {
227
244
  id: Generated<string>;
228
245
  subgraph_id: string;
229
246
  subgraph_name: string;
230
247
  gap_start: number;
231
248
  gap_end: number;
232
- reason: string;
249
+ reason: GapReason;
233
250
  detected_at: Generated<Date>;
234
251
  resolved_at: Date | null;
235
252
  }
@@ -275,12 +292,13 @@ interface SubgraphOperationsTable {
275
292
  * (those checkpoint on subgraphs.last_processed_block). */
276
293
  cursor_block: string | number | bigint | null;
277
294
  }
295
+ type ApiKeyStatus = "active" | "revoked";
278
296
  interface ApiKeysTable {
279
297
  id: Generated<string>;
280
298
  key_hash: string;
281
299
  key_prefix: string;
282
300
  name: string | null;
283
- status: Generated<string>;
301
+ status: Generated<ApiKeyStatus>;
284
302
  rate_limit: Generated<number>;
285
303
  ip_address: string;
286
304
  account_id: string;
@@ -641,6 +659,10 @@ interface SbtcSettlementsTable {
641
659
  last_checked_at: Generated<Date>;
642
660
  /** Set once, when `settlement_confirmed` first flips true. */
643
661
  confirmed_at: Date | null;
662
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
663
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
664
+ * runtime. */
665
+ seq: Generated<number | string>;
644
666
  updated_at: Generated<Date>;
645
667
  }
646
668
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -760,7 +782,9 @@ interface PendingForkBlocksTable {
760
782
  payload: ColumnType<unknown, unknown, unknown>;
761
783
  received_at: Generated<Date>;
762
784
  }
763
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
785
+ /** Mirrored by the CHECK on `observer_journal.status`. */
786
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
787
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
764
788
  /**
765
789
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
766
790
  * processing columns are updated only after the current derived-state write
@@ -795,7 +819,7 @@ interface StageRegistryTable {
795
819
  enabled: Generated<boolean>;
796
820
  created_at: Generated<Date>;
797
821
  }
798
- /** One versioned sweep of a stage. */
822
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
799
823
  interface StageRunsTable {
800
824
  id: Generated<string>;
801
825
  stage_id: string;
@@ -929,6 +953,7 @@ interface Database {
929
953
  archive_fetches: ArchiveFetchesTable;
930
954
  usage_ledger: UsageLedgerTable;
931
955
  account_balance_alerts: AccountBalanceAlertsTable;
956
+ hosted_stack_state: HostedStackStateTable;
932
957
  webhook_incident_alerts: WebhookIncidentAlertsTable;
933
958
  cli_device_logins: CliDeviceLoginsTable;
934
959
  oauth_clients: OauthClientsTable;
@@ -1012,7 +1037,11 @@ interface UsageLedgerTable {
1012
1037
  * floor to observe past. */
1013
1038
  observed_quantity: string | number | null;
1014
1039
  usd_micros: string | number | bigint;
1040
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1015
1041
  debited: Generated<boolean>;
1042
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1043
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1044
+ debited_usd_micros: Generated<string | number | bigint>;
1016
1045
  source: string;
1017
1046
  /** API key behind a metered read; null for non-read units and older rows. */
1018
1047
  api_key_id: string | null;
@@ -1030,6 +1059,14 @@ interface AccountBalanceAlertsTable {
1030
1059
  sent_2d_at: Date | null;
1031
1060
  sent_stopped_at: Date | null;
1032
1061
  }
1062
+ /** The workload host's report of one account's hosted stack. Written only by
1063
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1064
+ interface HostedStackStateTable {
1065
+ account_id: string;
1066
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1067
+ stop_reason: "credits" | "cap" | "idle" | null;
1068
+ reported_at: Date;
1069
+ }
1033
1070
  /** Debounce state for the webhook-down email: one row per incident, open
1034
1071
  * while `resolved_at` is null. No preference columns by design. */
1035
1072
  interface WebhookIncidentAlertsTable {
@@ -1166,7 +1203,7 @@ interface SentinelAccountsTable {
1166
1203
  linked_at: Generated<Date>;
1167
1204
  via: "created" | "consent";
1168
1205
  }
1169
- type WebhookStatus = "active" | "paused" | "error";
1206
+ type WebhookStatus = "active" | "paused";
1170
1207
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1171
1208
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1172
1209
  * webhooks; the column stays as the discriminator. */
@@ -1192,6 +1229,8 @@ interface WebhooksTable {
1192
1229
  concurrency: Generated<number>;
1193
1230
  circuit_failures: Generated<number>;
1194
1231
  circuit_opened_at: Date | null;
1232
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1233
+ pause_reason: WebhookPauseReason | null;
1195
1234
  last_delivery_at: Date | null;
1196
1235
  last_success_at: Date | null;
1197
1236
  last_error: string | null;
@@ -1202,6 +1241,10 @@ interface WebhooksTable {
1202
1241
  updated_at: Generated<Date>;
1203
1242
  }
1204
1243
  type OutboxStatus = "pending" | "delivered" | "dead";
1244
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1245
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1246
+ * longer contains. */
1247
+ type DeadReason = "exhausted" | "orphaned";
1205
1248
  interface WebhookOutboxTable {
1206
1249
  id: Generated<string>;
1207
1250
  webhook_id: string;
@@ -1231,6 +1274,8 @@ interface WebhookOutboxTable {
1231
1274
  * into an orphaned fork. Null otherwise — delivery failures track their
1232
1275
  * history on `webhooks.last_error`, not per-row. */
1233
1276
  last_error: string | null;
1277
+ /** Set exactly while `status` is `dead`. */
1278
+ dead_reason: DeadReason | null;
1234
1279
  created_at: Generated<Date>;
1235
1280
  }
1236
1281
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1280,6 +1325,13 @@ interface TriggerEvaluatorStateTable {
1280
1325
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1281
1326
  * the evaluator fast-forwards it on first run. */
1282
1327
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1328
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1329
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1330
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1331
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1332
+ * transaction that emits a batch and advances the cursor, so a reorg that
1333
+ * lands mid-tick rolls the batch back. */
1334
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1283
1335
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1284
1336
  * chain-trigger evaluator (plan 060) — a separate clock from
1285
1337
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards
@@ -1416,6 +1468,21 @@ interface Gap {
1416
1468
  gapEnd: number;
1417
1469
  size: number;
1418
1470
  }
1471
+ /**
1472
+ * The three honest answers to "what is the chain tip", so no reader derives its
1473
+ * own:
1474
+ *
1475
+ * seen highest block height the indexer has received (`index_progress`)
1476
+ * canonical highest block currently canonical in `blocks`
1477
+ * contiguous highest height with no gap below it (`index_progress`)
1478
+ *
1479
+ * `null` when nothing is recorded yet. The node's own tip is a different
1480
+ * question (it needs RPC) and is not answered here.
1481
+ */
1482
+ type ChainTipKind = "seen" | "canonical" | "contiguous";
1483
+ declare function resolveChainTip(db: Kysely<Database>, kind: ChainTipKind, opts?: {
1484
+ network?: string
1485
+ }): Promise<number | null>;
1419
1486
  declare function findGaps(db: Kysely<Database>, limit?: number): Promise<Gap[]>;
1420
1487
  declare function countMissingBlocks(db: Kysely<Database>): Promise<number>;
1421
1488
  interface ChainDataIntegrity {
@@ -1489,4 +1556,4 @@ declare function findBrokenLinks(db: Kysely<Database>, opts?: {
1489
1556
  window?: number | null
1490
1557
  limit?: number
1491
1558
  }): Promise<BrokenLink[]>;
1492
- export { BrokenLink, ChainDataIntegrity, Gap, ShortBlock, checkChainDataIntegrity, computeContiguousTip, countMissingBlocks, findBrokenLinks, findGaps, findShortBlocks };
1559
+ export { BrokenLink, ChainDataIntegrity, ChainTipKind, Gap, ShortBlock, checkChainDataIntegrity, computeContiguousTip, countMissingBlocks, findBrokenLinks, findGaps, findShortBlocks, resolveChainTip };
@@ -1,5 +1,238 @@
1
1
  // src/db/queries/integrity.ts
2
2
  import { sql } from "kysely";
3
+
4
+ // src/env.ts
5
+ import { z } from "zod";
6
+ var networksSchema = z.string().transform((val) => {
7
+ const networks = val.split(",").map((n) => n.trim()).filter(Boolean);
8
+ const valid = ["mainnet", "testnet"];
9
+ for (const n of networks) {
10
+ if (!valid.includes(n)) {
11
+ throw new Error(`Invalid network: ${n}. Must be one of: ${valid.join(", ")}`);
12
+ }
13
+ }
14
+ return networks;
15
+ });
16
+ var envSchema = z.object({
17
+ DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
18
+ SOURCE_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
19
+ TARGET_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
20
+ NETWORK: z.enum(["mainnet", "testnet"]).optional(),
21
+ NETWORKS: networksSchema.optional(),
22
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
23
+ NODE_ENV: z.enum(["development", "production", "test"]).default("development")
24
+ });
25
+ var cachedEnv = null;
26
+ function getEnv() {
27
+ if (cachedEnv) {
28
+ return cachedEnv;
29
+ }
30
+ const result = envSchema.safeParse(process.env);
31
+ if (!result.success) {
32
+ console.error("❌ Invalid environment configuration:");
33
+ console.error(z.treeifyError(result.error));
34
+ throw new Error("Invalid environment configuration");
35
+ }
36
+ let enabledNetworks;
37
+ if (result.data.NETWORKS && result.data.NETWORKS.length > 0) {
38
+ enabledNetworks = result.data.NETWORKS;
39
+ } else if (result.data.NETWORK) {
40
+ enabledNetworks = [result.data.NETWORK];
41
+ } else {
42
+ enabledNetworks = ["mainnet"];
43
+ }
44
+ cachedEnv = { ...result.data, enabledNetworks };
45
+ return cachedEnv;
46
+ }
47
+ function isProductionEnv() {
48
+ return process.env["NODE_ENV"] === "production";
49
+ }
50
+ function isPox4DecoderEnabled(env = process.env) {
51
+ return env.POX4_DECODER_ENABLED !== "false";
52
+ }
53
+ function isPox5DecoderEnabled(env = process.env) {
54
+ return env.POX5_DECODER_ENABLED !== "false";
55
+ }
56
+ function isSbtcDecoderEnabled(env = process.env) {
57
+ return env.SBTC_DECODER_ENABLED !== "false";
58
+ }
59
+ function isBnsDecoderEnabled(env = process.env) {
60
+ return env.BNS_DECODER_ENABLED === "true";
61
+ }
62
+ // src/logger.ts
63
+ var LOG_LEVELS = {
64
+ debug: 0,
65
+ info: 1,
66
+ warn: 2,
67
+ error: 3
68
+ };
69
+
70
+ class Logger {
71
+ _level;
72
+ _isProduction;
73
+ _initialized = false;
74
+ init() {
75
+ if (this._initialized)
76
+ return;
77
+ this._initialized = true;
78
+ try {
79
+ const env = getEnv();
80
+ this._level = env.LOG_LEVEL;
81
+ this._isProduction = env.NODE_ENV === "production";
82
+ } catch {
83
+ this._level = "info";
84
+ this._isProduction = false;
85
+ }
86
+ }
87
+ get level() {
88
+ this.init();
89
+ return this._level;
90
+ }
91
+ get isProduction() {
92
+ this.init();
93
+ return this._isProduction;
94
+ }
95
+ shouldLog(level) {
96
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
97
+ }
98
+ formatMessage(level, message, meta) {
99
+ const timestamp = new Date().toISOString();
100
+ if (this.isProduction) {
101
+ return JSON.stringify({
102
+ timestamp,
103
+ level,
104
+ message,
105
+ ...meta
106
+ });
107
+ }
108
+ const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
109
+ return `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;
110
+ }
111
+ debug(message, meta) {
112
+ if (this.shouldLog("debug")) {
113
+ console.debug(this.formatMessage("debug", message, meta));
114
+ }
115
+ }
116
+ info(message, meta) {
117
+ if (this.shouldLog("info")) {
118
+ console.info(this.formatMessage("info", message, meta));
119
+ }
120
+ }
121
+ warn(message, meta) {
122
+ if (this.shouldLog("warn")) {
123
+ console.warn(this.formatMessage("warn", message, meta));
124
+ }
125
+ }
126
+ error(message, meta) {
127
+ if (this.shouldLog("error")) {
128
+ console.error(this.formatMessage("error", message, meta));
129
+ }
130
+ }
131
+ }
132
+ var logger = new Logger;
133
+
134
+ // src/db/queries/instance.ts
135
+ var INSTANCE_NETWORKS = ["mainnet", "testnet", "devnet"];
136
+
137
+ class InstanceNetworkMismatchError extends Error {
138
+ existing;
139
+ requested;
140
+ name = "InstanceNetworkMismatchError";
141
+ constructor(existing, requested) {
142
+ super(`instance network is ${existing}; cannot change to ${requested}`);
143
+ this.existing = existing;
144
+ this.requested = requested;
145
+ }
146
+ }
147
+
148
+ class InvalidInstanceNetworkError extends Error {
149
+ value;
150
+ name = "InvalidInstanceNetworkError";
151
+ constructor(value) {
152
+ super(`instance network must be mainnet, testnet, or devnet (got ${value})`);
153
+ this.value = value;
154
+ }
155
+ }
156
+ function parseInstanceNetwork(value) {
157
+ const network = value.trim().toLowerCase();
158
+ if (INSTANCE_NETWORKS.includes(network)) {
159
+ return network;
160
+ }
161
+ throw new InvalidInstanceNetworkError(value);
162
+ }
163
+ var warnedNetworkFallback = false;
164
+ function stacksNetworkFromEnv(env = process.env) {
165
+ if (env.STACKS_NETWORK)
166
+ return env.STACKS_NETWORK;
167
+ if (env.NETWORK) {
168
+ if (!warnedNetworkFallback) {
169
+ warnedNetworkFallback = true;
170
+ logger.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
171
+ }
172
+ return env.NETWORK;
173
+ }
174
+ return "mainnet";
175
+ }
176
+ function instanceNetworkFromEnv(env = process.env) {
177
+ return parseInstanceNetwork(env.STACKS_NETWORK ?? env.NETWORK ?? "mainnet");
178
+ }
179
+ async function getInstance(db) {
180
+ const row = await db.selectFrom("instances").select(["id", "network", "created_at"]).executeTakeFirst();
181
+ return row ? toInstance(row) : null;
182
+ }
183
+ async function ensureInstance(db, input) {
184
+ const existing = await getInstance(db);
185
+ if (existing) {
186
+ if (existing.network !== input.network) {
187
+ throw new InstanceNetworkMismatchError(existing.network, input.network);
188
+ }
189
+ return existing;
190
+ }
191
+ try {
192
+ const inserted = await db.insertInto("instances").values({ network: input.network }).returning(["id", "network", "created_at"]).executeTakeFirstOrThrow();
193
+ return toInstance(inserted);
194
+ } catch {
195
+ const raced = await getInstance(db);
196
+ if (!raced)
197
+ throw new Error("failed to create instance");
198
+ if (raced.network !== input.network) {
199
+ throw new InstanceNetworkMismatchError(raced.network, input.network);
200
+ }
201
+ return raced;
202
+ }
203
+ }
204
+ function toInstance(row) {
205
+ return {
206
+ id: row.id,
207
+ network: parseInstanceNetwork(row.network),
208
+ created_at: row.created_at
209
+ };
210
+ }
211
+ async function hasNoLocalChain(db, opts = {}) {
212
+ const env = opts.env ?? process.env;
213
+ if (!env.SUBGRAPH_INDEX_API_URL)
214
+ return false;
215
+ const network = stacksNetworkFromEnv(env);
216
+ const hasRow = opts.hasProgressRow ?? ((n) => hasLocalProgressRow(db, n));
217
+ return !await hasRow(network);
218
+ }
219
+ async function hasLocalProgressRow(db, network) {
220
+ const row = await db.selectFrom("index_progress").select("network").where("network", "=", network).executeTakeFirst().catch(() => {
221
+ return;
222
+ });
223
+ return row !== undefined;
224
+ }
225
+
226
+ // src/db/queries/integrity.ts
227
+ async function resolveChainTip(db, kind, opts = {}) {
228
+ if (kind === "canonical") {
229
+ const row = await db.selectFrom("blocks").select("height").where("canonical", "=", true).orderBy("height", "desc").limit(1).executeTakeFirst();
230
+ return row ? Number(row.height) : null;
231
+ }
232
+ const column = kind === "seen" ? "highest_seen_block" : "last_contiguous_block";
233
+ const row = await db.selectFrom("index_progress").select(column).where("network", "=", opts.network ?? stacksNetworkFromEnv()).executeTakeFirst();
234
+ return row ? Number(row[column]) : null;
235
+ }
3
236
  async function findGaps(db, limit) {
4
237
  const limitClause = limit ? sql`LIMIT ${limit}` : sql``;
5
238
  const { rows } = await sql`
@@ -129,8 +362,9 @@ export {
129
362
  countMissingBlocks,
130
363
  findBrokenLinks,
131
364
  findGaps,
132
- findShortBlocks
365
+ findShortBlocks,
366
+ resolveChainTip
133
367
  };
134
368
 
135
- //# debugId=E92283960DE6C55264756E2164756E21
369
+ //# debugId=939BB1A42238203764756E2164756E21
136
370
  //# sourceMappingURL=integrity.js.map