@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

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 (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -22,19 +22,9 @@ class CrawlerLeaseLostError extends Error {
22
22
  constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
23
23
  }
24
24
  /**
25
- * CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
26
- * start block and bulk-indexes Blocks + Transactions (+ inputs/outputs/assets) into the
27
- * DB, so consumers can query local data instead of hitting a backend per request.
28
- *
29
- * Two sources (see CRAWLER_DESIGN.md):
30
- * - **Ogmios chain-sync** (primary): ordered rollForward + native rollBackward (reorg).
31
- * - **Blockfrost/Koios pagination** (fallback): forward walk + parent-hash reorg recovery.
32
- *
33
- * Lifecycle: start() launches the ingest pipeline detached so the HTTP server binds
34
- * immediately, but the pipeline promise is retained — stop() halts the loops (waking
35
- * any pending poll sleep) and AWAITS the pipeline, so shutdown never races in-flight
36
- * block writes. All per-block writes are atomic. The crawler NEVER crawls from genesis
37
- * implicitly — it requires an explicit configured start point or an existing cursor.
25
+ * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
26
+ * Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
27
+ * Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
38
28
  */
39
29
  class CardanoCrawler {
40
30
  client;
@@ -44,21 +34,13 @@ class CardanoCrawler {
44
34
  leaseOwner;
45
35
  /** Transient-failure retries per block before giving up. */
46
36
  static PERSIST_RETRIES = 3;
47
- /**
48
- * A block whose persist keeps failing across crawler restarts is a poison block
49
- * (e.g. data PostgreSQL rejects). After this many failed persistBlock() calls for
50
- * the same hash the crawler latches off (desiredRunning=false) instead of
51
- * restarting forever; an operator fixes the cause and calls resumeCrawler().
52
- */
37
+ /** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
53
38
  static POISON_BLOCK_THRESHOLD = 5;
54
39
  /** Process-wide, survives instance restarts: the block currently failing and how often. */
55
40
  static poison = null;
56
41
  /**
57
- * Database errors that are deterministic for the block's data — the same bytes fail
58
- * the same way on every restart. Only these count towards the poison-block latch:
59
- * a DB outage, a statement timeout or an exhausted pool fails the same block too,
60
- * but a restart fixes those, and latching on them would disable the pre-sync for
61
- * good (the contract of halt()).
42
+ * Errors deterministic for the block's data — only these count towards the poison latch.
43
+ * Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
62
44
  */
63
45
  static DATA_REJECTION_PATTERNS = [
64
46
  /unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
@@ -73,34 +55,18 @@ class CardanoCrawler {
73
55
  ];
74
56
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
75
57
  static CALL_TIMEOUT_MS = 60_000;
76
- /**
77
- * Epoch snapshots are ~100 batched provider requests on mainnet, so they get a wider
78
- * bound than an ordinary call — still bounded, and cancelled by beginHalt.
79
- */
58
+ /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
80
59
  static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
81
- /**
82
- * Backoff after a failed snapshot attempt, doubling up to the cap. Without it a provider
83
- * outage would re-trigger a full pool/DRep enumeration on every single block for the rest
84
- * of the epoch — the marker is only set on success, by design.
85
- */
60
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
86
61
  static SNAPSHOT_RETRY_BASE_MS = 30_000;
87
62
  static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
88
- /**
89
- * How often a crawl that runs on pagination for lack of a chain-sync backend retries
90
- * that backend's init. Pagination is roughly fifty times slower than chain-sync, so
91
- * the cadence errs on the frequent side; the probe is free when no chain-sync backend
92
- * is configured at all and bounded by the backend's init timeout when it is down.
93
- */
63
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
94
64
  static CHAIN_SYNC_RETRY_MS = 30_000;
95
65
  running = false;
96
66
  chainSyncHandle = null;
97
67
  /** What the ingest loop is currently reading from; null while stopped. */
98
68
  activeSource = null;
99
- /**
100
- * Chain-sync init retry while the crawl runs on pagination for lack of one: its own
101
- * timer (independent of the pagination cadence — a poll sleep can be an hour long),
102
- * the in-flight recover call, and its outcome.
103
- */
69
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
104
70
  chainSyncProbeTimer = null;
105
71
  chainSyncProbe = null;
106
72
  chainSyncRecovered = false;
@@ -113,11 +79,7 @@ class CardanoCrawler {
113
79
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
114
80
  inFlightCallbacks = new Set();
115
81
  haltPromise = null;
116
- /**
117
- * Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
118
- * block, so the ingest loop takes it through the paginating backend and then reopens
119
- * chain-sync — see runIngestPipeline().
120
- */
82
+ /** An unparseable chain-sync frame; the ingest loop fetches that block via pagination, then reopens chain-sync. */
121
83
  frameFailure = null;
122
84
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
123
85
  streamEnded = null;
@@ -149,11 +111,7 @@ class CardanoCrawler {
149
111
  haltedWithError() {
150
112
  return !this.running && this.finalStatus === 'error';
151
113
  }
152
- /**
153
- * The source this crawler is ingesting from right now, or null while it is not
154
- * running. Lets an operator see a crawl that degraded to pagination — it still makes
155
- * progress, so the cursor alone looks healthy.
156
- */
114
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
157
115
  getActiveSource() {
158
116
  return this.running ? this.activeSource : null;
159
117
  }
@@ -197,9 +155,8 @@ class CardanoCrawler {
197
155
  // Ledger state is only ever applied from a known anchor — no snapshot, no writes.
198
156
  if (this.config.utxoSet) {
199
157
  const u = cursor.utxoSet;
200
- // Blocks crawled while the mode was off (or after an invalidation that was then
201
- // flipped back on) never reached the ledger tables: the cursor is ahead of the last
202
- // applied slot. The set is stale and cannot be caught up — invalidate it explicitly.
158
+ // Blocks crawled while the mode was off never reached the ledger tables: the cursor is
159
+ // ahead of the last applied slot and the set cannot be caught up — invalidate it.
203
160
  const lastApplied = u.appliedSlot ?? u.anchorSlot;
204
161
  if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
205
162
  const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
@@ -234,10 +191,8 @@ class CardanoCrawler {
234
191
  });
235
192
  }
236
193
  /**
237
- * Stop crawling and WAIT for the pipeline to finish its in-flight step: halts the
238
- * loops (waking any pending poll sleep), closes the chain-sync stream, records the
239
- * final status, then awaits the detached pipeline so callers (shutdownAppContext)
240
- * can safely tear down backends/DB afterwards.
194
+ * Stop crawling and await the pipeline's in-flight step, so callers can tear down
195
+ * backends/DB afterwards.
241
196
  */
242
197
  async stop(finalStatus = 'stopped') {
243
198
  this.beginHalt(finalStatus);
@@ -246,24 +201,14 @@ class CardanoCrawler {
246
201
  this.pipeline = null;
247
202
  }
248
203
  /**
249
- * Halt without awaiting the pipeline — the variant safe to call FROM INSIDE the
250
- * pipeline (persistBlock failure, stream onError), where awaiting the pipeline
251
- * would deadlock.
252
- */
253
- /**
254
- * @param latch clears `desiredRunning`, so NO restart brings the crawler back —
255
- * only an operator's resumeCrawler does. Reserved for failures a restart cannot
256
- * fix (misconfiguration, missing resume point). Runtime failures — a dropped
257
- * chain-sync socket, a provider outage, a node restart — must leave it false,
258
- * otherwise a routine node restart silently disables the pre-sync for good.
204
+ * Halt without awaiting the pipeline — safe to call from inside it.
205
+ * @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
206
+ * a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
259
207
  */
260
208
  async halt(finalStatus = 'stopped', latch = false) {
261
209
  this.beginHalt(finalStatus, latch);
262
210
  }
263
- /**
264
- * Start teardown without awaiting it. Internal callers can therefore halt from
265
- * inside a tracked callback/pipeline without waiting on their own promise.
266
- */
211
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
267
212
  beginHalt(finalStatus, latch = false) {
268
213
  if (latch)
269
214
  this.latchOnHalt = true;
@@ -321,10 +266,8 @@ class CardanoCrawler {
321
266
  while (this.running) {
322
267
  const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
323
268
  if (chainSync) {
324
- // One pass per chain-sync stream. A frame the client's parser cannot turn into an
325
- // object ends the stream without ending the crawler: pagination fetches that one
326
- // block over HTTP, and chain-sync takes over again as soon as it is behind the
327
- // cursor. Any other stream error still halts, as it always did.
269
+ // One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
270
+ // pagination fetches that block, then chain-sync takes over again. Other errors halt.
328
271
  while (this.running) {
329
272
  const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
330
273
  await this.runChainSync(chainSync);
@@ -350,26 +293,17 @@ class CardanoCrawler {
350
293
  await this.runPagination();
351
294
  return;
352
295
  }
353
- // 'auto', and no chain-sync backend is usable right now. After a restart of a box
354
- // that hosts node and ODATANO together this is the normal case, not the exception:
355
- // the node validates its chunks and replays the ledger for minutes while ODATANO is
356
- // up in seconds, so Ogmios refused its init. Crawl on pagination meanwhile, but
357
- // keep retrying chain-sync — a crawl that makes progress at a fiftieth of the
358
- // speed looks healthy to every monitor that watches only the cursor.
296
+ // 'auto' with no usable chain-sync backend (typical while the node still replays after a
297
+ // restart): crawl on pagination and keep retrying chain-sync.
359
298
  logger.warn('No chain-sync backend usable — crawling on pagination and retrying chain-sync periodically');
360
299
  await this.runPagination({ untilChainSync: true });
361
300
  // Returned because chain-sync came back (or we stopped): the loop reopens it.
362
301
  }
363
302
  }
364
303
  /**
365
- * Retry the init of a chain-sync backend that was unusable when the crawl began, on
366
- * its own timer: the pagination loop may be asleep for a whole poll interval (up to
367
- * an hour) or inside a slow batch, and neither must delay the retry. The probe runs
368
- * in the background so no pagination round waits for it, and one at a time so a node
369
- * that is still replaying is not hammered. On success `chainSyncRecovered` is set and
370
- * a pending poll sleep is cut short; the pagination loop leaves at its next check
371
- * (between rounds, or between blocks of a batch — the block in flight completes) and
372
- * the ingest loop reopens chain-sync from the cursor.
304
+ * Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
305
+ * one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
306
+ * the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
373
307
  */
374
308
  startChainSyncProbing() {
375
309
  this.chainSyncRecovered = false;
@@ -492,11 +426,8 @@ class CardanoCrawler {
492
426
  return failure;
493
427
  }
494
428
  /**
495
- * Can this unparseable frame be worked around by fetching the block over HTTP instead?
496
- *
497
- * Requires a height to walk to, a paginating backend to walk with, and an operator who has
498
- * not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
499
- * degrading to the weaker pagination reorg handling would defeat the point of it.
429
+ * Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
430
+ * backend, and a source not pinned to 'ogmios' (chain-sync only).
500
431
  */
501
432
  canDegradeToPagination(err) {
502
433
  return err.height != null
@@ -504,9 +435,8 @@ class CardanoCrawler {
504
435
  && !!this.client.getPaginatingBackend();
505
436
  }
506
437
  /**
507
- * End the chain-sync stream and hand control back to the ingest loop, which continues on
508
- * pagination past the offending block. Records the error first, so `lastError` names the
509
- * block rather than leaving the empty status a crashed process used to leave behind.
438
+ * End the chain-sync stream and hand back to the ingest loop, which continues on pagination
439
+ * past the offending block. The error is recorded first so `lastError` names the block.
510
440
  */
511
441
  async degradeToPagination(err) {
512
442
  const streak = await this.recordCrawlerError(err);
@@ -529,16 +459,9 @@ class CardanoCrawler {
529
459
  this.streamEnded?.();
530
460
  }
531
461
  /**
532
- * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
533
- * spaced ladder of our own already-crawled ancestors, then the configured start
534
- * block as the deepest anchor.
535
- *
536
- * Why more than the cursor: if the cursor's block was orphaned while the crawler
537
- * was down, a single-point intersection fails outright ("No intersection found")
538
- * and the stream never opens. With ancestors on the list the node intersects at
539
- * the last common block and reports it as a rollBackward — the ordinary reorg path
540
- * that handleReorg already implements. Doubling offsets cover ~32k blocks with 16
541
- * points; anything deeper is past any realistic rollback and should fail loudly.
462
+ * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
463
+ * ancestors, then the configured start block. If the cursor's block was orphaned while the
464
+ * crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
542
465
  */
543
466
  async buildIntersectionPoints(cursor) {
544
467
  const points = [];
@@ -551,11 +474,8 @@ class CardanoCrawler {
551
474
  };
552
475
  if (cursor?.lastBlockHash) {
553
476
  add({ slot: cursor.lastSlot, hash: cursor.lastBlockHash, height: cursor.lastHeight });
554
- // Dense over the last DENSE_DEPTH blocks, doubling after that. Real rollbacks
555
- // are a handful of blocks deep, and those must intersect EXACTLY — a gap in
556
- // the ladder is not wrong (rolling back too far only re-crawls), but it costs
557
- // needless work on the common case. The doubling tail keeps the deep-reorg
558
- // reach without sending hundreds of points.
477
+ // Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
478
+ // exactly), doubling after that for deep-reorg reach without hundreds of points.
559
479
  const DENSE_DEPTH = 10;
560
480
  const heights = [];
561
481
  const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
@@ -588,13 +508,9 @@ class CardanoCrawler {
588
508
  // Pagination (Blockfrost/Koios) — fallback
589
509
  // ---------------------------------------------------------------------------
590
510
  /**
591
- * @param untilHeight when set, return as soon as the cursor has reached it instead of
592
- * looping forever. Used to walk past a block the chain-sync stream cannot deliver and
593
- * then hand back to it — pagination is roughly seven times slower, so staying on it
594
- * for the rest of a backfill would be a poor trade.
595
- * @param untilChainSync when set, keep retrying a chain-sync backend in the background
596
- * and return once one is usable, so the ingest loop can hand over to it. Used when
597
- * the crawl started without one (source 'auto', node still coming up).
511
+ * @param untilHeight return once the cursor reaches it — walks past a block chain-sync
512
+ * cannot deliver, then hands back.
513
+ * @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
598
514
  */
599
515
  async runPagination(opts = {}) {
600
516
  if (opts.untilChainSync)
@@ -616,9 +532,8 @@ class CardanoCrawler {
616
532
  backend.configureCrawl?.({ certificates: this.config.certificates });
617
533
  this.activeSource = 'pagination';
618
534
  logger.info('Crawler running (pagination)');
619
- // Tip cache: during deep catch-up the exact tip is irrelevant (only "am I still
620
- // behind the target" matters) — refetching it every round wasted one HTTP call
621
- // per batch. Refresh only when the cursor reaches the cached target.
535
+ // Tip cache, refreshed only when the cursor reaches the cached target; during catch-up
536
+ // the exact tip is irrelevant.
622
537
  let tip = null;
623
538
  let target = Number.NEGATIVE_INFINITY;
624
539
  while (this.running) {
@@ -712,10 +627,8 @@ class CardanoCrawler {
712
627
  }
713
628
  }
714
629
  /**
715
- * Poll pause between pagination rounds. Skipped when a handover to chain-sync is
716
- * already due: the probe's wake-up only reaches a sleep that has begun, so a probe
717
- * that succeeded while the round was still fetching (tip, blocks) would otherwise be
718
- * followed by a full poll interval — up to an hour — before the loop notices.
630
+ * Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
631
+ * since the probe's wake-up only reaches a sleep that has begun.
719
632
  */
720
633
  async pollPause(untilChainSync) {
721
634
  if (untilChainSync && this.chainSyncRecovered)
@@ -753,10 +666,8 @@ class CardanoCrawler {
753
666
  if (ours?.hash && onChain.hash === ours.hash) {
754
667
  if (h === cursor.lastHeight)
755
668
  return false; // tip still matches → not a reorg
756
- // handleReorg deletes everything with slot > forkSlot. A null provider slot
757
- // (BlockData.slot is nullable) would make forkSlot 0 and wipe the ENTIRE
758
- // crawled dataset — abort this round instead; the next round can retry with
759
- // a healthy provider response. (Same guard philosophy as the height axis.)
669
+ // A null provider slot would make forkSlot 0 and wipe the entire crawled dataset —
670
+ // abort this round instead.
760
671
  if (onChain.slot == null)
761
672
  return false;
762
673
  await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
@@ -769,10 +680,8 @@ class CardanoCrawler {
769
680
  // Persist + reorg (shared)
770
681
  // ---------------------------------------------------------------------------
771
682
  /**
772
- * Persist one block atomically and advance the cursor. Transient failures are retried
773
- * a few times (recording the error streak); only repeated failure stops the crawler —
774
- * the cursor is not advanced on failure, so a resume re-syncs cleanly from it.
775
- * Marks the cursor 'synced' when the block is at the reported tip.
683
+ * Persist one block atomically and advance the cursor. Transient failures are retried; the
684
+ * cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
776
685
  * @returns true when the block was persisted, false when the crawler was stopped
777
686
  */
778
687
  async persistBlock(block, txs, tip) {
@@ -845,9 +754,8 @@ class CardanoCrawler {
845
754
  const cause = err instanceof Error ? err.message : String(err);
846
755
  const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
847
756
  logger.error(`persistBlock failed for ${block.hash} (height ${block.height}) ${failures}x across restarts — poison block, latching the crawler off. Fix the cause, then resumeCrawler():`, err);
848
- // Lease-independent on purpose (see latchPoisonBlock). The memory is only
849
- // forgotten once the latch is durable, so a failed write is retried after
850
- // the next restart instead of restarting the count from one.
757
+ // Lease-independent on purpose (see latchPoisonBlock); the memory is only forgotten
758
+ // once the latch is durable, so a failed write is retried after the next restart.
851
759
  const latched = await cds_1.default.tx((tx) => (0, sync_state_1.latchPoisonBlock)(tx, message)).then(() => true, (e) => { logger.error('poison-block latch could not be written — retried after the next restart:', e); return false; });
852
760
  if (latched)
853
761
  CardanoCrawler.poison = null;
@@ -868,25 +776,9 @@ class CardanoCrawler {
868
776
  return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
869
777
  }
870
778
  /**
871
- * Take the epoch snapshot of pools and DReps once per epoch, detached from the block that
872
- * triggered it (v2.0 analytics coverage, opt-in via `epochSnapshots`).
873
- *
874
- * ONLY AT THE TIP. The providers that can enumerate the pool and DRep set report their
875
- * CURRENT state — Koios `/pool_info` and `/drep_info` take no epoch parameter. Snapshotting
876
- * while the crawl is still backfilling would therefore write today's stake and vote power
877
- * under every historical epoch number it passes: a table that reads as a time series but is
878
- * a constant. So the block's epoch must be the epoch the reported tip is in; otherwise the
879
- * epoch is skipped, permanently and by design. Backfilled ranges have no snapshots, live
880
- * ones do.
881
- *
882
- * Detached on purpose: the snapshot is a few thousand rows plus ~100 provider requests, and
883
- * the crawl must not wait for it or fail because of it. It is tracked as an in-flight
884
- * callback, so a shutdown still drains it, and bounded by a timeout that beginHalt cancels.
885
- *
886
- * "Once per epoch" survives a restart: the process-local marker only skips work, the
887
- * authority is a `PoolEpochSnapshots` row for that epoch — so a crawler restarted right
888
- * after a boundary still records the epoch, and one restarted mid-epoch does not redo it.
889
- * A failed attempt leaves the marker unset and backs off (see SNAPSHOT_RETRY_BASE_MS).
779
+ * Pool/DRep snapshot once per epoch, detached from the triggering block and ONLY at the tip:
780
+ * the enumerating providers report current state (no epoch parameter), so epochs passed
781
+ * during a backfill are skipped permanently. Authority is the `PoolEpochSnapshots` row.
890
782
  */
891
783
  maybeSnapshotEpoch(block, tip) {
892
784
  if (!this.config.epochSnapshots || block.epoch == null)
@@ -929,14 +821,9 @@ class CardanoCrawler {
929
821
  .finally(() => { this.snapshotInFlight = null; });
930
822
  }
931
823
  /**
932
- * Handle a chain rollback: in one transaction, delete every block after the fork point
933
- * and exactly the transactions belonging to those blocks (plus their child rows), reset
934
- * the cursor to the fork, and write a CardanoReorgLog audit row.
935
- *
936
- * The cut runs on the absolute-slot axis of Blocks (same axis as the fork point), and
937
- * transactions are resolved via their blockHash — so:
938
- * - an unresolvable fork height can never widen the delete (no height-0 fallback), and
939
- * - lazily-indexed transactions of blocks the crawler never wrote are left untouched.
824
+ * Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
825
+ * height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
826
+ * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
940
827
  */
941
828
  async handleReorg(point) {
942
829
  const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
@@ -989,10 +876,8 @@ class CardanoCrawler {
989
876
  }
990
877
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
991
878
  }
992
- // Crawler-fed ledger state, driven by the PERSISTED state so a process with the mode
993
- // off still keeps the set consistent: a fork after the anchor is undone (drop created,
994
- // reopen spent, recount touched addresses) and the progress marker follows the cursor
995
- // back; a fork before the anchor invalidates the whole set.
879
+ // Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
880
+ // progress marker follows the cursor back; a fork before the anchor invalidates the set.
996
881
  const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
997
882
  if (persisted?.status === 'active' && persisted.anchorSlot != null) {
998
883
  if (forkSlot < persisted.anchorSlot) {
@@ -1,14 +1,6 @@
1
1
  /**
2
- * Crawler event hooks (v2.1).
3
- *
4
- * Small listener registry that lets other subsystems (currently the wallet-worker
5
- * confirmation tracker) observe crawler progress without the crawler importing
6
- * them (dependency direction stays crawler ← consumer). The crawler emits:
7
- * - `blockIndexed` after each successfully persisted block (with its tx hashes), and
8
- * - `reorg` after a completed rollback (with the fork slot).
9
- *
10
- * Listener failures are logged and swallowed — a broken consumer must never
11
- * stop the crawler.
2
+ * Listener registry for crawler progress: `blockIndexed` after each persisted block,
3
+ * `reorg` after a completed rollback. Listener failures are logged and swallowed.
12
4
  */
13
5
  export interface BlockIndexedEvent {
14
6
  hash: string;
@@ -24,10 +16,7 @@ export interface ReorgEvent {
24
16
  forkSlot: number;
25
17
  /** How many blocks the rollback removed (0 when the fork was already the tip). */
26
18
  blocksRolledBack?: number;
27
- /**
28
- * Block height of the fork point, when known. Listeners tracking confirmation
29
- * depth must clamp their tip to this — the pre-fork tip height no longer exists.
30
- */
19
+ /** Block height of the fork point, when known; depth trackers must clamp their tip to it. */
31
20
  forkHeight: number | null;
32
21
  }
33
22
  export type BlockIndexedListener = (event: BlockIndexedEvent) => void;
@@ -2,12 +2,8 @@ import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { CardanoCrawler, type CrawlerConfig } from './crawler';
4
4
  /**
5
- * Delay before the next standby start attempt. A healthy standby (a lease loser, or
6
- * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
7
- * process halted with an error does the shared cursor's consecutiveErrors drive an
8
- * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
9
- * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
10
- * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
5
+ * Delay before the next standby start attempt: 5 s for a healthy standby; after a local
6
+ * error halt, exponential backoff (5 s … 5 min) driven by the shared cursor's error streak.
11
7
  */
12
8
  export declare function standbyDelayMs(consecutiveErrors: number): number;
13
9
  export interface StartCrawlerDeps {
@@ -15,9 +15,8 @@ const crawler_1 = require("./crawler");
15
15
  const sync_state_1 = require("./sync-state");
16
16
  const logger = cds_1.default.log('CardanoCrawler');
17
17
  /**
18
- * Module-level singleton lifecycle for the chain crawler. Mirrors NIGHTGATE's
19
- * srv/crawler/index.ts: one active crawler per process, started fire-and-forget from
20
- * the server's `served` hook and controlled (pause/resume/status) via the indexer service.
18
+ * Process-wide crawler singleton: started fire-and-forget from the `served` hook,
19
+ * controlled (pause/resume/status) via the indexer service.
21
20
  */
22
21
  let active = null;
23
22
  let lifecycleQueue = Promise.resolve();
@@ -27,12 +26,8 @@ let standbyGeneration = 0;
27
26
  const STANDBY_RETRY_MS = 5_000;
28
27
  const STANDBY_MAX_BACKOFF_MS = 5 * 60_000;
29
28
  /**
30
- * Delay before the next standby start attempt. A healthy standby (a lease loser, or
31
- * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
32
- * process halted with an error does the shared cursor's consecutiveErrors drive an
33
- * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
34
- * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
35
- * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
29
+ * Delay before the next standby start attempt: 5 s for a healthy standby; after a local
30
+ * error halt, exponential backoff (5 s … 5 min) driven by the shared cursor's error streak.
36
31
  */
37
32
  function standbyDelayMs(consecutiveErrors) {
38
33
  if (!Number.isFinite(consecutiveErrors) || consecutiveErrors <= 1)
@@ -1,14 +1,8 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  /**
3
- * Chain crawler cursor helpers (v2.0 pre-sync).
4
- *
5
- * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
6
- * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
7
- *
8
- * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
9
- * STRINGS, not JS numbers — the same change that makes them strings over OData.
10
- * Every read here therefore coerces numeric fields with `num()`; callers get a
11
- * clean numeric `SyncCursor` and never have to think about it.
3
+ * Cursor helpers for `CardanoSyncState`, the singleton row recording how far the crawler
4
+ * has indexed. Integer64/Decimal columns come back from the DB as strings, so every read
5
+ * coerces numeric fields; callers get a numeric `SyncCursor`.
12
6
  */
13
7
  export declare const SINGLETON_ID = "SINGLETON";
14
8
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
@@ -51,10 +45,8 @@ export interface SyncCursor {
51
45
  utxoSet: UtxoSetState;
52
46
  }
53
47
  /**
54
- * Idempotently ensure the singleton cursor row exists and return it.
55
- * On first call (fresh DB) the row is created with the configured start point
56
- * (if given) and status 'stopped'. Subsequent calls just return the current row.
57
- * Safe to call from both the crawler and the control service.
48
+ * Ensure the singleton cursor row exists and return it; a fresh DB gets the configured
49
+ * start point and status 'stopped'.
58
50
  */
59
51
  export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
60
52
  /** Read the current cursor, or null if it has not been initialized yet. */
@@ -62,9 +54,8 @@ export declare function readCursor(db: CapTransaction): Promise<SyncCursor | nul
62
54
  /** Whether the shared lease currently represents a live cluster-wide crawler. */
63
55
  export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
64
56
  /**
65
- * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
66
- * The post-update read is intentional: CAP adapters consistently return the row
67
- * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
57
+ * Acquire an expired/unowned lease with compare-and-swap semantics. Verified by a read-back
58
+ * SELECT: affected-row return shapes differ between SQLite and HANA.
68
59
  */
69
60
  export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
70
61
  /**
@@ -73,33 +64,23 @@ export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string
73
64
  */
74
65
  export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
75
66
  /**
76
- * Release only the caller's lease; a stale process can never clear a successor.
77
- *
78
- * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
79
- * then refuses to start until an operator calls resumeCrawler. Reserve it for
80
- * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
81
- * crashed stream, a provider outage or a node restart must NOT latch: those are
82
- * exactly the cases where coming back up should resume the pre-sync by itself.
67
+ * Release only the caller's lease. `pauseCluster` clears `desiredRunning`, which no restart
68
+ * undoes — reserve it for failures a restart cannot fix (misconfiguration, no resume point).
83
69
  */
84
70
  export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
85
71
  /**
86
- * Persist the pause/resume intent shared by every app instance. Resuming also clears
87
- * the error streak: the operator says the cause is fixed, and a stale streak would
88
- * otherwise keep the standby backoff at its cap for the first retry.
72
+ * Persist the pause/resume intent shared by every instance. Resuming clears the error
73
+ * streak so the standby backoff restarts at its base.
89
74
  */
90
75
  export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
91
76
  /**
92
- * Latch the cluster off because of a poison block (a block whose data the database
93
- * deterministically rejects). Deliberately NOT lease-scoped, unlike releaseCrawlerLease:
94
- * the poison is a property of the block, not of the instance that observed it, and
95
- * that instance may have lost its lease while the failure was being recorded. Only
96
- * an operator's resumeCrawler brings the crawler back.
77
+ * Latch the cluster off because of a poison block. Deliberately not lease-scoped: the poison
78
+ * is a property of the block, not of the instance. Only resumeCrawler brings the crawler back.
97
79
  */
98
80
  export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
99
81
  /**
100
- * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
101
- * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
102
- * lastIndexedAt. Optionally records the latest known tip (for progress).
82
+ * Advance the cursor to a freshly indexed block, clear the error streak and optionally
83
+ * record the latest known tip. Pass status 'synced' when the block is at the tip.
103
84
  */
104
85
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
105
86
  slot: number;
@@ -108,11 +89,8 @@ export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip
108
89
  /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
109
90
  extra?: Record<string, unknown>): Promise<void>;
110
91
  /**
111
- * Lease for the UTxO set import: the same `leaseOwner` / `leaseUntil` columns the crawler
112
- * uses, so a crawler start on ANY instance is refused while the import holds it (its CAS
113
- * sees a foreign owner with a live deadline) and a second import is refused the same way.
114
- * Unlike the crawler lease it does not require `desiredRunning` — the cluster is paused
115
- * during an import by design.
92
+ * Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
93
+ * instance and a second import are refused while it is held. Does not require `desiredRunning`.
116
94
  */
117
95
  export declare function tryAcquireImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
118
96
  export declare function renewImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;