@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -7,21 +7,23 @@ exports.CardanoClient = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const cardano_backend_1 = require("./backends/cardano-backend");
9
9
  const errors_1 = require("../utils/errors");
10
+ const pending_spends_1 = require("./pending-spends");
10
11
  const circuit_breaker_1 = require("./circuit-breaker");
11
12
  const request_coalescer_1 = require("./request-coalescer");
12
13
  const ogmios_backend_1 = require("./backends/ogmios-backend");
13
14
  const blockfrost_backend_1 = require("./backends/blockfrost-backend");
14
15
  const koios_backend_1 = require("./backends/koios-backend");
16
+ const odatano_backend_1 = require("./backends/odatano-backend");
15
17
  const logger = cds_1.default.log('CardanoClient');
16
- /**
17
- * Method routing configuration - defines which backend type to prefer for each method
18
- */
18
+ /** Which backend type to prefer per method. */
19
19
  const METHOD_ROUTING = {
20
20
  getTransaction: { preferLive: false },
21
+ // node first: UTxOs at the tip; Ogmios decodes the type itself (base/enterprise/…, not shelley/byron)
21
22
  getAddress: { preferLive: true },
22
- getAddressUtxos: { preferLive: false },
23
+ getAddressUtxos: { preferLive: true },
23
24
  getAddressTransactions: { preferLive: false },
24
- getNetworkInformation: { preferLive: true },
25
+ // providers first: they report circulation; Ogmios only has treasury and reserves
26
+ getNetworkInformation: { preferLive: false },
25
27
  getTransactionMetadata: { preferLive: false },
26
28
  getBlock: { preferLive: false },
27
29
  getEpoch: { preferLive: false },
@@ -30,19 +32,17 @@ const METHOD_ROUTING = {
30
32
  getCurrentSlot: { preferLive: true },
31
33
  isUtxoUnspent: { preferLive: true },
32
34
  getPool: { preferLive: true },
33
- getDrep: { preferLive: false },
35
+ // node first; a DRep the ledger no longer lists (retired) falls through to the providers
36
+ getDrep: { preferLive: true },
34
37
  getAccount: { preferLive: true },
35
38
  getAssetInfo: { preferLive: false },
36
39
  getProtocolParameters: { preferLive: true },
37
- submitTransaction: { preferLive: true },
40
+ // a node's rejection (4xx) is final: another backend submits to the same ledger
41
+ submitTransaction: { preferLive: true, finalOnClientError: true },
38
42
  };
39
43
  /**
40
- * CardanoClient - Smart Multi-backend Cardano Client
41
- *
42
- * Routes requests to appropriate backends:
43
- * - Live/State queries → Ogmios (if available)
44
- * - Historical queries → Blockfrost/Koios (if available)
45
- * - Automatic fallback between backends
44
+ * Multi-backend Cardano client: live/state queries prefer Ogmios, historical queries prefer
45
+ * Blockfrost/Koios, with automatic fallback between them.
46
46
  */
47
47
  class CardanoClient {
48
48
  config;
@@ -55,18 +55,18 @@ class CardanoClient {
55
55
  uninitializedBackends = new Set();
56
56
  network;
57
57
  max_age_ms = 60000; // default 1 minute for temporary caching
58
+ /** Transactions submitted through this client that the ledger view does not show yet. */
59
+ pendingSpends = new pending_spends_1.PendingSpends();
58
60
  protocolParamsCache;
59
61
  protocolParamsFetchPromise = null;
62
+ /** Last protocol parameters the live backend (node) answered. */
63
+ lastLiveProtocolParams;
60
64
  static PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes
61
65
  // Request coalescers — deduplicate concurrent fetches for the same resource
62
66
  txCoalescer = new request_coalescer_1.RequestCoalescer();
63
67
  addrCoalescer = new request_coalescer_1.RequestCoalescer();
64
68
  credCoalescer = new request_coalescer_1.RequestCoalescer();
65
- /**
66
- * Constructor for CardanoClient
67
- * @param liveBackend - Optional backend for live/state queries (typically Ogmios)
68
- * @param historicalBackends - Optional backends for historical queries (typically Blockfrost/Koios)
69
- */
69
+ /** Builds the configured backends; throws ConfigError when none is configured. */
70
70
  constructor(clientConfig) {
71
71
  this.network = clientConfig.network;
72
72
  const backends = clientConfig.backends;
@@ -79,13 +79,15 @@ class CardanoClient {
79
79
  if (backends.includes('koios')) {
80
80
  this.historicalBackends.push(new koios_backend_1.KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
81
81
  }
82
+ if (backends.includes('odatano')) {
83
+ // A remote ODATANO runs its own failover chain: allow its primary timeout plus the fallback.
84
+ this.historicalBackends.push(new odatano_backend_1.OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
85
+ }
82
86
  if (!this.liveBackend && this.historicalBackends.length === 0) {
83
87
  throw new errors_1.ConfigError('No valid backends configured for CardanoClient');
84
88
  }
85
89
  this.circuitBreaker = new circuit_breaker_1.CircuitBreakerManager(clientConfig.circuitBreaker);
86
- // Wire the configured cache TTL into the field the indexer actually reads.
87
- // Previously max_age_ms stayed hardcoded at 60s and indexTtlMs was dead — the
88
- // documented/configurable 1h default never took effect.
90
+ // indexTtlMs is the cache TTL the indexer reads via max_age_ms
89
91
  if (Number.isFinite(clientConfig.indexTtlMs) && clientConfig.indexTtlMs > 0) {
90
92
  this.max_age_ms = clientConfig.indexTtlMs;
91
93
  }
@@ -101,16 +103,13 @@ class CardanoClient {
101
103
  return names;
102
104
  }
103
105
  /**
104
- * Ensure backends are initialized.
105
- * A REJECTED init promise is cleared so the next request retries — previously
106
- * a transient startup failure (e.g. Ogmios briefly down) left the client
107
- * permanently broken until process restart.
108
- * @returns {Promise<void>}
106
+ * Ensure backends are initialized. A rejected init promise is cleared so the next request
107
+ * retries instead of leaving the client permanently broken.
109
108
  */
110
109
  async ensureInitialized() {
111
110
  if (this.initialized)
112
111
  return;
113
- // Use nullish coalescing assignment for atomic operation to prevent race conditions
112
+ // ??= keeps concurrent callers on one init promise
114
113
  this.initPromise ??= this.initBackends().catch((err) => {
115
114
  this.initPromise = null;
116
115
  throw err;
@@ -118,10 +117,8 @@ class CardanoClient {
118
117
  await this.initPromise;
119
118
  }
120
119
  /**
121
- * Transient (retryable) init failures: a backend momentarily unreachable at
122
- * startup — e.g. Ogmios's /health response cut short while the node processes
123
- * a freshly-arrived block ("Premature close"), or the socket still coming up
124
- * (ECONNREFUSED). Config/validation errors are NOT transient.
120
+ * Transient (retryable) init failures: a backend momentarily unreachable at startup
121
+ * (connection refused/reset, a cut-short health response). Config/validation errors are not.
125
122
  */
126
123
  static isTransientInitError(err) {
127
124
  const e = err;
@@ -132,12 +129,8 @@ class CardanoClient {
132
129
  return /premature close|socket hang up|econnreset|econnrefused|etimedout|timeout|fetch failed|terminated|other side closed/.test(msg);
133
130
  }
134
131
  /**
135
- * Init a backend, retrying brief transient failures. Deliberately SMALL: the
136
- * integration suites bootstrap under a 20s cds.test() hook, so total retry
137
- * time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
138
- * ≈ 14s worst case; in practice "Premature close" returns sub-second). With
139
- * the node at tip these failures are momentary block-processing blips, so a
140
- * couple of quick retries ride over them; a sustained outage still fails fast.
132
+ * Init a backend, retrying brief transient failures. Kept small (3 attempts, 1 s backoff) so
133
+ * a sustained outage still fails fast and the total stays under the test bootstrap hook.
141
134
  */
142
135
  async initBackendWithRetry(backend) {
143
136
  const maxAttempts = 3;
@@ -155,12 +148,8 @@ class CardanoClient {
155
148
  }
156
149
  }
157
150
  /**
158
- * Initialize all backends from configuration.
159
- * Backends that fail to initialize are KEPT (previously removed permanently)
160
- * and tracked in `uninitializedBackends` — the request loops retry their
161
- * init lazily, so a backend that comes back online recovers without a
162
- * process restart. The circuit breaker bounds the retry cost.
163
- * @returns {Promise<void>}
151
+ * Initialize all backends. Backends whose init fails stay in rotation, tracked in
152
+ * `uninitializedBackends`, and are retried lazily per request (bounded by the circuit breaker).
164
153
  */
165
154
  async initBackends() {
166
155
  const initErrors = [];
@@ -220,13 +209,7 @@ class CardanoClient {
220
209
  return false;
221
210
  }
222
211
  }
223
- /**
224
- * Wrap a promise with a timeout
225
- * @param promise - the promise to wrap
226
- * @param ms - timeout in milliseconds
227
- * @param backendName - name of the backend (for error context)
228
- * @returns {Promise<T>} the result of the promise or a timeout error
229
- */
212
+ /** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
230
213
  withTimeout(promise, ms, backendName) {
231
214
  let timeoutId;
232
215
  const timeoutPromise = new Promise((_, reject) => {
@@ -236,22 +219,15 @@ class CardanoClient {
236
219
  clearTimeout(timeoutId);
237
220
  });
238
221
  }
239
- /**
240
- * Get timeout for specific backend
241
- * @param backend CardanoBackend instance
242
- * @returns {number} timeout in milliseconds
243
- */
222
+ /** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
244
223
  getTimeoutForBackend(backend) {
245
- if (backend.name === 'koios')
224
+ if (backend.name === 'koios' || backend.name === 'odatano')
246
225
  return this.config.fallbackTimeoutMs;
247
226
  return this.config.primaryTimeoutMs;
248
227
  }
249
228
  /**
250
- * Run a single-backend call with the same resilience contract as
251
- * executeWithPriority: circuit-breaker gate, timeout, success/failure
252
- * recording (4xx exempt). For the paths that cannot fail over (Koios-only,
253
- * Ogmios-only, batch-capable loops) — these previously bypassed timeout AND
254
- * breaker entirely, so a hanging socket blocked the caller indefinitely.
229
+ * Single-backend call with the executeWithPriority resilience contract (breaker gate, timeout,
230
+ * success/failure recording, 4xx exempt) for paths that cannot fail over.
255
231
  */
256
232
  async callWithResilience(backend, fn) {
257
233
  if (!this.circuitBreaker.shouldAttempt(backend.name)) {
@@ -275,15 +251,11 @@ class CardanoClient {
275
251
  throw backendError;
276
252
  }
277
253
  }
278
- /**
279
- * Execute with priority-based backend selection and automatic fallback
280
- * @param fn function to execute on backend
281
- * @param preferLive whether to prefer live backend over historical
282
- * @returns {Promise<T>} result from backend
283
- */
284
- async executeWithPriority(fn, preferLive, methodName) {
254
+ /** Execute on backends in preference order (live vs historical) with automatic fallback. */
255
+ async executeWithPriority(fn, preferLive, methodName, finalOnClientError = false) {
285
256
  await this.ensureInitialized();
286
257
  const errors = [];
258
+ const skipped = [];
287
259
  // Determine backend order based on preference
288
260
  const primaryBackends = preferLive
289
261
  ? (this.liveBackend ? [this.liveBackend] : [])
@@ -297,10 +269,12 @@ class CardanoClient {
297
269
  // capability routing: declared non-support is a skip, not a failure
298
270
  if (methodName && backend.unsupportedMethods?.has(methodName)) {
299
271
  logger.debug(`${backend.name} does not support ${methodName}, skipping`);
272
+ skipped.push(`${backend.name}: does not support ${methodName}`);
300
273
  continue;
301
274
  }
302
275
  if (!this.circuitBreaker.shouldAttempt(backend.name)) {
303
276
  logger.debug(`Circuit open for ${backend.name}, skipping`);
277
+ skipped.push(`${backend.name}: circuit open`);
304
278
  continue;
305
279
  }
306
280
  // fast-path sync check — only await the init retry in the rare failure case
@@ -317,148 +291,80 @@ class CardanoClient {
317
291
  catch (err) {
318
292
  const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
319
293
  errors.push(backendError);
320
- // 4xx are definitive verdicts from a HEALTHY backend (bad input, not found,
321
- // conflict, rate limit) — only 5xx/timeouts/transport errors indicate backend
322
- // health and may open the circuit. Counting client errors opened the breaker
323
- // on user mistakes and took working backends out of rotation.
294
+ // 4xx are definitive verdicts from a healthy backend and must not open the circuit;
295
+ // only 5xx/timeouts/transport errors indicate backend health.
324
296
  const isClientError = backendError.statusCode >= 400 && backendError.statusCode < 500;
325
297
  if (!isClientError) {
326
298
  this.circuitBreaker.recordFailure(backend.name);
327
299
  }
328
300
  const logLevel = backendError.statusCode === 404 ? 'debug' : 'warn';
329
301
  logger[logLevel](`Backend failed${backendError.statusCode === 404 ? ': resource not found' : ''}: ${backend.name} - ${backendError.message}`);
302
+ if (finalOnClientError && isClientError)
303
+ throw backendError;
330
304
  }
331
305
  }
332
- throw new errors_1.AllBackendsFailedError(errors);
306
+ throw new errors_1.AllBackendsFailedError(errors, undefined, skipped);
333
307
  }
334
- /**
335
- * Route method call to appropriate backend based on method routing configuration
336
- * @param methodName name of the method being called
337
- * @param fn function to execute on backend
338
- * @returns {Promise<T>} result from backend
339
- */
308
+ /** Route a call by METHOD_ROUTING (default: historical first). */
340
309
  route(methodName, fn) {
341
310
  const config = METHOD_ROUTING[methodName] ?? { preferLive: false };
342
- return this.executeWithPriority(fn, config.preferLive, methodName);
311
+ return this.executeWithPriority(fn, config.preferLive, methodName, config.finalOnClientError);
343
312
  }
344
- /**
345
- * Get transaction by hash with fallback between backends
346
- * @param txHash transaction hash (hex)
347
- * @returns {Promise<Transaction>} transaction data
348
- */
313
+ /** Transaction by hash (coalesced across concurrent callers). */
349
314
  getTransaction(txHash) {
350
315
  return this.txCoalescer.get(txHash, () => this.route('getTransaction', b => b.getTransaction(txHash)));
351
316
  }
352
- /**
353
- * Get address by bech32 address with fallback between backends
354
- * @param address bech32 address
355
- * @returns {Promise<Address>} address data
356
- */
317
+ /** Address data (coalesced across concurrent callers). */
357
318
  getAddress(address) {
358
319
  return this.addrCoalescer.get(address, () => this.route('getAddress', b => b.getAddress(address)));
359
320
  }
360
- /**
361
- * Get address UTxOs with fallback between backends
362
- * @param address bech32 address
363
- * @returns {Promise<UTxO[]>} list of UTxOs
364
- */
365
321
  getAddressUtxos(address) {
366
322
  return this.route('getAddressUtxos', b => b.getAddressUtxos(address));
367
323
  }
368
324
  /**
369
- * Get UTxOs by 28-byte payment credential. Koios-only — bypasses generic
370
- * failover because no other backend exposes a credential-keyed UTxO endpoint.
371
- * Throws ProviderUnavailableError if Koios is not configured.
372
- * @param credHash 28-byte payment credential as 56-char lowercase hex
373
- * @returns {Promise<UTxO[]>} list of UTxOs across all bech32 forms sharing the credential
325
+ * UTxOs by 28-byte payment credential (56-char hex), across all bech32 forms sharing it.
326
+ * Needs a credential-keyed backend (Koios, or another ODATANO); Blockfrost has none.
374
327
  */
375
328
  getCredentialUtxos(credHash) {
376
329
  const candidates = [this.liveBackend, ...this.historicalBackends];
377
- const koios = candidates.find(b => b?.name === 'koios' && typeof b.getCredentialUtxos === 'function');
378
- if (!koios) {
379
- throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires Koios backend. Configure 'koios' in cds.requires.odatano-core.backends.", 'koios');
330
+ const capable = candidates.filter((b) => typeof b?.getCredentialUtxos === 'function');
331
+ const backend = capable.find(b => b.name === 'koios') ?? capable[0];
332
+ if (!backend) {
333
+ throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires a Koios or odatano backend. Configure one in cds.requires.odatano-core.backends.", 'koios');
380
334
  }
381
- return this.credCoalescer.get(credHash, () => this.callWithResilience(koios, () => koios.getCredentialUtxos(credHash)));
335
+ return this.credCoalescer.get(credHash, () => this.callWithResilience(backend, () => backend.getCredentialUtxos(credHash)));
382
336
  }
383
- /**
384
- * Get address transactions with fallback between backends
385
- * @param address bech32 address
386
- * @returns {Promise<Transaction[]>} list of transactions for this address
387
- */
388
337
  getAddressTransactions(address, limit) {
389
338
  return this.route('getAddressTransactions', b => b.getAddressTransactions(address, limit));
390
339
  }
391
- /**
392
- * Get network information with fallback between backends
393
- * @returns {Promise<Network>} network information
394
- */
395
340
  getNetworkInformation() {
396
341
  return this.route('getNetworkInformation', b => b.getNetworkInformation());
397
342
  }
398
- /**
399
- * Get transaction metadata with fallback between backends
400
- * @param tx_hash transaction hash (hex)
401
- * @returns {Promise<MetadataLabelTx[]>} transaction metadata
402
- */
403
343
  getTransactionMetadata(tx_hash) {
404
344
  return this.route('getTransactionMetadata', b => b.getTransactionMetadata(tx_hash));
405
345
  }
406
- /**
407
- * Get block data with fallback between backends
408
- * @param block_hash block hash (hex)
409
- * @returns {Promise<BlockData>} block data
410
- */
411
346
  getBlock(block_hash) {
412
347
  return this.route('getBlock', b => b.getBlock(block_hash));
413
348
  }
414
- /**
415
- * Get epoch data with fallback between backends
416
- * @param epochNumber epoch number
417
- * @returns {Promise<EpochData>} epoch data
418
- */
419
349
  getEpoch(epochNumber) {
420
350
  return this.route('getEpoch', b => b.getEpoch(epochNumber));
421
351
  }
422
- /**
423
- * Get Pool data with fallback between backends
424
- * @param poolId pool id
425
- * @returns {Promise<PoolData>} pool data
426
- */
427
352
  getPool(poolId) {
428
353
  return this.route('getPool', b => b.getPool(poolId));
429
354
  }
430
- /**
431
- * Get drep data with fallback between backends
432
- * @param drepId drep id
433
- * @returns {Promise<DrepData>} drep data
434
- */
435
355
  getDrep(drepId) {
436
356
  return this.route('getDrep', b => b.getDrep(drepId));
437
357
  }
438
- /**
439
- * Get account data with fallback between backends
440
- * @param stakeAddress stake address
441
- * @returns {Promise<AccountData>} account data
442
- */
443
358
  getAccount(stakeAddress) {
444
359
  return this.route('getAccount', b => b.getAccount(stakeAddress));
445
360
  }
446
- /**
447
- * Get asset info (supply, mint history, CIP-25 + CIP-26 metadata) with fallback.
448
- * Both Blockfrost and Koios implement; Ogmios throws "not supported".
449
- * @param unit policyId + assetNameHex (concatenated hex)
450
- * @returns {Promise<AssetInfo>} canonical asset info
451
- */
361
+ /** Asset info (supply, mint history, CIP-25/CIP-26 metadata); Blockfrost and Koios only. */
452
362
  getAssetInfo(unit) {
453
363
  return this.route('getAssetInfo', b => b.getAssetInfo(unit));
454
364
  }
455
365
  /**
456
- * Get latest mint/burn events for an asset. Prefers Koios because it provides
457
- * block timestamps; Blockfrost is the fallback (timestamps left null).
458
- * Ogmios doesn't implement — fallback skips it via the optional method check.
459
- * @param unit policyId + assetNameHex (concatenated hex)
460
- * @param limit max number of events (default 100)
461
- * @returns {Promise<AssetHistoryEntry[]>} list of mint/burn events (most recent first)
366
+ * Latest mint/burn events for an asset, most recent first. Prefers Koios (block timestamps);
367
+ * Blockfrost is the fallback with timestamps left null.
462
368
  */
463
369
  getAssetHistory(unit, limit = 100) {
464
370
  const candidates = [...this.historicalBackends, this.liveBackend];
@@ -475,15 +381,10 @@ class CardanoClient {
475
381
  // Batch Methods (N+1 Optimization)
476
382
  //-----------------------------------------------------------------------------
477
383
  /**
478
- * Get transaction hashes for an address (lightweight — no full tx details).
479
- * Uses getAddressTransactionHashes() if backend supports it, otherwise
480
- * falls back to getAddressTransactions() and extracts hashes.
481
- * @param address bech32 address
482
- * @param limit maximum number of hashes
483
- * @returns {Promise<string[]>} list of transaction hashes
384
+ * Transaction hashes for an address; falls back to a full getAddressTransactions when no
385
+ * backend supports the lightweight listing.
484
386
  */
485
387
  async getAddressTransactionHashes(address, limit) {
486
- // Try backends with getAddressTransactionHashes support
487
388
  const allBackends = this.getOrderedBackends();
488
389
  for (const backend of allBackends) {
489
390
  if (backend.getAddressTransactionHashes) {
@@ -499,15 +400,8 @@ class CardanoClient {
499
400
  const txs = await this.getAddressTransactions(address, limit);
500
401
  return txs.map(tx => tx.hash);
501
402
  }
502
- /**
503
- * Batch fetch multiple transactions by hash.
504
- * Uses getTransactionsBatch() if backend supports it, otherwise
505
- * falls back to individual getTransaction() calls (still coalesced).
506
- * @param txHashes array of transaction hashes
507
- * @returns {Promise<Map<string, Transaction>>} map of hash -> Transaction
508
- */
403
+ /** Batch fetch transactions by hash; falls back to individual coalesced getTransaction calls. */
509
404
  async getTransactionsBatch(txHashes) {
510
- // Try backends with batch support
511
405
  const allBackends = this.getOrderedBackends();
512
406
  for (const backend of allBackends) {
513
407
  if (backend.getTransactionsBatch) {
@@ -523,11 +417,7 @@ class CardanoClient {
523
417
  const entries = await Promise.all(txHashes.map(h => this.getTransaction(h).then(tx => [h, tx])));
524
418
  return new Map(entries);
525
419
  }
526
- /**
527
- * Backends in historical-first order. Used by the batch methods — both
528
- * always prefer historical data, so the former preferLive parameter was a
529
- * dead branch.
530
- */
420
+ /** Backends in historical-first order, for the batch methods. */
531
421
  getOrderedBackends() {
532
422
  const backends = [...this.historicalBackends];
533
423
  if (this.liveBackend)
@@ -535,11 +425,8 @@ class CardanoClient {
535
425
  return backends;
536
426
  }
537
427
  /**
538
- * Get a backend that supports streamed chain-synchronization (Ogmios), or null.
539
- * The crawler's primary, reorg-aware source. Checks the live backend first.
540
- * Backends whose init() failed are skipped — the crawler uses these instances
541
- * DIRECTLY (outside executeWithPriority's lazy-retry/breaker), so handing out an
542
- * uninitialized backend would wedge it.
428
+ * A backend that supports streamed chain-sync (Ogmios), or null. Backends whose init failed
429
+ * are skipped: the crawler uses these instances directly, outside the lazy-retry/breaker path.
543
430
  */
544
431
  getChainSyncBackend() {
545
432
  const candidates = [this.liveBackend, ...this.historicalBackends];
@@ -550,13 +437,80 @@ class CardanoClient {
550
437
  return null;
551
438
  }
552
439
  /**
553
- * Get a backend that can be walked forward by pagination (Blockfrost/Koios), or null.
554
- * The crawler's fallback source when no Ogmios chain-sync is available.
555
- * Skips backends whose init() failed (see getChainSyncBackend).
556
- *
557
- * Koios is preferred over Blockfrost for bulk block-crawling: Koios batches 100 txs
558
- * per POST /tx_info, while Blockfrost has no batch endpoint (~3 HTTP calls per tx) —
559
- * roughly a 40x difference in request volume per crawled block.
440
+ * getChainSyncBackend(), retrying a failed startup init. Polled by the crawler while it runs
441
+ * on pagination because no chain-sync source was usable when it started.
442
+ */
443
+ async recoverChainSyncBackend() {
444
+ const candidates = [this.liveBackend, ...this.historicalBackends];
445
+ for (const b of candidates) {
446
+ if (!b || !(0, cardano_backend_1.isChainSyncBackend)(b))
447
+ continue;
448
+ if (await this.ensureBackendInitialized(b))
449
+ return b;
450
+ }
451
+ return null;
452
+ }
453
+ /** The first usable backend that can dump the UTxO set at a point (Ogmios) — crawler.utxoSet import. */
454
+ getLedgerStateBackend() {
455
+ const candidates = [this.liveBackend, ...this.historicalBackends];
456
+ for (const b of candidates) {
457
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isLedgerStateBackend)(b))
458
+ return b;
459
+ }
460
+ return null;
461
+ }
462
+ /**
463
+ * Outputs among `refs` that are unspent at the tip, read from the node's ledger (Ogmios, or a remote
464
+ * ODATANO that asks its node); null when no backend can (the caller then resolves via the producing
465
+ * transaction, which carries no reference-script bytes).
466
+ */
467
+ async getUnspentOutputs(refs) {
468
+ const backend = this.getLedgerStateBackend() ?? this.outputLookupBackend();
469
+ return backend ? backend.getUnspentOutputs(refs) : null;
470
+ }
471
+ /** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
472
+ outputLookupBackend() {
473
+ const candidates = [this.liveBackend, ...this.historicalBackends];
474
+ for (const b of candidates) {
475
+ const lookup = b;
476
+ if (lookup && !this.uninitializedBackends.has(lookup) && typeof lookup.getUnspentOutputs === 'function') {
477
+ return lookup;
478
+ }
479
+ }
480
+ return null;
481
+ }
482
+ /** True when an initialized backend implements `method` and does not declare it unsupported. */
483
+ hasBackendFor(method) {
484
+ const candidates = [this.liveBackend, ...this.historicalBackends];
485
+ return candidates.some((b) => !!b
486
+ && !this.uninitializedBackends.has(b)
487
+ && typeof b[method] === 'function'
488
+ && !b.unsupportedMethods?.has(method));
489
+ }
490
+ /** A backend that reads pool/DRep/pot state at a block (Ogmios) — preferred source of epoch snapshots. */
491
+ getEpochStateBackend() {
492
+ const candidates = [this.liveBackend, ...this.historicalBackends];
493
+ for (const b of candidates) {
494
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isEpochStateBackend)(b))
495
+ return b;
496
+ }
497
+ return null;
498
+ }
499
+ /**
500
+ * A backend that can enumerate the full pool/DRep set (Koios), or null; without one the epoch
501
+ * snapshots stay off instead of degrading into thousands of single requests.
502
+ */
503
+ getEnumeratingBackend() {
504
+ const candidates = [...this.historicalBackends, this.liveBackend];
505
+ for (const b of candidates) {
506
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isEnumeratingBackend)(b))
507
+ return b;
508
+ }
509
+ return null;
510
+ }
511
+ /**
512
+ * A backend that can be walked forward by pagination (Blockfrost/Koios), or null. Koios is
513
+ * preferred: it batches 100 txs per call, Blockfrost needs ~3 calls per tx.
560
514
  */
561
515
  getPaginatingBackend() {
562
516
  const usable = this.historicalBackends.filter((b) => !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isPaginatingBackend)(b));
@@ -570,21 +524,25 @@ class CardanoClient {
570
524
  }
571
525
  return null;
572
526
  }
573
- /**
574
- * Get protocol parameters with caching (5 minute TTL)
575
- * Protocol parameters rarely change (once per epoch at most), so caching improves performance
576
- * @returns {Promise<LedgerProtocolParameters>} protocol parameters
577
- */
527
+ /** Protocol parameters with a 5-minute in-memory cache and coalesced refresh. */
578
528
  async getProtocolParameters() {
579
529
  const now = Date.now();
580
530
  if (this.protocolParamsCache && (now - this.protocolParamsCache.fetchedAt) < CardanoClient.PROTOCOL_PARAMS_TTL_MS) {
581
531
  logger.debug('Returning cached protocol parameters');
582
532
  return this.protocolParamsCache.data;
583
533
  }
584
- // Promise coalescing: deduplicate concurrent requests during cache miss
585
534
  if (!this.protocolParamsFetchPromise) {
586
535
  logger.debug('Fetching fresh protocol parameters');
587
- this.protocolParamsFetchPromise = this.route('getProtocolParameters', b => b.getProtocolParameters())
536
+ this.protocolParamsFetchPromise = this.route('getProtocolParameters', async (b) => {
537
+ const params = await b.getProtocolParameters();
538
+ if (b === this.liveBackend) {
539
+ this.lastLiveProtocolParams = params;
540
+ return params;
541
+ }
542
+ // A fallback answering for the epoch the node last reported: keep the node's values
543
+ const live = this.lastLiveProtocolParams;
544
+ return live && Number(live.epoch) === Number(params.epoch) ? live : params;
545
+ })
588
546
  .then(params => {
589
547
  this.protocolParamsCache = { data: params, fetchedAt: Date.now() };
590
548
  this.protocolParamsFetchPromise = null;
@@ -597,12 +555,9 @@ class CardanoClient {
597
555
  }
598
556
  return this.protocolParamsFetchPromise;
599
557
  }
600
- /**
601
- * Shutdown all backends (for cleanup in tests)
602
- */
558
+ /** Shut down all backends. */
603
559
  async shutdown() {
604
560
  logger.info('Shutting down CardanoClient backends...');
605
- // Shutdown live backend if it has a shutdown method
606
561
  if (this.liveBackend && 'shutdown' in this.liveBackend && typeof this.liveBackend.shutdown === 'function') {
607
562
  try {
608
563
  await this.liveBackend.shutdown();
@@ -612,7 +567,6 @@ class CardanoClient {
612
567
  logger.error(`Error shutting down live backend ${this.liveBackend.name}: ${err}`);
613
568
  }
614
569
  }
615
- // Shutdown historical backends
616
570
  for (const backend of this.historicalBackends) {
617
571
  if ('shutdown' in backend && typeof backend.shutdown === 'function') {
618
572
  try {
@@ -628,70 +582,60 @@ class CardanoClient {
628
582
  this.initPromise = null;
629
583
  logger.info('CardanoClient shutdown complete');
630
584
  }
631
- /**
632
- * Get latest block data with fallback between backends
633
- * @returns {Promise<BlockData>} latest block data
634
- */
635
585
  getLatestBlock() {
636
586
  return this.route('getLatestBlock', b => b.getLatestBlock());
637
587
  }
638
- /**
639
- * Get latest epoch data with fallback between backends
640
- * @returns {Promise<EpochData>} latest epoch data
641
- */
642
588
  getLatestEpoch() {
643
589
  return this.route('getLatestEpoch', b => b.getLatestEpoch());
644
590
  }
645
- /**
646
- * Get the current chain slot with fallback between backends.
647
- * @returns {Promise<number>} current chain slot
648
- */
649
591
  getCurrentSlot() {
650
592
  return this.route('getCurrentSlot', b => b.getCurrentSlot());
651
593
  }
652
- /**
653
- * Check whether a UTxO is still unspent with fallback between backends.
654
- * @param txHash 64-char lowercase hex transaction hash
655
- * @param outputIndex non-negative integer output index
656
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
657
- */
594
+ /** True iff the UTxO exists and is unspent. */
658
595
  isUtxoUnspent(txHash, outputIndex) {
659
596
  return this.route('isUtxoUnspent', b => b.isUtxoUnspent(txHash, outputIndex));
660
597
  }
661
598
  /**
662
- * Submit transaction with fallback between backends
663
- * @param signedTxCbor signed transaction in CBOR hex format
664
- * @returns {Promise<string>} transaction hash
665
- *
666
- * NOTE on failover semantics: when the preferred backend ACCEPTS the tx but
667
- * its response is lost (timeout), the failover resubmits on the next backend,
668
- * which may answer 409 "already submitted". Callers should treat a
669
- * TransactionAlreadySubmittedError after a submit attempt as success — the
670
- * transaction IS in the mempool.
599
+ * Submit a signed transaction (CBOR hex); returns its hash. On failover after a lost response
600
+ * the next backend may answer 409 "already submitted" — callers treat that as success.
671
601
  */
672
- submitTransaction(signedTxCbor) {
673
- return this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
602
+ async submitTransaction(signedTxCbor) {
603
+ try {
604
+ const hash = await this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
605
+ this.pendingSpends.record(signedTxCbor);
606
+ return hash;
607
+ }
608
+ catch (err) {
609
+ // already in the mempool or on chain: its inputs are gone all the same
610
+ if (err instanceof errors_1.TransactionAlreadySubmittedError)
611
+ this.pendingSpends.record(signedTxCbor);
612
+ throw err;
613
+ }
674
614
  }
675
- /**
676
- * Check if Ogmios backend is available for transaction evaluation
677
- * @returns {boolean} true if Ogmios is the live backend
678
- */
615
+ /** True when Ogmios is the live backend. */
679
616
  hasOgmiosBackend() {
680
617
  return this.liveBackend?.name === 'ogmios';
681
618
  }
682
- /**
683
- * Evaluate transaction script execution units (Ogmios only)
684
- * @param unsignedTxCbor unsigned transaction in CBOR hex format
685
- * @returns {Promise<ScriptEvaluationResult[]>} evaluation results
686
- */
619
+ /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
620
+ evaluatingBackend() {
621
+ const candidates = [this.liveBackend, ...this.historicalBackends];
622
+ for (const b of candidates)
623
+ if (b && (0, cardano_backend_1.isEvaluatingBackend)(b))
624
+ return b;
625
+ return null;
626
+ }
627
+ /** True when some backend can evaluate script execution units. */
628
+ hasEvaluatingBackend() {
629
+ return this.evaluatingBackend() != null;
630
+ }
631
+ /** Evaluate script execution units of an unsigned transaction. */
687
632
  async evaluateTransaction(unsignedTxCbor) {
688
633
  await this.ensureInitialized();
689
- // Evaluation requires an EvaluatingBackend (typically Ogmios)
690
- if (!this.liveBackend || !(0, cardano_backend_1.isEvaluatingBackend)(this.liveBackend)) {
691
- throw new errors_1.ProviderUnavailableError('Transaction evaluation requires an evaluating backend (e.g., Ogmios)');
634
+ const backend = this.evaluatingBackend();
635
+ if (!backend) {
636
+ throw new errors_1.ProviderUnavailableError('Transaction evaluation requires an evaluating backend (Ogmios or odatano)');
692
637
  }
693
- // timeout + breaker — a hanging Ogmios socket previously blocked Plutus builds indefinitely
694
- const backend = this.liveBackend;
638
+ // timeout + breaker, so a hanging socket cannot block Plutus builds
695
639
  return this.callWithResilience(backend, () => backend.evaluateTransaction(unsignedTxCbor));
696
640
  }
697
641
  }