@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,4 +1,15 @@
1
- import { Kysely } from "kysely";
1
+ import { Kysely as Kysely2 } from "kysely";
2
+ /**
3
+ * The one convention for state machines: states are a const array (mirrored by
4
+ * a DB CHECK), transitions are a table next to the states, and every status
5
+ * write goes through `casTransition`.
6
+ */
7
+ interface Machine<S extends string> {
8
+ readonly states: readonly S[];
9
+ canTransition(from: S, to: S): boolean;
10
+ /** Throws on an illegal move. */
11
+ assert(from: S, to: S): void;
12
+ }
2
13
  import { ColumnType, Generated, Selectable } from "kysely";
3
14
  /**
4
15
  * Coverage-kernel constraints. SQL CHECKs in migration 0116 must stay
@@ -40,6 +51,12 @@ interface SubgraphVerification {
40
51
  /** What stays unproven even at this level, e.g. tx attribution of writes. */
41
52
  unproven: string[];
42
53
  }
54
+ /** Every state `subgraphs.status` can hold; mirrored by the
55
+ * `subgraphs_status_check` CHECK (migration 0189). */
56
+ declare const SUBGRAPH_STATES: readonly ["active", "reindexing", "error"];
57
+ type SubgraphStatus = (typeof SUBGRAPH_STATES)[number];
58
+ /** Why a webhook is paused: the customer did it, or the circuit breaker did. */
59
+ type WebhookPauseReason = "user" | "circuit";
43
60
  interface BlocksTable {
44
61
  height: number;
45
62
  hash: string;
@@ -179,7 +196,7 @@ interface SubgraphsTable {
179
196
  id: Generated<string>;
180
197
  name: string;
181
198
  version: Generated<string>;
182
- status: Generated<string>;
199
+ status: Generated<SubgraphStatus>;
183
200
  definition: Record<string, unknown>;
184
201
  schema_hash: string;
185
202
  handler_path: string;
@@ -196,8 +213,10 @@ interface SubgraphsTable {
196
213
  handler_code: string | null;
197
214
  source_code: string | null;
198
215
  project_id: string | null;
199
- /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
200
- expires_at: Date | null;
216
+ /** Set while the account's metered reads are refused (spend cap, credits).
217
+ * Both columns are set or both null; `last_error` stays for real errors. */
218
+ billing_paused_at: Date | null;
219
+ billing_paused_code: string | null;
201
220
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
202
221
  sparse_probe_targets: unknown | null;
203
222
  /** sha256 over everything that shapes rows (schema, handler bundle,
@@ -211,6 +230,9 @@ interface SubgraphsTable {
211
230
  created_at: Generated<Date>;
212
231
  updated_at: Generated<Date>;
213
232
  }
233
+ /** Mirrored by the CHECK on `contracts.abi_status`. */
234
+ declare const ABI_STATUSES: readonly ["pending", "fetched", "unparseable", "failed"];
235
+ type AbiStatus = (typeof ABI_STATUSES)[number];
214
236
  interface ContractsTable {
215
237
  contract_id: string;
216
238
  deployer: string;
@@ -219,17 +241,23 @@ interface ContractsTable {
219
241
  abi: unknown | null;
220
242
  declared_traits: Generated<string[]>;
221
243
  inferred_standards: Generated<string[]>;
222
- abi_status: Generated<string>;
244
+ abi_status: Generated<AbiStatus>;
223
245
  abi_fetched_at: Date | null;
246
+ /** Failed fetches so far; `failed` re-polls until the registry's attempt cap. */
247
+ abi_attempts: Generated<number>;
248
+ /** When a `failed` row is next due; NULL once attempts are exhausted. */
249
+ abi_next_attempt_at: Date | null;
224
250
  created_at: Generated<Date>;
225
251
  }
252
+ /** The only reasons the runtime records; mirrored by a CHECK on `subgraph_gaps.reason`. */
253
+ type GapReason = "block_missing" | "processing_error";
226
254
  interface SubgraphGapsTable {
227
255
  id: Generated<string>;
228
256
  subgraph_id: string;
229
257
  subgraph_name: string;
230
258
  gap_start: number;
231
259
  gap_end: number;
232
- reason: string;
260
+ reason: GapReason;
233
261
  detected_at: Generated<Date>;
234
262
  resolved_at: Date | null;
235
263
  }
@@ -275,12 +303,13 @@ interface SubgraphOperationsTable {
275
303
  * (those checkpoint on subgraphs.last_processed_block). */
276
304
  cursor_block: string | number | bigint | null;
277
305
  }
306
+ type ApiKeyStatus = "active" | "revoked";
278
307
  interface ApiKeysTable {
279
308
  id: Generated<string>;
280
309
  key_hash: string;
281
310
  key_prefix: string;
282
311
  name: string | null;
283
- status: Generated<string>;
312
+ status: Generated<ApiKeyStatus>;
284
313
  rate_limit: Generated<number>;
285
314
  ip_address: string;
286
315
  account_id: string;
@@ -641,6 +670,10 @@ interface SbtcSettlementsTable {
641
670
  last_checked_at: Generated<Date>;
642
671
  /** Set once, when `settlement_confirmed` first flips true. */
643
672
  confirmed_at: Date | null;
673
+ /** Monotonic stamp from `sbtc_settlements_seq`, retaken each time the sweep
674
+ * becomes confirmed. The webhook scan's watermark. BIGINT: a string at
675
+ * runtime. */
676
+ seq: Generated<number | string>;
644
677
  updated_at: Generated<Date>;
645
678
  }
646
679
  type BnsNameEventTopic = "new-name" | "transfer-name" | "renew-name" | "burn-name" | "new-airdrop";
@@ -760,7 +793,9 @@ interface PendingForkBlocksTable {
760
793
  payload: ColumnType<unknown, unknown, unknown>;
761
794
  received_at: Generated<Date>;
762
795
  }
763
- type ObserverJournalStatus = "received" | "processed" | "failed" | "retried";
796
+ /** Mirrored by the CHECK on `observer_journal.status`. */
797
+ declare const OBSERVER_JOURNAL_STATUSES: readonly ["received", "processed", "failed", "retried", "poisoned", "skipped"];
798
+ type ObserverJournalStatus = (typeof OBSERVER_JOURNAL_STATUSES)[number];
764
799
  /**
765
800
  * Exact observer callback receipt. `raw_body` is immutable evidence; the
766
801
  * processing columns are updated only after the current derived-state write
@@ -795,7 +830,7 @@ interface StageRegistryTable {
795
830
  enabled: Generated<boolean>;
796
831
  created_at: Generated<Date>;
797
832
  }
798
- /** One versioned sweep of a stage. */
833
+ /** One versioned sweep of a stage. Nothing writes this table yet; kept because the receipts and failures tables reference it. */
799
834
  interface StageRunsTable {
800
835
  id: Generated<string>;
801
836
  stage_id: string;
@@ -929,6 +964,7 @@ interface Database {
929
964
  archive_fetches: ArchiveFetchesTable;
930
965
  usage_ledger: UsageLedgerTable;
931
966
  account_balance_alerts: AccountBalanceAlertsTable;
967
+ hosted_stack_state: HostedStackStateTable;
932
968
  webhook_incident_alerts: WebhookIncidentAlertsTable;
933
969
  cli_device_logins: CliDeviceLoginsTable;
934
970
  oauth_clients: OauthClientsTable;
@@ -1012,7 +1048,11 @@ interface UsageLedgerTable {
1012
1048
  * floor to observe past. */
1013
1049
  observed_quantity: string | number | null;
1014
1050
  usd_micros: string | number | bigint;
1051
+ /** True when the whole price was taken; derived from `debited_usd_micros`. */
1015
1052
  debited: Generated<boolean>;
1053
+ /** Amount actually taken from the balance, `0..usd_micros` (bounded the
1054
+ * other way for a negative top-up/grant row). Unpaid = price - this. */
1055
+ debited_usd_micros: Generated<string | number | bigint>;
1016
1056
  source: string;
1017
1057
  /** API key behind a metered read; null for non-read units and older rows. */
1018
1058
  api_key_id: string | null;
@@ -1030,6 +1070,14 @@ interface AccountBalanceAlertsTable {
1030
1070
  sent_2d_at: Date | null;
1031
1071
  sent_stopped_at: Date | null;
1032
1072
  }
1073
+ /** The workload host's report of one account's hosted stack. Written only by
1074
+ * `POST /internal/stack-state`; `reported_at` is the host's observation time. */
1075
+ interface HostedStackStateTable {
1076
+ account_id: string;
1077
+ state: "provisioning" | "running" | "stopped" | "destroyed";
1078
+ stop_reason: "credits" | "cap" | "idle" | null;
1079
+ reported_at: Date;
1080
+ }
1033
1081
  /** Debounce state for the webhook-down email: one row per incident, open
1034
1082
  * while `resolved_at` is null. No preference columns by design. */
1035
1083
  interface WebhookIncidentAlertsTable {
@@ -1167,7 +1215,7 @@ interface SentinelAccountsTable {
1167
1215
  via: "created" | "consent";
1168
1216
  }
1169
1217
  type Contract = Selectable<ContractsTable>;
1170
- type WebhookStatus = "active" | "paused" | "error";
1218
+ type WebhookStatus = "active" | "paused";
1171
1219
  /** Webhooks react to raw chain events matched directly off the Index/Streams
1172
1220
  * clock. `chain` is the only kind since migration 0159 removed subgraph-row
1173
1221
  * webhooks; the column stays as the discriminator. */
@@ -1193,6 +1241,8 @@ interface WebhooksTable {
1193
1241
  concurrency: Generated<number>;
1194
1242
  circuit_failures: Generated<number>;
1195
1243
  circuit_opened_at: Date | null;
1244
+ /** Why a paused webhook is paused. Set exactly while `status` is `paused`. */
1245
+ pause_reason: WebhookPauseReason | null;
1196
1246
  last_delivery_at: Date | null;
1197
1247
  last_success_at: Date | null;
1198
1248
  last_error: string | null;
@@ -1203,6 +1253,10 @@ interface WebhooksTable {
1203
1253
  updated_at: Generated<Date>;
1204
1254
  }
1205
1255
  type OutboxStatus = "pending" | "delivered" | "dead";
1256
+ /** Why a row is dead: retries ran out, or a reorg removed its event. An
1257
+ * orphaned row stays dead; requeueing it would resend an event the chain no
1258
+ * longer contains. */
1259
+ type DeadReason = "exhausted" | "orphaned";
1206
1260
  interface WebhookOutboxTable {
1207
1261
  id: Generated<string>;
1208
1262
  webhook_id: string;
@@ -1232,6 +1286,8 @@ interface WebhookOutboxTable {
1232
1286
  * into an orphaned fork. Null otherwise — delivery failures track their
1233
1287
  * history on `webhooks.last_error`, not per-row. */
1234
1288
  last_error: string | null;
1289
+ /** Set exactly while `status` is `dead`. */
1290
+ dead_reason: DeadReason | null;
1235
1291
  created_at: Generated<Date>;
1236
1292
  }
1237
1293
  type WebhookReplayStatus = "scanning" | "running" | "done" | "failed";
@@ -1281,6 +1337,13 @@ interface TriggerEvaluatorStateTable {
1281
1337
  /** Watermark for the async sBTC settlement-confirmed webhook scan; null until
1282
1338
  * the evaluator fast-forwards it on first run. */
1283
1339
  last_settlement_scan_at: ColumnType<Date | null, Date | null | undefined, Date | null>;
1340
+ /** `sbtc_settlements.seq` watermark. Null until the first settlement row is
1341
+ * scanned; `last_settlement_scan_at` is the forward-only floor until then. */
1342
+ last_settlement_scan_seq: ColumnType<bigint | null, bigint | number | null | undefined, bigint | number | null>;
1343
+ /** Counts reorg rewinds. The evaluator checks it under the row lock in the
1344
+ * transaction that emits a batch and advances the cursor, so a reorg that
1345
+ * lands mid-tick rolls the batch back. */
1346
+ reorg_generation: ColumnType<bigint, bigint | number | undefined, bigint | number>;
1284
1347
  /** Streams cursor (`<block_height>:<event_index>`) for the Bitcoin (Runes)
1285
1348
  * chain-trigger evaluator (plan 060) — a separate clock from
1286
1349
  * `last_processed_block` (Stacks). Null until the evaluator fast-forwards
@@ -1413,11 +1476,6 @@ interface FeedbackTicketsTable {
1413
1476
  created_at: Generated<Date>;
1414
1477
  }
1415
1478
  /**
1416
- * Contract registry queries — backing for trait-based discovery. Populated from
1417
- * contract deploys; ABI fetched async; standards inferred by static analysis.
1418
- */
1419
- type AbiStatus = "pending" | "fetched" | "failed" | "unparseable";
1420
- /**
1421
1479
  * Record a contract deploy (idempotent). ABI is fetched separately + async.
1422
1480
  * On conflict the row is re-canonicalized rather than skipped: after a reorg
1423
1481
  * flips contracts non-canonical (markContractsNonCanonical), discovery
@@ -1425,35 +1483,57 @@ type AbiStatus = "pending" | "fetched" | "failed" | "unparseable";
1425
1483
  * restores `canonical` with the fork's height. ABI fields are untouched, so a
1426
1484
  * previously fetched ABI survives the round trip.
1427
1485
  */
1428
- declare function recordContractDeploy(db: Kysely<Database>, row: {
1486
+ declare function recordContractDeploy(db: Kysely2<Database>, row: {
1429
1487
  contractId: string
1430
1488
  deployer: string
1431
1489
  blockHeight: number
1432
1490
  }): Promise<void>;
1433
- /** Store a fetched ABI + the traits/standards derived from it. */
1434
- declare function setContractAbi(db: Kysely<Database>, contractId: string, data: {
1491
+ /**
1492
+ * ABI fetch lifecycle. `failed` is retryable: a transient RPC error must not
1493
+ * strand a contract. Each failure backs off (see {@link abiRetryDelayMs}) and
1494
+ * after {@link ABI_MAX_ATTEMPTS} failures the row stays `failed` for good.
1495
+ */
1496
+ declare const ABI_MACHINE: Machine<AbiStatus>;
1497
+ declare const ABI_MAX_ATTEMPTS = 5;
1498
+ /** Wait before the next fetch after `attempts` failures: 30 min, 1 h, 2 h, 4 h. */
1499
+ declare function abiRetryDelayMs(attempts: number): number;
1500
+ /**
1501
+ * Store a fetched ABI + the traits/standards derived from it. Moves a
1502
+ * `pending` or retried `failed` row only; `null` means another writer got
1503
+ * there first.
1504
+ */
1505
+ declare function setContractAbi(db: Kysely2<Database>, contractId: string, data: {
1435
1506
  abi: unknown | null
1436
- status: AbiStatus
1507
+ status: Extract<AbiStatus, "fetched" | "unparseable">
1437
1508
  declaredTraits?: string[]
1438
1509
  inferredStandards?: string[]
1439
- }): Promise<void>;
1510
+ }): Promise<boolean>;
1511
+ /**
1512
+ * Record a failed ABI fetch: bump `abi_attempts` and schedule the retry, or
1513
+ * stop scheduling once attempts run out.
1514
+ */
1515
+ declare function recordAbiFetchFailure(db: Kysely2<Database>, contractId: string, now?: Date): Promise<boolean>;
1440
1516
  /**
1441
1517
  * Re-classification: replace a contract's inferred standards. Bumps
1442
1518
  * `abi_fetched_at`, which /v1/contracts serves as `classified_at` (hosted
1443
1519
  * tenants poll `classified_after`), so changed rows reach them.
1444
1520
  */
1445
- declare function setInferredStandards(db: Kysely<Database>, contractId: string, inferred: string[]): Promise<void>;
1521
+ declare function setInferredStandards(db: Kysely2<Database>, contractId: string, inferred: string[]): Promise<void>;
1446
1522
  /**
1447
1523
  * A contract reorged out and not (yet) redeployed on the new fork is not on
1448
1524
  * the canonical chain — serve 404, not its stale row/ABI. Matches every other
1449
1525
  * contracts read (list, trait scope, pending-ABI), which already filter.
1450
1526
  */
1451
- declare function getContract(db: Kysely<Database>, contractId: string): Promise<Contract | null>;
1452
- /** Contracts still awaiting an ABI fetch (drives the fetch/backfill worker). */
1453
- declare function listContractsPendingAbi(db: Kysely<Database>, limit?: number): Promise<Contract[]>;
1527
+ declare function getContract(db: Kysely2<Database>, contractId: string): Promise<Contract | null>;
1528
+ /**
1529
+ * Contracts awaiting an ABI fetch (drives the fetch/backfill worker): `pending`
1530
+ * first, then `failed` rows that are due for a retry. `limit` bounds both
1531
+ * together, so retries never out-poll the node faster than new deploys.
1532
+ */
1533
+ declare function listContractsPendingAbi(db: Kysely2<Database>, limit?: number, now?: Date): Promise<Contract[]>;
1454
1534
  type Conformance = "declared" | "inferred" | "any";
1455
1535
  /** Discovery: contracts matching a trait/standard, by conformance source. */
1456
- declare function listContractsByTrait(db: Kysely<Database>, trait: string, opts?: {
1536
+ declare function listContractsByTrait(db: Kysely2<Database>, trait: string, opts?: {
1457
1537
  conformance?: Conformance
1458
1538
  limit?: number
1459
1539
  afterId?: string
@@ -1465,12 +1545,12 @@ declare function listContractsByTrait(db: Kysely<Database>, trait: string, opts?
1465
1545
  * deploy block ≤ `asOfBlock`. Lets a trait-scoped subgraph reindex a token's
1466
1546
  * full history even if classification lagged its deploy.
1467
1547
  */
1468
- declare function resolveTraitContractIds(db: Kysely<Database>, trait: string, asOfBlock: number): Promise<string[]>;
1548
+ declare function resolveTraitContractIds(db: Kysely2<Database>, trait: string, asOfBlock: number): Promise<string[]>;
1469
1549
  /**
1470
1550
  * Reorg: flip contracts deployed at/above a reorged height to non-canonical.
1471
1551
  * Called from the indexer's handleReorg tx. Recovery is eventual: discovery
1472
1552
  * (discoverDeploys) re-selects non-canonical ids whose deploy tx exists on
1473
1553
  * the new fork and recordContractDeploy re-canonicalizes them.
1474
1554
  */
1475
- declare function markContractsNonCanonical(db: Kysely<Database>, fromBlockHeight: number): Promise<void>;
1476
- export { AbiStatus, Conformance, getContract, listContractsByTrait, listContractsPendingAbi, markContractsNonCanonical, recordContractDeploy, resolveTraitContractIds, setContractAbi, setInferredStandards };
1555
+ declare function markContractsNonCanonical(db: Kysely2<Database>, fromBlockHeight: number): Promise<void>;
1556
+ export { ABI_MACHINE, ABI_MAX_ATTEMPTS, AbiStatus, Conformance, abiRetryDelayMs, getContract, listContractsByTrait, listContractsPendingAbi, markContractsNonCanonical, recordAbiFetchFailure, recordContractDeploy, resolveTraitContractIds, setContractAbi, setInferredStandards };
@@ -1,5 +1,5 @@
1
1
  // src/db/queries/contracts.ts
2
- import { sql as sql2 } from "kysely";
2
+ import { sql as sql3 } from "kysely";
3
3
 
4
4
  // src/db/jsonb.ts
5
5
  import { sql } from "kysely";
@@ -18,6 +18,54 @@ function parseJsonb(value) {
18
18
  return value ?? {};
19
19
  }
20
20
 
21
+ // src/db/transition.ts
22
+ import { sql as sql2 } from "kysely";
23
+ function defineMachine(def) {
24
+ const canTransition = (from, to) => def.transitions[from]?.includes(to) ?? false;
25
+ return {
26
+ states: def.states,
27
+ canTransition,
28
+ assert(from, to) {
29
+ if (!canTransition(from, to)) {
30
+ throw new Error(`illegal transition ${from} -> ${to}`);
31
+ }
32
+ }
33
+ };
34
+ }
35
+ async function casTransition(db, t) {
36
+ const column = sql2.id(t.column ?? "status");
37
+ const assignments = [sql2`${column} = ${t.to}`];
38
+ if (t.stampUpdatedAt !== false)
39
+ assignments.push(sql2`updated_at = now()`);
40
+ for (const [key, value] of Object.entries(t.set ?? {})) {
41
+ assignments.push(sql2`${sql2.id(key)} = ${value}`);
42
+ }
43
+ const returning = t.returning ? sql2.join(t.returning.map((c) => sql2.id(c))) : sql2.raw("*");
44
+ const { rows } = await sql2`
45
+ UPDATE ${sql2.table(t.table)}
46
+ SET ${sql2.join(assignments)}
47
+ WHERE ${sql2.id(t.key ?? "id")} = ${t.id} AND ${column} = ANY(${sql2.val([...t.from])})
48
+ RETURNING ${returning}
49
+ `.execute(db);
50
+ return rows[0] ?? null;
51
+ }
52
+
53
+ // src/db/types.ts
54
+ var ABI_STATUSES = [
55
+ "pending",
56
+ "fetched",
57
+ "unparseable",
58
+ "failed"
59
+ ];
60
+ var OBSERVER_JOURNAL_STATUSES = [
61
+ "received",
62
+ "processed",
63
+ "failed",
64
+ "retried",
65
+ "poisoned",
66
+ "skipped"
67
+ ];
68
+
21
69
  // src/db/queries/contracts.ts
22
70
  async function recordContractDeploy(db, row) {
23
71
  await db.insertInto("contracts").values({
@@ -30,14 +78,55 @@ async function recordContractDeploy(db, row) {
30
78
  canonical: true
31
79
  })).execute();
32
80
  }
81
+ var ABI_MACHINE = defineMachine({
82
+ states: ABI_STATUSES,
83
+ transitions: {
84
+ pending: ["fetched", "unparseable", "failed"],
85
+ failed: ["fetched", "unparseable", "failed"]
86
+ }
87
+ });
88
+ var ABI_MAX_ATTEMPTS = 5;
89
+ var ABI_RETRY_BASE_MS = 15 * 60 * 1000;
90
+ function abiRetryDelayMs(attempts) {
91
+ return ABI_RETRY_BASE_MS * 2 ** Math.max(1, attempts);
92
+ }
33
93
  async function setContractAbi(db, contractId, data) {
34
- await db.updateTable("contracts").set({
35
- abi: data.abi == null ? null : jsonb(data.abi),
36
- abi_status: data.status,
37
- abi_fetched_at: new Date,
38
- ...data.declaredTraits ? { declared_traits: data.declaredTraits } : {},
39
- ...data.inferredStandards ? { inferred_standards: data.inferredStandards } : {}
40
- }).where("contract_id", "=", contractId).execute();
94
+ const row = await casTransition(db, {
95
+ table: "contracts",
96
+ key: "contract_id",
97
+ column: "abi_status",
98
+ id: contractId,
99
+ from: ["pending", "failed"],
100
+ to: data.status,
101
+ stampUpdatedAt: false,
102
+ set: {
103
+ abi: data.abi == null ? null : jsonb(data.abi),
104
+ abi_fetched_at: new Date,
105
+ ...data.declaredTraits ? { declared_traits: data.declaredTraits } : {},
106
+ ...data.inferredStandards ? { inferred_standards: data.inferredStandards } : {}
107
+ }
108
+ });
109
+ return row !== null;
110
+ }
111
+ async function recordAbiFetchFailure(db, contractId, now = new Date) {
112
+ const current = await db.selectFrom("contracts").select("abi_attempts").where("contract_id", "=", contractId).executeTakeFirst();
113
+ if (!current)
114
+ return false;
115
+ const attempts = Number(current.abi_attempts) + 1;
116
+ const row = await casTransition(db, {
117
+ table: "contracts",
118
+ key: "contract_id",
119
+ column: "abi_status",
120
+ id: contractId,
121
+ from: ["pending", "failed"],
122
+ to: "failed",
123
+ stampUpdatedAt: false,
124
+ set: {
125
+ abi_attempts: attempts,
126
+ abi_next_attempt_at: attempts >= ABI_MAX_ATTEMPTS ? null : new Date(now.getTime() + abiRetryDelayMs(attempts))
127
+ }
128
+ });
129
+ return row !== null;
41
130
  }
42
131
  async function setInferredStandards(db, contractId, inferred) {
43
132
  await db.updateTable("contracts").set({ inferred_standards: inferred, abi_fetched_at: new Date }).where("contract_id", "=", contractId).execute();
@@ -45,18 +134,25 @@ async function setInferredStandards(db, contractId, inferred) {
45
134
  async function getContract(db, contractId) {
46
135
  return await db.selectFrom("contracts").selectAll().where("contract_id", "=", contractId).where("canonical", "=", true).executeTakeFirst() ?? null;
47
136
  }
48
- async function listContractsPendingAbi(db, limit = 100) {
49
- return db.selectFrom("contracts").selectAll().where("abi_status", "=", "pending").where("canonical", "=", true).orderBy("block_height", "asc").limit(limit).execute();
137
+ async function listContractsPendingAbi(db, limit = 100, now = new Date) {
138
+ return db.selectFrom("contracts").selectAll().where("canonical", "=", true).where((eb) => eb.or([
139
+ eb("abi_status", "=", "pending"),
140
+ eb.and([
141
+ eb("abi_status", "=", "failed"),
142
+ eb("abi_attempts", "<", ABI_MAX_ATTEMPTS),
143
+ eb("abi_next_attempt_at", "<=", now)
144
+ ])
145
+ ])).orderBy(sql3`(abi_status = 'pending')`, "desc").orderBy("block_height", "asc").limit(limit).execute();
50
146
  }
51
147
  async function listContractsByTrait(db, trait, opts = {}) {
52
148
  const conformance = opts.conformance ?? "any";
53
149
  let q = db.selectFrom("contracts").selectAll().where("canonical", "=", true);
54
150
  if (conformance === "declared") {
55
- q = q.where(sql2`${sql2.ref("declared_traits")} @> ARRAY[${trait}]`);
151
+ q = q.where(sql3`${sql3.ref("declared_traits")} @> ARRAY[${trait}]`);
56
152
  } else if (conformance === "inferred") {
57
- q = q.where(sql2`${sql2.ref("inferred_standards")} @> ARRAY[${trait}]`);
153
+ q = q.where(sql3`${sql3.ref("inferred_standards")} @> ARRAY[${trait}]`);
58
154
  } else {
59
- q = q.where(sql2`(${sql2.ref("declared_traits")} @> ARRAY[${trait}] OR ${sql2.ref("inferred_standards")} @> ARRAY[${trait}])`);
155
+ q = q.where(sql3`(${sql3.ref("declared_traits")} @> ARRAY[${trait}] OR ${sql3.ref("inferred_standards")} @> ARRAY[${trait}])`);
60
156
  }
61
157
  if (opts.afterId)
62
158
  q = q.where("contract_id", ">", opts.afterId);
@@ -66,22 +162,26 @@ async function listContractsByTrait(db, trait, opts = {}) {
66
162
  return q.orderBy("contract_id", "asc").limit(opts.limit ?? 100).execute();
67
163
  }
68
164
  async function resolveTraitContractIds(db, trait, asOfBlock) {
69
- const rows = await db.selectFrom("contracts").select("contract_id").where("canonical", "=", true).where("block_height", "<=", asOfBlock).where(sql2`(${sql2.ref("declared_traits")} @> ARRAY[${trait}] OR ${sql2.ref("inferred_standards")} @> ARRAY[${trait}])`).execute();
165
+ const rows = await db.selectFrom("contracts").select("contract_id").where("canonical", "=", true).where("block_height", "<=", asOfBlock).where(sql3`(${sql3.ref("declared_traits")} @> ARRAY[${trait}] OR ${sql3.ref("inferred_standards")} @> ARRAY[${trait}])`).execute();
70
166
  return rows.map((r) => r.contract_id);
71
167
  }
72
168
  async function markContractsNonCanonical(db, fromBlockHeight) {
73
169
  await db.updateTable("contracts").set({ canonical: false }).where("block_height", ">=", fromBlockHeight).execute();
74
170
  }
75
171
  export {
172
+ ABI_MACHINE,
173
+ ABI_MAX_ATTEMPTS,
174
+ abiRetryDelayMs,
76
175
  getContract,
77
176
  listContractsByTrait,
78
177
  listContractsPendingAbi,
79
178
  markContractsNonCanonical,
179
+ recordAbiFetchFailure,
80
180
  recordContractDeploy,
81
181
  resolveTraitContractIds,
82
182
  setContractAbi,
83
183
  setInferredStandards
84
184
  };
85
185
 
86
- //# debugId=F52EB3C4FFD0BA8464756E2164756E21
186
+ //# debugId=722EB7AB7475218564756E2164756E21
87
187
  //# sourceMappingURL=contracts.js.map