@odatano/core 2.0.0-rc.50 → 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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -11,6 +11,7 @@ const pending_spends_1 = require("./pending-spends");
11
11
  const const_1 = require("../utils/const");
12
12
  const circuit_breaker_1 = require("./circuit-breaker");
13
13
  const request_coalescer_1 = require("./request-coalescer");
14
+ const call_signal_1 = require("./backends/call-signal");
14
15
  // A backend module loads when its backend is configured, and its provider SDK with it.
15
16
  const backendModules = {
16
17
  ogmios: () => require('./backends/ogmios-backend'),
@@ -55,6 +56,8 @@ class CardanoClient {
55
56
  circuitBreaker;
56
57
  /** Backends whose init failed. They stay in rotation and init is retried per request. */
57
58
  uninitializedBackends = new Set();
59
+ /** Running init retry per backend, shared by concurrent callers. */
60
+ initRetries = new Map();
58
61
  network;
59
62
  max_age_ms = const_1.DEFAULT_INDEX_TTL_MS;
60
63
  /** Transactions submitted through this client that the ledger view does not show yet. */
@@ -81,10 +84,11 @@ class CardanoClient {
81
84
  }
82
85
  if (backends.includes('koios')) {
83
86
  const { KoiosBackend } = backendModules.koios();
84
- this.historicalBackends.push(new KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
87
+ // the same timeout the client allows a Koios call, see getTimeoutForBackend
88
+ this.historicalBackends.push(new KoiosBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.koiosApiKey));
85
89
  }
86
90
  if (backends.includes('odatano')) {
87
- // A remote ODATANO runs its own failover chain: allow its primary timeout plus the fallback.
91
+ // A remote ODATANO runs its own failover chain behind one call, so it gets the longer fallback timeout.
88
92
  const { OdatanoBackend } = backendModules.odatano();
89
93
  this.historicalBackends.push(new OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
90
94
  }
@@ -181,31 +185,55 @@ class CardanoClient {
181
185
  }
182
186
  this.initialized = true;
183
187
  }
184
- /** Retries a failed startup init. False records a breaker failure. */
188
+ // Retries a failed startup init. Concurrent callers share one attempt, so a backend that holds
189
+ // a connection (Ogmios) opens one. False records a breaker failure.
185
190
  async ensureBackendInitialized(backend, errors) {
186
191
  if (!this.uninitializedBackends.has(backend))
187
192
  return true;
193
+ let attempt = this.initRetries.get(backend);
194
+ if (!attempt) {
195
+ attempt = backend.init().then(() => {
196
+ this.uninitializedBackends.delete(backend);
197
+ logger.info(`Backend ${backend.name} recovered (lazy init succeeded)`);
198
+ return true;
199
+ }, (err) => {
200
+ const initError = new errors_1.BackendInitError(backend.name, err);
201
+ this.circuitBreaker.recordFailure(backend.name);
202
+ logger.debug(`Lazy init retry for ${backend.name} failed: ${initError.message}`);
203
+ throw initError;
204
+ }).finally(() => this.initRetries.delete(backend));
205
+ this.initRetries.set(backend, attempt);
206
+ }
188
207
  try {
189
- await backend.init();
190
- this.uninitializedBackends.delete(backend);
191
- logger.info(`Backend ${backend.name} recovered (lazy init succeeded)`);
192
- return true;
208
+ return await attempt;
193
209
  }
194
210
  catch (err) {
195
- const initError = new errors_1.BackendInitError(backend.name, err);
196
- errors?.push(initError);
197
- this.circuitBreaker.recordFailure(backend.name);
198
- logger.debug(`Lazy init retry for ${backend.name} failed: ${initError.message}`);
211
+ errors?.push(err instanceof errors_1.BackendError ? err : new errors_1.BackendInitError(backend.name, err));
199
212
  return false;
200
213
  }
201
214
  }
202
- /** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
203
- withTimeout(promise, ms, backendName) {
215
+ // Runs `call` with a deadline. On timeout it rejects with ProviderUnavailableError and aborts the
216
+ // call's signal, so the HTTP requests and batch loops the call started stop too.
217
+ withTimeout(call, ms, backendName) {
218
+ const controller = new AbortController();
204
219
  let timeoutId;
205
220
  const timeoutPromise = new Promise((_, reject) => {
206
- timeoutId = setTimeout(() => reject(new errors_1.ProviderUnavailableError('Backend timeout', backendName, ms)), ms);
221
+ timeoutId = setTimeout(() => {
222
+ const timeout = new errors_1.ProviderUnavailableError('Backend timeout', backendName, ms);
223
+ controller.abort(timeout);
224
+ reject(timeout);
225
+ }, ms);
207
226
  });
208
- return Promise.race([promise, timeoutPromise]).finally(() => {
227
+ let run;
228
+ try {
229
+ run = (0, call_signal_1.withCallSignal)(controller.signal, call);
230
+ }
231
+ catch (err) {
232
+ // a call that throws before it returns its promise leaves no timer behind
233
+ clearTimeout(timeoutId);
234
+ return Promise.reject(err);
235
+ }
236
+ return Promise.race([run, timeoutPromise]).finally(() => {
209
237
  clearTimeout(timeoutId);
210
238
  });
211
239
  }
@@ -226,19 +254,24 @@ class CardanoClient {
226
254
  throw new errors_1.ProviderUnavailableError(`Backend ${backend.name} is not initialized (lazy retry failed)`, backend.name);
227
255
  }
228
256
  try {
229
- const result = await this.withTimeout(fn(), this.getTimeoutForBackend(backend), backend.name);
257
+ const result = await this.withTimeout(fn, this.getTimeoutForBackend(backend), backend.name);
230
258
  this.circuitBreaker.recordSuccess(backend.name);
231
259
  return result;
232
260
  }
233
261
  catch (err) {
234
262
  const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
235
- const isClientError = backendError.statusCode >= 400 && backendError.statusCode < 500;
236
- if (!isClientError) {
237
- this.circuitBreaker.recordFailure(backend.name);
238
- }
263
+ this.recordOutcome(backend, backendError);
239
264
  throw backendError;
240
265
  }
241
266
  }
267
+ // A verdict about the request (404, 400) comes from a healthy backend: it releases a half-open
268
+ // probe and is no failure. Anything else, a rate limit included, counts as a failure.
269
+ recordOutcome(backend, error) {
270
+ if ((0, errors_1.isBackendVerdict)(error))
271
+ this.circuitBreaker.recordVerdict(backend.name);
272
+ else
273
+ this.circuitBreaker.recordFailure(backend.name);
274
+ }
242
275
  /** Execute on backends in preference order (live vs historical) with automatic fallback. */
243
276
  async executeWithPriority(fn, preferLive, methodName, finalOnClientError = false) {
244
277
  await this.ensureInitialized();
@@ -272,22 +305,17 @@ class CardanoClient {
272
305
  try {
273
306
  const backendType = backend === this.liveBackend ? 'live' : 'historical';
274
307
  logger.debug(`Calling backend: ${backend.name} (${backendType})`);
275
- const result = await this.withTimeout(fn(backend), this.getTimeoutForBackend(backend), backend.name);
308
+ const result = await this.withTimeout(() => fn(backend), this.getTimeoutForBackend(backend), backend.name);
276
309
  this.circuitBreaker.recordSuccess(backend.name);
277
310
  return result;
278
311
  }
279
312
  catch (err) {
280
313
  const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
281
314
  errors.push(backendError);
282
- // 4xx are definitive verdicts from a healthy backend and must not open the circuit;
283
- // only 5xx/timeouts/transport errors indicate backend health.
284
- const isClientError = backendError.statusCode >= 400 && backendError.statusCode < 500;
285
- if (!isClientError) {
286
- this.circuitBreaker.recordFailure(backend.name);
287
- }
315
+ this.recordOutcome(backend, backendError);
288
316
  const logLevel = backendError.statusCode === 404 ? 'debug' : 'warn';
289
317
  logger[logLevel](`Backend failed${backendError.statusCode === 404 ? ': resource not found' : ''}: ${backend.name} - ${backendError.message}`);
290
- if (finalOnClientError && isClientError)
318
+ if (finalOnClientError && (0, errors_1.isBackendVerdict)(backendError))
291
319
  throw backendError;
292
320
  }
293
321
  }
@@ -309,16 +337,36 @@ class CardanoClient {
309
337
  getAddressUtxos(address) {
310
338
  return this.route('getAddressUtxos', b => b.getAddressUtxos(address));
311
339
  }
312
- // UTxOs of every address form that shares the payment credential.
313
- // Needs Koios or another ODATANO, because Blockfrost has no credential lookup.
340
+ // UTxOs of every address form that shares the payment credential, Koios first, then another ODATANO.
341
+ // Blockfrost has no credential lookup.
314
342
  getCredentialUtxos(credHash) {
315
- const candidates = [this.liveBackend, ...this.historicalBackends];
316
- const capable = candidates.filter((b) => typeof b?.getCredentialUtxos === 'function');
317
- const backend = capable.find(b => b.name === 'koios') ?? capable[0];
318
- if (!backend) {
343
+ const capable = this.capableBackends(b => typeof b.getCredentialUtxos === 'function', 'koios');
344
+ if (!capable.length) {
319
345
  throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires a Koios or odatano backend. Configure one in cds.requires.odatano-core.backends.", 'koios');
320
346
  }
321
- return this.credCoalescer.get(credHash, () => this.callWithResilience(backend, () => backend.getCredentialUtxos(credHash)));
347
+ return this.credCoalescer.get(credHash, () => this.firstAnswer(capable, b => b.getCredentialUtxos(credHash)));
348
+ }
349
+ /** Backends that pass `can`, the one named `preferred` first. */
350
+ capableBackends(can, preferred) {
351
+ const candidates = [this.liveBackend, ...this.historicalBackends].filter((b) => !!b && can(b));
352
+ return [...candidates.filter(b => b.name === preferred), ...candidates.filter(b => b.name !== preferred)];
353
+ }
354
+ // Asks `backends` in order with the breaker and timeout rules and fails over to the next one.
355
+ // A verdict other than 404 ends the round, as on the routed paths.
356
+ async firstAnswer(backends, fn) {
357
+ const errors = [];
358
+ for (const backend of backends) {
359
+ try {
360
+ return await this.callWithResilience(backend, () => fn(backend));
361
+ }
362
+ catch (err) {
363
+ const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
364
+ errors.push(backendError);
365
+ if ((0, errors_1.isBackendVerdict)(backendError) && backendError.statusCode !== 404)
366
+ throw backendError;
367
+ }
368
+ }
369
+ throw new errors_1.AllBackendsFailedError(errors);
322
370
  }
323
371
  getAddressTransactions(address, limit) {
324
372
  return this.route('getAddressTransactions', b => b.getAddressTransactions(address, limit));
@@ -352,43 +400,59 @@ class CardanoClient {
352
400
  return await this.callWithResilience(provider, () => provider.getAccount(stakeAddress));
353
401
  }
354
402
  catch (err) {
355
- logger.debug(`getAccount on ${provider.name} failed, trying the next provider: ${err instanceof Error ? err.message : String(err)}`);
403
+ logger.debug(`getAccount on ${provider.name} failed, trying the next provider: ${(0, errors_1.errorText)(err)}`);
356
404
  }
357
405
  }
358
406
  return account;
359
407
  }
360
- // The node lists only delegated credentials, so its absence proves nothing and providers decide.
361
- // A provider 404 means not registered. Null when no source could tell.
408
+ // The node lists only delegated credentials, so its 404 proves nothing. A provider 404 means not
409
+ // registered. Another ODATANO gives its own verdict; its null, like the node's 404, is a healthy
410
+ // "cannot tell". Null when nobody could tell, and a failure only when nobody answered at all.
362
411
  async isRewardAccountRegistered(stakeAddress) {
363
- try {
364
- return await this.executeWithPriority(async (b) => (await b.getAccount(stakeAddress)).active, true, 'getAccount');
365
- }
366
- catch (err) {
367
- if (err instanceof errors_1.AllBackendsFailedError) {
368
- const providers = err.errors.filter(e => e.backendName !== this.liveBackend?.name);
369
- if (providers.some(e => e.statusCode === 404))
370
- return false;
371
- if (err.errors.length > 0 && err.errors.every(e => e.statusCode === 404))
372
- return null;
412
+ await this.ensureInitialized();
413
+ const backends = [this.liveBackend, ...this.historicalBackends].filter((b) => !!b);
414
+ const errors = [];
415
+ let answered = false;
416
+ let notRegistered = false;
417
+ for (const backend of backends) {
418
+ if (backend.unsupportedMethods?.has('getAccount') && !backend.isRewardAccountRegistered)
419
+ continue;
420
+ try {
421
+ const verdict = backend.isRewardAccountRegistered
422
+ ? await this.callWithResilience(backend, () => backend.isRewardAccountRegistered(stakeAddress))
423
+ : (await this.callWithResilience(backend, () => backend.getAccount(stakeAddress))).active;
424
+ answered = true;
425
+ if (verdict !== null)
426
+ return verdict;
427
+ }
428
+ catch (err) {
429
+ const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
430
+ if (backendError.statusCode !== 404) {
431
+ errors.push(backendError);
432
+ continue;
433
+ }
434
+ answered = true;
435
+ if (backend !== this.liveBackend)
436
+ notRegistered = true;
373
437
  }
374
- throw err;
375
438
  }
439
+ if (notRegistered)
440
+ return false;
441
+ if (answered)
442
+ return null;
443
+ throw new errors_1.AllBackendsFailedError(errors);
376
444
  }
377
445
  /** Asset info (supply, mint history, CIP-25/CIP-26 metadata); Blockfrost and Koios only. */
378
446
  getAssetInfo(unit) {
379
447
  return this.route('getAssetInfo', b => b.getAssetInfo(unit));
380
448
  }
381
- /** Latest mint and burn events. Prefers Koios, because Blockfrost leaves timestamps null. */
449
+ /** Latest mint and burn events. Koios first, because Blockfrost leaves timestamps null. */
382
450
  getAssetHistory(unit, limit = 100) {
383
- const candidates = [...this.historicalBackends, this.liveBackend];
384
- const koios = candidates.find(b => b?.name === 'koios' && typeof b.getAssetHistory === 'function');
385
- if (koios)
386
- return this.callWithResilience(koios, () => koios.getAssetHistory(unit, limit));
387
- const anyImpl = candidates.find(b => typeof b?.getAssetHistory === 'function');
388
- if (!anyImpl) {
451
+ const capable = this.capableBackends(b => typeof b.getAssetHistory === 'function', 'koios');
452
+ if (!capable.length) {
389
453
  throw new errors_1.ProviderUnavailableError("getAssetHistory requires Blockfrost or Koios backend.", 'asset-history');
390
454
  }
391
- return this.callWithResilience(anyImpl, () => anyImpl.getAssetHistory(unit, limit));
455
+ return this.firstAnswer(capable, b => b.getAssetHistory(unit, limit));
392
456
  }
393
457
  //-----------------------------------------------------------------------------
394
458
  // Batch Methods (N+1 Optimization)
@@ -402,7 +466,7 @@ class CardanoClient {
402
466
  return await this.callWithResilience(backend, () => backend.getAddressTransactionHashes(address, limit));
403
467
  }
404
468
  catch (err) {
405
- logger.debug(`getAddressTransactionHashes failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)}, trying next backend`);
469
+ logger.debug(`getAddressTransactionHashes failed on ${backend.name}: ${(0, errors_1.errorText)(err)}, trying next backend`);
406
470
  }
407
471
  }
408
472
  }
@@ -419,7 +483,7 @@ class CardanoClient {
419
483
  return await this.callWithResilience(backend, () => backend.getTransactionsBatch(txHashes));
420
484
  }
421
485
  catch (err) {
422
- logger.debug(`getTransactionsBatch failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)}, trying next backend`);
486
+ logger.debug(`getTransactionsBatch failed on ${backend.name}: ${(0, errors_1.errorText)(err)}, trying next backend`);
423
487
  }
424
488
  }
425
489
  }
@@ -464,22 +528,30 @@ class CardanoClient {
464
528
  }
465
529
  return null;
466
530
  }
531
+ // The tip, then whether each reference is unspent, both from the same backend, the node first, so
532
+ // the answers are at least as new as the tip. `live` says it is the node's own ledger; an indexer
533
+ // may lag it. A reference the backend does not know is not unspent.
534
+ async readLedger(refs) {
535
+ const backends = [this.liveBackend, ...this.historicalBackends].filter((b) => !!b);
536
+ return this.firstAnswer(backends, async (b) => {
537
+ const tip = await b.getCurrentSlot();
538
+ const unspent = [];
539
+ for (const ref of refs)
540
+ unspent.push(await b.isUtxoUnspent(ref.txHash, ref.outputIndex));
541
+ return { live: b === this.liveBackend, tip, unspent };
542
+ });
543
+ }
467
544
  // Outputs among refs that are unspent at the tip, read from the node's ledger.
468
545
  // Null when no backend can. The caller then reads the producing tx, which lacks reference-script bytes.
546
+ // With timeout, breaker and failover: the node first, then another ODATANO.
469
547
  async getUnspentOutputs(refs) {
470
- const backend = this.getLedgerStateBackend() ?? this.outputLookupBackend();
471
- return backend ? backend.getUnspentOutputs(refs) : null;
472
- }
473
- /** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
474
- outputLookupBackend() {
475
548
  const candidates = [this.liveBackend, ...this.historicalBackends];
476
- for (const b of candidates) {
477
- const lookup = b;
478
- if (lookup && !this.uninitializedBackends.has(lookup) && typeof lookup.getUnspentOutputs === 'function') {
479
- return lookup;
480
- }
481
- }
482
- return null;
549
+ const usable = candidates.filter((b) => !!b && !this.uninitializedBackends.has(b) && typeof b.getUnspentOutputs === 'function');
550
+ // a backend with the whole ledger first
551
+ const backends = [...usable.filter(b => (0, cardano_backend_1.isLedgerStateBackend)(b)), ...usable.filter(b => !(0, cardano_backend_1.isLedgerStateBackend)(b))];
552
+ if (!backends.length)
553
+ return null;
554
+ return this.firstAnswer(backends, b => b.getUnspentOutputs(refs));
483
555
  }
484
556
  /** True when an initialized backend implements `method` and does not declare it unsupported. */
485
557
  hasBackendFor(method) {
@@ -21,8 +21,13 @@ export interface FetchedAddress {
21
21
  /** An account as read, with the addresses it controls. */
22
22
  export interface FetchedAccount {
23
23
  account: AccountData;
24
- addresses: FetchedAddress[];
25
24
  }
25
+ /** `Accounts.addressList`: the addresses under a stake key, unique and sorted. */
26
+ export type AccountAddressList = string[];
27
+ /** The address list of an account as stored: unique and sorted. */
28
+ export declare function accountAddressList(addresses: readonly string[]): AccountAddressList;
29
+ /** Reads `Accounts.addressList`; null when the column is empty or not a list of addresses. */
30
+ export declare function parseAccountAddressList(json: unknown): AccountAddressList | null;
26
31
  /** A block as read; `epoch` is missing when the backend has no data for its epoch. */
27
32
  export interface FetchedBlock {
28
33
  block: BlockData;
@@ -54,7 +59,7 @@ export declare class CardanoIndexer {
54
59
  private static readonly CRAWL_EPOCH_RETRY_MS;
55
60
  private crawlEpochCache;
56
61
  private crawlEpochCurrent;
57
- /** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
62
+ /** Committed epoch rows and the final flag they were written with; a refresh creates a new row object. */
58
63
  private crawlEpochWritten;
59
64
  /** Memo updates of the running block transaction, applied only after its commit. */
60
65
  private pendingCommit;
@@ -147,11 +152,13 @@ export declare class CardanoIndexer {
147
152
  /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
148
153
  stopAssetEnrichment(): void;
149
154
  prefetchCrawlEpoch(epochNumber: number): Promise<void>;
155
+ /** True when the epoch has a stored row that is not final yet. Never throws. */
156
+ private storedOpenEpoch;
150
157
  private refreshCrawlEpoch;
151
158
  private crawledEpochTotals;
152
159
  /** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
153
160
  private bareEpochRow;
154
- backfillEpochs(onProgress?: (p: EpochBackfillProgress) => void): Promise<EpochBackfillProgress>;
161
+ backfillEpochs(onProgress?: (p: EpochBackfillProgress) => void, shouldStop?: () => boolean): Promise<EpochBackfillProgress>;
155
162
  constructor(client: CardanoClient, txBuilder: CardanoTransactionBuilder);
156
163
  private localAddressUtxos;
157
164
  /** A transaction from the backend. 404 when the crawled chain answers for it alone. */
@@ -183,6 +190,7 @@ export declare class CardanoIndexer {
183
190
  indexAddressUtxos(tx: CapTransaction, addr: string): Promise<AddressUTxO[]>;
184
191
  /** The UTxOs of an address from the backend. */
185
192
  fetchAddressUtxos(addr: string): Promise<OdatanoUtxo[]>;
193
+ storeAddressFromUtxos(tx: CapTransaction, addr: string, utxos: OdatanoUtxo[]): Promise<Address>;
186
194
  /** Stores the UTxOs of an address. Writes no parent Addresses row. */
187
195
  storeAddressUtxos(tx: CapTransaction, addr: string, utxos: OdatanoUtxo[]): Promise<AddressUTxO[]>;
188
196
  invalidateUtxoCacheForTx(tx: CapTransaction, targets: TxCacheTargets, extraAddresses?: string[]): Promise<void>;
@@ -212,6 +220,7 @@ export declare class CardanoIndexer {
212
220
  /** A block and its epoch from the backend. 404 when the crawled chain answers for it alone. */
213
221
  fetchBlock(tx: CapTransaction, blockHash: string): Promise<FetchedBlock>;
214
222
  private withEpoch;
223
+ private writeCrawlEpochs;
215
224
  /** Stores a block and, when it was read, its epoch. */
216
225
  storeBlock(tx: CapTransaction, fetched: FetchedBlock): Promise<Block>;
217
226
  indexBlockFull(tx: CapTransaction, blockData: BlockData, txs: ProviderTransaction[]): Promise<void>;
@@ -225,11 +234,14 @@ export declare class CardanoIndexer {
225
234
  private buildAssetHistoryRows;
226
235
  private ensureAssetRows;
227
236
  private noteAssetSeen;
237
+ /** Forgets the epoch totals in memory. A rollback removed blocks they counted. */
238
+ forgetCrawlEpochs(): void;
239
+ reconcileRolledBackAssets(tx: CapTransaction, units: string[], forkSlot: number): Promise<void>;
228
240
  snapshotEpoch(epoch: number, at: {
229
241
  slot: number;
230
242
  time: number;
231
243
  hash?: string | null;
232
- }): Promise<{
244
+ }, shouldStop?: () => boolean): Promise<{
233
245
  pools: number;
234
246
  dreps: number;
235
247
  source: 'ogmios' | 'koios' | null;
@@ -245,11 +257,11 @@ export declare class CardanoIndexer {
245
257
  /** An epoch row from the backend. */
246
258
  fetchEpoch(epochNumber: number): Promise<Epoch>;
247
259
  storeEpoch(tx: CapTransaction, epochEntity: Epoch): Promise<Epoch>;
248
- /** Index an account by stake address, plus its addresses when it has any. */
260
+ withFinal(epochEntity: Epoch, now?: number, crawlComplete?: boolean): Epoch;
261
+ /** Index an account by stake address. Its addresses are read on their own. */
249
262
  indexAccount(tx: CapTransaction, stakeAddress: string): Promise<Account>;
250
- /** An account and the addresses it controls, read but not stored. */
263
+ /** An account, read but not stored. */
251
264
  fetchAccount(tx: CapTransaction, stakeAddress: string): Promise<FetchedAccount>;
252
- /** Stores what fetchAccount read. */
253
265
  storeAccount(tx: CapTransaction, fetched: FetchedAccount): Promise<Account>;
254
266
  /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
255
267
  resolveAccount(tx: CapTransaction, stakeAddress: string): Promise<AccountData>;
@@ -377,23 +389,22 @@ export declare class CardanoIndexer {
377
389
  indexLatestEpoch(tx: CapTransaction): Promise<Epoch>;
378
390
  /** Index the latest block, with best-effort epoch enrichment. */
379
391
  indexLatestBlock(tx: CapTransaction): Promise<Block>;
380
- /** Max addresses to index concurrently (avoid overloading backends) */
381
- private static readonly ADDR_CONCURRENCY;
382
- /** Block position of a transaction already in the local index (crawled or cached), or null. */
383
- findIndexedTransaction(tx: CapTransaction, txHash: string): Promise<{
384
- slot: number | null;
385
- blockHeight: number | null;
386
- blockHash: string | null;
387
- } | null>;
388
392
  resolveTransactionConfirmations(tx: CapTransaction, txHash: string): Promise<TransactionConfirmations>;
389
393
  /** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
390
394
  private crawledTransactionDepth;
395
+ findCrawledTransaction(tx: CapTransaction, txHash: string): Promise<{
396
+ slot: number;
397
+ blockHeight: number;
398
+ blockHash: string;
399
+ tipHeight: number;
400
+ spendsCollaterals: boolean;
401
+ validityKnown: boolean;
402
+ } | null>;
391
403
  /** Batch-fetches the missing ones, stores them and returns only those. */
392
404
  ensureTransactionsIndexed(tx: CapTransaction, txHashes: string[]): Promise<Map<string, ProviderTransaction>>;
393
405
  /** The hashes among the given ones that have no stored transaction. */
394
406
  private unstoredTransactionHashes;
395
407
  /** Stores transactions read from a backend, each with its inputs, outputs and metadata. */
396
408
  private storeTransactions;
397
- private fetchAddresses;
398
409
  }
399
410
  //# sourceMappingURL=cardano-indexer.d.ts.map