@secondlayer/shared 7.9.0 → 7.11.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.
@@ -0,0 +1,1670 @@
1
+ /**
2
+ * Coverage-kernel constraints. SQL CHECKs in migration 0116 must stay
3
+ * identical — property tests treat this file as the spec.
4
+ */
5
+ declare const STAGE_KINDS: readonly ["raw", "decode", "subgraph", "queue"];
6
+ type StageKind = (typeof STAGE_KINDS)[number];
7
+ declare const NATIVE_CLOCKS: readonly ["block", "cursor", "queue"];
8
+ type NativeClock = (typeof NATIVE_CLOCKS)[number];
9
+ declare const REPAIR_MODES: readonly ["range_safe", "full_reindex", "archive_replay", "none"];
10
+ type RepairMode = (typeof REPAIR_MODES)[number];
11
+ declare const RUN_STATUSES: readonly ["pending", "running", "complete", "syncing", "lagging", "gap", "stale", "failed", "unverified_import", "unanchored", "source_unavailable", "out_of_scope", "disabled", "halted"];
12
+ type RunStatus = (typeof RUN_STATUSES)[number];
13
+ declare const FAILURE_UNITS: readonly ["block", "range", "cursor", "queue"];
14
+ type FailureUnit = (typeof FAILURE_UNITS)[number];
15
+ declare const FAILURE_CLASSES: readonly ["omission", "version", "digest_mismatch", "crash", "reorg", "source_gap", "handler", "timeout", "unknown"];
16
+ type FailureClass = (typeof FAILURE_CLASSES)[number];
17
+ declare const RETRY_STATES: readonly ["open", "retrying", "halted", "resolved"];
18
+ type RetryState = (typeof RETRY_STATES)[number];
19
+ /** Default failure retention after `created_at`. */
20
+ declare const FAILURE_RETENTION_DAYS = 30;
21
+ type CoverageRange = {
22
+ from_height: number
23
+ to_height: number
24
+ };
25
+ type ReceiptRow = {
26
+ block_height: number
27
+ input_count: number
28
+ finalized: boolean
29
+ compacted_at: Date | null
30
+ };
31
+ type FailureRow = {
32
+ from_height: number | null
33
+ to_height: number | null
34
+ retry_state: RetryState
35
+ retry_count: number
36
+ resolved_at: Date | null
37
+ created_at: Date
38
+ retain_until: Date
39
+ };
40
+ declare function isStageKind(value: string): value is StageKind;
41
+ declare function isNativeClock(value: string): value is NativeClock;
42
+ declare function isRepairMode(value: string): value is RepairMode;
43
+ declare function isRunStatus(value: string): value is RunStatus;
44
+ declare function isFailureUnit(value: string): value is FailureUnit;
45
+ declare function isFailureClass(value: string): value is FailureClass;
46
+ declare function isRetryState(value: string): value is RetryState;
47
+ declare function isNonNegativeInt(value: number): boolean;
48
+ declare function rangeIsOrdered(from: number, to: number): boolean;
49
+ /** Compacted receipts must already be finalized. */
50
+ declare function receiptRetentionHolds(row: ReceiptRow): boolean;
51
+ declare function failureRangeHolds(row: FailureRow): boolean;
52
+ /** Resolved rows need `resolved_at`; open rows keep `retain_until` ≥ created. */
53
+ declare function failureRetentionHolds(row: FailureRow): boolean;
54
+ /** Two closed ranges on the same stage must not overlap. */
55
+ declare function segmentsOverlap(a: CoverageRange, b: CoverageRange): boolean;
56
+ declare function defaultRetainUntil(createdAt: Date): Date;
57
+ declare const COVERAGE_REPORT_SCHEMA_VERSION: 1;
58
+ declare const COVERAGE_STATES: readonly ["complete", "syncing", "lagging", "gap", "stale", "failed", "unverified_import", "unanchored", "source_unavailable", "out_of_scope", "disabled"];
59
+ type CoverageState = (typeof COVERAGE_STATES)[number];
60
+ type BootstrapSource = "archive" | "genesis" | "import";
61
+ type SyncScope = {
62
+ network: string
63
+ start_height: number
64
+ target_height: number | null
65
+ bootstrap: {
66
+ source: BootstrapSource
67
+ manifest_digest: string | null
68
+ genesis_hash: string | null
69
+ }
70
+ };
71
+ type StageDeclaration = {
72
+ id: string
73
+ kind: StageKind
74
+ depends_on: string | null
75
+ native_clock: NativeClock
76
+ producer_version: string
77
+ repair_mode: RepairMode
78
+ enabled: boolean
79
+ };
80
+ type StageRunView = {
81
+ stage_id: string
82
+ code_hash: string
83
+ config_hash: string
84
+ handler_hash: string | null
85
+ target_height: number | null
86
+ target_cursor: string | null
87
+ status: RunStatus
88
+ complete_through: number | null
89
+ };
90
+ type OpenFailure = {
91
+ unit_kind: FailureUnit
92
+ class: FailureClass
93
+ retry_state: Exclude<RetryState, "resolved">
94
+ from_height: number | null
95
+ to_height: number | null
96
+ };
97
+ type QueueCounters = {
98
+ accepted: number
99
+ decided: number
100
+ enqueued: number
101
+ delivered: number
102
+ dead: number
103
+ fence_cursor: string | null
104
+ };
105
+ type StageEvidence = {
106
+ stage_id: string
107
+ ranges: CoverageRange[]
108
+ open_failures: OpenFailure[]
109
+ cursor: string | null
110
+ queue: QueueCounters | null
111
+ unanchored: boolean
112
+ unverified_import: boolean
113
+ /** False when this stage's native source (node, bitcoin RPC, …) is down. */
114
+ source_available: boolean
115
+ };
116
+ type SourceClock = {
117
+ tip_height: number | null
118
+ finalized_height: number | null
119
+ observed_at: string | null
120
+ };
121
+ type EvaluatorOptions = {
122
+ now: Date
123
+ maxBlocksBehindFinalized?: number
124
+ maxSourceAgeSeconds?: number
125
+ };
126
+ type EvaluatorInput = {
127
+ scope: SyncScope
128
+ stages: StageDeclaration[]
129
+ runs: StageRunView[]
130
+ evidence: StageEvidence[]
131
+ source: SourceClock
132
+ options: EvaluatorOptions
133
+ };
134
+ type StageCoverage = {
135
+ stage_id: string
136
+ kind: StageKind
137
+ native_clock: NativeClock
138
+ depends_on: string | null
139
+ state: CoverageState
140
+ detail: string
141
+ complete_through: number | null
142
+ source_tip: number | null
143
+ finalized_height: number | null
144
+ recorded_target: number | null
145
+ declared_range: {
146
+ from_height: number
147
+ to_height: number
148
+ } | null
149
+ gaps: CoverageRange[]
150
+ caught_up: boolean
151
+ blocked_by: string | null
152
+ };
153
+ type CoverageReport = {
154
+ schema_version: typeof COVERAGE_REPORT_SCHEMA_VERSION
155
+ network: string
156
+ generated_at: string
157
+ source_tip: number | null
158
+ finalized_height: number | null
159
+ stages: StageCoverage[]
160
+ evaluation_order: string[]
161
+ cycles: string[][]
162
+ };
163
+ declare function mergeRanges(ranges: readonly CoverageRange[]): CoverageRange[];
164
+ /** Highest height reachable from `start` without a hole. */
165
+ declare function contiguousThrough(ranges: readonly CoverageRange[], start: number): number | null;
166
+ declare function findRangeGaps(ranges: readonly CoverageRange[], from: number, to: number): CoverageRange[];
167
+ declare function cursorHeight(cursor: string | null): number | null;
168
+ declare function topoSort(stages: readonly StageDeclaration[]): {
169
+ order: string[]
170
+ cycles: string[][]
171
+ };
172
+ declare function evaluateCoverage(input: EvaluatorInput): CoverageReport;
173
+ declare const RUNNER_STATUSES: readonly ["pending", "running", "complete", "failed", "halted"];
174
+ type RunnerStatus = (typeof RUNNER_STATUSES)[number];
175
+ declare const RUNNER_EVENT_TYPES: readonly ["start", "ack", "fail", "retry", "halt", "resume", "reorg", "version", "finish"];
176
+ type RunnerEventType = (typeof RUNNER_EVENT_TYPES)[number];
177
+ declare const DEFAULT_MAX_RETRIES = 3;
178
+ type RunnerVersion = {
179
+ code_hash: string
180
+ config_hash: string
181
+ handler_hash: string | null
182
+ };
183
+ type RunnerFailure = {
184
+ unit_kind: FailureUnit
185
+ class: FailureClass
186
+ retry_state: Exclude<RetryState, "resolved">
187
+ from_height: number | null
188
+ to_height: number | null
189
+ error: string | null
190
+ };
191
+ type RunnerState = {
192
+ stage_id: string
193
+ status: RunnerStatus
194
+ version: RunnerVersion
195
+ start_height: number
196
+ target_height: number | null
197
+ complete_through: number | null
198
+ last_acked_hash: string | null
199
+ retry_count: number
200
+ open_failure: RunnerFailure | null
201
+ };
202
+ type RunnerEvent = {
203
+ type: "start"
204
+ } | {
205
+ type: "ack"
206
+ height: number
207
+ hash: string
208
+ input_count: number
209
+ input_digest: string
210
+ effect_digest: string
211
+ } | {
212
+ type: "fail"
213
+ unit_kind: FailureUnit
214
+ class: FailureClass
215
+ from_height: number | null
216
+ to_height: number | null
217
+ error: string | null
218
+ } | {
219
+ type: "retry"
220
+ } | {
221
+ type: "halt"
222
+ } | {
223
+ type: "resume"
224
+ } | {
225
+ type: "reorg"
226
+ fork_point: number
227
+ } | {
228
+ type: "version"
229
+ version: RunnerVersion
230
+ } | {
231
+ type: "finish"
232
+ };
233
+ type RunnerEffect = {
234
+ type: "invalidate_receipts"
235
+ range: CoverageRange
236
+ } | {
237
+ type: "spawn_run"
238
+ version: RunnerVersion
239
+ } | {
240
+ type: "open_failure"
241
+ failure: RunnerFailure
242
+ } | {
243
+ type: "resolve_failure"
244
+ };
245
+ type RunnerResult = {
246
+ ok: true
247
+ state: RunnerState
248
+ effects: RunnerEffect[]
249
+ } | {
250
+ ok: false
251
+ reason: string
252
+ state: RunnerState
253
+ };
254
+ type TransitionRule = {
255
+ from: RunnerStatus
256
+ event: RunnerEventType
257
+ to: RunnerStatus | "reject"
258
+ };
259
+ /**
260
+ * Structural transition table. Guards (order, retry budget, version
261
+ * equality, reorg overlap) are applied on top in `applyRunnerEvent`.
262
+ */
263
+ declare const RUNNER_TRANSITION_TABLE: readonly TransitionRule[];
264
+ declare function lookupTransition(from: RunnerStatus, event: RunnerEventType): TransitionRule;
265
+ declare function versionsEqual(a: RunnerVersion, b: RunnerVersion): boolean;
266
+ /** Next height this run must acknowledge. */
267
+ declare function expectedAckHeight(state: RunnerState): number;
268
+ declare function createRunnerState(init: {
269
+ stage_id: string
270
+ start_height: number
271
+ target_height?: number | null
272
+ version: RunnerVersion
273
+ }): RunnerState;
274
+ declare function applyRunnerEvent(state: RunnerState, event: RunnerEvent, opts?: {
275
+ maxRetries?: number
276
+ }): RunnerResult;
277
+ /**
278
+ * Canonical Streams cursor codec, shared by every product (Streams, Index,
279
+ * Datasets, bulk). A cursor is `"<block_height>:<event_index>"` — an opaque,
280
+ * monotonic resume token. One implementation so encode/decode and the
281
+ * empty-range sentinel can never drift between products.
282
+ *
283
+ * NOTE: this codec IS the shared piece worth centralizing. A broader "shared
284
+ * canonical reader" across the ~10 raw-event query sites (streams-events,
285
+ * streams-bulk/query, l2/storage) was deliberately NOT built: those sites split
286
+ * into distinct query patterns and share only the row_number ordering *pattern*,
287
+ * not an identical reader. The reorg-archive design (migration 0084) keeps the
288
+ * main tables canonical-only, so each reader's `WHERE canonical` filter already
289
+ * needs no dedup logic. Forcing one mega-reader was the wrong abstraction; this
290
+ * codec captures the only part that actually drifts.
291
+ */
292
+ type StreamsCursor = {
293
+ block_height: number
294
+ event_index: number
295
+ };
296
+ type CanonicalBlock = {
297
+ height: number
298
+ hash: string
299
+ };
300
+ type DecoderClockEvent = {
301
+ cursor: string
302
+ block_hash: string
303
+ matched: boolean
304
+ };
305
+ type DecoderClockInput = {
306
+ start_height: number
307
+ /** Exclusive. Null = before `start_height`. */
308
+ from_cursor: string | null
309
+ /** Exclusive high-water after this batch. */
310
+ to_cursor: string
311
+ blocks: readonly CanonicalBlock[]
312
+ events: readonly DecoderClockEvent[]
313
+ };
314
+ type DecoderClockReceipt = {
315
+ height: number
316
+ hash: string
317
+ input_count: number
318
+ input_cursors: string[]
319
+ input_digest: string
320
+ through_cursor: string
321
+ no_match: boolean
322
+ };
323
+ type DecoderClockResult = {
324
+ ok: true
325
+ receipts: DecoderClockReceipt[]
326
+ through_cursor: string
327
+ } | {
328
+ ok: false
329
+ reason: string
330
+ receipts: DecoderClockReceipt[]
331
+ };
332
+ declare function inputDigest(cursors: readonly string[]): string;
333
+ declare function cursorIsAfterBlock(cursor: StreamsCursor, height: number): boolean;
334
+ /** True when `from` is strictly before the first event that can live in `height`. */
335
+ declare function cursorIsBeforeBlock(cursor: StreamsCursor, height: number): boolean;
336
+ declare function planDecoderReceipts(input: DecoderClockInput): DecoderClockResult;
337
+ import { Kysely } from "kysely";
338
+ import { ColumnType, Generated } from "kysely";
339
+ interface BlocksTable {
340
+ height: number;
341
+ hash: string;
342
+ parent_hash: string;
343
+ burn_block_height: number;
344
+ burn_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
345
+ /** Nakamoto StacksBlockId. Null on rows ingested before it was persisted. */
346
+ index_block_hash: ColumnType<string | null, string | null | undefined, string | null>;
347
+ timestamp: number;
348
+ canonical: Generated<boolean>;
349
+ created_at: Generated<Date>;
350
+ }
351
+ interface TransactionsTable {
352
+ tx_id: string;
353
+ block_height: number;
354
+ tx_index: Generated<number>;
355
+ type: string;
356
+ sender: string;
357
+ status: string;
358
+ contract_id: string | null;
359
+ function_name: string | null;
360
+ function_args: Generated<unknown | null>;
361
+ raw_result: Generated<string | null>;
362
+ raw_tx: string;
363
+ created_at: Generated<Date>;
364
+ }
365
+ interface EventsTable {
366
+ id: Generated<string>;
367
+ tx_id: string;
368
+ block_height: number;
369
+ event_index: number;
370
+ type: string;
371
+ data: unknown;
372
+ created_at: Generated<Date>;
373
+ }
374
+ interface TransactionsArchiveTable {
375
+ archive_id: Generated<string>;
376
+ tx_id: string;
377
+ block_height: number;
378
+ tx_index: number;
379
+ type: string;
380
+ sender: string;
381
+ status: string;
382
+ contract_id: string | null;
383
+ function_name: string | null;
384
+ function_args: unknown | null;
385
+ raw_result: string | null;
386
+ raw_tx: string;
387
+ created_at: Date;
388
+ orphaned_block_hash: string | null;
389
+ archived_at: Generated<Date>;
390
+ }
391
+ interface EventsArchiveTable {
392
+ archive_id: Generated<string>;
393
+ id: string;
394
+ tx_id: string;
395
+ block_height: number;
396
+ event_index: number;
397
+ type: string;
398
+ data: unknown;
399
+ created_at: Date;
400
+ orphaned_block_hash: string | null;
401
+ archived_at: Generated<Date>;
402
+ }
403
+ interface DeadLetterEventsTable {
404
+ id: Generated<string>;
405
+ block_height: number;
406
+ tx_id: string;
407
+ event_index: number;
408
+ event_type: string;
409
+ data: unknown;
410
+ reason: string;
411
+ created_at: Generated<Date>;
412
+ }
413
+ interface MempoolTransactionsTable {
414
+ seq: Generated<string>;
415
+ tx_id: string;
416
+ raw_tx: string;
417
+ type: string;
418
+ sender: string;
419
+ contract_id: string | null;
420
+ function_name: string | null;
421
+ function_args: unknown | null;
422
+ received_at: Generated<Date>;
423
+ }
424
+ interface IndexProgressTable {
425
+ network: string;
426
+ last_indexed_block: Generated<number>;
427
+ last_contiguous_block: Generated<number>;
428
+ highest_seen_block: Generated<number>;
429
+ updated_at: Generated<Date>;
430
+ }
431
+ interface SubgraphsTable {
432
+ id: Generated<string>;
433
+ name: string;
434
+ version: Generated<string>;
435
+ status: Generated<string>;
436
+ definition: Record<string, unknown>;
437
+ schema_hash: string;
438
+ handler_path: string;
439
+ schema_name: string | null;
440
+ start_block: Generated<number>;
441
+ last_processed_block: Generated<number>;
442
+ reindex_from_block: number | null;
443
+ reindex_to_block: number | null;
444
+ last_error: string | null;
445
+ last_error_at: Date | null;
446
+ total_processed: Generated<number>;
447
+ total_errors: Generated<number>;
448
+ account_id: string;
449
+ handler_code: string | null;
450
+ source_code: string | null;
451
+ project_id: string | null;
452
+ visibility: Generated<string>;
453
+ /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
454
+ expires_at: Date | null;
455
+ /** (event type, contract) probe pairs persisted at deploy for weight classification. */
456
+ sparse_probe_targets: unknown | null;
457
+ database_url_enc: ColumnType<Buffer | null, Buffer | null | undefined, Buffer | null>;
458
+ sandbox_workers: Generated<boolean>;
459
+ created_at: Generated<Date>;
460
+ updated_at: Generated<Date>;
461
+ }
462
+ interface ContractsTable {
463
+ contract_id: string;
464
+ deployer: string;
465
+ block_height: number;
466
+ canonical: Generated<boolean>;
467
+ abi: unknown | null;
468
+ declared_traits: Generated<string[]>;
469
+ inferred_standards: Generated<string[]>;
470
+ abi_status: Generated<string>;
471
+ abi_fetched_at: Date | null;
472
+ created_at: Generated<Date>;
473
+ }
474
+ interface SubgraphGapsTable {
475
+ id: Generated<string>;
476
+ subgraph_id: string;
477
+ subgraph_name: string;
478
+ gap_start: number;
479
+ gap_end: number;
480
+ reason: string;
481
+ detected_at: Generated<Date>;
482
+ resolved_at: Date | null;
483
+ }
484
+ type SubgraphOperationKind = "reindex" | "backfill";
485
+ type SubgraphOperationStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
486
+ interface SubgraphOperationsTable {
487
+ id: Generated<string>;
488
+ subgraph_id: string;
489
+ subgraph_name: string;
490
+ account_id: string | null;
491
+ kind: ColumnType<SubgraphOperationKind, SubgraphOperationKind, SubgraphOperationKind>;
492
+ status: ColumnType<SubgraphOperationStatus, SubgraphOperationStatus | undefined, SubgraphOperationStatus>;
493
+ from_block: number | null;
494
+ to_block: number | null;
495
+ cancel_requested: Generated<boolean>;
496
+ locked_by: string | null;
497
+ locked_until: Date | null;
498
+ started_at: Date | null;
499
+ finished_at: Date | null;
500
+ processed_blocks: number | null;
501
+ error: string | null;
502
+ created_at: Generated<Date>;
503
+ updated_at: Generated<Date>;
504
+ /** 'light' (contract-scoped sparse) | 'heavy' (broad). Claim budgets heavy. */
505
+ weight: Generated<string>;
506
+ /** Candidate-event denominator computed at enqueue (sparse ops only). */
507
+ estimated_events: string | number | bigint | null;
508
+ /** Events processed so far — written by the progress flush. */
509
+ processed_events: string | number | bigint | null;
510
+ /** Backfill ops' own crash checkpoint — advanced conditionally in-tx with
511
+ * each written block; replays skip at/below it. NULL for reindex ops
512
+ * (those checkpoint on subgraphs.last_processed_block). */
513
+ cursor_block: string | number | bigint | null;
514
+ }
515
+ interface ApiKeysTable {
516
+ id: Generated<string>;
517
+ key_hash: string;
518
+ key_prefix: string;
519
+ name: string | null;
520
+ status: Generated<string>;
521
+ rate_limit: Generated<number>;
522
+ ip_address: string;
523
+ account_id: string;
524
+ product: Generated<"account" | "streams" | "index">;
525
+ tier: "free" | "build" | "scale" | "enterprise" | null;
526
+ last_used_at: Date | null;
527
+ revoked_at: Date | null;
528
+ created_at: Generated<Date>;
529
+ }
530
+ /** Singleton self-host / publisher identity. Network is immutable. */
531
+ interface InstancesTable {
532
+ id: Generated<string>;
533
+ network: string;
534
+ created_at: Generated<Date>;
535
+ }
536
+ interface AccountsTable {
537
+ id: Generated<string>;
538
+ /** NULL for unclaimed ghost accounts (anonymous self-serve keys). */
539
+ email: string | null;
540
+ /** True for anonymous self-serve accounts until claimed via magic link. */
541
+ ghost: Generated<boolean>;
542
+ /** Stacks principal owning a wallet-ghost account (x402-paid deploys). */
543
+ wallet_principal: string | null;
544
+ plan: Generated<string>;
545
+ display_name: string | null;
546
+ bio: string | null;
547
+ avatar_url: string | null;
548
+ slug: string | null;
549
+ stripe_customer_id: string | null;
550
+ /** Opt-out toggle for the subgraph reindex-completion email. Defaults true. */
551
+ notify_reindex_complete: Generated<boolean>;
552
+ created_at: Generated<Date>;
553
+ }
554
+ interface SessionsTable {
555
+ id: Generated<string>;
556
+ token_hash: string;
557
+ token_prefix: string;
558
+ account_id: string;
559
+ ip_address: string;
560
+ expires_at: Generated<Date>;
561
+ revoked_at: Date | null;
562
+ last_used_at: Date | null;
563
+ created_at: Generated<Date>;
564
+ }
565
+ /**
566
+ * One-time claim tokens for ghost accounts. The raw token only ever appears in
567
+ * the claim URL returned at mint time; we store its sha256. A used token marks
568
+ * the account as claimed (or merged into an existing account).
569
+ */
570
+ interface ClaimTokensTable {
571
+ id: Generated<string>;
572
+ account_id: string;
573
+ token_hash: string;
574
+ created_at: Generated<Date>;
575
+ expires_at: Date;
576
+ used_at: Date | null;
577
+ }
578
+ interface MagicLinksTable {
579
+ id: Generated<string>;
580
+ email: string;
581
+ token: string;
582
+ code: string | null;
583
+ expires_at: Date;
584
+ used_at: Date | null;
585
+ failed_attempts: Generated<number>;
586
+ created_at: Generated<Date>;
587
+ }
588
+ interface UsageDailyTable {
589
+ account_id: string;
590
+ tenant_id: string | null;
591
+ date: string;
592
+ api_requests: Generated<number>;
593
+ deliveries: Generated<number>;
594
+ streams_events_returned: Generated<number>;
595
+ index_decoded_events_returned: Generated<number>;
596
+ }
597
+ interface UsageSnapshotsTable {
598
+ id: Generated<string>;
599
+ account_id: string;
600
+ measured_at: Generated<Date>;
601
+ storage_bytes: Generated<number>;
602
+ }
603
+ interface AccountInsightsTable {
604
+ id: Generated<string>;
605
+ account_id: string;
606
+ category: string;
607
+ insight_type: string;
608
+ resource_id: string | null;
609
+ severity: string;
610
+ title: string;
611
+ body: string;
612
+ data: unknown;
613
+ dismissed_at: Date | null;
614
+ expires_at: Date | null;
615
+ created_at: Generated<Date>;
616
+ }
617
+ interface AccountAgentRunsTable {
618
+ id: Generated<string>;
619
+ account_id: string;
620
+ started_at: Generated<Date>;
621
+ completed_at: Date | null;
622
+ status: Generated<string>;
623
+ input_tokens: Generated<number>;
624
+ output_tokens: Generated<number>;
625
+ cost_usd: Generated<number>;
626
+ insights_created: Generated<number>;
627
+ error: string | null;
628
+ }
629
+ interface SubgraphProcessingStatsTable {
630
+ id: Generated<string>;
631
+ subgraph_name: string;
632
+ api_key_id: string | null;
633
+ bucket_start: Date | null;
634
+ bucket_end: Date | null;
635
+ blocks_processed: number | null;
636
+ total_time_ms: number | null;
637
+ handler_time_ms: number | null;
638
+ flush_time_ms: number | null;
639
+ max_block_time_ms: number | null;
640
+ max_handler_time_ms: number | null;
641
+ avg_ops_per_block: number | null;
642
+ is_catchup: Generated<boolean>;
643
+ created_at: Generated<Date>;
644
+ }
645
+ interface SubgraphTableSnapshotsTable {
646
+ id: Generated<string>;
647
+ subgraph_name: string;
648
+ api_key_id: string | null;
649
+ table_name: string;
650
+ row_count: number | null;
651
+ created_at: Generated<Date>;
652
+ }
653
+ interface SubgraphHealthSnapshotsTable {
654
+ id: Generated<string>;
655
+ subgraph_id: string;
656
+ total_processed: number;
657
+ total_errors: number;
658
+ last_processed_block: number | null;
659
+ captured_at: Generated<Date>;
660
+ }
661
+ interface SubgraphUsageDailyTable {
662
+ subgraph_id: string;
663
+ date: string;
664
+ query_count: Generated<number>;
665
+ }
666
+ interface ProjectsTable {
667
+ id: Generated<string>;
668
+ name: string;
669
+ slug: string;
670
+ account_id: string;
671
+ settings: Generated<Record<string, unknown>>;
672
+ network: Generated<string>;
673
+ node_rpc: string | null;
674
+ created_at: Generated<Date>;
675
+ updated_at: Generated<Date>;
676
+ }
677
+ interface TeamMembersTable {
678
+ id: Generated<string>;
679
+ project_id: string;
680
+ account_id: string;
681
+ role: Generated<string>;
682
+ invited_by: string | null;
683
+ created_at: Generated<Date>;
684
+ }
685
+ interface TeamInvitationsTable {
686
+ id: Generated<string>;
687
+ project_id: string;
688
+ email: string;
689
+ role: Generated<string>;
690
+ token: string;
691
+ invited_by: string | null;
692
+ expires_at: Date;
693
+ accepted_at: Date | null;
694
+ created_at: Generated<Date>;
695
+ }
696
+ interface ProcessedStripeEventsTable {
697
+ event_id: string;
698
+ event_type: string;
699
+ processed_at: Generated<Date>;
700
+ }
701
+ interface DecodedEventsTable {
702
+ cursor: string;
703
+ block_height: number;
704
+ tx_id: string;
705
+ tx_index: number;
706
+ event_index: number;
707
+ event_type: string;
708
+ microblock_hash: string | null;
709
+ canonical: Generated<boolean>;
710
+ contract_id: string | null;
711
+ sender: string | null;
712
+ recipient: string | null;
713
+ amount: string | null;
714
+ asset_identifier: string | null;
715
+ value: string | null;
716
+ memo: string | null;
717
+ /** Decoded payload for event types that don't fit the flat columns
718
+ * (e.g. `print`: { topic, value, raw_value }). Null for transfer types. */
719
+ payload: unknown | null;
720
+ source_cursor: string;
721
+ created_at: Generated<Date>;
722
+ }
723
+ interface DecoderCheckpointsTable {
724
+ decoder_name: string;
725
+ last_cursor: string | null;
726
+ updated_at: Generated<Date>;
727
+ }
728
+ interface ChainReorgsTable {
729
+ id: Generated<string>;
730
+ detected_at: Generated<Date>;
731
+ fork_point_height: number;
732
+ old_index_block_hash: string | null;
733
+ new_index_block_hash: string | null;
734
+ orphaned_from_height: number;
735
+ orphaned_from_event_index: number;
736
+ orphaned_to_height: number;
737
+ orphaned_to_event_index: number;
738
+ new_canonical_height: number;
739
+ new_canonical_event_index: number;
740
+ created_at: Generated<Date>;
741
+ }
742
+ type Pox4FunctionName = "stack-stx" | "delegate-stx" | "stack-extend" | "stack-increase" | "revoke-delegate-stx" | "delegate-stack-stx" | "delegate-stack-extend" | "delegate-stack-increase" | "stack-aggregation-commit" | "stack-aggregation-commit-indexed" | "stack-aggregation-increase" | "set-signer-key-authorization";
743
+ interface Pox4CallsTable {
744
+ cursor: string;
745
+ block_height: number;
746
+ block_time: Date;
747
+ burn_block_height: number;
748
+ tx_id: string;
749
+ tx_index: number;
750
+ function_name: Pox4FunctionName;
751
+ caller: string;
752
+ stacker: string | null;
753
+ delegate_to: string | null;
754
+ amount_ustx: string | null;
755
+ lock_period: number | null;
756
+ pox_addr_version: number | null;
757
+ pox_addr_hashbytes: string | null;
758
+ pox_addr_btc: string | null;
759
+ start_cycle: number | null;
760
+ end_cycle: number | null;
761
+ signer_key: string | null;
762
+ signer_signature: string | null;
763
+ auth_id: string | null;
764
+ max_amount: string | null;
765
+ reward_cycle: number | null;
766
+ aggregated_amount_ustx: string | null;
767
+ aggregated_signer_index: number | null;
768
+ auth_period: number | null;
769
+ auth_topic: string | null;
770
+ auth_allowed: boolean | null;
771
+ result_ok: boolean;
772
+ result_raw: string;
773
+ canonical: Generated<boolean>;
774
+ source_cursor: string;
775
+ created_at: Generated<Date>;
776
+ }
777
+ interface Pox4CyclesDailyTable {
778
+ date: string;
779
+ reward_cycle: number;
780
+ total_stacked_ustx: Generated<string>;
781
+ solo_stackers: Generated<number>;
782
+ delegated_principals: Generated<number>;
783
+ unique_pools: Generated<number>;
784
+ unique_signers: Generated<number>;
785
+ calls_today: Generated<number>;
786
+ updated_at: Generated<Date>;
787
+ }
788
+ interface Pox4SignersDailyTable {
789
+ date: string;
790
+ reward_cycle: number;
791
+ signer_key: string;
792
+ weight_ustx: Generated<string>;
793
+ stacker_count: Generated<number>;
794
+ aggregation_calls: Generated<number>;
795
+ updated_at: Generated<Date>;
796
+ }
797
+ type Pox5EventTopic = "set-bond-admin" | "set-pause-admin" | "pause-rewards" | "setup-bond" | "add-to-allowlist" | "register-for-bond" | "update-bond-registration" | "register-signer" | "stake" | "stake-update" | "announce-l1-early-exit" | "unstake-sbtc" | "unstake" | "calculate-rewards" | "bond-distribution" | "claim-rewards" | "claim-staker-rewards-for-signer" | "grant-signer-key" | "revoke-signer-grant";
798
+ interface Pox5EventsTable {
799
+ cursor: string;
800
+ block_height: number;
801
+ block_time: Date;
802
+ tx_id: string;
803
+ tx_index: number;
804
+ event_index: number;
805
+ topic: Pox5EventTopic;
806
+ staker: string | null;
807
+ signer: string | null;
808
+ signer_manager: string | null;
809
+ bond_index: number | null;
810
+ amount_ustx: string | null;
811
+ amount_sats: string | null;
812
+ reward_cycle: number | null;
813
+ first_reward_cycle: number | null;
814
+ unlock_cycle: number | null;
815
+ unlock_burn_height: number | null;
816
+ is_l1_lock: boolean | null;
817
+ signer_key: string | null;
818
+ data: unknown;
819
+ canonical: Generated<boolean>;
820
+ source_cursor: string;
821
+ created_at: Generated<Date>;
822
+ }
823
+ interface BurnBlockRewardsTable {
824
+ cursor: string;
825
+ burn_block_height: number;
826
+ burn_block_hash: string;
827
+ reward_index: number;
828
+ recipient_btc: string;
829
+ amount_sats: string;
830
+ burn_amount: Generated<string>;
831
+ created_at: Generated<Date>;
832
+ }
833
+ interface BurnBlockRewardSlotsTable {
834
+ cursor: string;
835
+ burn_block_height: number;
836
+ burn_block_hash: string;
837
+ slot_index: number;
838
+ holder_btc: string;
839
+ created_at: Generated<Date>;
840
+ }
841
+ type SbtcEventTopic = "completed-deposit" | "withdrawal-create" | "withdrawal-accept" | "withdrawal-reject" | "key-rotation" | "update-protocol-contract";
842
+ interface SbtcEventsTable {
843
+ cursor: string;
844
+ block_height: number;
845
+ block_time: Date;
846
+ tx_id: string;
847
+ tx_index: number;
848
+ event_index: number;
849
+ topic: SbtcEventTopic;
850
+ request_id: number | null;
851
+ amount: string | null;
852
+ sender: string | null;
853
+ recipient_btc_version: number | null;
854
+ recipient_btc_hashbytes: string | null;
855
+ bitcoin_txid: string | null;
856
+ output_index: number | null;
857
+ sweep_txid: string | null;
858
+ burn_hash: string | null;
859
+ burn_height: number | null;
860
+ signer_bitmap: string | null;
861
+ max_fee: string | null;
862
+ fee: string | null;
863
+ block_height_at_request: number | null;
864
+ governance_contract_type: number | null;
865
+ governance_new_contract: string | null;
866
+ signer_aggregate_pubkey: string | null;
867
+ signer_threshold: number | null;
868
+ signer_address: string | null;
869
+ signer_keys_count: number | null;
870
+ canonical: Generated<boolean>;
871
+ source_cursor: string;
872
+ created_at: Generated<Date>;
873
+ }
874
+ type SbtcTokenEventType = "transfer" | "mint" | "burn";
875
+ interface SbtcTokenEventsTable {
876
+ cursor: string;
877
+ block_height: number;
878
+ block_time: Date;
879
+ tx_id: string;
880
+ tx_index: number;
881
+ event_index: number;
882
+ event_type: SbtcTokenEventType;
883
+ sender: string | null;
884
+ recipient: string | null;
885
+ amount: string;
886
+ memo: string | null;
887
+ canonical: Generated<boolean>;
888
+ source_cursor: string;
889
+ created_at: Generated<Date>;
890
+ }
891
+ /**
892
+ * BTC L1 settlement status for sBTC withdrawal sweeps. Filled by the indexer's
893
+ * settlement-confirmer worker, which polls our own bitcoind for confirmations of
894
+ * each `withdrawal-accept`'s `sweep_txid` and surfaces real settlement on the
895
+ * withdrawal lifecycle (the API's `settlement.{btc_confirmations,
896
+ * settlement_confirmed}` placeholder). Keyed on `sweep_txid` (not `request_id`):
897
+ * a request can produce more than one sweep over its life (RBF/rebroadcast), so
898
+ * each broadcast keeps its own confirmation history.
899
+ */
900
+ interface SbtcSettlementsTable {
901
+ sweep_txid: string;
902
+ request_id: number;
903
+ btc_confirmations: Generated<number>;
904
+ settlement_confirmed: Generated<boolean>;
905
+ /** Confirming Bitcoin block — null while the sweep is unconfirmed. */
906
+ block_hash: string | null;
907
+ block_height: number | null;
908
+ first_seen_at: Generated<Date>;
909
+ last_checked_at: Generated<Date>;
910
+ /** Set once, when `settlement_confirmed` first flips true. */
911
+ confirmed_at: Date | null;
912
+ updated_at: Generated<Date>;
913
+ }
914
+ interface SbtcSupplySnapshotsTable {
915
+ date: string;
916
+ total_supply: Generated<string>;
917
+ mints_today: Generated<string>;
918
+ burns_today: Generated<string>;
919
+ deposit_count: Generated<number>;
920
+ withdrawal_create_count: Generated<number>;
921
+ withdrawal_accept_count: Generated<number>;
922
+ withdrawal_reject_count: Generated<number>;
923
+ updated_at: Generated<Date>;
924
+ }
925
+ type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
926
+ interface BnsNameEventsTable {
927
+ cursor: string;
928
+ block_height: number;
929
+ block_time: Date;
930
+ tx_id: string;
931
+ tx_index: number;
932
+ event_index: number;
933
+ topic: BnsNameEventTopic;
934
+ namespace: string;
935
+ name: string;
936
+ fqn: string;
937
+ owner: string | null;
938
+ bns_id: string;
939
+ registered_at: number | null;
940
+ imported_at: number | null;
941
+ renewal_height: number | null;
942
+ stx_burn: string | null;
943
+ preordered_by: string | null;
944
+ hashed_salted_fqn_preorder: string | null;
945
+ canonical: Generated<boolean>;
946
+ source_cursor: string;
947
+ created_at: Generated<Date>;
948
+ }
949
+ type BnsNamespaceEventStatus = "launch" | "transfer-manager" | "freeze-manager" | "update-price-manager" | "freeze-price-manager" | "turn-off-manager-transfers";
950
+ interface BnsNamespaceEventsTable {
951
+ cursor: string;
952
+ block_height: number;
953
+ block_time: Date;
954
+ tx_id: string;
955
+ tx_index: number;
956
+ event_index: number;
957
+ status: BnsNamespaceEventStatus;
958
+ namespace: string;
959
+ manager: string | null;
960
+ manager_frozen: boolean | null;
961
+ manager_transfers_disabled: boolean | null;
962
+ price_function: string | null;
963
+ price_frozen: boolean | null;
964
+ lifetime: number | null;
965
+ revealed_at: number | null;
966
+ launched_at: number | null;
967
+ canonical: Generated<boolean>;
968
+ source_cursor: string;
969
+ created_at: Generated<Date>;
970
+ }
971
+ type BnsMarketplaceAction = "list-in-ustx" | "unlist-in-ustx" | "buy-in-ustx";
972
+ interface BnsMarketplaceEventsTable {
973
+ cursor: string;
974
+ block_height: number;
975
+ block_time: Date;
976
+ tx_id: string;
977
+ tx_index: number;
978
+ event_index: number;
979
+ action: BnsMarketplaceAction;
980
+ bns_id: string;
981
+ price_ustx: string | null;
982
+ commission: string | null;
983
+ canonical: Generated<boolean>;
984
+ source_cursor: string;
985
+ created_at: Generated<Date>;
986
+ }
987
+ interface BnsNamesTable {
988
+ fqn: string;
989
+ namespace: string;
990
+ name: string;
991
+ owner: string;
992
+ bns_id: string;
993
+ registered_at: number | null;
994
+ renewal_height: number | null;
995
+ last_event_cursor: string;
996
+ last_event_at: Date;
997
+ updated_at: Generated<Date>;
998
+ }
999
+ interface BnsNamespacesTable {
1000
+ namespace: string;
1001
+ manager: string | null;
1002
+ manager_frozen: Generated<boolean>;
1003
+ price_frozen: Generated<boolean>;
1004
+ lifetime: number | null;
1005
+ launched_at: number | null;
1006
+ last_event_cursor: string;
1007
+ last_event_at: Date;
1008
+ name_count: Generated<number>;
1009
+ updated_at: Generated<Date>;
1010
+ }
1011
+ /**
1012
+ * Memoized `ctx.client.readOnly()` results. Keyed on `index_block_hash` so a
1013
+ * reorg-replaced block never inherits the orphaned fork's answer; a NULL
1014
+ * `index_block_hash` marks a caller-declared contract-constant value, cached
1015
+ * once per contract+args instead of once per block.
1016
+ */
1017
+ interface ChainReadCacheTable {
1018
+ id: Generated<number>;
1019
+ contract_id: string;
1020
+ function_name: string;
1021
+ args_hash: string;
1022
+ index_block_hash: string | null;
1023
+ block_height: ColumnType<number | null, number | null | undefined, number | null>;
1024
+ result_hex: string;
1025
+ created_at: Generated<Date>;
1026
+ }
1027
+ /**
1028
+ * A block that arrived for a height we already hold, staged until a later
1029
+ * block's `parent_hash` says which of the two the chain kept. See migration
1030
+ * 0112 — adopting on first sight picked the losing fork twice.
1031
+ */
1032
+ interface PendingForkBlocksTable {
1033
+ height: number;
1034
+ block_hash: string;
1035
+ parent_hash: string;
1036
+ /** The canonical hash we held at this height when the contender arrived. */
1037
+ incumbent_hash: string;
1038
+ /** The raw observer payload, replayed verbatim if this fork wins. */
1039
+ payload: ColumnType<unknown, unknown, unknown>;
1040
+ received_at: Generated<Date>;
1041
+ }
1042
+ type ObserverJournalStatus = "received" | "processed" | "failed";
1043
+ /**
1044
+ * Exact observer callback receipt. `raw_body` is immutable evidence; the
1045
+ * processing columns are updated only after the current derived-state write
1046
+ * succeeds or fails.
1047
+ */
1048
+ interface ObserverJournalTable {
1049
+ sequence: Generated<string>;
1050
+ network: string;
1051
+ path: string;
1052
+ source: string | null;
1053
+ received_at: Generated<Date>;
1054
+ raw_body: ColumnType<Buffer, Buffer, Buffer>;
1055
+ raw_body_sha256: string;
1056
+ status: ColumnType<ObserverJournalStatus, ObserverJournalStatus | undefined, ObserverJournalStatus>;
1057
+ semantic_sha256: string | null;
1058
+ block_height: number | null;
1059
+ block_hash: string | null;
1060
+ burn_block_height: number | null;
1061
+ burn_block_hash: string | null;
1062
+ result: unknown | null;
1063
+ error: string | null;
1064
+ processed_at: Date | null;
1065
+ }
1066
+ /** Declared coverage stage. Identity is the `id` string (`raw`, `decode:stx`, …). */
1067
+ interface StageRegistryTable {
1068
+ id: string;
1069
+ kind: StageKind;
1070
+ depends_on: string | null;
1071
+ native_clock: NativeClock;
1072
+ producer_version: string;
1073
+ repair_mode: RepairMode;
1074
+ enabled: Generated<boolean>;
1075
+ created_at: Generated<Date>;
1076
+ }
1077
+ /** One versioned sweep of a stage. */
1078
+ interface StageRunsTable {
1079
+ id: Generated<string>;
1080
+ stage_id: string;
1081
+ code_hash: string;
1082
+ config_hash: string;
1083
+ handler_hash: string | null;
1084
+ target_height: number | null;
1085
+ target_cursor: string | null;
1086
+ status: RunStatus;
1087
+ complete_through: number | null;
1088
+ started_at: Generated<Date>;
1089
+ finished_at: Date | null;
1090
+ }
1091
+ /** Per-block acknowledgement. Unique on (stage, height, hash). */
1092
+ interface StageBlockReceiptsTable {
1093
+ id: Generated<string>;
1094
+ stage_id: string;
1095
+ run_id: string | null;
1096
+ block_height: number;
1097
+ block_hash: string;
1098
+ input_count: number;
1099
+ input_digest: string;
1100
+ effect_digest: string;
1101
+ finalized: Generated<boolean>;
1102
+ compacted_at: Date | null;
1103
+ created_at: Generated<Date>;
1104
+ }
1105
+ /** Compacted finalized range. Only sealed after receipts in the range finalize. */
1106
+ interface CoverageSegmentsTable {
1107
+ id: Generated<string>;
1108
+ stage_id: string;
1109
+ from_height: number;
1110
+ to_height: number;
1111
+ chain_digest: string;
1112
+ input_digest: string;
1113
+ output_digest: string;
1114
+ sealed_at: Generated<Date>;
1115
+ }
1116
+ /** Exact unit or range that failed, plus retry/retention state. */
1117
+ interface StageFailuresTable {
1118
+ id: Generated<string>;
1119
+ stage_id: string;
1120
+ run_id: string | null;
1121
+ unit_kind: FailureUnit;
1122
+ from_height: number | null;
1123
+ to_height: number | null;
1124
+ class: FailureClass;
1125
+ retry_state: RetryState;
1126
+ retry_count: Generated<number>;
1127
+ last_error: string | null;
1128
+ created_at: Generated<Date>;
1129
+ resolved_at: Date | null;
1130
+ retain_until: Generated<Date>;
1131
+ }
1132
+ interface Database {
1133
+ blocks: BlocksTable;
1134
+ transactions: TransactionsTable;
1135
+ events: EventsTable;
1136
+ transactions_archive: TransactionsArchiveTable;
1137
+ events_archive: EventsArchiveTable;
1138
+ dead_letter_events: DeadLetterEventsTable;
1139
+ mempool_transactions: MempoolTransactionsTable;
1140
+ index_progress: IndexProgressTable;
1141
+ contracts: ContractsTable;
1142
+ subgraphs: SubgraphsTable;
1143
+ api_keys: ApiKeysTable;
1144
+ instances: InstancesTable;
1145
+ accounts: AccountsTable;
1146
+ sessions: SessionsTable;
1147
+ magic_links: MagicLinksTable;
1148
+ claim_tokens: ClaimTokensTable;
1149
+ usage_daily: UsageDailyTable;
1150
+ usage_snapshots: UsageSnapshotsTable;
1151
+ account_insights: AccountInsightsTable;
1152
+ account_agent_runs: AccountAgentRunsTable;
1153
+ subgraph_health_snapshots: SubgraphHealthSnapshotsTable;
1154
+ subgraph_processing_stats: SubgraphProcessingStatsTable;
1155
+ subgraph_table_snapshots: SubgraphTableSnapshotsTable;
1156
+ subgraph_gaps: SubgraphGapsTable;
1157
+ subgraph_operations: SubgraphOperationsTable;
1158
+ subgraph_usage_daily: SubgraphUsageDailyTable;
1159
+ projects: ProjectsTable;
1160
+ team_members: TeamMembersTable;
1161
+ team_invitations: TeamInvitationsTable;
1162
+ processed_stripe_events: ProcessedStripeEventsTable;
1163
+ tenants: TenantsTable;
1164
+ tenant_usage_monthly: TenantUsageMonthlyTable;
1165
+ tenant_compute_addons: TenantComputeAddonsTable;
1166
+ account_spend_caps: AccountSpendCapsTable;
1167
+ account_credits: AccountCreditsTable;
1168
+ provisioning_audit_log: ProvisioningAuditLogTable;
1169
+ subscriptions: SubscriptionsTable;
1170
+ subscription_outbox: SubscriptionOutboxTable;
1171
+ subscription_deliveries: SubscriptionDeliveriesTable;
1172
+ trigger_evaluator_state: TriggerEvaluatorStateTable;
1173
+ decoded_events: DecodedEventsTable;
1174
+ decoder_checkpoints: DecoderCheckpointsTable;
1175
+ chain_reorgs: ChainReorgsTable;
1176
+ pox4_calls: Pox4CallsTable;
1177
+ pox4_cycles_daily: Pox4CyclesDailyTable;
1178
+ pox4_signers_daily: Pox4SignersDailyTable;
1179
+ pox5_events: Pox5EventsTable;
1180
+ burn_block_rewards: BurnBlockRewardsTable;
1181
+ burn_block_reward_slots: BurnBlockRewardSlotsTable;
1182
+ sbtc_events: SbtcEventsTable;
1183
+ sbtc_token_events: SbtcTokenEventsTable;
1184
+ sbtc_settlements: SbtcSettlementsTable;
1185
+ sbtc_supply_snapshots: SbtcSupplySnapshotsTable;
1186
+ bns_name_events: BnsNameEventsTable;
1187
+ bns_namespace_events: BnsNamespaceEventsTable;
1188
+ bns_marketplace_events: BnsMarketplaceEventsTable;
1189
+ bns_names: BnsNamesTable;
1190
+ bns_namespaces: BnsNamespacesTable;
1191
+ service_heartbeats: ServiceHeartbeatsTable;
1192
+ x402_payments: X402PaymentsTable;
1193
+ x402_balances: X402BalancesTable;
1194
+ chain_read_cache: ChainReadCacheTable;
1195
+ pending_fork_blocks: PendingForkBlocksTable;
1196
+ observer_journal: ObserverJournalTable;
1197
+ stage_registry: StageRegistryTable;
1198
+ stage_runs: StageRunsTable;
1199
+ stage_block_receipts: StageBlockReceiptsTable;
1200
+ coverage_segments: CoverageSegmentsTable;
1201
+ stage_failures: StageFailuresTable;
1202
+ }
1203
+ /** Prepaid x402 credit — one running USD-micros balance per payer principal. */
1204
+ interface X402BalancesTable {
1205
+ principal: string;
1206
+ balance_usd_micros: Generated<string | number | bigint>;
1207
+ /** Month bucket ("YYYY-MM") the spend counter applies to. */
1208
+ spent_month: string | null;
1209
+ spent_month_usd_micros: Generated<string | number | bigint>;
1210
+ updated_at: Generated<Date>;
1211
+ }
1212
+ interface ServiceHeartbeatsTable {
1213
+ name: string;
1214
+ updated_at: Generated<Date>;
1215
+ }
1216
+ /** x402 pay-per-request ledger (control plane). One row per settled payment,
1217
+ * keyed by challenge nonce + settled txid. `state` tracks confirmed-tier
1218
+ * settlement and post-serve reorg reversal. */
1219
+ interface X402PaymentsTable {
1220
+ id: Generated<string>;
1221
+ nonce: string;
1222
+ txid: string;
1223
+ asset: string;
1224
+ amount: string;
1225
+ payer: string;
1226
+ surface: string;
1227
+ state: Generated<"pending" | "confirmed" | "reverted">;
1228
+ created_at: Generated<Date>;
1229
+ updated_at: Generated<Date>;
1230
+ /** "payment" = per-call settle; "deposit" = prepaid balance top-up. */
1231
+ kind: Generated<string>;
1232
+ /** Linked claimed account once the paying wallet is attached (continuity). */
1233
+ account_id: string | null;
1234
+ /** USD-micros to credit on confirmation, for deposit rows the reconciler
1235
+ * settles asynchronously. NULL for per-call settles (credit nothing). */
1236
+ credit_usd_micros: string | null;
1237
+ /** Idempotency key: stamped exactly once when this row's credit is applied.
1238
+ * NULL means never credited (or not a credit-bearing row). Pre-migration
1239
+ * non-pending deposit rows are backfilled to a non-null sentinel so the
1240
+ * reconciler's heal path can never double-credit them. */
1241
+ credited_at: Generated<Date> | null;
1242
+ }
1243
+ type TenantStatus = "provisioning" | "active" | "limit_warning" | "paused_limit" | "suspended" | "error" | "deleted";
1244
+ interface TenantsTable {
1245
+ id: Generated<string>;
1246
+ account_id: string;
1247
+ slug: string;
1248
+ status: ColumnType<TenantStatus, TenantStatus | undefined, TenantStatus>;
1249
+ plan: string;
1250
+ cpus: ColumnType<number, number | string, number | string>;
1251
+ memory_mb: number;
1252
+ storage_limit_mb: number;
1253
+ storage_used_mb: number | null;
1254
+ pg_container_id: string | null;
1255
+ api_container_id: string | null;
1256
+ processor_container_id: string | null;
1257
+ target_database_url_enc: Buffer;
1258
+ tenant_jwt_secret_enc: Buffer;
1259
+ anon_key_enc: Buffer;
1260
+ service_key_enc: Buffer;
1261
+ api_url_internal: string;
1262
+ api_url_public: string;
1263
+ suspended_at: Date | null;
1264
+ last_health_check_at: Date | null;
1265
+ last_active_at: Generated<Date>;
1266
+ service_gen: Generated<number>;
1267
+ anon_gen: Generated<number>;
1268
+ project_id: string | null;
1269
+ created_at: Generated<Date>;
1270
+ updated_at: Generated<Date>;
1271
+ }
1272
+ interface TenantUsageMonthlyTable {
1273
+ id: Generated<string>;
1274
+ tenant_id: string;
1275
+ period_month: Date;
1276
+ storage_peak_mb: Generated<number>;
1277
+ storage_avg_mb: Generated<number>;
1278
+ storage_last_mb: Generated<number>;
1279
+ measurements: Generated<number>;
1280
+ first_at: Generated<Date>;
1281
+ last_at: Generated<Date>;
1282
+ }
1283
+ interface TenantComputeAddonsTable {
1284
+ id: Generated<string>;
1285
+ tenant_id: string;
1286
+ memory_mb_delta: Generated<number>;
1287
+ cpu_delta: Generated<number | string>;
1288
+ storage_mb_delta: Generated<number>;
1289
+ effective_from: Generated<Date>;
1290
+ effective_until: Date | null;
1291
+ stripe_subscription_item_id: string | null;
1292
+ created_at: Generated<Date>;
1293
+ }
1294
+ interface AccountSpendCapsTable {
1295
+ account_id: string;
1296
+ monthly_cap_cents: number | null;
1297
+ compute_cap_cents: number | null;
1298
+ storage_cap_cents: number | null;
1299
+ alert_threshold_pct: Generated<number>;
1300
+ alert_sent_at: Date | null;
1301
+ frozen_at: Date | null;
1302
+ updated_at: Generated<Date>;
1303
+ }
1304
+ /** Prepaid dev credits — card-funded balance per account (peer to x402_balances). */
1305
+ interface AccountCreditsTable {
1306
+ account_id: string;
1307
+ balance_usd_micros: Generated<string | number | bigint>;
1308
+ /** Month bucket ("YYYY-MM") the spend counter applies to. */
1309
+ spent_month: string | null;
1310
+ spent_month_usd_micros: Generated<string | number | bigint>;
1311
+ updated_at: Generated<Date>;
1312
+ }
1313
+ type ProvisioningAuditEvent = "provision.start" | "provision.success" | "provision.failure" | "suspend" | "resume" | "resize" | "keys.rotate" | "bastion.key.upload" | "bastion.key.revoke" | "teardown";
1314
+ type ProvisioningAuditStatus = "ok" | "error";
1315
+ interface ProvisioningAuditLogTable {
1316
+ id: Generated<string>;
1317
+ tenant_id: string | null;
1318
+ tenant_slug: string | null;
1319
+ account_id: string | null;
1320
+ actor: string;
1321
+ event: ProvisioningAuditEvent;
1322
+ status: ProvisioningAuditStatus;
1323
+ detail: unknown | null;
1324
+ error: string | null;
1325
+ created_at: Generated<Date>;
1326
+ }
1327
+ type SubscriptionStatus = "active" | "paused" | "error";
1328
+ /** Polymorphic subscription mode: `subgraph` reacts to processed table rows;
1329
+ * `chain` reacts to raw chain events matched directly off the Index/Streams
1330
+ * clock (no subgraph). See migration 0088. */
1331
+ type SubscriptionKind = "subgraph" | "chain";
1332
+ type SubscriptionFormat = "standard-webhooks" | "inngest" | "trigger" | "cloudflare" | "cloudevents" | "raw";
1333
+ type SubscriptionRuntime = "inngest" | "trigger" | "cloudflare" | "node";
1334
+ interface SubscriptionsTable {
1335
+ id: Generated<string>;
1336
+ account_id: string;
1337
+ project_id: string | null;
1338
+ name: string;
1339
+ status: ColumnType<SubscriptionStatus, SubscriptionStatus | undefined, SubscriptionStatus>;
1340
+ kind: ColumnType<SubscriptionKind, SubscriptionKind | undefined, SubscriptionKind>;
1341
+ /** Null for chain subscriptions (CHECK subscriptions_kind_shape). */
1342
+ subgraph_name: string | null;
1343
+ /** Null for chain subscriptions (CHECK subscriptions_kind_shape). */
1344
+ table_name: string | null;
1345
+ /** Chain-trigger filter array (the `SubgraphFilter` shape, JSON). Null for
1346
+ * subgraph subscriptions. Typed loosely here to avoid a shared→subgraphs
1347
+ * import cycle; the Zod schema in schemas/subscriptions.ts owns the shape. */
1348
+ triggers: unknown | null;
1349
+ filter: Generated<unknown>;
1350
+ format: ColumnType<SubscriptionFormat, SubscriptionFormat | undefined, SubscriptionFormat>;
1351
+ runtime: SubscriptionRuntime | null;
1352
+ url: string;
1353
+ signing_secret_enc: Buffer;
1354
+ auth_config: Generated<unknown>;
1355
+ max_retries: Generated<number>;
1356
+ timeout_ms: Generated<number>;
1357
+ concurrency: Generated<number>;
1358
+ circuit_failures: Generated<number>;
1359
+ circuit_opened_at: Date | null;
1360
+ last_delivery_at: Date | null;
1361
+ last_success_at: Date | null;
1362
+ last_error: string | null;
1363
+ created_at: Generated<Date>;
1364
+ updated_at: Generated<Date>;
1365
+ }
1366
+ type OutboxStatus = "pending" | "delivered" | "dead";
1367
+ interface SubscriptionOutboxTable {
1368
+ id: Generated<string>;
1369
+ subscription_id: string;
1370
+ kind: ColumnType<SubscriptionKind, SubscriptionKind | undefined, SubscriptionKind>;
1371
+ /** Null for chain-subscription rows. */
1372
+ subgraph_name: string | null;
1373
+ /** Null for chain-subscription rows. */
1374
+ table_name: string | null;
1375
+ block_height: number | bigint;
1376
+ tx_id: string | null;
1377
+ row_pk: unknown;
1378
+ event_type: string;
1379
+ payload: unknown;
1380
+ dedup_key: string;
1381
+ attempt: Generated<number>;
1382
+ next_attempt_at: Generated<Date>;
1383
+ status: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;
1384
+ is_replay: Generated<boolean>;
1385
+ delivered_at: Date | null;
1386
+ failed_at: Date | null;
1387
+ locked_by: string | null;
1388
+ locked_until: Date | null;
1389
+ created_at: Generated<Date>;
1390
+ }
1391
+ interface SubscriptionDeliveriesTable {
1392
+ id: Generated<string>;
1393
+ /** Nullable after migration 0077 — outbox row may be cleaned up while
1394
+ * delivery telemetry is retained. */
1395
+ outbox_id: string | null;
1396
+ subscription_id: string;
1397
+ attempt: number;
1398
+ status_code: number | null;
1399
+ response_headers: unknown | null;
1400
+ response_body: string | null;
1401
+ error_message: string | null;
1402
+ duration_ms: number | null;
1403
+ dispatched_at: Generated<Date>;
1404
+ }
1405
+ /** Single-row (id always TRUE) high-water mark for the chain-trigger evaluator.
1406
+ * One loop serves all chain subscriptions, so the cursor is global. */
1407
+ interface TriggerEvaluatorStateTable {
1408
+ id: Generated<boolean>;
1409
+ last_processed_block: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1410
+ /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1411
+ * the evaluator fast-forwards it on first run. */
1412
+ last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1413
+ updated_at: Generated<Date>;
1414
+ }
1415
+ declare const DECODER_COMMIT_STEPS: readonly ["output", "checkpoint", "receipt", "failure"];
1416
+ type DecoderCommitStep = (typeof DECODER_COMMIT_STEPS)[number];
1417
+ declare class DecoderAdapterCrash extends Error {
1418
+ readonly step: DecoderCommitStep;
1419
+ readonly name = "DecoderAdapterCrash";
1420
+ constructor(step: DecoderCommitStep);
1421
+ }
1422
+ type DecoderAdapterFailure = {
1423
+ unit_kind: FailureUnit
1424
+ class: FailureClass
1425
+ retry_state: Exclude<RetryState, "resolved">
1426
+ from_height: number | null
1427
+ to_height: number | null
1428
+ error: string | null
1429
+ retry_count?: number
1430
+ };
1431
+ type DecoderAdapterReceipt = DecoderClockReceipt & {
1432
+ effect_digest: string
1433
+ };
1434
+ type DecoderAdapterCommit = {
1435
+ stage_id: string
1436
+ run_id?: string | null
1437
+ decoder_name: string
1438
+ /** Null = do not move the checkpoint (empty page). */
1439
+ checkpoint_cursor: string | null
1440
+ receipts: readonly DecoderAdapterReceipt[]
1441
+ failure?: DecoderAdapterFailure | null
1442
+ writeOutput: (tx: Kysely<Database>) => Promise<void>
1443
+ crashAfter?: DecoderCommitStep
1444
+ };
1445
+ declare function runDecoderCommitSteps(steps: Record<DecoderCommitStep, () => Promise<void>>, crashAfter?: DecoderCommitStep): Promise<void>;
1446
+ declare function applyDecoderReceipts(state: RunnerState, receipts: readonly DecoderAdapterReceipt[]): RunnerResult;
1447
+ /**
1448
+ * Persist output + checkpoint + receipts + failure in one transaction.
1449
+ * Runner validation is the caller's job (`applyDecoderReceipts`) so a
1450
+ * rejected ack never opens a transaction.
1451
+ */
1452
+ declare function commitDecoderAdapter(db: Kysely<Database>, input: DecoderAdapterCommit): Promise<void>;
1453
+ type SealableReceipt = {
1454
+ height: number
1455
+ hash: string
1456
+ input_digest: string
1457
+ effect_digest: string
1458
+ finalized: boolean
1459
+ };
1460
+ type SealedSegment = {
1461
+ from_height: number
1462
+ to_height: number
1463
+ chain_digest: string
1464
+ input_digest: string
1465
+ output_digest: string
1466
+ };
1467
+ type SealResult = {
1468
+ ok: true
1469
+ segment: SealedSegment
1470
+ compacted: number
1471
+ } | {
1472
+ ok: false
1473
+ reason: string
1474
+ };
1475
+ declare function rangeDigestOf(parts: readonly string[]): string;
1476
+ declare function sealFinalizedRange(receipts: readonly SealableReceipt[], range: CoverageRange): SealResult;
1477
+ /** After a reorg at `fork`, any sealed segment that overlaps cannot stay green. */
1478
+ declare function segmentsSurviveReorg(segments: readonly SealedSegment[], fork: number): SealedSegment[];
1479
+ declare function receiptsAfterReorg(receipts: readonly SealableReceipt[], fork: number): SealableReceipt[];
1480
+ type EffectOp = "insert" | "update" | "delete" | "increment";
1481
+ type EffectMutation = {
1482
+ op: EffectOp
1483
+ table: string
1484
+ key: Record<string, string | number | boolean | null>
1485
+ value?: Record<string, string | number | boolean | null>
1486
+ };
1487
+ declare function canonicalizeMutations(ops: readonly EffectMutation[]): EffectMutation[];
1488
+ declare function hashEffectManifest(ops: readonly EffectMutation[]): string;
1489
+ declare function manifestsEqual(a: readonly EffectMutation[], b: readonly EffectMutation[]): boolean;
1490
+ declare const SUBGRAPH_COMMIT_STEPS: readonly ["effects", "rows", "journal", "cursor", "receipt", "failure"];
1491
+ type SubgraphCommitStep = (typeof SUBGRAPH_COMMIT_STEPS)[number];
1492
+ declare class SubgraphAdapterCrash extends Error {
1493
+ readonly step: SubgraphCommitStep;
1494
+ readonly name = "SubgraphAdapterCrash";
1495
+ constructor(step: SubgraphCommitStep);
1496
+ }
1497
+ type SubgraphCommitInput = {
1498
+ stage_id: string
1499
+ effects: readonly EffectMutation[]
1500
+ receipts: readonly (DecoderClockReceipt & {
1501
+ effect_digest: string
1502
+ })[]
1503
+ failure?: DecoderAdapterFailure | null
1504
+ writeEffects: () => Promise<void>
1505
+ writeRows: () => Promise<void>
1506
+ writeJournal: () => Promise<void>
1507
+ writeCursor: () => Promise<void>
1508
+ writeReceipts: () => Promise<void>
1509
+ writeFailure: () => Promise<void>
1510
+ crashAfter?: SubgraphCommitStep
1511
+ };
1512
+ declare function runSubgraphCommitSteps(steps: Record<SubgraphCommitStep, () => Promise<void>>, crashAfter?: SubgraphCommitStep): Promise<void>;
1513
+ declare function commitSubgraphAdapter(input: SubgraphCommitInput, wrap?: (fn: () => Promise<void>) => Promise<void>): Promise<void>;
1514
+ type SparseSkip = CoverageRange & {
1515
+ reason: "no-match" | "filtered"
1516
+ };
1517
+ type HeightDigest = {
1518
+ height: number
1519
+ hash: string
1520
+ effect_digest: string
1521
+ row_digest: string
1522
+ };
1523
+ declare function sequentialDigests(heights: readonly HeightDigest[]): {
1524
+ chain: string
1525
+ effect: string
1526
+ row: string
1527
+ };
1528
+ declare function sparseDigests(executed: readonly HeightDigest[], skips: readonly {
1529
+ skip: SparseSkip
1530
+ hash: string
1531
+ }[]): {
1532
+ chain: string
1533
+ effect: string
1534
+ row: string
1535
+ };
1536
+ declare function proofsAgree(sequential: {
1537
+ chain: string
1538
+ effect: string
1539
+ row: string
1540
+ }, sparse: {
1541
+ chain: string
1542
+ effect: string
1543
+ row: string
1544
+ }): boolean;
1545
+ type RowSnapshot = {
1546
+ table: string
1547
+ key: string
1548
+ value: string
1549
+ };
1550
+ declare function finalRowDigest(rows: readonly RowSnapshot[]): string;
1551
+ declare function applyMutations(rows: readonly RowSnapshot[], ops: readonly EffectMutation[]): RowSnapshot[];
1552
+ type DeepVerifyResult = {
1553
+ ok: boolean
1554
+ live_digest: string
1555
+ scratch_digest: string
1556
+ found_mutation: boolean
1557
+ };
1558
+ declare function deepVerify(opts: {
1559
+ live: readonly RowSnapshot[]
1560
+ replay: readonly EffectMutation[]
1561
+ seed?: EffectMutation
1562
+ }): DeepVerifyResult;
1563
+ declare const QUEUE_STAGES: readonly ["decision", "outbox", "delivery", "rollback", "dlq", "replay"];
1564
+ type QueueStage = (typeof QUEUE_STAGES)[number];
1565
+ type QueueEvent = {
1566
+ type: "accept"
1567
+ } | {
1568
+ type: "decide"
1569
+ matched: boolean
1570
+ } | {
1571
+ type: "enqueue"
1572
+ } | {
1573
+ type: "deliver"
1574
+ } | {
1575
+ type: "fail"
1576
+ } | {
1577
+ type: "dead"
1578
+ } | {
1579
+ type: "requeue"
1580
+ } | {
1581
+ type: "rollback"
1582
+ } | {
1583
+ type: "replay"
1584
+ cursor: string
1585
+ };
1586
+ type QueueState = QueueCounters & {
1587
+ stage: QueueStage
1588
+ last_cursor: string | null
1589
+ dedupe: Set<string>
1590
+ };
1591
+ declare function emptyQueueState(): QueueState;
1592
+ type QueueApply = {
1593
+ ok: true
1594
+ state: QueueState
1595
+ } | {
1596
+ ok: false
1597
+ reason: string
1598
+ state: QueueState
1599
+ };
1600
+ declare function applyQueueEvent(state: QueueState, event: QueueEvent, dedupeKey?: string): QueueApply;
1601
+ declare function queueCaughtUp(state: QueueState): boolean;
1602
+ declare const SAFE_REPAIR_MODES: readonly RepairMode[];
1603
+ type RepairDefect = "gap" | "digest_mismatch" | "omission" | "version" | "reorg" | "source_gap";
1604
+ type RepairPlan = {
1605
+ stage_id: string
1606
+ range: CoverageRange
1607
+ mode: RepairMode
1608
+ defect: RepairDefect
1609
+ safe: boolean
1610
+ reason: string
1611
+ };
1612
+ declare function planRepair(input: {
1613
+ stage_id: string
1614
+ range: CoverageRange
1615
+ mode: RepairMode
1616
+ defect: RepairDefect
1617
+ range_safe_proven?: boolean
1618
+ }): RepairPlan;
1619
+ type RepairApplyResult = {
1620
+ ok: true
1621
+ applied: boolean
1622
+ plan: RepairPlan
1623
+ } | {
1624
+ ok: false
1625
+ reason: string
1626
+ plan: RepairPlan
1627
+ };
1628
+ declare function applyRepair(plan: RepairPlan, opts?: {
1629
+ apply?: boolean
1630
+ }): RepairApplyResult;
1631
+ /**
1632
+ * Unified verify targets — library used by CLI (and REST later).
1633
+ * Exit codes match `sl verify`: 0 clean, 1 diverged, 2 unanchored.
1634
+ */
1635
+ declare const VERIFY_EXIT: {
1636
+ readonly CLEAN: 0
1637
+ readonly DIVERGED: 1
1638
+ readonly UNANCHORED: 2
1639
+ };
1640
+ type VerifyExit = (typeof VERIFY_EXIT)[keyof typeof VERIFY_EXIT];
1641
+ type VerifyTarget = {
1642
+ kind: "all"
1643
+ } | {
1644
+ kind: "raw"
1645
+ } | {
1646
+ kind: "decode"
1647
+ name: string
1648
+ } | {
1649
+ kind: "subgraph"
1650
+ name: string
1651
+ };
1652
+ type VerifyMode = "quick" | "deep" | "anchor";
1653
+ declare function parseVerifyTarget(value: string | undefined): VerifyTarget;
1654
+ /** Whether an archive/coverage dataset belongs to this verify target. */
1655
+ declare function datasetMatchesTarget(dataset: string, target: VerifyTarget): boolean;
1656
+ type VerifyReport = {
1657
+ target: VerifyTarget
1658
+ mode: VerifyMode
1659
+ exit: VerifyExit
1660
+ status: "clean" | "diverged" | "unanchored"
1661
+ detail: string
1662
+ };
1663
+ declare function reportVerify(opts: {
1664
+ target: VerifyTarget
1665
+ mode?: VerifyMode
1666
+ anchored?: boolean
1667
+ diverged?: boolean
1668
+ detail?: string
1669
+ }): VerifyReport;
1670
+ export { versionsEqual, topoSort, sparseDigests, sequentialDigests, segmentsSurviveReorg, segmentsOverlap, sealFinalizedRange, runSubgraphCommitSteps, runDecoderCommitSteps, reportVerify, receiptsAfterReorg, receiptRetentionHolds, rangeIsOrdered, rangeDigestOf, queueCaughtUp, proofsAgree, planRepair, planDecoderReceipts, parseVerifyTarget, mergeRanges, manifestsEqual, lookupTransition, isStageKind, isRunStatus, isRetryState, isRepairMode, isNonNegativeInt, isNativeClock, isFailureUnit, isFailureClass, inputDigest, hashEffectManifest, findRangeGaps, finalRowDigest, failureRetentionHolds, failureRangeHolds, expectedAckHeight, evaluateCoverage, emptyQueueState, defaultRetainUntil, deepVerify, datasetMatchesTarget, cursorIsBeforeBlock, cursorIsAfterBlock, cursorHeight, createRunnerState, contiguousThrough, commitSubgraphAdapter, commitDecoderAdapter, canonicalizeMutations, applyRunnerEvent, applyRepair, applyQueueEvent, applyMutations, applyDecoderReceipts, VerifyTarget, VerifyReport, VerifyMode, VerifyExit, VERIFY_EXIT, TransitionRule, SyncScope, SubgraphCommitStep, SubgraphCommitInput, SubgraphAdapterCrash, StageRunView, StageKind, StageEvidence, StageDeclaration, StageCoverage, SourceClock, SealedSegment, SealableReceipt, SealResult, SUBGRAPH_COMMIT_STEPS, STAGE_KINDS, SAFE_REPAIR_MODES, RunnerVersion, RunnerStatus, RunnerState, RunnerResult, RunnerFailure, RunnerEventType, RunnerEvent, RunnerEffect, RunStatus, RowSnapshot, RetryState, RepairPlan, RepairMode, RepairDefect, RepairApplyResult, ReceiptRow, RUN_STATUSES, RUNNER_TRANSITION_TABLE, RUNNER_STATUSES, RUNNER_EVENT_TYPES, RETRY_STATES, REPAIR_MODES, QueueState, QueueStage, QueueEvent, QueueCounters, QueueApply, QUEUE_STAGES, OpenFailure, NativeClock, NATIVE_CLOCKS, FailureUnit, FailureRow, FailureClass, FAILURE_UNITS, FAILURE_RETENTION_DAYS, FAILURE_CLASSES, EvaluatorOptions, EvaluatorInput, EffectOp, EffectMutation, DeepVerifyResult, DecoderCommitStep, DecoderClockResult, DecoderClockReceipt, DecoderClockInput, DecoderClockEvent, DecoderAdapterReceipt, DecoderAdapterFailure, DecoderAdapterCrash, DecoderAdapterCommit, DEFAULT_MAX_RETRIES, DECODER_COMMIT_STEPS, CoverageState, CoverageReport, CoverageRange, CanonicalBlock, COVERAGE_STATES, COVERAGE_REPORT_SCHEMA_VERSION, BootstrapSource };