@odatano/core 2.0.0-rc.44 → 2.0.0-rc.45

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 (168) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +5 -20
  4. package/@cds-models/CardanoODataService/index.d.ts +18 -47
  5. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  7. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  8. package/@cds-models/index.d.ts +17 -0
  9. package/@cds-models/index.js +2 -0
  10. package/@cds-models/odatano/cardano/index.d.ts +0 -34
  11. package/README.md +6 -6
  12. package/db/schema.cds +25 -44
  13. package/db/types.cds +22 -5
  14. package/package.json +3 -1
  15. package/scripts/migrate-slot-leader.mjs +3 -11
  16. package/scripts/migrate-txseq.mjs +3 -12
  17. package/src/index.d.ts +0 -4
  18. package/src/index.js +3 -5
  19. package/src/plugin.js +4 -8
  20. package/srv/blockchain/asset-decimals.d.ts +0 -9
  21. package/srv/blockchain/asset-decimals.js +21 -16
  22. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  23. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  24. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  25. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  26. package/srv/blockchain/backends/koios-backend.js +40 -164
  27. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  28. package/srv/blockchain/backends/odatano-backend.js +11 -12
  29. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  30. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  31. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  32. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  33. package/srv/blockchain/cardano-client.d.ts +12 -80
  34. package/srv/blockchain/cardano-client.js +36 -88
  35. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  36. package/srv/blockchain/cardano-indexer.js +126 -222
  37. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  38. package/srv/blockchain/cardano-tx-builder.js +17 -34
  39. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  40. package/srv/blockchain/circuit-breaker.js +5 -15
  41. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +0 -5
  42. package/srv/blockchain/crawler/asset-decimals-backfill.js +2 -5
  43. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  44. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  45. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  46. package/srv/blockchain/crawler/crawler.js +85 -160
  47. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -10
  48. package/srv/blockchain/crawler/credential-backfill.js +2 -4
  49. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  50. package/srv/blockchain/crawler/index.d.ts +0 -12
  51. package/srv/blockchain/crawler/index.js +6 -20
  52. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  53. package/srv/blockchain/crawler/sync-state.js +18 -53
  54. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  55. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  56. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  57. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  58. package/srv/blockchain/ledger-state.d.ts +10 -54
  59. package/srv/blockchain/ledger-state.js +11 -27
  60. package/srv/blockchain/pending-spends.d.ts +0 -12
  61. package/srv/blockchain/pending-spends.js +4 -12
  62. package/srv/blockchain/request-coalescer.d.ts +2 -16
  63. package/srv/blockchain/request-coalescer.js +2 -16
  64. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  65. package/srv/blockchain/signing/cose-verifier.js +4 -10
  66. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  67. package/srv/blockchain/signing/external-signer.js +2 -8
  68. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  69. package/srv/blockchain/signing/hsm-signer.js +16 -28
  70. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  71. package/srv/blockchain/signing/signature-verifier.js +9 -19
  72. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  73. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  74. package/srv/blockchain/stored-chain.d.ts +1 -14
  75. package/srv/blockchain/stored-chain.js +3 -8
  76. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  78. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  79. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  80. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  81. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  82. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  83. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  84. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  85. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  87. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  88. package/srv/blockchain/wallet-worker/index.js +3 -5
  89. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  90. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  91. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  93. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  94. package/srv/blockchain/wallet-worker/signers.js +3 -6
  95. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  96. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  97. package/srv/cardano-agent-service.cds +123 -146
  98. package/srv/cardano-agent-service.js +2 -5
  99. package/srv/cardano-backend-service.cds +10 -17
  100. package/srv/cardano-backend-service.js +7 -12
  101. package/srv/cardano-indexer-service.cds +16 -37
  102. package/srv/cardano-indexer-service.d.ts +5 -1
  103. package/srv/cardano-indexer-service.js +44 -35
  104. package/srv/cardano-service.cds +56 -40
  105. package/srv/cardano-service.js +42 -69
  106. package/srv/cardano-sign-service.cds +14 -23
  107. package/srv/cardano-sign-service.js +18 -24
  108. package/srv/cardano-tx-service.cds +27 -29
  109. package/srv/cardano-tx-service.js +60 -122
  110. package/srv/cardano-worker-service.cds +109 -125
  111. package/srv/cardano-worker-service.js +21 -31
  112. package/srv/cbor/cip68.d.ts +0 -4
  113. package/srv/cbor/cip68.js +2 -4
  114. package/srv/cbor/parse.d.ts +3 -18
  115. package/srv/cbor/parse.js +2 -7
  116. package/srv/cbor/plutus-data-json.d.ts +0 -4
  117. package/srv/server.d.ts +5 -36
  118. package/srv/server.js +30 -51
  119. package/srv/utils/agent-grants-config.d.ts +0 -18
  120. package/srv/utils/agent-grants-config.js +6 -13
  121. package/srv/utils/agent-grants.d.ts +14 -68
  122. package/srv/utils/agent-grants.js +42 -60
  123. package/srv/utils/agent-token-auth.d.ts +0 -5
  124. package/srv/utils/agent-token-auth.js +2 -5
  125. package/srv/utils/backend-request-handler.d.ts +1 -1
  126. package/srv/utils/collections.d.ts +1 -4
  127. package/srv/utils/collections.js +1 -4
  128. package/srv/utils/const.d.ts +0 -18
  129. package/srv/utils/const.js +7 -18
  130. package/srv/utils/crypto.js +3 -5
  131. package/srv/utils/db-indexes.d.ts +2 -0
  132. package/srv/utils/db-indexes.js +22 -9
  133. package/srv/utils/db-sanitize.d.ts +1 -8
  134. package/srv/utils/db-sanitize.js +3 -8
  135. package/srv/utils/epoch-slots.d.ts +1 -8
  136. package/srv/utils/epoch-slots.js +3 -8
  137. package/srv/utils/error-codes.d.ts +0 -4
  138. package/srv/utils/error-codes.js +2 -4
  139. package/srv/utils/errors.d.ts +2 -22
  140. package/srv/utils/errors.js +13 -27
  141. package/srv/utils/liveness.d.ts +0 -4
  142. package/srv/utils/liveness.js +2 -4
  143. package/srv/utils/mappers.d.ts +0 -37
  144. package/srv/utils/mappers.js +19 -39
  145. package/srv/utils/network-context.js +2 -4
  146. package/srv/utils/paging.d.ts +31 -0
  147. package/srv/utils/paging.js +43 -0
  148. package/srv/utils/pg-inline-json.js +3 -7
  149. package/srv/utils/pg-order-nulls.js +2 -5
  150. package/srv/utils/plutus-placeholders.d.ts +0 -13
  151. package/srv/utils/plutus-placeholders.js +6 -13
  152. package/srv/utils/rate-limiter.d.ts +0 -8
  153. package/srv/utils/rate-limiter.js +2 -4
  154. package/srv/utils/reference-script.d.ts +0 -18
  155. package/srv/utils/reference-script.js +8 -19
  156. package/srv/utils/service-events.d.ts +0 -4
  157. package/srv/utils/service-events.js +2 -4
  158. package/srv/utils/signing-helper.d.ts +1 -8
  159. package/srv/utils/signing-helper.js +3 -8
  160. package/srv/utils/tx-build-helper.d.ts +2 -32
  161. package/srv/utils/tx-build-helper.js +26 -40
  162. package/srv/utils/tx-request-parsers.d.ts +1 -25
  163. package/srv/utils/tx-request-parsers.js +10 -25
  164. package/srv/utils/tx-utils.d.ts +0 -8
  165. package/srv/utils/tx-utils.js +10 -13
  166. package/srv/utils/types.d.ts +2 -37
  167. package/srv/utils/validators.d.ts +0 -4
  168. package/srv/utils/validators.js +2 -4
@@ -22,11 +22,8 @@ class CrawlerStoppedError extends Error {
22
22
  class CrawlerLeaseLostError extends Error {
23
23
  constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
24
24
  }
25
- /**
26
- * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
27
- * Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
28
- * Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
29
- */
25
+ // Streams the chain forward from a start block and bulk-indexes it.
26
+ // Ogmios chain-sync is the primary source, provider pagination the fallback. Each block is written atomically.
30
27
  class CardanoCrawler {
31
28
  client;
32
29
  indexer;
@@ -39,10 +36,7 @@ class CardanoCrawler {
39
36
  static POISON_BLOCK_THRESHOLD = 5;
40
37
  /** Process-wide, survives instance restarts: the block currently failing and how often. */
41
38
  static poison = null;
42
- /**
43
- * Errors deterministic for the block's data — only these count towards the poison latch.
44
- * Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
45
- */
39
+ /** Errors caused by the block's data. Only these count towards the poison latch, outages never do. */
46
40
  static DATA_REJECTION_PATTERNS = [
47
41
  /unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
48
42
  /invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
@@ -71,7 +65,7 @@ class CardanoCrawler {
71
65
  chainSyncProbeTimer = null;
72
66
  chainSyncProbe = null;
73
67
  chainSyncRecovered = false;
74
- /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
68
+ /** The detached ingest pipeline. stop() awaits it so teardown never races it. */
75
69
  pipeline = null;
76
70
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
77
71
  wake = null;
@@ -89,7 +83,7 @@ class CardanoCrawler {
89
83
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
90
84
  streamEnded = null;
91
85
  finalStatus = 'stopped';
92
- /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
86
+ /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
93
87
  latchOnHalt = false;
94
88
  /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
95
89
  static SNAPSHOT_WINDOW_MARGIN = 10;
@@ -124,11 +118,7 @@ class CardanoCrawler {
124
118
  getActiveSource() {
125
119
  return this.running ? this.activeSource : null;
126
120
  }
127
- /**
128
- * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
129
- * Refuses to start without a resume point: an explicit configured start block or an
130
- * existing cursor — never an implicit full-chain sync from genesis.
131
- */
121
+ /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
132
122
  async start() {
133
123
  if (this.running)
134
124
  return;
@@ -141,7 +131,7 @@ class CardanoCrawler {
141
131
  // must never leave a healthy-looking crawler behind.
142
132
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.ensureSyncStateSingleton)(tx, this.network, start));
143
133
  if (!cursor.lastBlockHash && !start) {
144
- logger.error('Crawler start refused: no start block configured and no existing cursor — set crawler.startSlot + crawler.startBlockHash.');
134
+ logger.error('Crawler start refused: no start block configured and no existing cursor. Set crawler.startSlot + crawler.startBlockHash.');
145
135
  return;
146
136
  }
147
137
  if (this.leaseOwner) {
@@ -162,14 +152,13 @@ class CardanoCrawler {
162
152
  utxoSet: this.config.utxoSet,
163
153
  authoritative: this.config.authoritative ?? false,
164
154
  });
165
- // Ledger state is only ever applied from a known anchor — no snapshot, no writes.
155
+ // Ledger state is only applied after an imported snapshot.
166
156
  if (this.config.utxoSet) {
167
157
  const u = cursor.utxoSet;
168
- // Blocks crawled while the mode was off never reached the ledger tables: the cursor is
169
- // ahead of the last applied slot and the set cannot be caught up — invalidate it.
158
+ // Blocks crawled while the mode was off never reached the ledger tables, so the set is stale.
170
159
  const lastApplied = u.appliedSlot ?? u.anchorSlot;
171
160
  if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
172
- const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
161
+ const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied}: blocks were crawled without the set; re-import`;
173
162
  await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
174
163
  u.status = 'invalid';
175
164
  u.error = error;
@@ -177,11 +166,11 @@ class CardanoCrawler {
177
166
  if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
178
167
  this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
179
168
  void this.indexer.paymentCredentialsReady();
180
- logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
169
+ logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash}, ledger tables are maintained`);
181
170
  }
182
171
  else {
183
172
  this.indexer.setUtxoAnchor(null);
184
- logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''} — ` +
173
+ logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''}: ` +
185
174
  'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
186
175
  }
187
176
  }
@@ -189,8 +178,7 @@ class CardanoCrawler {
189
178
  this.indexer.setUtxoAnchor(null);
190
179
  }
191
180
  this.startLeaseHeartbeat();
192
- // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
193
- // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
181
+ // A pipeline crash must show on the cursor, or the crawler looks healthy while idle.
194
182
  this.pipeline = this.runIngestPipeline().catch(async (err) => {
195
183
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
196
184
  await this.halt('stopped');
@@ -201,21 +189,15 @@ class CardanoCrawler {
201
189
  await this.halt(streak < 0 ? 'stopped' : 'error');
202
190
  });
203
191
  }
204
- /**
205
- * Stop crawling and await the pipeline's in-flight step, so callers can tear down
206
- * backends/DB afterwards.
207
- */
192
+ /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
208
193
  async stop(finalStatus = 'stopped') {
209
194
  this.beginHalt(finalStatus);
210
195
  if (this.haltPromise)
211
196
  await this.haltPromise;
212
197
  this.pipeline = null;
213
198
  }
214
- /**
215
- * Halt without awaiting the pipeline — safe to call from inside it.
216
- * @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
217
- * a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
218
- */
199
+ // Halt without awaiting the pipeline, so it is safe to call from inside it.
200
+ // `latch` keeps the crawler down across restarts. Use it only for misconfiguration, never for outages.
219
201
  async halt(finalStatus = 'stopped', latch = false) {
220
202
  this.beginHalt(finalStatus, latch);
221
203
  }
@@ -228,11 +210,11 @@ class CardanoCrawler {
228
210
  this.finalStatus = finalStatus;
229
211
  this.running = false;
230
212
  this.activeSource = null;
231
- // Background asset enrichment belongs to the crawl — it must not outlive it.
213
+ // Background asset enrichment belongs to the crawl and must not outlive it.
232
214
  this.indexer.stopAssetEnrichment();
233
215
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
234
216
  this.stopChainSyncProbing();
235
- this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
217
+ this.streamEnded?.(); // release the ingest loop, the pipeline is awaited below
236
218
  this.leaseWake?.();
237
219
  for (const cancel of [...this.callCancels])
238
220
  cancel();
@@ -294,15 +276,14 @@ class CardanoCrawler {
294
276
  }
295
277
  if (failure?.height == null)
296
278
  return;
297
- logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
279
+ logger.warn(`chain-sync cannot deliver block ${failure.height}, switching to pagination until it is behind the cursor`);
298
280
  await this.runPagination({ untilHeight: failure.height + 1 });
299
281
  }
300
282
  return;
301
283
  }
302
284
  if (this.config.source === 'ogmios') {
303
- // 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
304
- // pagination reorg handling the operator explicitly opted out of.
305
- logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
285
+ // 'ogmios' means chain-sync only. Never fall back to pagination the operator opted out of.
286
+ logger.error("Crawler source is 'ogmios' but no chain-sync backend is available. Crawler not started (use source 'auto' to allow pagination fallback).");
306
287
  await this.halt('error', true); // config error: a restart cannot fix it
307
288
  return;
308
289
  }
@@ -312,19 +293,16 @@ class CardanoCrawler {
312
293
  }
313
294
  // 'auto' with no usable chain-sync backend (typical while the node still replays after a
314
295
  // restart): crawl on pagination and keep retrying chain-sync.
315
- logger.warn('No chain-sync backend usable — crawling on pagination and retrying chain-sync periodically');
296
+ logger.warn('No chain-sync backend usable, crawling on pagination and retrying chain-sync periodically');
316
297
  await this.runPagination({ untilChainSync: true });
317
298
  // Returned because chain-sync came back (or we stopped): the loop reopens it.
318
299
  }
319
300
  }
320
- /**
321
- * Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
322
- * one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
323
- * the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
324
- */
301
+ // Retry the chain-sync init on its own timer, because a poll sleep can last an hour.
302
+ // On success the sleep is cut short and the ingest loop reopens chain-sync.
325
303
  startChainSyncProbing() {
326
304
  this.chainSyncRecovered = false;
327
- // The startup init has only just failed — give the node a full interval first.
305
+ // The startup init has just failed, so give the node a full interval first.
328
306
  this.scheduleChainSyncProbe();
329
307
  }
330
308
  scheduleChainSyncProbe() {
@@ -356,7 +334,7 @@ class CardanoCrawler {
356
334
  clearTimeout(this.chainSyncProbeTimer);
357
335
  this.chainSyncProbeTimer = null;
358
336
  }
359
- /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
337
+ /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
360
338
  withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
361
339
  return new Promise((resolve, reject) => {
362
340
  let settled = false;
@@ -378,13 +356,13 @@ class CardanoCrawler {
378
356
  });
379
357
  }
380
358
  // ---------------------------------------------------------------------------
381
- // Chain-sync (Ogmios) — primary, reorg-aware
359
+ // Chain-sync (Ogmios): primary source, reorg-aware
382
360
  // ---------------------------------------------------------------------------
383
361
  async runChainSync(backend) {
384
362
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
385
363
  const points = await this.buildIntersectionPoints(cursor);
386
364
  if (!points.length) {
387
- // Defense in depth — start() already refuses this state.
365
+ // start() already refuses this state.
388
366
  logger.error('Chain-sync refused: no resume point (configured start block or cursor) available.');
389
367
  await this.halt('error', true); // config error: a restart cannot fix it
390
368
  return;
@@ -400,12 +378,11 @@ class CardanoCrawler {
400
378
  rollBackward: (point) => this.trackCallback(async () => {
401
379
  if (!this.running)
402
380
  return;
403
- // Ogmios ALWAYS opens the stream with a rollBackward to the intersection
404
- // point — that is the protocol handshake, not a reorg. Only roll back when
405
- // the point differs from our cursor.
381
+ // Ogmios always opens the stream with a rollBackward to the intersection. That is the
382
+ // handshake, not a reorg, so only roll back when the point differs from the cursor.
406
383
  const current = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
407
384
  if (point !== 'origin' && current?.lastBlockHash === point.hash) {
408
- logger.debug(`chain-sync intersection acknowledged at slot ${point.slot} — no reorg`);
385
+ logger.debug(`chain-sync intersection acknowledged at slot ${point.slot}, no reorg`);
409
386
  return;
410
387
  }
411
388
  await this.handleReorg(point);
@@ -413,18 +390,16 @@ class CardanoCrawler {
413
390
  onError: (err) => this.trackCallback(async () => {
414
391
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
415
392
  return;
416
- // A frame the client's parser cannot handle is a fault of that one block, not of the
417
- // crawler or the node — pagination can still fetch it, so degrade instead of halting.
393
+ // An unparseable frame is a fault of that one block. Pagination can still fetch it.
418
394
  if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
419
395
  await this.degradeToPagination(err);
420
396
  return;
421
397
  }
422
- // The server dropped the socket. After progress: reopen at the cursor. Without progress
423
- // the server fails on the next block itself (e.g. a header it cannot decode): fetch that
424
- // block over pagination, then chain-sync takes over again.
398
+ // Socket dropped. After progress, reopen at the cursor. Without progress the server
399
+ // cannot decode the next block, so fetch that block over pagination first.
425
400
  if (err instanceof errors_1.ChainSyncClosedError) {
426
401
  if (this.blocksThisStream > 0) {
427
- logger.warn(`${err.message} after ${this.blocksThisStream} block(s) — reopening chain-sync at the cursor`);
402
+ logger.warn(`${err.message} after ${this.blocksThisStream} block(s), reopening chain-sync at the cursor`);
428
403
  await this.endStream(() => { this.reopenStream = true; });
429
404
  return;
430
405
  }
@@ -434,14 +409,13 @@ class CardanoCrawler {
434
409
  return;
435
410
  }
436
411
  }
437
- // The stream is stalled (mapping/callback failure) — record and halt cleanly
438
- // so the cursor status shows 'error' instead of a healthy-looking hang.
412
+ // Record and halt, so the cursor shows 'error' instead of a healthy-looking hang.
439
413
  const streak = await this.recordCrawlerError(err);
440
- logger.error('Chain-sync stream error — stopping crawler:', err);
414
+ logger.error('Chain-sync stream error, stopping crawler:', err);
441
415
  await this.halt(streak < 0 ? 'stopped' : 'error');
442
416
  }),
443
417
  });
444
- // stop() may have raced the async open — close the fresh socket instead of leaking it.
418
+ // stop() may have raced the async open. Close the fresh socket instead of leaking it.
445
419
  if (!this.running) {
446
420
  try {
447
421
  await handle.close();
@@ -459,26 +433,19 @@ class CardanoCrawler {
459
433
  this.frameFailure = null;
460
434
  return failure;
461
435
  }
462
- /**
463
- * Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
464
- * backend, and a source not pinned to 'ogmios' (chain-sync only).
465
- */
466
436
  canDegradeToPagination(err) {
467
437
  return err.height != null
468
438
  && this.config.source !== 'ogmios'
469
439
  && !!this.client.getPaginatingBackend();
470
440
  }
471
- /**
472
- * End the chain-sync stream and hand back to the ingest loop, which continues on pagination
473
- * past the offending block. The error is recorded first so `lastError` names the block.
474
- */
441
+ /** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
475
442
  async degradeToPagination(err) {
476
443
  const streak = await this.recordCrawlerError(err);
477
444
  if (streak < 0) {
478
445
  await this.halt('stopped');
479
446
  return;
480
447
  }
481
- logger.error('Chain-sync cannot deliver a block — continuing on pagination:', err.message);
448
+ logger.error('Chain-sync cannot deliver a block, continuing on pagination:', err.message);
482
449
  await this.endStream(() => { this.frameFailure = err; });
483
450
  }
484
451
  /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
@@ -496,11 +463,8 @@ class CardanoCrawler {
496
463
  }
497
464
  this.streamEnded?.();
498
465
  }
499
- /**
500
- * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
501
- * ancestors, then the configured start block. If the cursor's block was orphaned while the
502
- * crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
503
- */
466
+ // Intersection points, newest first: cursor, crawled ancestors, configured start block.
467
+ // The ancestors let the node find the last common block if the cursor was orphaned.
504
468
  async buildIntersectionPoints(cursor) {
505
469
  const points = [];
506
470
  const seen = new Set();
@@ -543,13 +507,9 @@ class CardanoCrawler {
543
507
  return promise;
544
508
  }
545
509
  // ---------------------------------------------------------------------------
546
- // Pagination (Blockfrost/Koios) — fallback
510
+ // Pagination (Blockfrost, Koios): fallback source
547
511
  // ---------------------------------------------------------------------------
548
- /**
549
- * @param untilHeight return once the cursor reaches it — walks past a block chain-sync
550
- * cannot deliver, then hands back.
551
- * @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
552
- */
512
+ /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
553
513
  async runPagination(opts = {}) {
554
514
  if (opts.untilChainSync)
555
515
  this.startChainSyncProbing();
@@ -563,21 +523,20 @@ class CardanoCrawler {
563
523
  async paginate({ untilHeight, untilChainSync = false }) {
564
524
  const backend = this.client.getPaginatingBackend();
565
525
  if (!backend) {
566
- logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
526
+ logger.error('No paginating backend available: cannot crawl without Ogmios or Blockfrost/Koios');
567
527
  await this.halt('error', true); // config error: a restart cannot fix it
568
528
  return;
569
529
  }
570
530
  backend.configureCrawl?.({ certificates: this.config.certificates });
571
531
  this.activeSource = 'pagination';
572
532
  logger.info('Crawler running (pagination)');
573
- // Tip cache, refreshed only when the cursor reaches the cached target; during catch-up
574
- // the exact tip is irrelevant.
533
+ // Tip cache, refreshed only when the cursor reaches the cached target.
575
534
  let tip = null;
576
535
  let target = Number.NEGATIVE_INFINITY;
577
536
  while (this.running) {
578
537
  try {
579
538
  if (untilChainSync && this.chainSyncRecovered) {
580
- logger.info('chain-sync backend usable again — leaving pagination');
539
+ logger.info('chain-sync backend usable again, leaving pagination');
581
540
  return;
582
541
  }
583
542
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
@@ -587,7 +546,7 @@ class CardanoCrawler {
587
546
  return;
588
547
  }
589
548
  if (untilHeight != null && cursor.lastHeight >= untilHeight) {
590
- logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
549
+ logger.info(`pagination reached block ${cursor.lastHeight}, handing back to chain-sync`);
591
550
  return;
592
551
  }
593
552
  if (!tip || cursor.lastHeight >= target) {
@@ -595,8 +554,7 @@ class CardanoCrawler {
595
554
  target = (tip.height ?? 0) - this.config.confirmationDepth;
596
555
  }
597
556
  const tipHeight = tip.height ?? 0;
598
- // Unknown tip slot must mean "NOT at tip" — a 0-fallback would mark every
599
- // block 'synced' (block.slot >= 0 is always true).
557
+ // An unknown tip slot means "not at tip". A 0 fallback would mark every block 'synced'.
600
558
  const tipPoint = tip.slot != null
601
559
  ? { slot: tip.slot, hash: tip.hash, height: tipHeight }
602
560
  : undefined;
@@ -615,8 +573,7 @@ class CardanoCrawler {
615
573
  continue;
616
574
  }
617
575
  const blocks = await this.withTimeout(
618
- // pass the cursor height as anchor hint (>0 only — 0 can mean "unknown"
619
- // on a fresh start without configured startHeight)
576
+ // Cursor height as a hint. Height 0 can mean unknown on a fresh start.
620
577
  backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
621
578
  if (!blocks.length) {
622
579
  await this.pollPause(untilChainSync);
@@ -631,8 +588,7 @@ class CardanoCrawler {
631
588
  const ok = await this.persistBlock(block, txs, tipPoint);
632
589
  if (!ok)
633
590
  return; // persistBlock already recorded + halted
634
- // Chain-sync came back mid-batch: the block just written is complete and on the
635
- // cursor, the rest of the batch is cheaper to stream than to fetch one by one.
591
+ // Chain-sync came back mid-batch. Streaming the rest is cheaper than fetching it.
636
592
  if (untilChainSync && this.chainSyncRecovered)
637
593
  break;
638
594
  }
@@ -640,9 +596,8 @@ class CardanoCrawler {
640
596
  catch (err) {
641
597
  if (!this.running || err instanceof CrawlerStoppedError)
642
598
  return;
643
- // Only the backend's explicit anchor/hash mismatch proves that our cursor may
644
- // be orphaned. Provider outages and partial tx responses must back off instead
645
- // of launching up to 100 additional provider calls.
599
+ // Only an explicit chain point mismatch suggests an orphaned cursor.
600
+ // Outages back off instead of starting up to 100 more provider calls.
646
601
  if (err instanceof Error && err.message.startsWith(CHAIN_POINT_MISMATCH_PREFIX)) {
647
602
  const recovered = await this.tryReorgRecovery(backend).catch(() => false);
648
603
  if (recovered)
@@ -664,20 +619,14 @@ class CardanoCrawler {
664
619
  }
665
620
  }
666
621
  }
667
- /**
668
- * Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
669
- * since the probe's wake-up only reaches a sleep that has begun.
670
- */
622
+ /** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
671
623
  async pollPause(untilChainSync) {
672
624
  if (untilChainSync && this.chainSyncRecovered)
673
625
  return;
674
626
  await this.sleep(this.config.pollIntervalMs);
675
627
  }
676
- /**
677
- * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
678
- * our stored one until they agree — that height is the fork point. If the last-indexed
679
- * block still matches on-chain, there is no reorg (returns false → treat as transient).
680
- */
628
+ // Walk back by height until the on-chain hash matches the stored one. That height is the fork point.
629
+ // Returns false if the cursor block still matches, so the error counts as transient.
681
630
  async tryReorgRecovery(backend) {
682
631
  if (!this.running)
683
632
  return false;
@@ -704,8 +653,7 @@ class CardanoCrawler {
704
653
  if (ours?.hash && onChain.hash === ours.hash) {
705
654
  if (h === cursor.lastHeight)
706
655
  return false; // tip still matches → not a reorg
707
- // A null provider slot would make forkSlot 0 and wipe the entire crawled dataset —
708
- // abort this round instead.
656
+ // A null slot would make forkSlot 0 and wipe all crawled data.
709
657
  if (onChain.slot == null)
710
658
  return false;
711
659
  await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
@@ -717,18 +665,13 @@ class CardanoCrawler {
717
665
  // ---------------------------------------------------------------------------
718
666
  // Persist + reorg (shared)
719
667
  // ---------------------------------------------------------------------------
720
- /**
721
- * Persist one block atomically and advance the cursor. Transient failures are retried; the
722
- * cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
723
- * @returns true when the block was persisted, false when the crawler was stopped
724
- */
668
+ /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
725
669
  async persistBlock(block, txs, tip) {
726
670
  if (txs.length !== block.txCount) {
727
671
  throw new errors_1.ProviderUnavailableError(`Incomplete block ${block.hash}: backend returned ${txs.length}/${block.txCount} transactions`, 'crawler');
728
672
  }
729
673
  const isAtTip = tip != null && block.slot != null && block.slot >= tip.slot;
730
- // Epoch enrichment needs a backend round-trip on epoch boundaries — do it BEFORE
731
- // opening the write transaction so the DB lock is never held across network I/O.
674
+ // Fetch epoch data before the write transaction, so no DB lock is held across network I/O.
732
675
  if (block.epoch != null) {
733
676
  await this.indexer.prefetchCrawlEpoch(block.epoch);
734
677
  }
@@ -738,8 +681,7 @@ class CardanoCrawler {
738
681
  try {
739
682
  await cds_1.default.tx(async (tx) => {
740
683
  await this.indexer.indexBlockFull(tx, block, txs);
741
- // Ledger progress marker: written in the same statement as the cursor, so "the
742
- // cursor is ahead of the marker" always means blocks went by without the set.
684
+ // Written with the cursor, so a cursor ahead of this marker means blocks skipped the set.
743
685
  const anchor = this.indexer.getUtxoAnchor();
744
686
  const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
745
687
  // The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
@@ -751,14 +693,12 @@ class CardanoCrawler {
751
693
  this.indexer.confirmBlockCommit();
752
694
  if (CardanoCrawler.poison?.hash === block.hash)
753
695
  CardanoCrawler.poison = null;
754
- // A ledger invalidation decided inside the block transaction takes effect in memory
755
- // only now, after the commit that carries it — a rolled-back attempt changes nothing.
696
+ // Applied in memory only after the commit, so a rolled-back attempt changes nothing.
756
697
  const invalidation = this.indexer.takeLedgerInvalidation();
757
698
  if (invalidation) {
758
- logger.error(`UTxO set invalidated: ${invalidation} — ledger tables stop updating until importUtxoSet runs again`);
699
+ logger.error(`UTxO set invalidated: ${invalidation}. Ledger tables stop updating until importUtxoSet runs again`);
759
700
  }
760
- // Notify observers (wallet-worker confirmation tracker) AFTER the commit —
761
- // listener failures are swallowed inside emitBlockIndexed.
701
+ // Notify observers after the commit. emitBlockIndexed swallows listener failures.
762
702
  (0, hooks_1.emitBlockIndexed)({
763
703
  hash: block.hash,
764
704
  slot: block.slot ?? null,
@@ -782,7 +722,7 @@ class CardanoCrawler {
782
722
  return false;
783
723
  }
784
724
  if (attempt < CardanoCrawler.PERSIST_RETRIES && streak < sync_state_1.MAX_CONSECUTIVE_ERRORS) {
785
- logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}) — retrying:`, err);
725
+ logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}), retrying:`, err);
786
726
  await this.sleep(1000 * attempt);
787
727
  continue;
788
728
  }
@@ -791,17 +731,16 @@ class CardanoCrawler {
791
731
  if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
792
732
  const cause = err instanceof Error ? err.message : String(err);
793
733
  const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
794
- 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);
795
- // Lease-independent on purpose (see latchPoisonBlock); the memory is only forgotten
796
- // once the latch is durable, so a failed write is retried after the next restart.
797
- 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; });
734
+ 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);
735
+ // Memory is cleared only once the latch is stored, so a failed write retries after restart.
736
+ 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; });
798
737
  if (latched)
799
738
  CardanoCrawler.poison = null;
800
739
  await this.halt('error', true);
801
740
  return false;
802
741
  }
803
742
  const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
804
- logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
743
+ logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock}, stopping crawler (resume re-syncs from cursor):`, err);
805
744
  await this.halt('error');
806
745
  return false;
807
746
  }
@@ -813,19 +752,14 @@ class CardanoCrawler {
813
752
  ?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
814
753
  return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
815
754
  }
816
- /**
817
- * Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
818
- * state is read AT the block, which works while the block is inside the node's volatile window
819
- * (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
820
- * tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
821
- * `EpochLedgerSnapshots` (or a pool row written before the marker existed).
822
- */
755
+ // Snapshot pools and DReps once per epoch. Ogmios reads the ledger at a block within k of the tip.
756
+ // Koios reports only current state, so the crawl must be in the tip's epoch. Other epochs are skipped.
823
757
  maybeSnapshotEpoch(block, tip) {
824
758
  if (!this.config.epochSnapshots || block.epoch == null)
825
759
  return;
826
760
  if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
827
761
  return;
828
- // No tip reported = we cannot prove we are live, so we do not pretend to be.
762
+ // Without a tip the crawler cannot prove it is live.
829
763
  if (tip == null) {
830
764
  logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
831
765
  return;
@@ -843,7 +777,7 @@ class CardanoCrawler {
843
777
  else {
844
778
  const tipEpoch = this.epochOfSlot(tip.slot);
845
779
  if (block.epoch !== tipEpoch) {
846
- logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
780
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}); ` +
847
781
  `the provider reports the pool/DRep set as it is now, never as it was`);
848
782
  return;
849
783
  }
@@ -860,7 +794,7 @@ class CardanoCrawler {
860
794
  const previous = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('max(epoch) as e').where({ epoch: { '<': epoch } })));
861
795
  const last = previous?.e == null ? null : Number(previous.e);
862
796
  if (last != null && epoch > last + 1) {
863
- logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1} — passed outside the snapshot window`);
797
+ logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1}: passed outside the snapshot window`);
864
798
  }
865
799
  }
866
800
  this.snapshotedEpoch = epoch;
@@ -868,8 +802,7 @@ class CardanoCrawler {
868
802
  this.snapshotRetryAfter = 0;
869
803
  })
870
804
  .catch((err) => {
871
- // Never fatal: the crawl keeps its data, the epoch is retried on a later block —
872
- // but not on the very next one, or an outage would re-enumerate per block.
805
+ // Never fatal. The epoch is retried after a backoff, so an outage does not re-run per block.
873
806
  this.snapshotFailures++;
874
807
  const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
875
808
  this.snapshotRetryAfter = Date.now() + backoff;
@@ -878,11 +811,8 @@ class CardanoCrawler {
878
811
  })
879
812
  .finally(() => { this.snapshotInFlight = null; });
880
813
  }
881
- /**
882
- * Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
883
- * height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
884
- * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
885
- */
814
+ // Roll back in one transaction. Deletes blocks after the fork slot, never by height, and their transactions.
815
+ // Lazily indexed transactions of other blocks stay. Resets the cursor and logs the reorg.
886
816
  async handleReorg(point) {
887
817
  const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
888
818
  let blocksRolledBack = 0;
@@ -897,7 +827,7 @@ class CardanoCrawler {
897
827
  if (!renewed)
898
828
  throw new CrawlerLeaseLostError();
899
829
  }
900
- // Fork height is metrics/cursor info only — NEVER a delete axis.
830
+ // Fork height is for the cursor and the log only, never a delete criterion.
901
831
  let forkHeight = point === 'origin' ? 0 : point.height;
902
832
  if (forkHeight == null && point !== 'origin') {
903
833
  const fb = await tx.run(SELECT.one.from(cardano_1.Blocks).where({ hash: point.hash }));
@@ -905,20 +835,18 @@ class CardanoCrawler {
905
835
  }
906
836
  emittedForkHeight = forkHeight ?? null;
907
837
  // Blocks strictly after the fork, cut on the absolute-slot axis. Rows without a
908
- // slot (pre-v2.0 lazily indexed blocks) are deliberately excluded.
838
+ // slot (lazily indexed blocks from an older schema) are deliberately excluded.
909
839
  const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': forkSlot } }));
910
840
  const blockHashes = staleBlocks.map((b) => b.hash);
911
841
  blocksRolledBack = blockHashes.length;
912
842
  for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
913
- // Only transactions of the rolled-back blocks — resolved via blockHash, so
914
- // lazily-indexed txs of unrelated blocks are not collateral damage.
843
+ // Select by blockHash, so lazily indexed transactions of other blocks stay.
915
844
  const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
916
845
  const txHashes = staleTxs.map((t) => t.hash);
917
846
  txsRolledBack += txHashes.length;
918
847
  rolledBackTxHashes.push(...txHashes);
919
848
  for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
920
- // These denormalized/lazy indexes have no generated FK cascades. Remove
921
- // them before their parent tx/output rows so orphan data cannot leak via OData.
849
+ // These tables have no cascading delete. Remove them first so no orphans leak via OData.
922
850
  await tx.run(DELETE.from(cardano_1.UTxOAssets).where({ utxo_hash: { in: txChunk } }));
923
851
  await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
924
852
  await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
@@ -933,14 +861,13 @@ class CardanoCrawler {
933
861
  await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
934
862
  }
935
863
  }
936
- // Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
937
- // progress marker follows the cursor back; a fork before the anchor invalidates the set.
864
+ // Uses the stored status. A fork after the snapshot slot is undone, one before it invalidates the set.
938
865
  const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
939
866
  if (persisted?.status === 'active' && persisted.anchorSlot != null) {
940
867
  if (forkSlot < persisted.anchorSlot) {
941
868
  await (0, sync_state_1.setUtxoSetState)(tx, {
942
869
  status: 'invalid',
943
- error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot} — re-import the set`,
870
+ error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot}: re-import the set`,
944
871
  });
945
872
  ledgerInvalidated = true;
946
873
  }
@@ -975,11 +902,9 @@ class CardanoCrawler {
975
902
  }
976
903
  if (ledgerInvalidated) {
977
904
  this.indexer.setUtxoAnchor(null);
978
- logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor — ledger tables stop updating until importUtxoSet runs again`);
905
+ logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor. Ledger tables stop updating until importUtxoSet runs again`);
979
906
  }
980
- // Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
981
- // the rollback commit.
982
- // The rollback may have removed this epoch's snapshot; the next block re-checks it.
907
+ // The rollback may have removed this epoch's snapshot. The next block re-checks it.
983
908
  this.snapshotedEpoch = null;
984
909
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
985
910
  logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
@@ -1046,7 +971,7 @@ class CardanoCrawler {
1046
971
  this.leaseWake = () => { clearTimeout(timer); this.leaseWake = null; resolve(); };
1047
972
  });
1048
973
  }
1049
- /** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
974
+ /** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
1050
975
  sleep(ms) {
1051
976
  return new Promise((resolve) => {
1052
977
  const timer = setTimeout(() => { this.wake = null; resolve(); }, ms);