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

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 (208) 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 +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -7,21 +7,27 @@ 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");
11
+ const const_1 = require("../utils/const");
10
12
  const circuit_breaker_1 = require("./circuit-breaker");
11
13
  const request_coalescer_1 = require("./request-coalescer");
12
- const ogmios_backend_1 = require("./backends/ogmios-backend");
13
- const blockfrost_backend_1 = require("./backends/blockfrost-backend");
14
- const koios_backend_1 = require("./backends/koios-backend");
14
+ // A backend module loads when its backend is configured, and its provider SDK with it.
15
+ const backendModules = {
16
+ ogmios: () => require('./backends/ogmios-backend'),
17
+ blockfrost: () => require('./backends/blockfrost-backend'),
18
+ koios: () => require('./backends/koios-backend'),
19
+ odatano: () => require('./backends/odatano-backend'),
20
+ };
15
21
  const logger = cds_1.default.log('CardanoClient');
16
- /**
17
- * Method routing configuration - defines which backend type to prefer for each method
18
- */
22
+ /** Which backend type to prefer per method. */
19
23
  const METHOD_ROUTING = {
20
24
  getTransaction: { preferLive: false },
25
+ // node first: UTxOs at the tip; Ogmios decodes the type itself (base/enterprise/…, not shelley/byron)
21
26
  getAddress: { preferLive: true },
22
- getAddressUtxos: { preferLive: false },
27
+ getAddressUtxos: { preferLive: true },
23
28
  getAddressTransactions: { preferLive: false },
24
- getNetworkInformation: { preferLive: true },
29
+ // providers first: they report circulation; Ogmios only has treasury and reserves
30
+ getNetworkInformation: { preferLive: false },
25
31
  getTransactionMetadata: { preferLive: false },
26
32
  getBlock: { preferLive: false },
27
33
  getEpoch: { preferLive: false },
@@ -30,20 +36,16 @@ const METHOD_ROUTING = {
30
36
  getCurrentSlot: { preferLive: true },
31
37
  isUtxoUnspent: { preferLive: true },
32
38
  getPool: { preferLive: true },
33
- getDrep: { preferLive: false },
39
+ // node first; a DRep the ledger no longer lists (retired) falls through to the providers
40
+ getDrep: { preferLive: true },
34
41
  getAccount: { preferLive: true },
35
42
  getAssetInfo: { preferLive: false },
36
43
  getProtocolParameters: { preferLive: true },
37
- submitTransaction: { preferLive: true },
44
+ // a node's rejection (4xx) is final: another backend submits to the same ledger
45
+ submitTransaction: { preferLive: true, finalOnClientError: true },
38
46
  };
39
- /**
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
46
- */
47
+ // Multi-backend client. Live state queries prefer Ogmios, historical queries prefer Blockfrost
48
+ // or Koios, with automatic fallback between them.
47
49
  class CardanoClient {
48
50
  config;
49
51
  liveBackend;
@@ -51,41 +53,46 @@ class CardanoClient {
51
53
  initialized = false;
52
54
  initPromise = null;
53
55
  circuitBreaker;
54
- /** Backends whose init failed — kept in rotation and retried lazily per request */
56
+ /** Backends whose init failed. They stay in rotation and init is retried per request. */
55
57
  uninitializedBackends = new Set();
56
58
  network;
57
- max_age_ms = 60000; // default 1 minute for temporary caching
59
+ max_age_ms = const_1.DEFAULT_INDEX_TTL_MS;
60
+ /** Transactions submitted through this client that the ledger view does not show yet. */
61
+ pendingSpends = new pending_spends_1.PendingSpends();
58
62
  protocolParamsCache;
59
63
  protocolParamsFetchPromise = null;
60
- static PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes
61
- // Request coalescers — deduplicate concurrent fetches for the same resource
64
+ /** Last protocol parameters the live backend (node) answered. */
65
+ lastLiveProtocolParams;
66
+ // Deduplicate concurrent fetches for the same resource.
62
67
  txCoalescer = new request_coalescer_1.RequestCoalescer();
63
68
  addrCoalescer = new request_coalescer_1.RequestCoalescer();
64
69
  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
- */
70
+ /** Builds the configured backends; throws ConfigError when none is configured. */
70
71
  constructor(clientConfig) {
71
72
  this.network = clientConfig.network;
72
73
  const backends = clientConfig.backends;
73
74
  if (backends.includes('ogmios')) {
74
- this.liveBackend = new ogmios_backend_1.OgmiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.ogmiosUrl);
75
+ const { OgmiosBackend } = backendModules.ogmios();
76
+ this.liveBackend = new OgmiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.ogmiosUrl);
75
77
  }
76
78
  if (backends.includes('blockfrost')) {
77
- this.historicalBackends.push(new blockfrost_backend_1.BlockfrostBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.blockfrostApiKey, clientConfig.blockfrostCustomBackend));
79
+ const { BlockfrostBackend } = backendModules.blockfrost();
80
+ this.historicalBackends.push(new BlockfrostBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.blockfrostApiKey, clientConfig.blockfrostCustomBackend));
78
81
  }
79
82
  if (backends.includes('koios')) {
80
- this.historicalBackends.push(new koios_backend_1.KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
83
+ const { KoiosBackend } = backendModules.koios();
84
+ this.historicalBackends.push(new KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
85
+ }
86
+ if (backends.includes('odatano')) {
87
+ // A remote ODATANO runs its own failover chain: allow its primary timeout plus the fallback.
88
+ const { OdatanoBackend } = backendModules.odatano();
89
+ this.historicalBackends.push(new OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
81
90
  }
82
91
  if (!this.liveBackend && this.historicalBackends.length === 0) {
83
92
  throw new errors_1.ConfigError('No valid backends configured for CardanoClient');
84
93
  }
85
94
  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.
95
+ // indexTtlMs is the cache TTL the indexer reads via max_age_ms
89
96
  if (Number.isFinite(clientConfig.indexTtlMs) && clientConfig.indexTtlMs > 0) {
90
97
  this.max_age_ms = clientConfig.indexTtlMs;
91
98
  }
@@ -100,29 +107,18 @@ class CardanoClient {
100
107
  names.push(...this.historicalBackends.map(b => b.name));
101
108
  return names;
102
109
  }
103
- /**
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>}
109
- */
110
+ /** A failed init promise is cleared so the next request retries instead of staying broken. */
110
111
  async ensureInitialized() {
111
112
  if (this.initialized)
112
113
  return;
113
- // Use nullish coalescing assignment for atomic operation to prevent race conditions
114
+ // ??= keeps concurrent callers on one init promise
114
115
  this.initPromise ??= this.initBackends().catch((err) => {
115
116
  this.initPromise = null;
116
117
  throw err;
117
118
  });
118
119
  await this.initPromise;
119
120
  }
120
- /**
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.
125
- */
121
+ /** True for a backend that is briefly unreachable at startup. Config errors are not transient. */
126
122
  static isTransientInitError(err) {
127
123
  const e = err;
128
124
  const code = e?.code ?? e?.cause?.code ?? '';
@@ -131,14 +127,8 @@ class CardanoClient {
131
127
  return true;
132
128
  return /premature close|socket hang up|econnreset|econnrefused|etimedout|timeout|fetch failed|terminated|other side closed/.test(msg);
133
129
  }
134
- /**
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.
141
- */
130
+ // Retries brief transient init failures. Few attempts with a short backoff, so a real
131
+ // outage still fails fast and stays under the test bootstrap timeout.
142
132
  async initBackendWithRetry(backend) {
143
133
  const maxAttempts = 3;
144
134
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
@@ -149,19 +139,12 @@ class CardanoClient {
149
139
  catch (err) {
150
140
  if (attempt >= maxAttempts || !CardanoClient.isTransientInitError(err))
151
141
  throw err;
152
- logger.warn(`Init of ${backend.name} failed (attempt ${attempt}/${maxAttempts}) — transient, retrying in 1s`, err);
142
+ logger.warn(`Init of ${backend.name} failed (attempt ${attempt}/${maxAttempts}), transient, retrying in 1s`, err);
153
143
  await new Promise(r => setTimeout(r, 1000));
154
144
  }
155
145
  }
156
146
  }
157
- /**
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>}
164
- */
147
+ /** Backends whose init fails stay in rotation and are retried per request, bounded by the breaker. */
165
148
  async initBackends() {
166
149
  const initErrors = [];
167
150
  // Initialize live backend
@@ -174,7 +157,7 @@ class CardanoClient {
174
157
  }
175
158
  catch (err) {
176
159
  initErrors.push(new errors_1.BackendInitError(this.liveBackend.name, err));
177
- logger.error(`Failed to initialize live backend: ${this.liveBackend.name} — kept for lazy retry`, err);
160
+ logger.error(`Failed to initialize live backend: ${this.liveBackend.name}, kept for lazy retry`, err);
178
161
  this.uninitializedBackends.add(this.liveBackend);
179
162
  }
180
163
  }
@@ -188,7 +171,7 @@ class CardanoClient {
188
171
  }
189
172
  catch (err) {
190
173
  initErrors.push(new errors_1.BackendInitError(backend.name, err));
191
- logger.error(`Failed to initialize historical backend: ${backend.name} — kept for lazy retry`, err);
174
+ logger.error(`Failed to initialize historical backend: ${backend.name}, kept for lazy retry`, err);
192
175
  this.uninitializedBackends.add(backend);
193
176
  }
194
177
  }
@@ -198,11 +181,7 @@ class CardanoClient {
198
181
  }
199
182
  this.initialized = true;
200
183
  }
201
- /**
202
- * Lazily retry a backend's init when it failed at startup. Returns true when
203
- * the backend is usable; false (after recording a breaker failure) when the
204
- * retry failed.
205
- */
184
+ /** Retries a failed startup init. False records a breaker failure. */
206
185
  async ensureBackendInitialized(backend, errors) {
207
186
  if (!this.uninitializedBackends.has(backend))
208
187
  return true;
@@ -220,13 +199,7 @@ class CardanoClient {
220
199
  return false;
221
200
  }
222
201
  }
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
- */
202
+ /** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
230
203
  withTimeout(promise, ms, backendName) {
231
204
  let timeoutId;
232
205
  const timeoutPromise = new Promise((_, reject) => {
@@ -236,28 +209,19 @@ class CardanoClient {
236
209
  clearTimeout(timeoutId);
237
210
  });
238
211
  }
239
- /**
240
- * Get timeout for specific backend
241
- * @param backend CardanoBackend instance
242
- * @returns {number} timeout in milliseconds
243
- */
212
+ /** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
244
213
  getTimeoutForBackend(backend) {
245
- if (backend.name === 'koios')
214
+ if (backend.name === 'koios' || backend.name === 'odatano')
246
215
  return this.config.fallbackTimeoutMs;
247
216
  return this.config.primaryTimeoutMs;
248
217
  }
249
- /**
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.
255
- */
218
+ // One backend call with the same breaker, timeout and recording rules as executeWithPriority.
219
+ // For paths that cannot fail over.
256
220
  async callWithResilience(backend, fn) {
257
221
  if (!this.circuitBreaker.shouldAttempt(backend.name)) {
258
222
  throw new errors_1.ProviderUnavailableError(`Circuit open for ${backend.name}`, backend.name);
259
223
  }
260
- // fast-path sync check — keeps fn() synchronous for the request coalescers
224
+ // Sync check first keeps fn() synchronous for the request coalescers.
261
225
  if (this.uninitializedBackends.has(backend) && !(await this.ensureBackendInitialized(backend))) {
262
226
  throw new errors_1.ProviderUnavailableError(`Backend ${backend.name} is not initialized (lazy retry failed)`, backend.name);
263
227
  }
@@ -275,15 +239,11 @@ class CardanoClient {
275
239
  throw backendError;
276
240
  }
277
241
  }
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) {
242
+ /** Execute on backends in preference order (live vs historical) with automatic fallback. */
243
+ async executeWithPriority(fn, preferLive, methodName, finalOnClientError = false) {
285
244
  await this.ensureInitialized();
286
245
  const errors = [];
246
+ const skipped = [];
287
247
  // Determine backend order based on preference
288
248
  const primaryBackends = preferLive
289
249
  ? (this.liveBackend ? [this.liveBackend] : [])
@@ -297,13 +257,15 @@ class CardanoClient {
297
257
  // capability routing: declared non-support is a skip, not a failure
298
258
  if (methodName && backend.unsupportedMethods?.has(methodName)) {
299
259
  logger.debug(`${backend.name} does not support ${methodName}, skipping`);
260
+ skipped.push(`${backend.name}: does not support ${methodName}`);
300
261
  continue;
301
262
  }
302
263
  if (!this.circuitBreaker.shouldAttempt(backend.name)) {
303
264
  logger.debug(`Circuit open for ${backend.name}, skipping`);
265
+ skipped.push(`${backend.name}: circuit open`);
304
266
  continue;
305
267
  }
306
- // fast-path sync check — only await the init retry in the rare failure case
268
+ // Sync check first, so only the rare failure case awaits the init retry.
307
269
  if (this.uninitializedBackends.has(backend) && !(await this.ensureBackendInitialized(backend, errors))) {
308
270
  continue;
309
271
  }
@@ -317,149 +279,106 @@ class CardanoClient {
317
279
  catch (err) {
318
280
  const backendError = (0, errors_1.normalizeBackendError)(err, backend.name);
319
281
  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.
282
+ // 4xx are definitive verdicts from a healthy backend and must not open the circuit;
283
+ // only 5xx/timeouts/transport errors indicate backend health.
324
284
  const isClientError = backendError.statusCode >= 400 && backendError.statusCode < 500;
325
285
  if (!isClientError) {
326
286
  this.circuitBreaker.recordFailure(backend.name);
327
287
  }
328
288
  const logLevel = backendError.statusCode === 404 ? 'debug' : 'warn';
329
289
  logger[logLevel](`Backend failed${backendError.statusCode === 404 ? ': resource not found' : ''}: ${backend.name} - ${backendError.message}`);
290
+ if (finalOnClientError && isClientError)
291
+ throw backendError;
330
292
  }
331
293
  }
332
- throw new errors_1.AllBackendsFailedError(errors);
294
+ throw new errors_1.AllBackendsFailedError(errors, undefined, skipped);
333
295
  }
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
- */
296
+ /** Route a call by METHOD_ROUTING (default: historical first). */
340
297
  route(methodName, fn) {
341
298
  const config = METHOD_ROUTING[methodName] ?? { preferLive: false };
342
- return this.executeWithPriority(fn, config.preferLive, methodName);
299
+ return this.executeWithPriority(fn, config.preferLive, methodName, config.finalOnClientError);
343
300
  }
344
- /**
345
- * Get transaction by hash with fallback between backends
346
- * @param txHash transaction hash (hex)
347
- * @returns {Promise<Transaction>} transaction data
348
- */
301
+ /** Transaction by hash (coalesced across concurrent callers). */
349
302
  getTransaction(txHash) {
350
303
  return this.txCoalescer.get(txHash, () => this.route('getTransaction', b => b.getTransaction(txHash)));
351
304
  }
352
- /**
353
- * Get address by bech32 address with fallback between backends
354
- * @param address bech32 address
355
- * @returns {Promise<Address>} address data
356
- */
305
+ /** Address data (coalesced across concurrent callers). */
357
306
  getAddress(address) {
358
307
  return this.addrCoalescer.get(address, () => this.route('getAddress', b => b.getAddress(address)));
359
308
  }
360
- /**
361
- * Get address UTxOs with fallback between backends
362
- * @param address bech32 address
363
- * @returns {Promise<UTxO[]>} list of UTxOs
364
- */
365
309
  getAddressUtxos(address) {
366
310
  return this.route('getAddressUtxos', b => b.getAddressUtxos(address));
367
311
  }
368
- /**
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
374
- */
312
+ // UTxOs of every address form that shares the payment credential.
313
+ // Needs Koios or another ODATANO, because Blockfrost has no credential lookup.
375
314
  getCredentialUtxos(credHash) {
376
315
  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');
316
+ const capable = candidates.filter((b) => typeof b?.getCredentialUtxos === 'function');
317
+ const backend = capable.find(b => b.name === 'koios') ?? capable[0];
318
+ if (!backend) {
319
+ throw new errors_1.ProviderUnavailableError("getCredentialUtxos requires a Koios or odatano backend. Configure one in cds.requires.odatano-core.backends.", 'koios');
380
320
  }
381
- return this.credCoalescer.get(credHash, () => this.callWithResilience(koios, () => koios.getCredentialUtxos(credHash)));
321
+ return this.credCoalescer.get(credHash, () => this.callWithResilience(backend, () => backend.getCredentialUtxos(credHash)));
382
322
  }
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
323
  getAddressTransactions(address, limit) {
389
324
  return this.route('getAddressTransactions', b => b.getAddressTransactions(address, limit));
390
325
  }
391
- /**
392
- * Get network information with fallback between backends
393
- * @returns {Promise<Network>} network information
394
- */
395
326
  getNetworkInformation() {
396
327
  return this.route('getNetworkInformation', b => b.getNetworkInformation());
397
328
  }
398
- /**
399
- * Get transaction metadata with fallback between backends
400
- * @param tx_hash transaction hash (hex)
401
- * @returns {Promise<MetadataLabelTx[]>} transaction metadata
402
- */
403
329
  getTransactionMetadata(tx_hash) {
404
330
  return this.route('getTransactionMetadata', b => b.getTransactionMetadata(tx_hash));
405
331
  }
406
- /**
407
- * Get block data with fallback between backends
408
- * @param block_hash block hash (hex)
409
- * @returns {Promise<BlockData>} block data
410
- */
411
332
  getBlock(block_hash) {
412
333
  return this.route('getBlock', b => b.getBlock(block_hash));
413
334
  }
414
- /**
415
- * Get epoch data with fallback between backends
416
- * @param epochNumber epoch number
417
- * @returns {Promise<EpochData>} epoch data
418
- */
419
335
  getEpoch(epochNumber) {
420
336
  return this.route('getEpoch', b => b.getEpoch(epochNumber));
421
337
  }
422
- /**
423
- * Get Pool data with fallback between backends
424
- * @param poolId pool id
425
- * @returns {Promise<PoolData>} pool data
426
- */
427
338
  getPool(poolId) {
428
339
  return this.route('getPool', b => b.getPool(poolId));
429
340
  }
430
- /**
431
- * Get drep data with fallback between backends
432
- * @param drepId drep id
433
- * @returns {Promise<DrepData>} drep data
434
- */
435
341
  getDrep(drepId) {
436
342
  return this.route('getDrep', b => b.getDrep(drepId));
437
343
  }
438
- /**
439
- * Get account data with fallback between backends
440
- * @param stakeAddress stake address
441
- * @returns {Promise<AccountData>} account data
442
- */
443
- getAccount(stakeAddress) {
444
- return this.route('getAccount', b => b.getAccount(stakeAddress));
445
- }
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
- */
344
+ // The node reports no balance for an account without a pool delegation. A provider then
345
+ // answers in its place; without one the node's answer stands, balance unknown.
346
+ async getAccount(stakeAddress) {
347
+ const account = await this.route('getAccount', b => b.getAccount(stakeAddress));
348
+ if (account.withdrawableAmount != null)
349
+ return account;
350
+ for (const provider of this.historicalBackends) {
351
+ try {
352
+ return await this.callWithResilience(provider, () => provider.getAccount(stakeAddress));
353
+ }
354
+ catch (err) {
355
+ logger.debug(`getAccount on ${provider.name} failed, trying the next provider: ${err instanceof Error ? err.message : String(err)}`);
356
+ }
357
+ }
358
+ return account;
359
+ }
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.
362
+ 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;
373
+ }
374
+ throw err;
375
+ }
376
+ }
377
+ /** Asset info (supply, mint history, CIP-25/CIP-26 metadata); Blockfrost and Koios only. */
452
378
  getAssetInfo(unit) {
453
379
  return this.route('getAssetInfo', b => b.getAssetInfo(unit));
454
380
  }
455
- /**
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)
462
- */
381
+ /** Latest mint and burn events. Prefers Koios, because Blockfrost leaves timestamps null. */
463
382
  getAssetHistory(unit, limit = 100) {
464
383
  const candidates = [...this.historicalBackends, this.liveBackend];
465
384
  const koios = candidates.find(b => b?.name === 'koios' && typeof b.getAssetHistory === 'function');
@@ -474,16 +393,8 @@ class CardanoClient {
474
393
  //-----------------------------------------------------------------------------
475
394
  // Batch Methods (N+1 Optimization)
476
395
  //-----------------------------------------------------------------------------
477
- /**
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
484
- */
396
+ /** Falls back to a full getAddressTransactions when no backend lists hashes only. */
485
397
  async getAddressTransactionHashes(address, limit) {
486
- // Try backends with getAddressTransactionHashes support
487
398
  const allBackends = this.getOrderedBackends();
488
399
  for (const backend of allBackends) {
489
400
  if (backend.getAddressTransactionHashes) {
@@ -491,7 +402,7 @@ class CardanoClient {
491
402
  return await this.callWithResilience(backend, () => backend.getAddressTransactionHashes(address, limit));
492
403
  }
493
404
  catch (err) {
494
- logger.debug(`getAddressTransactionHashes failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)} — trying next backend`);
405
+ logger.debug(`getAddressTransactionHashes failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)}, trying next backend`);
495
406
  }
496
407
  }
497
408
  }
@@ -499,15 +410,8 @@ class CardanoClient {
499
410
  const txs = await this.getAddressTransactions(address, limit);
500
411
  return txs.map(tx => tx.hash);
501
412
  }
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
- */
413
+ /** Batch fetch transactions by hash; falls back to individual coalesced getTransaction calls. */
509
414
  async getTransactionsBatch(txHashes) {
510
- // Try backends with batch support
511
415
  const allBackends = this.getOrderedBackends();
512
416
  for (const backend of allBackends) {
513
417
  if (backend.getTransactionsBatch) {
@@ -515,7 +419,7 @@ class CardanoClient {
515
419
  return await this.callWithResilience(backend, () => backend.getTransactionsBatch(txHashes));
516
420
  }
517
421
  catch (err) {
518
- logger.debug(`getTransactionsBatch failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)} — trying next backend`);
422
+ logger.debug(`getTransactionsBatch failed on ${backend.name}: ${err instanceof Error ? err.message : String(err)}, trying next backend`);
519
423
  }
520
424
  }
521
425
  }
@@ -523,24 +427,15 @@ class CardanoClient {
523
427
  const entries = await Promise.all(txHashes.map(h => this.getTransaction(h).then(tx => [h, tx])));
524
428
  return new Map(entries);
525
429
  }
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
- */
430
+ /** Backends in historical-first order, for the batch methods. */
531
431
  getOrderedBackends() {
532
432
  const backends = [...this.historicalBackends];
533
433
  if (this.liveBackend)
534
434
  backends.push(this.liveBackend);
535
435
  return backends;
536
436
  }
537
- /**
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.
543
- */
437
+ // Skips backends whose init failed, because the crawler uses this instance
438
+ // directly, without lazy retry or breaker.
544
439
  getChainSyncBackend() {
545
440
  const candidates = [this.liveBackend, ...this.historicalBackends];
546
441
  for (const b of candidates) {
@@ -549,15 +444,88 @@ class CardanoClient {
549
444
  }
550
445
  return null;
551
446
  }
552
- /**
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.
560
- */
447
+ /** Like getChainSyncBackend() but retries a failed init. The crawler polls it while on pagination. */
448
+ async recoverChainSyncBackend() {
449
+ const candidates = [this.liveBackend, ...this.historicalBackends];
450
+ for (const b of candidates) {
451
+ if (!b || !(0, cardano_backend_1.isChainSyncBackend)(b))
452
+ continue;
453
+ if (await this.ensureBackendInitialized(b))
454
+ return b;
455
+ }
456
+ return null;
457
+ }
458
+ /** First usable backend that can dump the UTxO set at a point, for the UTxO set import. */
459
+ getLedgerStateBackend() {
460
+ const candidates = [this.liveBackend, ...this.historicalBackends];
461
+ for (const b of candidates) {
462
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isLedgerStateBackend)(b))
463
+ return b;
464
+ }
465
+ return null;
466
+ }
467
+ // Outputs among refs that are unspent at the tip, read from the node's ledger.
468
+ // Null when no backend can. The caller then reads the producing tx, which lacks reference-script bytes.
469
+ 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
+ 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;
483
+ }
484
+ /** True when an initialized backend implements `method` and does not declare it unsupported. */
485
+ hasBackendFor(method) {
486
+ const candidates = [this.liveBackend, ...this.historicalBackends];
487
+ return candidates.some((b) => !!b
488
+ && !this.uninitializedBackends.has(b)
489
+ && typeof b[method] === 'function'
490
+ && !b.unsupportedMethods?.has(method));
491
+ }
492
+ /** Backend that reads pool, DRep and pot state at a block. Preferred source of epoch snapshots. */
493
+ getEpochStateBackend() {
494
+ const candidates = [this.liveBackend, ...this.historicalBackends];
495
+ for (const b of candidates) {
496
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isEpochStateBackend)(b))
497
+ return b;
498
+ }
499
+ return null;
500
+ }
501
+ /** Backend that reads reward accounts at a block, for account snapshots. */
502
+ getRewardAccountStateBackend() {
503
+ const candidates = [this.liveBackend, ...this.historicalBackends];
504
+ for (const b of candidates) {
505
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isRewardAccountStateBackend)(b))
506
+ return b;
507
+ }
508
+ return null;
509
+ }
510
+ /** Without one, epoch snapshots stay off instead of making thousands of single requests. */
511
+ getEnumeratingBackend() {
512
+ const candidates = [...this.historicalBackends, this.liveBackend];
513
+ for (const b of candidates) {
514
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isEnumeratingBackend)(b))
515
+ return b;
516
+ }
517
+ return null;
518
+ }
519
+ /** Backend that lists the CIP-26 token registry (Koios). Null when none is configured. */
520
+ getTokenRegistryBackend() {
521
+ const candidates = [...this.historicalBackends, this.liveBackend];
522
+ for (const b of candidates) {
523
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isTokenRegistryBackend)(b))
524
+ return b;
525
+ }
526
+ return null;
527
+ }
528
+ /** Prefers Koios, because it batches 100 txs per call and Blockfrost needs about 3 calls per tx. */
561
529
  getPaginatingBackend() {
562
530
  const usable = this.historicalBackends.filter((b) => !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isPaginatingBackend)(b));
563
531
  const koios = usable.find((b) => b.name === 'koios');
@@ -570,21 +538,25 @@ class CardanoClient {
570
538
  }
571
539
  return null;
572
540
  }
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
- */
541
+ /** Protocol parameters with a 5-minute in-memory cache and coalesced refresh. */
578
542
  async getProtocolParameters() {
579
543
  const now = Date.now();
580
- if (this.protocolParamsCache && (now - this.protocolParamsCache.fetchedAt) < CardanoClient.PROTOCOL_PARAMS_TTL_MS) {
544
+ if (this.protocolParamsCache && (now - this.protocolParamsCache.fetchedAt) < const_1.PROTOCOL_PARAMS_TTL_MS) {
581
545
  logger.debug('Returning cached protocol parameters');
582
546
  return this.protocolParamsCache.data;
583
547
  }
584
- // Promise coalescing: deduplicate concurrent requests during cache miss
585
548
  if (!this.protocolParamsFetchPromise) {
586
549
  logger.debug('Fetching fresh protocol parameters');
587
- this.protocolParamsFetchPromise = this.route('getProtocolParameters', b => b.getProtocolParameters())
550
+ this.protocolParamsFetchPromise = this.route('getProtocolParameters', async (b) => {
551
+ const params = await b.getProtocolParameters();
552
+ if (b === this.liveBackend) {
553
+ this.lastLiveProtocolParams = params;
554
+ return params;
555
+ }
556
+ // A fallback answering for the epoch the node last reported: keep the node's values
557
+ const live = this.lastLiveProtocolParams;
558
+ return live && Number(live.epoch) === Number(params.epoch) ? live : params;
559
+ })
588
560
  .then(params => {
589
561
  this.protocolParamsCache = { data: params, fetchedAt: Date.now() };
590
562
  this.protocolParamsFetchPromise = null;
@@ -597,12 +569,9 @@ class CardanoClient {
597
569
  }
598
570
  return this.protocolParamsFetchPromise;
599
571
  }
600
- /**
601
- * Shutdown all backends (for cleanup in tests)
602
- */
572
+ /** Shut down all backends. */
603
573
  async shutdown() {
604
574
  logger.info('Shutting down CardanoClient backends...');
605
- // Shutdown live backend if it has a shutdown method
606
575
  if (this.liveBackend && 'shutdown' in this.liveBackend && typeof this.liveBackend.shutdown === 'function') {
607
576
  try {
608
577
  await this.liveBackend.shutdown();
@@ -612,7 +581,6 @@ class CardanoClient {
612
581
  logger.error(`Error shutting down live backend ${this.liveBackend.name}: ${err}`);
613
582
  }
614
583
  }
615
- // Shutdown historical backends
616
584
  for (const backend of this.historicalBackends) {
617
585
  if ('shutdown' in backend && typeof backend.shutdown === 'function') {
618
586
  try {
@@ -628,70 +596,62 @@ class CardanoClient {
628
596
  this.initPromise = null;
629
597
  logger.info('CardanoClient shutdown complete');
630
598
  }
631
- /**
632
- * Get latest block data with fallback between backends
633
- * @returns {Promise<BlockData>} latest block data
634
- */
635
599
  getLatestBlock() {
636
600
  return this.route('getLatestBlock', b => b.getLatestBlock());
637
601
  }
638
- /**
639
- * Get latest epoch data with fallback between backends
640
- * @returns {Promise<EpochData>} latest epoch data
641
- */
642
602
  getLatestEpoch() {
643
603
  return this.route('getLatestEpoch', b => b.getLatestEpoch());
644
604
  }
645
- /**
646
- * Get the current chain slot with fallback between backends.
647
- * @returns {Promise<number>} current chain slot
648
- */
649
605
  getCurrentSlot() {
650
606
  return this.route('getCurrentSlot', b => b.getCurrentSlot());
651
607
  }
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
- */
608
+ /** True iff the UTxO exists and is unspent. */
658
609
  isUtxoUnspent(txHash, outputIndex) {
659
610
  return this.route('isUtxoUnspent', b => b.isUtxoUnspent(txHash, outputIndex));
660
611
  }
661
- /**
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.
671
- */
672
- submitTransaction(signedTxCbor) {
673
- return this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
674
- }
675
- /**
676
- * Check if Ogmios backend is available for transaction evaluation
677
- * @returns {boolean} true if Ogmios is the live backend
678
- */
612
+ // After a lost response, the next backend may answer 409 "already submitted".
613
+ // Callers treat that as success.
614
+ async submitTransaction(signedTxCbor) {
615
+ try {
616
+ const hash = await this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
617
+ this.pendingSpends.record(signedTxCbor);
618
+ return hash;
619
+ }
620
+ catch (err) {
621
+ // already in the mempool or on chain: its inputs are gone all the same
622
+ if (err instanceof errors_1.TransactionAlreadySubmittedError)
623
+ this.pendingSpends.record(signedTxCbor);
624
+ throw err;
625
+ }
626
+ }
627
+ /** True when a configured backend can serve the method. */
628
+ supports(methodName) {
629
+ return [this.liveBackend, ...this.historicalBackends].some((b) => !!b && !b.unsupportedMethods?.has(methodName));
630
+ }
631
+ /** True when Ogmios is the live backend. */
679
632
  hasOgmiosBackend() {
680
633
  return this.liveBackend?.name === 'ogmios';
681
634
  }
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
- */
635
+ /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
636
+ evaluatingBackend() {
637
+ const candidates = [this.liveBackend, ...this.historicalBackends];
638
+ for (const b of candidates)
639
+ if (b && (0, cardano_backend_1.isEvaluatingBackend)(b))
640
+ return b;
641
+ return null;
642
+ }
643
+ /** True when some backend can evaluate script execution units. */
644
+ hasEvaluatingBackend() {
645
+ return this.evaluatingBackend() != null;
646
+ }
647
+ /** Evaluate script execution units of an unsigned transaction. */
687
648
  async evaluateTransaction(unsignedTxCbor) {
688
649
  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)');
650
+ const backend = this.evaluatingBackend();
651
+ if (!backend) {
652
+ throw new errors_1.ProviderUnavailableError('Transaction evaluation requires an evaluating backend (Ogmios or odatano)');
692
653
  }
693
- // timeout + breaker — a hanging Ogmios socket previously blocked Plutus builds indefinitely
694
- const backend = this.liveBackend;
654
+ // timeout + breaker, so a hanging socket cannot block Plutus builds
695
655
  return this.callWithResilience(backend, () => backend.evaluateTransaction(unsignedTxCbor));
696
656
  }
697
657
  }