@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -3,38 +3,503 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CRAWLER_STALL_MS = void 0;
7
+ exports.isCrawlerStalled = isCrawlerStalled;
6
8
  const cds_1 = __importDefault(require("@sap/cds"));
7
9
  const backend_request_handler_1 = require("./utils/backend-request-handler");
8
10
  const errors_1 = require("./utils/errors");
9
11
  const crawler_1 = require("./blockchain/crawler");
10
12
  const sync_state_1 = require("./blockchain/crawler/sync-state");
13
+ const utxo_set_import_1 = require("./blockchain/crawler/utxo-set-import");
14
+ const certificate_backfill_1 = require("./blockchain/crawler/certificate-backfill");
15
+ const transaction_backfill_1 = require("./blockchain/crawler/transaction-backfill");
16
+ const credential_backfill_1 = require("./blockchain/crawler/credential-backfill");
17
+ const asset_decimals_backfill_1 = require("./blockchain/crawler/asset-decimals-backfill");
18
+ const asset_registry_backfill_1 = require("./blockchain/crawler/asset-registry-backfill");
19
+ const output_datum_backfill_1 = require("./blockchain/crawler/output-datum-backfill");
20
+ const metadata_position_backfill_1 = require("./blockchain/crawler/metadata-position-backfill");
21
+ const asset_slice_backfill_1 = require("./blockchain/crawler/asset-slice-backfill");
22
+ const input_asset_copies_1 = require("./blockchain/crawler/input-asset-copies");
23
+ const validators_1 = require("./utils/validators");
11
24
  const server_1 = require("./server");
25
+ const config_1 = require("./config");
26
+ const liveness_1 = require("./utils/liveness");
27
+ const readiness_1 = require("./utils/readiness");
28
+ const result_numbers_1 = require("./utils/result-numbers");
29
+ const detached_run_1 = require("./utils/detached-run");
30
+ const failed_recheck_1 = require("./blockchain/signing/failed-recheck");
31
+ const cardano_1 = require("#cds-models/odatano/cardano");
32
+ const { SELECT } = cds_1.default.ql;
12
33
  const logger = cds_1.default.log('CardanoIndexerService');
13
- /**
14
- * CardanoIndexerService handlers — thin control/observability surface over the crawler
15
- * singleton (srv/blockchain/crawler). Engine logic lives there; this only reads the
16
- * cursor and starts/stops the crawler.
17
- */
34
+ // One run per kind and process. Each keeps the state of its last run until the next start.
35
+ const certificateRun = new detached_run_1.DetachedRun('Certificate backfill', { fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0 }, ['fromSlot', 'toSlot', 'atSlot']);
36
+ const transactionRun = new detached_run_1.DetachedRun('Transaction backfill', { fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, inputs: 0, outputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0 }, ['fromSlot', 'toSlot', 'atSlot']);
37
+ const credentialRun = new detached_run_1.DetachedRun('Payment-credential backfill', { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0 });
38
+ const decimalsRun = new detached_run_1.DetachedRun('Asset-decimals backfill', { scanned: 0, candidates: 0, filled: 0 });
39
+ const registryRun = new detached_run_1.DetachedRun('Asset-registry backfill', { units: 0, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 });
40
+ const datumRun = new detached_run_1.DetachedRun('Output-datum backfill', { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 });
41
+ const metadataRun = new detached_run_1.DetachedRun('Metadata-position backfill', { atSlot: 0, toSlot: 0, rows: 0 }, ['atSlot', 'toSlot']);
42
+ const sliceRun = new detached_run_1.DetachedRun('Asset-slice backfill', { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, ledgerAddresses: 0, utxoSlices: 0, addressSlices: 0 });
43
+ const epochRun = new detached_run_1.DetachedRun('Epoch backfill', { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 });
44
+ const recheckRun = new detached_run_1.DetachedRun('Re-check of failed submits', { submissions: 0, requests: 0, jobs: 0, restored: 0 });
45
+ const pruneRun = new detached_run_1.DetachedRun('Prune of input asset copies', { atSlot: 0, toSlot: 0, referenced: 0, kept: 0, deleted: 0 }, ['atSlot', 'toSlot']);
46
+ const restoreRun = new detached_run_1.DetachedRun('Restore of input asset copies', { atSlot: 0, toSlot: 0, restored: 0, rows: 0 }, ['atSlot', 'toSlot']);
47
+ /** The UTxO set import and its two repairs: one at a time, the status shows it as importing. */
48
+ const utxoSetRun = new detached_run_1.DetachedRun('UTxO set import', {});
49
+ /** The runs cancelMaintenance can stop, by the name getStatus shows them under. */
50
+ const CANCELLABLE = {
51
+ certificateBackfill: certificateRun,
52
+ transactionBackfill: transactionRun,
53
+ credentialBackfill: credentialRun,
54
+ decimalsBackfill: decimalsRun,
55
+ registryBackfill: registryRun,
56
+ datumBackfill: datumRun,
57
+ metadataBackfill: metadataRun,
58
+ epochBackfill: epochRun,
59
+ failedRecheck: recheckRun,
60
+ sliceBackfill: sliceRun,
61
+ copyPrune: pruneRun,
62
+ copyRestore: restoreRun,
63
+ };
64
+ /** Slot range of a backfill: defaults to crawl start .. cursor, never past the cursor. */
65
+ async function backfillRange(db, data) {
66
+ const cursor = await (0, sync_state_1.readCursor)(db);
67
+ if (!cursor)
68
+ throw new errors_1.TransactionValidationError('No crawler cursor yet. The backfill covers crawled blocks only.');
69
+ const fromSlot = data.fromSlot != null ? Number(data.fromSlot) : (cursor.startSlot ?? 0);
70
+ const toSlot = data.toSlot != null ? Number(data.toSlot) : cursor.lastSlot;
71
+ if (toSlot < fromSlot)
72
+ throw new errors_1.TransactionValidationError(`toSlot ${toSlot} lies before fromSlot ${fromSlot}.`);
73
+ if (toSlot > cursor.lastSlot)
74
+ throw new errors_1.TransactionValidationError(`toSlot ${toSlot} is past the crawler cursor (slot ${cursor.lastSlot}). Only crawled blocks can be backfilled.`);
75
+ return { fromSlot, toSlot };
76
+ }
77
+ /** A crawler switch as configured; false when the configuration is invalid. */
78
+ function crawlerOption(name) {
79
+ try {
80
+ return Boolean((0, config_1.loadCrawlerConfigFromEnv)()?.[name]);
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /** Source the next epoch snapshot would use: the node's ledger first, Koios second. */
87
+ function epochSnapshotSource() {
88
+ try {
89
+ const client = (0, server_1.getCardanoClient)();
90
+ if (client.getEpochStateBackend())
91
+ return 'ogmios';
92
+ return client.getEnumeratingBackend() ? 'koios' : null;
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ /** No block committed for this long while the crawler holds its lease: it is stuck. */
99
+ exports.CRAWLER_STALL_MS = 10 * 60 * 1000;
100
+ /** A crawler that holds the lease but has committed no block within CRAWLER_STALL_MS. */
101
+ function isCrawlerStalled(cursor, now = Date.now()) {
102
+ if (!cursor || !(0, sync_state_1.isCrawlerLeaseActive)(cursor) || !cursor.lastIndexedAt)
103
+ return false;
104
+ return now - Date.parse(cursor.lastIndexedAt) > exports.CRAWLER_STALL_MS;
105
+ }
106
+ /** CardanoIndexerService handlers. They read the crawler cursor and start or stop the crawler. */
18
107
  module.exports = (srv) => {
19
- // getStatus — live run state + sync progress (numeric fields as strings, CAP-10 aligned)
108
+ (0, result_numbers_1.answerNumbersAsText)(srv);
109
+ // getLiveness: unauthenticated probe. No handleRequest and no app context.
110
+ srv.on('getLiveness', async () => (0, liveness_1.buildLiveness)());
111
+ // getReadiness: unauthenticated probe. A missing part answers 503 with the same body.
112
+ srv.on('getReadiness', async (req) => {
113
+ const readiness = await (0, readiness_1.buildReadiness)((0, server_1.readinessParts)());
114
+ if (readiness.status !== 'ready')
115
+ req.http?.res.status(503);
116
+ return readiness;
117
+ });
118
+ // getStatus: run state and sync progress. Numeric fields are strings, as CAP 10 serializes them.
20
119
  srv.on('getStatus', async (req) => {
21
120
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
22
121
  const cursor = await (0, sync_state_1.readCursor)(db);
122
+ const lastSnapshot = await db.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch', 'source', 'snapshotSlot').orderBy('epoch desc'));
123
+ const lastAccounts = await db.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch', 'accountCount').where({ accountCount: { '!=': null } }).orderBy('epoch desc'));
23
124
  const lastHeight = cursor?.lastHeight ?? 0;
24
125
  const tipHeight = cursor?.tipHeight ?? 0;
25
126
  const progress = tipHeight > 0 ? Math.min(100, (lastHeight / tipHeight) * 100) : 0;
26
127
  return {
27
128
  running: (0, sync_state_1.isCrawlerLeaseActive)(cursor),
28
129
  syncStatus: cursor?.syncStatus ?? 'stopped',
130
+ // Process-local: a standby without the lease or a stopped crawler reports null.
131
+ source: (0, crawler_1.getCrawler)()?.getActiveSource() ?? null,
29
132
  lastSlot: String(cursor?.lastSlot ?? 0),
30
133
  lastHeight: String(lastHeight),
31
134
  tipHeight: String(tipHeight),
32
135
  syncProgress: progress.toFixed(2),
33
136
  consecutiveErrors: cursor?.consecutiveErrors ?? 0,
137
+ lastIndexedAt: cursor?.lastIndexedAt ?? null,
138
+ stalled: isCrawlerStalled(cursor),
139
+ nodeBehindSince: cursor?.nodeBehindSince ?? null,
140
+ utxoSet: {
141
+ enabled: crawlerOption('utxoSet'),
142
+ status: utxoSetRun.isBusy() ? 'importing' : (cursor?.utxoSet?.status ?? 'none'),
143
+ anchorSlot: cursor?.utxoSet?.anchorSlot == null ? null : String(cursor.utxoSet.anchorSlot),
144
+ anchorHash: cursor?.utxoSet?.anchorHash ?? null,
145
+ importedAt: cursor?.utxoSet?.importedAt ?? null,
146
+ error: cursor?.utxoSet?.error ?? null,
147
+ },
148
+ ...Object.fromEntries(Object.entries(CANCELLABLE).map(([name, run]) => [name, run.snapshot()])),
149
+ epochBackfill: epochRun.snapshot(),
150
+ epochSnapshots: {
151
+ enabled: crawlerOption('epochSnapshots'),
152
+ source: epochSnapshotSource(),
153
+ lastEpoch: lastSnapshot?.epoch ?? null,
154
+ lastSource: lastSnapshot?.source ?? null,
155
+ lastSlot: lastSnapshot?.snapshotSlot == null ? null : String(lastSnapshot.snapshotSlot),
156
+ accounts: crawlerOption('accountSnapshots'),
157
+ lastAccountEpoch: lastAccounts?.epoch ?? null,
158
+ lastAccountCount: lastAccounts?.accountCount ?? null,
159
+ },
34
160
  };
35
161
  });
36
162
  });
37
- // pauseCrawler — stop the stream; the cursor is preserved so resume continues.
163
+ const busy = (req, action, run) => (0, errors_1.rejectInvalid)(req, action, `${run.label} is already running`);
164
+ /** A transaction backfill rewrites inputs a prune or restore moves, so they never overlap. */
165
+ const copyWalkBusy = () => pruneRun.isBusy() || restoreRun.isBusy();
166
+ // backfillCertificates: a second chain-sync stream over crawled blocks.
167
+ // Writes only the certificate and withdrawal tables and runs detached.
168
+ srv.on('backfillCertificates', async (req) => {
169
+ const data = (req.data ?? {});
170
+ if (certificateRun.isBusy())
171
+ return busy(req, 'backfillCertificates', certificateRun);
172
+ if (!(0, server_1.getCardanoClient)().getChainSyncBackend())
173
+ return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'No chain-sync backend available (needs Ogmios)');
174
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => certificateRun.start(async () => {
175
+ const { fromSlot, toSlot } = await backfillRange(db, data);
176
+ return {
177
+ initial: { fromSlot, toSlot, atSlot: fromSlot },
178
+ run: (ctl) => (0, certificate_backfill_1.backfillCertificates)({
179
+ client: (0, server_1.getCardanoClient)(), fromSlot, toSlot, shouldStop: ctl.shouldStop,
180
+ onProgress: (p) => {
181
+ ctl.progress(p);
182
+ if (p.blocks % 20_000 < 200)
183
+ logger.info(`Certificate backfill at slot ${p.atSlot}: ${p.blocks} blocks, ${p.certificates} certificates, ${p.withdrawals} withdrawals`);
184
+ },
185
+ }),
186
+ answer: {
187
+ accepted: true,
188
+ fromSlot: String(fromSlot),
189
+ toSlot: String(toSlot),
190
+ message: `Certificate backfill started for slots ${fromSlot}..${toSlot}; poll getStatus().certificateBackfill.`,
191
+ },
192
+ };
193
+ }));
194
+ });
195
+ // backfillTransactions: a second chain-sync stream over crawled blocks.
196
+ // Fills empty input fields and the redeemers and runs detached.
197
+ srv.on('backfillTransactions', async (req) => {
198
+ const data = (req.data ?? {});
199
+ if (transactionRun.isBusy())
200
+ return busy(req, 'backfillTransactions', transactionRun);
201
+ if (copyWalkBusy())
202
+ return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'A prune or restore of input asset copies is running; it moves the inputs this backfill rewrites');
203
+ if (!(0, server_1.getCardanoClient)().getChainSyncBackend())
204
+ return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'No chain-sync backend available (needs Ogmios)');
205
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => transactionRun.start(async () => {
206
+ const { fromSlot, toSlot } = await backfillRange(db, data);
207
+ return {
208
+ initial: { fromSlot, toSlot, atSlot: fromSlot },
209
+ run: (ctl) => (0, transaction_backfill_1.backfillTransactions)({
210
+ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), fromSlot, toSlot, shouldStop: ctl.shouldStop,
211
+ onProgress: (p) => {
212
+ ctl.progress(p);
213
+ if (p.blocks % 20_000 < 200)
214
+ logger.info(`Transaction backfill at slot ${p.atSlot}: ${p.blocks} blocks, ${p.inputs} inputs, ${p.redeemers} redeemers`);
215
+ },
216
+ }),
217
+ answer: {
218
+ accepted: true,
219
+ fromSlot: String(fromSlot),
220
+ toSlot: String(toSlot),
221
+ message: `Transaction backfill started for slots ${fromSlot}..${toSlot}; poll getStatus().transactionBackfill.`,
222
+ },
223
+ };
224
+ }));
225
+ });
226
+ // backfillPaymentCredentials: fills the credential from the stored address in every UTxO table.
227
+ // Needs no backend and runs detached. Progress is in getStatus().credentialBackfill.
228
+ srv.on('backfillPaymentCredentials', async (req) => {
229
+ if (credentialRun.isBusy())
230
+ return busy(req, 'backfillPaymentCredentials', credentialRun);
231
+ return credentialRun.start(() => ({
232
+ run: (ctl) => (0, credential_backfill_1.backfillUtxoCredentials)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
233
+ answer: { accepted: true, message: 'Payment-credential backfill started; poll getStatus().credentialBackfill.' },
234
+ }));
235
+ });
236
+ // backfillAssetDecimals: reads the CIP-68 reference datum of every label 333 and 444 unit.
237
+ // Needs no backend and runs detached. Progress is in getStatus().decimalsBackfill.
238
+ srv.on('backfillAssetDecimals', async (req) => {
239
+ if (decimalsRun.isBusy())
240
+ return busy(req, 'backfillAssetDecimals', decimalsRun);
241
+ return decimalsRun.start(() => ({
242
+ run: (ctl) => (0, asset_decimals_backfill_1.backfillAssetDecimals)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
243
+ answer: { accepted: true, message: 'Asset-decimals backfill started; poll getStatus().decimalsBackfill.' },
244
+ }));
245
+ });
246
+ // backfillAssetRegistry: writes the CIP-26 registry fields of every registered unit. The registry is
247
+ // off-chain: it comes from a backend that lists it, or from the entry files of its repository.
248
+ srv.on('backfillAssetRegistry', async (req) => {
249
+ const data = (req.data ?? {});
250
+ const source = data.source ?? 'koios';
251
+ if (registryRun.isBusy())
252
+ return busy(req, 'backfillAssetRegistry', registryRun);
253
+ if (source === 'file' && !data.path)
254
+ return (0, errors_1.rejectMissing)(req, 'backfillAssetRegistry', 'path');
255
+ if (source !== 'file' && !(0, server_1.getCardanoClient)().getTokenRegistryBackend()) {
256
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', 'No backend lists the token registry (needs Koios, or source file)');
257
+ }
258
+ const directory = source === 'file' ? String(data.path) : null;
259
+ try {
260
+ return await registryRun.start(async () => {
261
+ if (directory)
262
+ await (0, asset_registry_backfill_1.registryEntryFiles)(directory);
263
+ return {
264
+ run: (ctl) => directory
265
+ ? (0, asset_registry_backfill_1.backfillAssetRegistryFromFiles)({ directory, onProgress: ctl.progress, shouldStop: ctl.shouldStop })
266
+ : (0, asset_registry_backfill_1.backfillAssetRegistry)({ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
267
+ answer: { accepted: true, message: 'Asset-registry backfill started; poll getStatus().registryBackfill.' },
268
+ };
269
+ });
270
+ }
271
+ catch (err) {
272
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', err instanceof Error ? err.message : String(err), 'path');
273
+ }
274
+ });
275
+ // backfillOutputDatums: reads transactions again whose outputs hold a datum hash and no inline
276
+ // datum. Needs a backend that serves transactions. Progress is in getStatus().datumBackfill.
277
+ srv.on('backfillOutputDatums', async (req) => {
278
+ if (datumRun.isBusy())
279
+ return busy(req, 'backfillOutputDatums', datumRun);
280
+ if (!(0, server_1.getCardanoClient)().supports('getTransaction')) {
281
+ return (0, errors_1.rejectInvalid)(req, 'backfillOutputDatums', 'No configured backend serves transactions. With Ogmios only, run backfillTransactions over the crawled range');
282
+ }
283
+ return datumRun.start(() => ({
284
+ run: (ctl) => (0, output_datum_backfill_1.backfillOutputDatums)({ client: (0, server_1.getCardanoClient)(), onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
285
+ answer: { accepted: true, message: 'Output-datum backfill started; poll getStatus().datumBackfill.' },
286
+ }));
287
+ });
288
+ // backfillMetadataPositions: writes the chain position to metadata rows that lack it.
289
+ // Needs no backend and runs detached. Progress is in getStatus().metadataBackfill.
290
+ srv.on('backfillMetadataPositions', async (req) => {
291
+ const data = (req.data ?? {});
292
+ const range = { fromSlot: data.fromSlot == null ? null : Number(data.fromSlot), toSlot: data.toSlot == null ? null : Number(data.toSlot) };
293
+ if (range.fromSlot != null && range.toSlot != null && range.fromSlot > range.toSlot) {
294
+ return (0, errors_1.rejectInvalid)(req, 'backfillMetadataPositions', 'fromSlot must not be after toSlot', 'fromSlot');
295
+ }
296
+ if (metadataRun.isBusy())
297
+ return busy(req, 'backfillMetadataPositions', metadataRun);
298
+ return metadataRun.start(() => ({
299
+ run: (ctl) => (0, metadata_position_backfill_1.backfillMetadataPositions)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
300
+ answer: { accepted: true, message: 'Metadata-position backfill started; poll getStatus().metadataBackfill.' },
301
+ }));
302
+ });
303
+ // backfillAssetSlices: writes policy id, name and fingerprint of every stored asset row as derived
304
+ // from its unit. Needs no backend and runs detached. Progress is in getStatus().sliceBackfill.
305
+ srv.on('backfillAssetSlices', async (req) => {
306
+ if (sliceRun.isBusy())
307
+ return busy(req, 'backfillAssetSlices', sliceRun);
308
+ return sliceRun.start(() => ({
309
+ run: (ctl) => (0, asset_slice_backfill_1.backfillAssetSlices)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
310
+ answer: { accepted: true, message: 'Asset-slice backfill started; poll getStatus().sliceBackfill.' },
311
+ }));
312
+ });
313
+ // backfillEpochs: rebuilds the epoch rows of the crawled range from the stored blocks.
314
+ // Needs no backend and runs detached.
315
+ srv.on('backfillEpochs', async (req) => {
316
+ if (epochRun.isBusy())
317
+ return busy(req, 'backfillEpochs', epochRun);
318
+ return epochRun.start(() => ({
319
+ run: (ctl) => (0, server_1.getCardanoIndexer)().backfillEpochs(ctl.progress, () => ctl.shouldStop()),
320
+ answer: { accepted: true, message: 'Epoch backfill started; poll getStatus().epochBackfill.' },
321
+ }));
322
+ });
323
+ // recheckFailedSubmits: a submission or signing request marked failed whose transaction is on chain
324
+ // with passing scripts goes back to submitted. Rows an earlier version failed on a refusal or time.
325
+ srv.on('recheckFailedSubmits', async (req) => {
326
+ if (recheckRun.isBusy())
327
+ return busy(req, 'recheckFailedSubmits', recheckRun);
328
+ return recheckRun.start(() => ({
329
+ run: (ctl) => (0, failed_recheck_1.recheckFailed)({ indexer: (0, server_1.getCardanoIndexer)(), client: (0, server_1.getCardanoClient)() }, { shouldStop: () => ctl.shouldStop(), onProgress: ctl.progress }),
330
+ answer: { accepted: true, message: 'Re-check of failed submits started; poll getStatus().failedRecheck.' },
331
+ }));
332
+ });
333
+ // Slot range of a walk over input asset copies. Both bounds are required: the caller names what
334
+ // moves. Null after the request was rejected.
335
+ const copyRange = (req, action) => {
336
+ const data = (req.data ?? {});
337
+ if (data.fromSlot == null) {
338
+ (0, errors_1.rejectMissing)(req, action, 'fromSlot');
339
+ return null;
340
+ }
341
+ if (data.toSlot == null) {
342
+ (0, errors_1.rejectMissing)(req, action, 'toSlot');
343
+ return null;
344
+ }
345
+ const range = { fromSlot: Number(data.fromSlot), toSlot: Number(data.toSlot) };
346
+ if (range.fromSlot > range.toSlot) {
347
+ (0, errors_1.rejectInvalid)(req, action, 'fromSlot must not be after toSlot', 'fromSlot');
348
+ return null;
349
+ }
350
+ return data.slotWindow == null ? range : { ...range, slotWindow: Number(data.slotWindow) };
351
+ };
352
+ /** Why a copy walk cannot start now; null when it can. */
353
+ const copyWalkConflict = () => {
354
+ if (copyWalkBusy())
355
+ return 'A prune or restore of input asset copies is already running';
356
+ if (transactionRun.isBusy())
357
+ return 'A transaction backfill is running; it rewrites the inputs this walk moves';
358
+ return null;
359
+ };
360
+ // pruneInputAssetCopies: moves the inputs of a slot range from asset copies to the output they
361
+ // spent and deletes those copies. Needs no backend and runs detached.
362
+ srv.on('pruneInputAssetCopies', async (req) => {
363
+ const range = copyRange(req, 'pruneInputAssetCopies');
364
+ if (!range)
365
+ return;
366
+ const conflict = copyWalkConflict();
367
+ if (conflict)
368
+ return (0, errors_1.rejectInvalid)(req, 'pruneInputAssetCopies', conflict);
369
+ return pruneRun.start(() => ({
370
+ run: (ctl) => (0, input_asset_copies_1.pruneInputAssetCopies)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
371
+ answer: { accepted: true, message: 'Prune of input asset copies started; poll getStatus().copyPrune.' },
372
+ }));
373
+ });
374
+ // restoreInputAssetCopies: the way back, copies written from the outputs.
375
+ srv.on('restoreInputAssetCopies', async (req) => {
376
+ const range = copyRange(req, 'restoreInputAssetCopies');
377
+ if (!range)
378
+ return;
379
+ const conflict = copyWalkConflict();
380
+ if (conflict)
381
+ return (0, errors_1.rejectInvalid)(req, 'restoreInputAssetCopies', conflict);
382
+ return restoreRun.start(() => ({
383
+ run: (ctl) => (0, input_asset_copies_1.restoreInputAssetCopies)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
384
+ answer: { accepted: true, message: 'Restore of input asset copies started; poll getStatus().copyRestore.' },
385
+ }));
386
+ });
387
+ // cancelMaintenance: asks a running backfill or walk of this process to stop at its next window,
388
+ // page or batch. What it wrote so far stays; a new start begins again at its first slot or key.
389
+ srv.on('cancelMaintenance', async (req) => {
390
+ const name = String(req.data?.run ?? '');
391
+ const run = Object.hasOwn(CANCELLABLE, name) ? CANCELLABLE[name] : null;
392
+ if (!run)
393
+ return (0, errors_1.rejectInvalid)(req, 'cancelMaintenance', `run must be one of ${Object.keys(CANCELLABLE).join(', ')}`, 'run');
394
+ if (!run.cancel())
395
+ return { accepted: false, message: `${run.label} is not running in this process.` };
396
+ return { accepted: true, message: `${run.label} stops at its next step; poll getStatus().${name}.` };
397
+ });
398
+ // importUtxoSet: one-off snapshot import that anchors crawler.utxoSet.
399
+ // Runs detached. Progress is in getStatus().utxoSet.
400
+ srv.on('importUtxoSet', async (req) => {
401
+ const data = (req.data ?? {});
402
+ if (data.source === 'aggregates') {
403
+ if ((0, crawler_1.isCrawlerRunning)())
404
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
405
+ if (utxoSetRun.isBusy())
406
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
407
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
408
+ const cursor = await (0, sync_state_1.readCursor)(db);
409
+ const { anchorSlot, anchorHash } = cursor?.utxoSet ?? {};
410
+ if (anchorSlot == null || !anchorHash)
411
+ throw new errors_1.TransactionValidationError('No imported UTxO set to rebuild the sums from. Run importUtxoSet first.');
412
+ return {
413
+ label: 'UTxO set aggregate rebuild',
414
+ run: async () => {
415
+ const r = await (0, utxo_set_import_1.rebuildUtxoSetAggregates)({ indexer: (0, server_1.getCardanoIndexer)() });
416
+ logger.info(`UTxO set sums rebuilt: ${r.utxos} rows at ${r.anchor.slot}/${r.anchor.hash}`);
417
+ },
418
+ answer: {
419
+ accepted: true,
420
+ anchorSlot: String(anchorSlot),
421
+ anchorHash,
422
+ message: 'UTxO set sums are rebuilt from the imported rows; poll getStatus().utxoSet, then resumeCrawler.',
423
+ },
424
+ };
425
+ }));
426
+ }
427
+ if (data.source === 'scripts') {
428
+ if ((0, crawler_1.isCrawlerRunning)())
429
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
430
+ if (utxoSetRun.isBusy())
431
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
432
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
433
+ const cursor = await (0, sync_state_1.readCursor)(db);
434
+ const { anchorSlot, anchorHash } = cursor?.utxoSet ?? {};
435
+ if (anchorSlot == null || !anchorHash)
436
+ throw new errors_1.TransactionValidationError('No imported UTxO set to fill. Run importUtxoSet first.');
437
+ return {
438
+ label: 'UTxO set reference-script fill',
439
+ run: async () => {
440
+ const r = await (0, utxo_set_import_1.refreshUtxoSetReferenceScripts)({ filePath: data.filePath, client: (0, server_1.getCardanoClient)() });
441
+ logger.info(`UTxO set reference scripts filled: ${r.updated} of ${r.candidates} rows`);
442
+ },
443
+ answer: {
444
+ accepted: true,
445
+ anchorSlot: String(anchorSlot),
446
+ anchorHash,
447
+ message: `Reference-script columns of the UTxO set are being filled (${data.filePath ? 'from the dump' : 'from the node'}); watch the log, then resumeCrawler.`,
448
+ },
449
+ };
450
+ }));
451
+ }
452
+ // the model rejects an unknown source and a negative anchorSlot
453
+ const source = data.source;
454
+ if (source !== 'file' && source !== 'ogmios')
455
+ return (0, errors_1.rejectMissing)(req, 'importUtxoSet', 'source');
456
+ if (source === 'file' && !data.filePath)
457
+ return (0, errors_1.rejectMissing)(req, 'importUtxoSet', 'filePath');
458
+ const anchorGiven = data.anchorSlot != null || !!data.anchorHash;
459
+ if (source === 'file' && !anchorGiven) {
460
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'source "file" needs anchorSlot + anchorHash: the tip at dump time', 'anchorSlot');
461
+ }
462
+ if (anchorGiven && (data.anchorSlot == null || !Number.isInteger(Number(data.anchorSlot)) || !(0, validators_1.isBlockHash)(data.anchorHash))) {
463
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'anchorSlot must be an integer and anchorHash a 64-hex block hash', 'anchorHash');
464
+ }
465
+ if ((0, crawler_1.isCrawlerRunning)())
466
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
467
+ if (utxoSetRun.isBusy())
468
+ return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
469
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
470
+ const cursor = await (0, sync_state_1.readCursor)(db);
471
+ if (!cursor)
472
+ throw new errors_1.TransactionValidationError('No crawler cursor yet. Start the crawler once before importing.');
473
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
474
+ throw new errors_1.TransactionValidationError('Crawler is running (active lease). Run pauseCrawler first.');
475
+ const anchor = anchorGiven
476
+ ? { slot: Number(data.anchorSlot), hash: String(data.anchorHash).toLowerCase() }
477
+ : { slot: cursor.lastSlot, hash: cursor.lastBlockHash ?? '' };
478
+ if (!anchor.hash)
479
+ throw new errors_1.TransactionValidationError('Cursor has no block hash yet. Pass anchorSlot + anchorHash.');
480
+ if (cursor.lastSlot > anchor.slot) {
481
+ throw new errors_1.TransactionValidationError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}). Dump the set at or after the cursor.`);
482
+ }
483
+ return {
484
+ run: async () => {
485
+ const r = await (0, utxo_set_import_1.importUtxoSet)({
486
+ source, filePath: data.filePath, anchor,
487
+ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(),
488
+ onProgress: (n) => { if (n % 100_000 === 0)
489
+ logger.info(`UTxO set import: ${n} entries`); },
490
+ });
491
+ logger.info(`UTxO set import done: ${r.utxos} entries at ${r.anchor.slot}/${r.anchor.hash}`);
492
+ },
493
+ answer: {
494
+ accepted: true,
495
+ anchorSlot: String(anchor.slot),
496
+ anchorHash: anchor.hash,
497
+ message: `UTxO set import started (source=${source}); poll getStatus().utxoSet, then resumeCrawler.`,
498
+ },
499
+ };
500
+ }));
501
+ });
502
+ // pauseCrawler: stops the stream. The cursor is kept, so resume continues from it.
38
503
  srv.on('pauseCrawler', async (req) => {
39
504
  return (0, backend_request_handler_1.handleRequest)(req, async () => {
40
505
  await (0, crawler_1.stopCrawler)(true);
@@ -42,23 +507,19 @@ module.exports = (srv) => {
42
507
  return true;
43
508
  });
44
509
  });
45
- // resumeCrawler — (re)start from the persisted cursor using the configured source.
46
- // Gated on config.enabled: the control action must not start a crawler the operator
47
- // never configured (an unconfigured start would otherwise sync from genesis).
48
- // NOTE: to apply CHANGED config to a running crawler, call pauseCrawler first —
49
- // resume on a running crawler is a no-op by design.
510
+ // resumeCrawler: starts from the stored cursor, only when enabled, since otherwise it would sync from genesis.
511
+ // A no-op on a running crawler. Pause first to apply changed config.
50
512
  srv.on('resumeCrawler', async (req) => {
51
513
  let config;
52
514
  try {
53
- config = (0, server_1.loadCrawlerConfigFromEnv)();
515
+ config = (0, config_1.loadCrawlerConfigFromEnv)();
54
516
  }
55
517
  catch (err) {
56
- // e.g. ConfigError: enabled but no start block — a config problem is the
57
- // caller's 400, not a raw 500 from an escaping throw
518
+ // A config problem (e.g. enabled without a start block) is the caller's 400.
58
519
  return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', err instanceof Error ? err.message : String(err));
59
520
  }
60
521
  if (!config.enabled) {
61
- return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', 'Crawler is not enabled — set cds.requires.odatano-core.crawler.enabled (or CRAWLER_ENABLED=true) with a start block before resuming.');
522
+ return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', 'Crawler is not enabled. Set cds.requires.odatano-core.crawler.enabled (or CRAWLER_ENABLED=true) with a start block before resuming.');
62
523
  }
63
524
  return (0, backend_request_handler_1.handleRequest)(req, async () => {
64
525
  const client = (0, server_1.getCardanoClient)();