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

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