@secondlayer/shared 15.3.4 → 15.4.1

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 (61) hide show
  1. package/dist/src/archive/range-digest.d.ts +2 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +2 -0
  3. package/dist/src/classify/index.js +16 -2
  4. package/dist/src/classify/index.js.map +3 -3
  5. package/dist/src/coverage/index.d.ts +2 -0
  6. package/dist/src/coverage/index.js +35 -1
  7. package/dist/src/coverage/index.js.map +3 -3
  8. package/dist/src/crypto/secondlayer-webhook.js +16 -2
  9. package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
  10. package/dist/src/crypto/secrets.d.ts +8 -2
  11. package/dist/src/crypto/secrets.js +21 -7
  12. package/dist/src/crypto/secrets.js.map +3 -3
  13. package/dist/src/db/index.d.ts +10 -1
  14. package/dist/src/db/index.js +29 -7
  15. package/dist/src/db/index.js.map +5 -5
  16. package/dist/src/db/queries/chain-reorgs.d.ts +2 -0
  17. package/dist/src/db/queries/chain-reorgs.js +27 -7
  18. package/dist/src/db/queries/chain-reorgs.js.map +5 -5
  19. package/dist/src/db/queries/contracts.d.ts +13 -1
  20. package/dist/src/db/queries/contracts.js +13 -1
  21. package/dist/src/db/queries/contracts.js.map +4 -4
  22. package/dist/src/db/queries/instance.d.ts +28 -5
  23. package/dist/src/db/queries/instance.js +224 -14
  24. package/dist/src/db/queries/instance.js.map +6 -5
  25. package/dist/src/db/queries/integrity.d.ts +15 -1
  26. package/dist/src/db/queries/integrity.js +244 -14
  27. package/dist/src/db/queries/integrity.js.map +7 -6
  28. package/dist/src/db/queries/subgraph-gaps.d.ts +2 -0
  29. package/dist/src/db/queries/subgraph-operations.d.ts +2 -0
  30. package/dist/src/db/queries/subgraphs.d.ts +2 -0
  31. package/dist/src/db/queries/sync-scope.d.ts +2 -0
  32. package/dist/src/db/queries/webhook-replays.d.ts +2 -0
  33. package/dist/src/db/queries/webhook-replays.js +20 -7
  34. package/dist/src/db/queries/webhook-replays.js.map +3 -3
  35. package/dist/src/db/queries/webhooks.d.ts +2 -0
  36. package/dist/src/db/queries/webhooks.js +20 -7
  37. package/dist/src/db/queries/webhooks.js.map +3 -3
  38. package/dist/src/db/schema.d.ts +2 -0
  39. package/dist/src/db/schema.js.map +2 -2
  40. package/dist/src/email/index.js +16 -2
  41. package/dist/src/email/index.js.map +3 -3
  42. package/dist/src/env.d.ts +8 -1
  43. package/dist/src/env.js +18 -3
  44. package/dist/src/env.js.map +3 -3
  45. package/dist/src/index.d.ts +54 -1
  46. package/dist/src/index.js +68 -7
  47. package/dist/src/index.js.map +7 -7
  48. package/dist/src/insights/index.d.ts +2 -0
  49. package/dist/src/insights/index.js +16 -2
  50. package/dist/src/insights/index.js.map +3 -3
  51. package/dist/src/leader.js +915 -27
  52. package/dist/src/leader.js.map +13 -6
  53. package/dist/src/logger.js +16 -2
  54. package/dist/src/logger.js.map +3 -3
  55. package/dist/src/node/local-client.d.ts +2 -0
  56. package/dist/src/node/tx-summary.js +16 -2
  57. package/dist/src/node/tx-summary.js.map +3 -3
  58. package/dist/src/queue/listener.js +27 -7
  59. package/dist/src/queue/listener.js.map +5 -5
  60. package/migrations/0202_instances_secrets_key_canary.ts +36 -0
  61. package/package.json +2 -2
@@ -1,25 +1,10 @@
1
1
  // src/leader.ts
2
- import postgres from "postgres";
2
+ import postgres2 from "postgres";
3
3
 
4
- // src/db/tls.ts
5
- function tlsOptions(url) {
6
- let parsed = null;
7
- try {
8
- parsed = new URL(url);
9
- } catch {}
10
- if (parsed?.searchParams.has("sslmode") || parsed?.searchParams.has("ssl")) {
11
- return {};
12
- }
13
- const host = parsed?.hostname ?? "";
14
- const isLocal = host === "localhost" || host === "127.0.0.1" || !host.includes(".");
15
- if (isLocal)
16
- return {};
17
- return {
18
- ssl: {
19
- rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0"
20
- }
21
- };
22
- }
4
+ // src/db/index.ts
5
+ import { Kysely } from "kysely";
6
+ import { PostgresJSDialect } from "kysely-postgres-js";
7
+ import postgres from "postgres";
23
8
 
24
9
  // src/env.ts
25
10
  import { z } from "zod";
@@ -59,11 +44,25 @@ function getEnv() {
59
44
  } else if (result.data.NETWORK) {
60
45
  enabledNetworks = [result.data.NETWORK];
61
46
  } else {
62
- enabledNetworks = ["mainnet"];
47
+ const named = stacksNetwork();
48
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
63
49
  }
64
50
  cachedEnv = { ...result.data, enabledNetworks };
65
51
  return cachedEnv;
66
52
  }
53
+ var warnedNetworkFallback = false;
54
+ function stacksNetwork(env = process.env) {
55
+ if (env.STACKS_NETWORK)
56
+ return env.STACKS_NETWORK;
57
+ if (env.NETWORK) {
58
+ if (!warnedNetworkFallback) {
59
+ warnedNetworkFallback = true;
60
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
61
+ }
62
+ return env.NETWORK;
63
+ }
64
+ return "mainnet";
65
+ }
67
66
  function isProductionEnv() {
68
67
  return process.env["NODE_ENV"] === "production";
69
68
  }
@@ -151,18 +150,907 @@ class Logger {
151
150
  }
152
151
  var logger = new Logger;
153
152
 
153
+ // src/mode.ts
154
+ var VALID_MODES = [
155
+ "oss",
156
+ "platform",
157
+ "archive"
158
+ ];
159
+ function declaredMode() {
160
+ const raw = process.env.INSTANCE_MODE?.trim().toLowerCase();
161
+ if (raw && VALID_MODES.includes(raw)) {
162
+ return raw;
163
+ }
164
+ return "oss";
165
+ }
166
+ function getInstanceMode() {
167
+ const declared = declaredMode();
168
+ return declared === "archive" ? "platform" : declared;
169
+ }
170
+ function getDeclaredInstanceMode() {
171
+ return declaredMode();
172
+ }
173
+ function isMeteredReads() {
174
+ const override = process.env.METERED_READS?.trim().toLowerCase();
175
+ if (override === "true")
176
+ return true;
177
+ if (override === "false")
178
+ return false;
179
+ return getInstanceMode() === "platform";
180
+ }
181
+ function isPlatformMode() {
182
+ return getInstanceMode() === "platform";
183
+ }
184
+ function isOssMode() {
185
+ return getInstanceMode() === "oss";
186
+ }
187
+ function isTestnetWebhookStack() {
188
+ return process.env.TESTNET_WEBHOOK_STACK === "true";
189
+ }
190
+ function isWebhookAccountScoped() {
191
+ return isPlatformMode() || isTestnetWebhookStack();
192
+ }
193
+
194
+ // src/db/tls.ts
195
+ function tlsOptions(url) {
196
+ let parsed = null;
197
+ try {
198
+ parsed = new URL(url);
199
+ } catch {}
200
+ if (parsed?.searchParams.has("sslmode") || parsed?.searchParams.has("ssl")) {
201
+ return {};
202
+ }
203
+ const host = parsed?.hostname ?? "";
204
+ const isLocal = host === "localhost" || host === "127.0.0.1" || !host.includes(".");
205
+ if (isLocal)
206
+ return {};
207
+ return {
208
+ ssl: {
209
+ rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0"
210
+ }
211
+ };
212
+ }
213
+
214
+ // src/db/index.ts
215
+ import { sql as sql2 } from "kysely";
216
+
217
+ // src/db/types.ts
218
+ var ABI_STATUSES = [
219
+ "pending",
220
+ "fetched",
221
+ "unparseable",
222
+ "failed"
223
+ ];
224
+ var OBSERVER_JOURNAL_STATUSES = [
225
+ "received",
226
+ "processed",
227
+ "failed",
228
+ "retried",
229
+ "poisoned",
230
+ "skipped"
231
+ ];
232
+ // src/db/source-read-columns.ts
233
+ var SOURCE_READ_COLUMNS = {
234
+ blocks: [
235
+ "burn_block_hash",
236
+ "burn_block_height",
237
+ "canonical",
238
+ "hash",
239
+ "height",
240
+ "parent_hash",
241
+ "timestamp"
242
+ ],
243
+ decoded_events: [
244
+ "amount",
245
+ "asset_identifier",
246
+ "block_height",
247
+ "canonical",
248
+ "contract_id",
249
+ "cursor",
250
+ "event_index",
251
+ "event_type",
252
+ "memo",
253
+ "payload",
254
+ "recipient",
255
+ "sender",
256
+ "tx_id",
257
+ "tx_index",
258
+ "value"
259
+ ],
260
+ transactions: [
261
+ "block_height",
262
+ "contract_id",
263
+ "function_args",
264
+ "function_name",
265
+ "raw_result",
266
+ "raw_tx",
267
+ "sender",
268
+ "status",
269
+ "tx_id",
270
+ "tx_index",
271
+ "type"
272
+ ],
273
+ mempool_transactions: [
274
+ "contract_id",
275
+ "function_args",
276
+ "function_name",
277
+ "raw_tx",
278
+ "received_at",
279
+ "sender",
280
+ "seq",
281
+ "tx_id",
282
+ "type"
283
+ ],
284
+ pox4_calls: [
285
+ "aggregated_amount_ustx",
286
+ "aggregated_signer_index",
287
+ "amount_ustx",
288
+ "auth_allowed",
289
+ "auth_id",
290
+ "auth_period",
291
+ "auth_topic",
292
+ "block_height",
293
+ "block_time",
294
+ "burn_block_height",
295
+ "caller",
296
+ "canonical",
297
+ "cursor",
298
+ "delegate_to",
299
+ "end_cycle",
300
+ "function_name",
301
+ "lock_period",
302
+ "max_amount",
303
+ "pox_addr_btc",
304
+ "pox_addr_hashbytes",
305
+ "pox_addr_version",
306
+ "result_ok",
307
+ "reward_cycle",
308
+ "signer_key",
309
+ "signer_signature",
310
+ "source_cursor",
311
+ "stacker",
312
+ "start_cycle",
313
+ "tx_id",
314
+ "tx_index"
315
+ ],
316
+ pox5_events: [
317
+ "amount_sats",
318
+ "amount_ustx",
319
+ "block_height",
320
+ "block_time",
321
+ "bond_index",
322
+ "canonical",
323
+ "cursor",
324
+ "data",
325
+ "event_index",
326
+ "first_reward_cycle",
327
+ "is_l1_lock",
328
+ "reward_cycle",
329
+ "signer",
330
+ "signer_key",
331
+ "signer_manager",
332
+ "staker",
333
+ "topic",
334
+ "tx_id",
335
+ "tx_index",
336
+ "unlock_burn_height",
337
+ "unlock_cycle"
338
+ ],
339
+ sbtc_events: [
340
+ "amount",
341
+ "bitcoin_txid",
342
+ "block_height",
343
+ "block_time",
344
+ "burn_hash",
345
+ "burn_height",
346
+ "canonical",
347
+ "cursor",
348
+ "event_index",
349
+ "fee",
350
+ "governance_contract_type",
351
+ "governance_new_contract",
352
+ "max_fee",
353
+ "output_index",
354
+ "recipient_btc_hashbytes",
355
+ "recipient_btc_version",
356
+ "request_id",
357
+ "sender",
358
+ "signer_address",
359
+ "signer_aggregate_pubkey",
360
+ "signer_bitmap",
361
+ "signer_keys_count",
362
+ "signer_threshold",
363
+ "sweep_txid",
364
+ "topic",
365
+ "tx_id",
366
+ "tx_index"
367
+ ],
368
+ sbtc_token_events: [
369
+ "amount",
370
+ "block_height",
371
+ "block_time",
372
+ "canonical",
373
+ "cursor",
374
+ "event_index",
375
+ "event_type",
376
+ "memo",
377
+ "recipient",
378
+ "sender",
379
+ "tx_id",
380
+ "tx_index"
381
+ ],
382
+ bns_name_events: [
383
+ "block_height",
384
+ "block_time",
385
+ "bns_id",
386
+ "canonical",
387
+ "cursor",
388
+ "event_index",
389
+ "fqn",
390
+ "hashed_salted_fqn_preorder",
391
+ "imported_at",
392
+ "name",
393
+ "namespace",
394
+ "owner",
395
+ "preordered_by",
396
+ "registered_at",
397
+ "renewal_height",
398
+ "stx_burn",
399
+ "topic",
400
+ "tx_id",
401
+ "tx_index"
402
+ ],
403
+ bns_namespace_events: [
404
+ "block_height",
405
+ "block_time",
406
+ "canonical",
407
+ "cursor",
408
+ "event_index",
409
+ "launched_at",
410
+ "lifetime",
411
+ "manager",
412
+ "manager_frozen",
413
+ "manager_transfers_disabled",
414
+ "namespace",
415
+ "price_frozen",
416
+ "price_function",
417
+ "revealed_at",
418
+ "status",
419
+ "tx_id",
420
+ "tx_index"
421
+ ],
422
+ bns_marketplace_events: [
423
+ "action",
424
+ "block_height",
425
+ "block_time",
426
+ "bns_id",
427
+ "canonical",
428
+ "commission",
429
+ "cursor",
430
+ "event_index",
431
+ "price_ustx",
432
+ "tx_id",
433
+ "tx_index"
434
+ ],
435
+ bns_names: [
436
+ "bns_id",
437
+ "fqn",
438
+ "last_event_at",
439
+ "last_event_cursor",
440
+ "name",
441
+ "namespace",
442
+ "owner",
443
+ "registered_at",
444
+ "renewal_height"
445
+ ],
446
+ bns_namespaces: [
447
+ "last_event_at",
448
+ "last_event_cursor",
449
+ "launched_at",
450
+ "lifetime",
451
+ "manager",
452
+ "manager_frozen",
453
+ "name_count",
454
+ "namespace",
455
+ "price_frozen"
456
+ ],
457
+ burn_block_rewards: [
458
+ "amount_sats",
459
+ "burn_amount",
460
+ "burn_block_hash",
461
+ "burn_block_height",
462
+ "cursor",
463
+ "recipient_btc",
464
+ "reward_index"
465
+ ],
466
+ burn_block_reward_slots: [
467
+ "burn_block_hash",
468
+ "burn_block_height",
469
+ "cursor",
470
+ "holder_btc",
471
+ "slot_index"
472
+ ],
473
+ events: ["block_height", "data", "event_index", "tx_id", "type"],
474
+ chain_reorgs: ["detected_at"]
475
+ };
476
+ var SOURCE_READ_TYPES = {
477
+ blocks: {
478
+ burn_block_hash: { type: "text", nullable: true },
479
+ burn_block_height: { type: "int" },
480
+ canonical: { type: "boolean" },
481
+ hash: { type: "text" },
482
+ height: { type: "int" },
483
+ parent_hash: { type: "text" },
484
+ timestamp: { type: "int" }
485
+ },
486
+ decoded_events: {
487
+ amount: { type: "text", nullable: true },
488
+ asset_identifier: { type: "text", nullable: true },
489
+ block_height: { type: "int" },
490
+ canonical: { type: "boolean" },
491
+ contract_id: { type: "text", nullable: true },
492
+ cursor: { type: "text" },
493
+ event_index: { type: "int" },
494
+ event_type: { type: "text" },
495
+ memo: { type: "text", nullable: true },
496
+ payload: { type: "jsonb", nullable: true },
497
+ recipient: { type: "text", nullable: true },
498
+ sender: { type: "text", nullable: true },
499
+ tx_id: { type: "text" },
500
+ tx_index: { type: "int" },
501
+ value: { type: "text", nullable: true }
502
+ },
503
+ transactions: {
504
+ block_height: { type: "int" },
505
+ contract_id: { type: "text", nullable: true },
506
+ function_args: { type: "jsonb", nullable: true },
507
+ function_name: { type: "text", nullable: true },
508
+ raw_result: { type: "text", nullable: true },
509
+ raw_tx: { type: "text" },
510
+ sender: { type: "text" },
511
+ status: { type: "text" },
512
+ tx_id: { type: "text" },
513
+ tx_index: { type: "int" },
514
+ type: { type: "text" }
515
+ },
516
+ mempool_transactions: {
517
+ contract_id: { type: "text", nullable: true },
518
+ function_args: { type: "jsonb", nullable: true },
519
+ function_name: { type: "text", nullable: true },
520
+ raw_tx: { type: "text" },
521
+ received_at: { type: "timestamp" },
522
+ sender: { type: "text" },
523
+ seq: { type: "text" },
524
+ tx_id: { type: "text" },
525
+ type: { type: "text" }
526
+ },
527
+ pox4_calls: {
528
+ aggregated_amount_ustx: { type: "text", nullable: true },
529
+ aggregated_signer_index: { type: "int", nullable: true },
530
+ amount_ustx: { type: "text", nullable: true },
531
+ auth_allowed: { type: "boolean", nullable: true },
532
+ auth_id: { type: "text", nullable: true },
533
+ auth_period: { type: "int", nullable: true },
534
+ auth_topic: { type: "text", nullable: true },
535
+ block_height: { type: "int" },
536
+ block_time: { type: "timestamp" },
537
+ burn_block_height: { type: "int" },
538
+ caller: { type: "text" },
539
+ canonical: { type: "boolean" },
540
+ cursor: { type: "text" },
541
+ delegate_to: { type: "text", nullable: true },
542
+ end_cycle: { type: "int", nullable: true },
543
+ function_name: { type: "text" },
544
+ lock_period: { type: "int", nullable: true },
545
+ max_amount: { type: "text", nullable: true },
546
+ pox_addr_btc: { type: "text", nullable: true },
547
+ pox_addr_hashbytes: { type: "text", nullable: true },
548
+ pox_addr_version: { type: "int", nullable: true },
549
+ result_ok: { type: "boolean" },
550
+ reward_cycle: { type: "int", nullable: true },
551
+ signer_key: { type: "text", nullable: true },
552
+ signer_signature: { type: "text", nullable: true },
553
+ source_cursor: { type: "text" },
554
+ stacker: { type: "text", nullable: true },
555
+ start_cycle: { type: "int", nullable: true },
556
+ tx_id: { type: "text" },
557
+ tx_index: { type: "int" }
558
+ },
559
+ pox5_events: {
560
+ amount_sats: { type: "text", nullable: true },
561
+ amount_ustx: { type: "text", nullable: true },
562
+ block_height: { type: "int" },
563
+ block_time: { type: "timestamp" },
564
+ bond_index: { type: "int", nullable: true },
565
+ canonical: { type: "boolean" },
566
+ cursor: { type: "text" },
567
+ data: { type: "jsonb", nullable: true },
568
+ event_index: { type: "int" },
569
+ first_reward_cycle: { type: "int", nullable: true },
570
+ is_l1_lock: { type: "boolean", nullable: true },
571
+ reward_cycle: { type: "int", nullable: true },
572
+ signer: { type: "text", nullable: true },
573
+ signer_key: { type: "text", nullable: true },
574
+ signer_manager: { type: "text", nullable: true },
575
+ staker: { type: "text", nullable: true },
576
+ topic: { type: "text" },
577
+ tx_id: { type: "text" },
578
+ tx_index: { type: "int" },
579
+ unlock_burn_height: { type: "int", nullable: true },
580
+ unlock_cycle: { type: "int", nullable: true }
581
+ },
582
+ sbtc_events: {
583
+ amount: { type: "text", nullable: true },
584
+ bitcoin_txid: { type: "text", nullable: true },
585
+ block_height: { type: "int" },
586
+ block_time: { type: "timestamp" },
587
+ burn_hash: { type: "text", nullable: true },
588
+ burn_height: { type: "int", nullable: true },
589
+ canonical: { type: "boolean" },
590
+ cursor: { type: "text" },
591
+ event_index: { type: "int" },
592
+ fee: { type: "text", nullable: true },
593
+ governance_contract_type: { type: "int", nullable: true },
594
+ governance_new_contract: { type: "text", nullable: true },
595
+ max_fee: { type: "text", nullable: true },
596
+ output_index: { type: "int", nullable: true },
597
+ recipient_btc_hashbytes: { type: "text", nullable: true },
598
+ recipient_btc_version: { type: "int", nullable: true },
599
+ request_id: { type: "int", nullable: true },
600
+ sender: { type: "text", nullable: true },
601
+ signer_address: { type: "text", nullable: true },
602
+ signer_aggregate_pubkey: { type: "text", nullable: true },
603
+ signer_bitmap: { type: "text", nullable: true },
604
+ signer_keys_count: { type: "int", nullable: true },
605
+ signer_threshold: { type: "int", nullable: true },
606
+ sweep_txid: { type: "text", nullable: true },
607
+ topic: { type: "text" },
608
+ tx_id: { type: "text" },
609
+ tx_index: { type: "int" }
610
+ },
611
+ sbtc_token_events: {
612
+ amount: { type: "text" },
613
+ block_height: { type: "int" },
614
+ block_time: { type: "timestamp" },
615
+ canonical: { type: "boolean" },
616
+ cursor: { type: "text" },
617
+ event_index: { type: "int" },
618
+ event_type: { type: "text" },
619
+ memo: { type: "text", nullable: true },
620
+ recipient: { type: "text", nullable: true },
621
+ sender: { type: "text", nullable: true },
622
+ tx_id: { type: "text" },
623
+ tx_index: { type: "int" }
624
+ },
625
+ bns_name_events: {
626
+ block_height: { type: "int" },
627
+ block_time: { type: "timestamp" },
628
+ bns_id: { type: "text" },
629
+ canonical: { type: "boolean" },
630
+ cursor: { type: "text" },
631
+ event_index: { type: "int" },
632
+ fqn: { type: "text" },
633
+ hashed_salted_fqn_preorder: { type: "text", nullable: true },
634
+ imported_at: { type: "int", nullable: true },
635
+ name: { type: "text" },
636
+ namespace: { type: "text" },
637
+ owner: { type: "text", nullable: true },
638
+ preordered_by: { type: "text", nullable: true },
639
+ registered_at: { type: "int", nullable: true },
640
+ renewal_height: { type: "int", nullable: true },
641
+ stx_burn: { type: "text", nullable: true },
642
+ topic: { type: "text" },
643
+ tx_id: { type: "text" },
644
+ tx_index: { type: "int" }
645
+ },
646
+ bns_namespace_events: {
647
+ block_height: { type: "int" },
648
+ block_time: { type: "timestamp" },
649
+ canonical: { type: "boolean" },
650
+ cursor: { type: "text" },
651
+ event_index: { type: "int" },
652
+ launched_at: { type: "int", nullable: true },
653
+ lifetime: { type: "int", nullable: true },
654
+ manager: { type: "text", nullable: true },
655
+ manager_frozen: { type: "boolean", nullable: true },
656
+ manager_transfers_disabled: { type: "boolean", nullable: true },
657
+ namespace: { type: "text" },
658
+ price_frozen: { type: "boolean", nullable: true },
659
+ price_function: { type: "text", nullable: true },
660
+ revealed_at: { type: "int", nullable: true },
661
+ status: { type: "text" },
662
+ tx_id: { type: "text" },
663
+ tx_index: { type: "int" }
664
+ },
665
+ bns_marketplace_events: {
666
+ action: { type: "text" },
667
+ block_height: { type: "int" },
668
+ block_time: { type: "timestamp" },
669
+ bns_id: { type: "text" },
670
+ canonical: { type: "boolean" },
671
+ commission: { type: "text", nullable: true },
672
+ cursor: { type: "text" },
673
+ event_index: { type: "int" },
674
+ price_ustx: { type: "text", nullable: true },
675
+ tx_id: { type: "text" },
676
+ tx_index: { type: "int" }
677
+ },
678
+ bns_names: {
679
+ bns_id: { type: "text" },
680
+ fqn: { type: "text" },
681
+ last_event_at: { type: "timestamp" },
682
+ last_event_cursor: { type: "text" },
683
+ name: { type: "text" },
684
+ namespace: { type: "text" },
685
+ owner: { type: "text" },
686
+ registered_at: { type: "int", nullable: true },
687
+ renewal_height: { type: "int", nullable: true }
688
+ },
689
+ bns_namespaces: {
690
+ last_event_at: { type: "timestamp" },
691
+ last_event_cursor: { type: "text" },
692
+ launched_at: { type: "int", nullable: true },
693
+ lifetime: { type: "int", nullable: true },
694
+ manager: { type: "text", nullable: true },
695
+ manager_frozen: { type: "boolean" },
696
+ name_count: { type: "int" },
697
+ namespace: { type: "text" },
698
+ price_frozen: { type: "boolean" }
699
+ },
700
+ burn_block_rewards: {
701
+ amount_sats: { type: "text" },
702
+ burn_amount: { type: "text" },
703
+ burn_block_hash: { type: "text" },
704
+ burn_block_height: { type: "int" },
705
+ cursor: { type: "text" },
706
+ recipient_btc: { type: "text" },
707
+ reward_index: { type: "int" }
708
+ },
709
+ burn_block_reward_slots: {
710
+ burn_block_hash: { type: "text" },
711
+ burn_block_height: { type: "int" },
712
+ cursor: { type: "text" },
713
+ holder_btc: { type: "text" },
714
+ slot_index: { type: "int" }
715
+ },
716
+ events: {
717
+ block_height: { type: "int" },
718
+ data: { type: "jsonb" },
719
+ event_index: { type: "int" },
720
+ tx_id: { type: "text" },
721
+ type: { type: "text" }
722
+ },
723
+ chain_reorgs: {
724
+ detected_at: { type: "timestamp" }
725
+ }
726
+ };
727
+ var SOURCE_READ_PKS = {
728
+ blocks: ["height"],
729
+ decoded_events: ["cursor"],
730
+ transactions: ["tx_id"],
731
+ mempool_transactions: ["seq"],
732
+ pox4_calls: ["cursor"],
733
+ pox5_events: ["cursor"],
734
+ sbtc_events: ["cursor"],
735
+ sbtc_token_events: ["cursor"],
736
+ bns_name_events: ["cursor"],
737
+ bns_namespace_events: ["cursor"],
738
+ bns_marketplace_events: ["cursor"],
739
+ bns_names: ["fqn"],
740
+ bns_namespaces: ["namespace"],
741
+ burn_block_rewards: ["cursor"],
742
+ burn_block_reward_slots: ["cursor"],
743
+ events: ["tx_id", "event_index"],
744
+ chain_reorgs: null
745
+ };
746
+ // src/db/jsonb.ts
747
+ import { sql } from "kysely";
748
+ function jsonb(value) {
749
+ const escaped = JSON.stringify(value, (_k, v) => typeof v === "bigint" ? v.toString() : v).replace(/'/g, "''");
750
+ return sql`${sql.raw(`'${escaped}'::jsonb`)}`;
751
+ }
752
+ function parseJsonb(value) {
753
+ if (typeof value === "string") {
754
+ try {
755
+ return JSON.parse(value);
756
+ } catch {
757
+ return value;
758
+ }
759
+ }
760
+ return value ?? {};
761
+ }
762
+ // src/db/migration-role.ts
763
+ var currentRole = "both";
764
+ function setMigrationRole(role) {
765
+ currentRole = role;
766
+ }
767
+ function getMigrationRole() {
768
+ return currentRole;
769
+ }
770
+ async function onControlPlane(fn) {
771
+ if (currentRole === "target" || currentRole === "both")
772
+ await fn();
773
+ }
774
+ async function onChainPlane(fn) {
775
+ if (currentRole === "source" || currentRole === "both")
776
+ await fn();
777
+ }
778
+ // src/db/table-plane.ts
779
+ var TABLE_TO_DB = {
780
+ blocks: "source",
781
+ transactions: "source",
782
+ events: "source",
783
+ vm_events: "source",
784
+ state_writes: "source",
785
+ transactions_archive: "source",
786
+ events_archive: "source",
787
+ vm_events_archive: "source",
788
+ state_writes_archive: "source",
789
+ dead_letter_events: "source",
790
+ mempool_transactions: "source",
791
+ index_progress: "source",
792
+ contracts: "source",
793
+ chain_reorgs: "source",
794
+ chain_read_cache: "source",
795
+ pending_fork_blocks: "source",
796
+ observer_journal: "source",
797
+ sync_scopes: "source",
798
+ stage_registry: "source",
799
+ stage_runs: "source",
800
+ stage_block_receipts: "source",
801
+ coverage_segments: "source",
802
+ stage_failures: "source",
803
+ decoded_events: "source",
804
+ decoder_checkpoints: "source",
805
+ pox4_calls: "source",
806
+ pox5_events: "source",
807
+ pox5_cycles: "source",
808
+ pox5_cycle_signers: "source",
809
+ burn_block_rewards: "source",
810
+ burn_block_reward_slots: "source",
811
+ sbtc_events: "source",
812
+ sbtc_token_events: "source",
813
+ sbtc_settlements: "source",
814
+ bns_name_events: "source",
815
+ bns_namespace_events: "source",
816
+ bns_marketplace_events: "source",
817
+ bns_names: "source",
818
+ bns_namespaces: "source",
819
+ instances: "target",
820
+ accounts: "target",
821
+ api_keys: "target",
822
+ sessions: "target",
823
+ magic_links: "target",
824
+ cli_device_logins: "target",
825
+ oauth_clients: "target",
826
+ oauth_requests: "target",
827
+ oauth_codes: "target",
828
+ oauth_grants: "target",
829
+ oauth_tokens: "target",
830
+ oauth_refresh_retired: "target",
831
+ account_spend_caps: "target",
832
+ processed_stripe_events: "target",
833
+ webhooks: "target",
834
+ webhook_outbox: "target",
835
+ webhook_deliveries: "target",
836
+ webhook_delivery_hours: "target",
837
+ webhook_replays: "target",
838
+ trigger_evaluator_state: "target",
839
+ subgraphs: "target",
840
+ subgraph_operations: "target",
841
+ subgraph_health_snapshots: "target",
842
+ subgraph_gaps: "target",
843
+ subgraph_violations: "target",
844
+ subgraph_error_groups: "target",
845
+ subgraph_processing_stats: "target",
846
+ account_credits: "target",
847
+ archive_fetches: "target",
848
+ usage_ledger: "target",
849
+ account_balance_alerts: "target",
850
+ hosted_stack_state: "target",
851
+ webhook_incident_alerts: "target",
852
+ sentinel_accounts: "target",
853
+ waitlists: "target",
854
+ waitlist_signups: "target",
855
+ contact_requests: "target",
856
+ update_subscribers: "target",
857
+ update_sends: "target",
858
+ api_failed_requests: "target",
859
+ api_request_log: "target",
860
+ insights: "target",
861
+ insight_mutes: "target",
862
+ feedback_tickets: "target",
863
+ push_subscriptions: "target",
864
+ push_prefs: "target",
865
+ push_sent: "target",
866
+ service_heartbeats: "both"
867
+ };
868
+
869
+ // src/db/index.ts
870
+ var DEFAULT_URL = "postgres://postgres:postgres@localhost:5432/secondlayer_dev";
871
+ var pools = new Map;
872
+ var poolSeq = 0;
873
+ function maxPools() {
874
+ return Number.parseInt(process.env.DATABASE_MAX_POOLS ?? "25", 10);
875
+ }
876
+ function evictIfNeeded() {
877
+ if (pools.size <= maxPools())
878
+ return;
879
+ const protectedUrls = new Set([resolveSourceUrl(), resolveTargetUrl()]);
880
+ let lruUrl;
881
+ let lruEntry;
882
+ for (const [url, entry] of pools) {
883
+ if (protectedUrls.has(url))
884
+ continue;
885
+ if (!lruEntry || entry.lastUsed < lruEntry.lastUsed || entry.lastUsed === lruEntry.lastUsed && entry.seq < lruEntry.seq) {
886
+ lruUrl = url;
887
+ lruEntry = entry;
888
+ }
889
+ }
890
+ if (!lruUrl || !lruEntry)
891
+ return;
892
+ pools.delete(lruUrl);
893
+ const evicted = lruEntry;
894
+ evicted.db.destroy().catch(() => {}).then(() => evicted.rawClient.end({ timeout: 5 })).catch(() => {});
895
+ }
896
+ function applicationDatabaseUrl() {
897
+ return process.env.DATABASE_URL || DEFAULT_URL;
898
+ }
899
+ function resolveSourceUrl() {
900
+ return configuredSourceUrl() ?? DEFAULT_URL;
901
+ }
902
+ function resolveTargetUrl() {
903
+ return configuredTargetUrl() ?? DEFAULT_URL;
904
+ }
905
+ function configuredSourceUrl() {
906
+ if (!isPlatformMode())
907
+ return process.env.DATABASE_URL || undefined;
908
+ return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || undefined;
909
+ }
910
+ function configuredTargetUrl() {
911
+ if (!isPlatformMode())
912
+ return process.env.DATABASE_URL || undefined;
913
+ return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || undefined;
914
+ }
915
+ function describeDbUrl(url) {
916
+ try {
917
+ const u = new URL(url);
918
+ return `${u.hostname}${u.port ? `:${u.port}` : ""}${u.pathname}`;
919
+ } catch {
920
+ return "invalid-url";
921
+ }
922
+ }
923
+ var warnedDefaultUrlFallthrough = false;
924
+ function warnIfTestRunFallsThroughToDefault() {
925
+ if (warnedDefaultUrlFallthrough)
926
+ return;
927
+ if (process.env["NODE_ENV"] !== "test")
928
+ return;
929
+ if (process.env.DATABASE_URL || process.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL) {
930
+ return;
931
+ }
932
+ warnedDefaultUrlFallthrough = true;
933
+ console.warn(`⚠️ DATABASE_URL unset — falling through to the built-in DEFAULT_URL (${describeDbUrl(DEFAULT_URL)}). Database-backed tests will skip or hit the wrong Postgres. Copy .env.example to .env in this package (see \`bun run db\`).`);
934
+ }
935
+ warnIfTestRunFallsThroughToDefault();
936
+ function getDbSplitStatus() {
937
+ const source = resolveSourceUrl();
938
+ const target = resolveTargetUrl();
939
+ const active = source !== target;
940
+ return {
941
+ mode: active ? "split" : "single",
942
+ active,
943
+ sourceDb: describeDbUrl(source),
944
+ targetDb: describeDbUrl(target)
945
+ };
946
+ }
947
+ function assertDbSplit() {
948
+ const isProd = isProductionEnv();
949
+ const wantsSplit = !!(process.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL);
950
+ const databaseUrlSet = !!process.env.DATABASE_URL;
951
+ const source = resolveSourceUrl();
952
+ const target = resolveTargetUrl();
953
+ if (wantsSplit && !databaseUrlSet && (source === DEFAULT_URL || target === DEFAULT_URL)) {
954
+ const which = source === DEFAULT_URL ? "SOURCE_DATABASE_URL" : "TARGET_DATABASE_URL";
955
+ const msg = `${which} unset and DATABASE_URL absent — resolving to built-in DEFAULT_URL; refusing to silently use the wrong database`;
956
+ if (isProd)
957
+ console.error(`❌ ${msg}`);
958
+ else
959
+ console.warn(`⚠️ ${msg}`);
960
+ return;
961
+ }
962
+ if (!wantsSplit) {
963
+ if (isProd) {
964
+ console.warn("⚠️ DB split dormant — all services share one Postgres failure domain (SOURCE_/TARGET_DATABASE_URL unset)");
965
+ }
966
+ return;
967
+ }
968
+ if (source === target) {
969
+ const msg = "DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)";
970
+ if (isProd)
971
+ console.error(`❌ ${msg}`);
972
+ else
973
+ console.warn(`⚠️ ${msg}`);
974
+ }
975
+ }
976
+ function getOrCreatePool(url) {
977
+ const existing = pools.get(url);
978
+ if (existing) {
979
+ existing.lastUsed = Date.now();
980
+ existing.seq = poolSeq++;
981
+ return existing;
982
+ }
983
+ const poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? "20", 10);
984
+ const idleTimeout = Number.parseInt(process.env.DATABASE_IDLE_TIMEOUT ?? "300", 10);
985
+ const rawClient = postgres(url, {
986
+ max: poolMax,
987
+ idle_timeout: idleTimeout,
988
+ ...tlsOptions(url)
989
+ });
990
+ const db = new Kysely({
991
+ dialect: new PostgresJSDialect({ postgres: rawClient }),
992
+ log: (event) => {
993
+ if (event.level !== "error")
994
+ return;
995
+ const err = event.error;
996
+ if (err?.code !== "42P10")
997
+ return;
998
+ logger.warn("db.on_conflict_constraint_missing", {
999
+ code: err.code,
1000
+ message: err.message,
1001
+ sql: event.query.sql,
1002
+ params: event.query.parameters
1003
+ });
1004
+ }
1005
+ });
1006
+ const entry = {
1007
+ db,
1008
+ rawClient,
1009
+ lastUsed: Date.now(),
1010
+ seq: poolSeq++
1011
+ };
1012
+ pools.set(url, entry);
1013
+ evictIfNeeded();
1014
+ return entry;
1015
+ }
1016
+ function getSourceDb() {
1017
+ return getOrCreatePool(resolveSourceUrl()).db;
1018
+ }
1019
+ function getTargetDb() {
1020
+ return getOrCreatePool(resolveTargetUrl()).db;
1021
+ }
1022
+ function getDb(connectionString) {
1023
+ if (connectionString)
1024
+ return getOrCreatePool(connectionString).db;
1025
+ return getTargetDb();
1026
+ }
1027
+ function getRawClient(role = "target") {
1028
+ const url = role === "source" ? resolveSourceUrl() : resolveTargetUrl();
1029
+ return getOrCreatePool(url).rawClient;
1030
+ }
1031
+ async function closeDb() {
1032
+ for (const entry of pools.values()) {
1033
+ await entry.db.destroy();
1034
+ await entry.rawClient.end();
1035
+ }
1036
+ pools.clear();
1037
+ }
1038
+ var DEFAULT_CLOSE_DB_TIMEOUT_MS = 30000;
1039
+ async function closeDbOrTimeout(timeoutMs = DEFAULT_CLOSE_DB_TIMEOUT_MS, closeFn = closeDb) {
1040
+ await Promise.race([
1041
+ closeFn(),
1042
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
1043
+ ]);
1044
+ }
154
1045
  // src/leader.ts
155
1046
  var INDEXER_LEADER_LOCK_KEY = 7702026;
156
1047
  var WEBHOOK_EVALUATOR_LOCK_KEY = 7702027;
157
1048
  var SUBGRAPH_CATCHUP_LOCK_KEY = 7702028;
158
1049
  var OBSERVER_APPLY_LOCK_KEY = 7702029;
159
1050
  var INSIGHTS_EVALUATOR_LOCK_KEY = 7702030;
160
- function leaderDatabaseUrl() {
161
- return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || "postgres://localhost:5432/secondlayer";
162
- }
163
1051
  function createPostgresLeaderBackend(url) {
164
- const resolvedUrl = url ?? leaderDatabaseUrl();
165
- const sql = postgres(resolvedUrl, {
1052
+ const resolvedUrl = url ?? resolveSourceUrl();
1053
+ const sql = postgres2(resolvedUrl, {
166
1054
  max: 1,
167
1055
  idle_timeout: 0,
168
1056
  ...tlsOptions(resolvedUrl)
@@ -265,5 +1153,5 @@ export {
265
1153
  withLeaderLock
266
1154
  };
267
1155
 
268
- //# debugId=FE92FE3B968A756464756E2164756E21
1156
+ //# debugId=F42C04FA96CC595464756E2164756E21
269
1157
  //# sourceMappingURL=leader.js.map