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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -9,7 +9,15 @@ const axios_1 = __importDefault(require("axios"));
9
9
  const deep_json_1 = require("../../utils/deep-json");
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
+ const call_signal_1 = require("./call-signal");
12
13
  const logger = cds_1.default.log('OdatanoBackend');
14
+ // `scriptRef` is the script hash. An older remote fed by Koios sends the script CBOR there instead;
15
+ // that moves to `scriptRefCbor`, and the hash stays unknown.
16
+ function scriptRefAsHash(u) {
17
+ if (!u.scriptRef || u.scriptRef.length <= 56)
18
+ return u;
19
+ return { ...u, scriptRef: null, scriptRefCbor: u.scriptRefCbor ?? u.scriptRef };
20
+ }
13
21
  /** Public ODATANO API per network; mainnet has no default and needs `odatanoUrl`. */
14
22
  exports.ODATANO_API_URLS = {
15
23
  preview: 'https://api.preview.odatano.dev',
@@ -50,7 +58,7 @@ class OdatanoBackend {
50
58
  // --- CardanoBackend ------------------------------------------------------------------------
51
59
  getTransaction(txHash) { return this.call('GetTransaction', { hash: txHash }); }
52
60
  getAddress(address) { return this.call('GetAddress', { address }); }
53
- getAddressUtxos(address) { return this.call('GetAddressUtxos', { address }); }
61
+ async getAddressUtxos(address) { return (await this.call('GetAddressUtxos', { address })).map(scriptRefAsHash); }
54
62
  getAddressTransactions(address, limit) {
55
63
  return this.call('GetAddressTransactions', { address, limit });
56
64
  }
@@ -60,6 +68,7 @@ class OdatanoBackend {
60
68
  async getTransactionsBatch(txHashes) {
61
69
  const out = new Map();
62
70
  for (let i = 0; i < txHashes.length; i += ENUMERATION_BATCH) {
71
+ (0, call_signal_1.throwIfCallAborted)();
63
72
  const found = await this.call('GetTransactionsBatch', {
64
73
  hashes: JSON.stringify(txHashes.slice(i, i + ENUMERATION_BATCH)),
65
74
  });
@@ -68,12 +77,15 @@ class OdatanoBackend {
68
77
  }
69
78
  return out;
70
79
  }
71
- getCredentialUtxos(credHash) { return this.call('GetCredentialUtxos', { credential: credHash }); }
80
+ async getCredentialUtxos(credHash) {
81
+ return (await this.call('GetCredentialUtxos', { credential: credHash })).map(scriptRefAsHash);
82
+ }
72
83
  /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
73
84
  async getUnspentOutputs(refs) {
74
85
  const out = [];
75
86
  for (let i = 0; i < refs.length; i += ENUMERATION_BATCH) {
76
- out.push(...await this.call('GetUnspentOutputs', { refs: JSON.stringify(refs.slice(i, i + ENUMERATION_BATCH)) }));
87
+ (0, call_signal_1.throwIfCallAborted)();
88
+ out.push(...(await this.call('GetUnspentOutputs', { refs: JSON.stringify(refs.slice(i, i + ENUMERATION_BATCH)) })).map(scriptRefAsHash));
77
89
  }
78
90
  return out;
79
91
  }
@@ -89,7 +101,25 @@ class OdatanoBackend {
89
101
  }
90
102
  getPool(poolId) { return this.call('GetPool', { poolId }); }
91
103
  getDrep(drepId) { return this.call('GetDrep', { drepId }); }
92
- getAccount(stakeAddress) { return this.call('GetAccount', { stakeAddress }); }
104
+ async getAccount(stakeAddress) {
105
+ const account = await this.call('GetAccount', { stakeAddress });
106
+ // an older remote lists the addresses as objects
107
+ const addresses = (account.addresses ?? [])
108
+ .map(a => (typeof a === 'string' ? a : a?.address))
109
+ .filter((a) => typeof a === 'string' && a.length > 0);
110
+ return { ...account, addresses };
111
+ }
112
+ // The remote's own verdict. A remote without the operation answers 404, which says nothing about the account.
113
+ async isRewardAccountRegistered(stakeAddress) {
114
+ try {
115
+ return await this.call('IsRewardAccountRegistered', { stakeAddress });
116
+ }
117
+ catch (err) {
118
+ if (err instanceof errors_1.NotFoundError)
119
+ return null;
120
+ throw err;
121
+ }
122
+ }
93
123
  getAssetInfo(unit) { return this.call('GetAssetInfo', { unit }); }
94
124
  getAssetHistory(unit, limit = 100) { return this.call('GetAssetHistory', { unit, limit }); }
95
125
  getProtocolParameters() { return this.call('GetProtocolParameters'); }
@@ -103,7 +133,14 @@ class OdatanoBackend {
103
133
  getNextBlocks(afterHash, count, afterHeight) {
104
134
  return this.call('GetNextBlocks', { afterHash, count, afterHeight: afterHeight ?? null });
105
135
  }
106
- getBlockTransactions(blockHash) { return this.call('GetBlockTransactions', { blockHash }); }
136
+ // The count is checked here, not sent: a remote of an earlier version refuses a parameter it does not know.
137
+ async getBlockTransactions(blockHash, txCount) {
138
+ const txs = await this.call('GetBlockTransactions', { blockHash });
139
+ if (txCount !== undefined && txs.length !== txCount) {
140
+ throw new errors_1.ProviderUnavailableError(`Incomplete transaction list for block ${blockHash}: ${txs.length}/${txCount} transaction(s)`, this.name);
141
+ }
142
+ return txs;
143
+ }
107
144
  // --- EnumeratingBackend (epoch snapshots) -----------------------------------------------------
108
145
  getPoolIds() { return this.call('GetPoolIds'); }
109
146
  getPools(poolIds) { return this.batched('GetPools', poolIds); }
@@ -113,6 +150,7 @@ class OdatanoBackend {
113
150
  async batched(operation, ids) {
114
151
  const out = [];
115
152
  for (let i = 0; i < ids.length; i += ENUMERATION_BATCH) {
153
+ (0, call_signal_1.throwIfCallAborted)();
116
154
  out.push(...await this.call(operation, { ids: JSON.stringify(ids.slice(i, i + ENUMERATION_BATCH)) }));
117
155
  }
118
156
  return out;
@@ -121,7 +159,9 @@ class OdatanoBackend {
121
159
  // The remote error message stays verbatim, so `CHAIN_POINT_MISMATCH:` reaches the crawler.
122
160
  async call(operation, body = {}) {
123
161
  try {
124
- const res = await this.api.post(`/${operation}`, body);
162
+ // the request stops when the client gives up the call it belongs to
163
+ const signal = (0, call_signal_1.callSignal)();
164
+ const res = signal ? await this.api.post(`/${operation}`, body, { signal }) : await this.api.post(`/${operation}`, body);
125
165
  const left = Number(res.headers?.['x-access-units-left']);
126
166
  if (Number.isFinite(left))
127
167
  this.unitsLeft = left;
@@ -155,9 +195,11 @@ class OdatanoBackend {
155
195
  return new errors_1.TransactionAlreadySubmittedError(/[0-9a-f]{64}/.exec(message)?.[0] ?? '', message);
156
196
  }
157
197
  if (status === 400) {
158
- return code.includes(error_codes_1.ERROR_CODES.SCRIPT_VALIDATION_FAILURE)
159
- ? new errors_1.ScriptValidationError(message)
160
- : new errors_1.TransactionValidationError(message);
198
+ if (code.includes(error_codes_1.ERROR_CODES.SCRIPT_VALIDATION_FAILURE))
199
+ return new errors_1.ScriptValidationError(message);
200
+ // the remote names a node refusal with its JSON-RPC code; it is kept so the refusal is classified alike
201
+ const rpc = /node rejected the transaction \((3\d{3})\)/.exec(message);
202
+ return new errors_1.TransactionValidationError(message, rpc ? Object.assign(new Error(message), { code: Number(rpc[1]) }) : undefined);
161
203
  }
162
204
  if (status === 401 || status === 402 || status === 403) {
163
205
  logger.error(`${operation}: the remote ODATANO refused the key (${status}): ${message}`);
@@ -135,7 +135,6 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
135
135
  /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
136
136
  private mapOgmiosUtxo;
137
137
  private withLedgerStateAt;
138
- /** A connection of its own with the ledger state at `point` acquired. The caller closes it. */
139
138
  private openLedgerStateAt;
140
139
  rewardAccountsAt<T>(point: ChainPoint, read: (ask: AskRewardAccounts) => Promise<T>): Promise<T>;
141
140
  /** Whole UTxO set as of `point` (crawler snapshot import). */
@@ -149,7 +148,7 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
149
148
  submitTransaction(signedTxCbor: string): Promise<string>;
150
149
  /** Hash of a signed transaction, or null when the CBOR does not parse. */
151
150
  private txHashOrNull;
152
- /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. */
151
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. Null when the lookup failed. */
153
152
  private isKnownTransaction;
154
153
  /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
155
154
  private mempoolHas;
@@ -21,12 +21,20 @@ const backend_request_handler_1 = require("../../utils/backend-request-handler")
21
21
  const errors_1 = require("../../utils/errors");
22
22
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
23
23
  const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
24
+ const call_signal_1 = require("./call-signal");
24
25
  const epoch_slots_1 = require("../../utils/epoch-slots");
25
26
  const mappers_1 = require("../../utils/mappers");
26
27
  const const_1 = require("../../utils/const");
27
28
  const logger = cds_1.default.log('OgmiosBackend');
28
- /** Node rejection text for inputs that are no longer unspent. */
29
- const SPENT_INPUTS = /inputs are spent|unknown output reference|already been included/i;
29
+ /** Text of a mempool refusal whose inputs are spent. The mempool error carries no structured reason. */
30
+ const MEMPOOL_SPENT_INPUTS = /inputs are spent|badinputs|already been included/i;
31
+ /** True for a refusal over spent inputs, which a resubmit of a transaction the node already holds also gets. */
32
+ function refusedForSpentInputs(code, data) {
33
+ if (code === const_1.OGMIOS_UNKNOWN_OUTPUT_REFERENCES)
34
+ return true;
35
+ const error = data?.error;
36
+ return code === const_1.OGMIOS_UNEXPECTED_MEMPOOL_ERROR && MEMPOOL_SPENT_INPUTS.test(String(error ?? ''));
37
+ }
30
38
  /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
31
39
  function parseOgmiosRatio(ratio) {
32
40
  if (ratio === null || ratio === undefined)
@@ -103,14 +111,14 @@ function mapOgmiosEpochState(raw) {
103
111
  return {
104
112
  poolId,
105
113
  vrfKeyHash: p.vrfVerificationKeyHash || '',
106
- blocksMinted: 0,
114
+ blocksMinted: null,
107
115
  blocksEpoch: null,
108
116
  liveStake: live.toString(),
109
117
  liveSize: ratio(live, liveTotal),
110
118
  liveSaturation: ratio(live, saturationPoint),
111
119
  liveDelegators: null,
112
- activeStake: '0',
113
- activeSize: 0,
120
+ activeStake: null,
121
+ activeSize: null,
114
122
  pledge: ogmiosValueToLovelaceString(p.pledge),
115
123
  margin: parseOgmiosRatio(p.margin),
116
124
  fixedCost: ogmiosValueToLovelaceString(p.cost),
@@ -462,15 +470,16 @@ class OgmiosBackend {
462
470
  const max = const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
463
471
  const reserves = ogmiosValueToLovelaceString(pots.reserves);
464
472
  return {
473
+ // the ledger pots give treasury and reserves; circulation and stake are not in them
465
474
  supply: {
466
475
  max,
467
476
  total: (BigInt(max) - BigInt(reserves)).toString(),
468
- circulating: '0',
469
- locked: '0',
477
+ circulating: null,
478
+ locked: null,
470
479
  treasury: ogmiosValueToLovelaceString(pots.treasury),
471
480
  reserves,
472
481
  },
473
- stake: { live: '0', active: '0' },
482
+ stake: { live: null, active: null },
474
483
  };
475
484
  }, this.name);
476
485
  }
@@ -527,20 +536,34 @@ class OgmiosBackend {
527
536
  await session.close();
528
537
  }
529
538
  }
530
- /** A connection of its own with the ledger state at `point` acquired. The caller closes it. */
539
+ // A connection of its own with the ledger state at `point` acquired. The caller closes it. The
540
+ // call signal closes it too: a closed socket rejects every pending query, so a stuck caller ends.
531
541
  async openLedgerStateAt(point, label) {
542
+ const signal = (0, call_signal_1.callSignal)();
543
+ signal?.throwIfAborted();
532
544
  const url = new URL(this.ogmiosUrl);
533
545
  const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
534
546
  const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] ${label} context error: ${err.message}`), () => { }, { connection });
547
+ const onAbort = () => this.forceCloseContext(context);
535
548
  try {
549
+ if (signal?.aborted)
550
+ throw signal.reason;
551
+ signal?.addEventListener('abort', onAbort, { once: true });
536
552
  const client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
537
553
  // shutdown() closes THIS connection only; the backend's own socket is untouched
538
- return { client, close: async () => { try {
539
- await client.shutdown();
540
- }
541
- catch { /* best effort */ } } };
554
+ return {
555
+ client,
556
+ close: async () => {
557
+ signal?.removeEventListener('abort', onAbort);
558
+ try {
559
+ await client.shutdown();
560
+ }
561
+ catch { /* best effort */ }
562
+ },
563
+ };
542
564
  }
543
565
  catch (err) {
566
+ signal?.removeEventListener('abort', onAbort);
544
567
  this.forceCloseContext(context);
545
568
  throw err;
546
569
  }
@@ -617,18 +640,18 @@ class OgmiosBackend {
617
640
  return {
618
641
  poolId,
619
642
  vrfKeyHash: pool.vrfVerificationKeyHash || '',
620
- blocksMinted: 0,
621
- // not in the ledger state; null = unavailable, as on Koios
643
+ // block counts are not in the ledger state
644
+ blocksMinted: null,
622
645
  blocksEpoch: null,
623
646
  liveStake: pool.stake?.ada?.lovelace ? String(pool.stake.ada.lovelace) : '0',
624
647
  // no total live stake to divide by; null = unavailable
625
648
  liveSize: null,
626
649
  // not in the ledger state; null = unavailable
627
650
  liveDelegators: null,
628
- liveSaturation: 0,
629
- // Ogmios pool params have no active stake
630
- activeStake: '0',
631
- activeSize: 0,
651
+ // no saturation point and no active stake in the live pool view
652
+ liveSaturation: null,
653
+ activeStake: null,
654
+ activeSize: null,
632
655
  // pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
633
656
  pledge: ogmiosValueToLovelaceString(pool.pledge),
634
657
  margin: parseOgmiosRatio(pool.margin),
@@ -660,13 +683,14 @@ class OgmiosBackend {
660
683
  stakeaddress: stakeAddress,
661
684
  // a summary exists only for a registered credential
662
685
  active: true,
663
- activeEpoch: 0,
664
- // reward-account summaries carry no controlled amount and no withdrawal totals
665
- controlledAmount: '0',
666
- rewardsSum: ogmiosRewardBalance(account),
667
- withdrawalsSum: '0',
668
- reservesSum: '0',
669
- treasurySum: '0',
686
+ // a reward-account summary carries the current balance only: no registration epoch, no
687
+ // controlled amount, no totals of rewards, withdrawals or pot payments
688
+ activeEpoch: null,
689
+ controlledAmount: null,
690
+ rewardsSum: null,
691
+ withdrawalsSum: null,
692
+ reservesSum: null,
693
+ treasurySum: null,
670
694
  withdrawableAmount: ogmiosRewardBalance(account),
671
695
  poolId: account.stakePool?.id || null,
672
696
  drepId: ogmiosDrepToId(account.delegateRepresentative),
@@ -681,23 +705,27 @@ class OgmiosBackend {
681
705
  return await this.txSubmissionClient.submitTransaction(signedTxCbor);
682
706
  }
683
707
  catch (err) {
684
- // JSON-RPC 3000-3999: the node rejected the transaction. Known kinds keep their class
685
- // (already submitted = 409, script failure = 400); anything else becomes a 400 with its reason.
686
- const known = (0, errors_1.normalizeBackendError)(err, this.name);
687
- if (known.statusCode >= 400 && known.statusCode < 500)
688
- throw known;
708
+ // JSON-RPC 3000-3999: the node rejected the transaction, and the code decides, never its text.
709
+ // Only a node that holds the transaction makes it a 409. The code stays on the error as
710
+ // originalError.code for the callers to classify.
689
711
  const e = err;
690
- if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
691
- const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
692
- // spent inputs are also what a resubmit of a transaction the node already holds reports
693
- if (SPENT_INPUTS.test(`${String(e.message ?? '')}${detail}`)) {
712
+ const rpcCode = typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000 ? e.code : null;
713
+ if (rpcCode !== null) {
714
+ if (refusedForSpentInputs(rpcCode, e.data)) {
694
715
  const txHash = this.txHashOrNull(signedTxCbor);
695
- if (txHash && await this.isKnownTransaction(txHash))
716
+ const held = txHash ? await this.isKnownTransaction(txHash) : false;
717
+ if (held === true)
696
718
  throw new errors_1.TransactionAlreadySubmittedError(txHash, err);
719
+ // without the lookup the refusal may be about this very transaction: no verdict
720
+ if (held === null) {
721
+ throw new errors_1.ProviderUnavailableError(`node refused ${txHash} with spent inputs, and whether it holds the transaction could not be read`, this.name, undefined, err);
722
+ }
697
723
  }
698
- throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
724
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
725
+ throw new errors_1.TransactionValidationError(`node rejected the transaction (${rpcCode}): ${String(e.message ?? '')}${detail}`, err);
699
726
  }
700
- throw err;
727
+ // no node verdict, whatever the text says: a socket or session failure
728
+ throw new errors_1.ProviderUnavailableError(`submit to the node failed without a verdict: ${(0, errors_1.errorText)(err)}`, this.name, undefined, err);
701
729
  }
702
730
  }, this.name);
703
731
  }
@@ -710,7 +738,7 @@ class OgmiosBackend {
710
738
  return null;
711
739
  }
712
740
  }
713
- /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. */
741
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. Null when the lookup failed. */
714
742
  async isKnownTransaction(txHash) {
715
743
  try {
716
744
  if (await this.mempoolHas(txHash))
@@ -720,8 +748,8 @@ class OgmiosBackend {
720
748
  return onChain.length > 0;
721
749
  }
722
750
  catch (err) {
723
- logger.warn(`[OgmiosBackend] could not check whether ${txHash} is known: ${err instanceof Error ? err.message : String(err)}`);
724
- return false;
751
+ logger.warn(`[OgmiosBackend] could not check whether ${txHash} is known: ${(0, errors_1.errorText)(err)}`);
752
+ return null;
725
753
  }
726
754
  }
727
755
  /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
@@ -825,12 +853,13 @@ class OgmiosBackend {
825
853
  epoch: currentEpoch,
826
854
  start_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
827
855
  end_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, endSlot),
828
- first_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
856
+ // block statistics are not in the ledger state
857
+ first_block_time: null,
829
858
  last_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot),
830
- block_count: 0, // Not available from Ogmios state queries
831
- tx_count: 0, // Not available from Ogmios state queries
832
- output: '0',
833
- fees: '0',
859
+ block_count: null,
860
+ tx_count: null,
861
+ output: null,
862
+ fees: null,
834
863
  active_stake: null,
835
864
  };
836
865
  }, this.name);
@@ -1040,10 +1069,14 @@ class OgmiosBackend {
1040
1069
  await reportStreamError(err);
1041
1070
  }
1042
1071
  },
1043
- rollBackward: async ({ point }, nextBlock) => {
1072
+ rollBackward: async ({ point, tip }, nextBlock) => {
1044
1073
  try {
1045
1074
  const p = point;
1046
- await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id });
1075
+ const t = tip;
1076
+ const tipPoint = t && t !== 'origin' && t.slot != null && t.id
1077
+ ? { slot: t.slot, hash: t.id, height: t.height }
1078
+ : undefined;
1079
+ await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id }, tipPoint);
1047
1080
  nextBlock();
1048
1081
  }
1049
1082
  catch (err) {
@@ -1114,6 +1147,7 @@ class OgmiosBackend {
1114
1147
  size: block.size?.bytes ?? 0,
1115
1148
  txCount: txs.length,
1116
1149
  fees: totalFees.toString(),
1150
+ previousHash: block.ancestor === 'genesis' ? null : block.ancestor,
1117
1151
  };
1118
1152
  return { block: blockData, txs };
1119
1153
  }
@@ -29,6 +29,8 @@ export declare class CardanoClient {
29
29
  private circuitBreaker;
30
30
  /** Backends whose init failed. They stay in rotation and init is retried per request. */
31
31
  private uninitializedBackends;
32
+ /** Running init retry per backend, shared by concurrent callers. */
33
+ private initRetries;
32
34
  network: Network;
33
35
  max_age_ms: number;
34
36
  /** Transactions submitted through this client that the ledger view does not show yet. */
@@ -51,13 +53,12 @@ export declare class CardanoClient {
51
53
  private initBackendWithRetry;
52
54
  /** Backends whose init fails stay in rotation and are retried per request, bounded by the breaker. */
53
55
  private initBackends;
54
- /** Retries a failed startup init. False records a breaker failure. */
55
56
  private ensureBackendInitialized;
56
- /** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
57
57
  private withTimeout;
58
58
  /** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
59
59
  private getTimeoutForBackend;
60
60
  private callWithResilience;
61
+ private recordOutcome;
61
62
  /** Execute on backends in preference order (live vs historical) with automatic fallback. */
62
63
  private executeWithPriority;
63
64
  /** Route a call by METHOD_ROUTING (default: historical first). */
@@ -68,6 +69,9 @@ export declare class CardanoClient {
68
69
  getAddress(address: string): Promise<Address>;
69
70
  getAddressUtxos(address: string): Promise<UTxO[]>;
70
71
  getCredentialUtxos(credHash: string): Promise<UTxO[]>;
72
+ /** Backends that pass `can`, the one named `preferred` first. */
73
+ private capableBackends;
74
+ private firstAnswer;
71
75
  getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
72
76
  getNetworkInformation(): Promise<NetworkInformation>;
73
77
  getTransactionMetadata(tx_hash: string): Promise<MetadataLabelTx[]>;
@@ -79,7 +83,7 @@ export declare class CardanoClient {
79
83
  isRewardAccountRegistered(stakeAddress: string): Promise<boolean | null>;
80
84
  /** Asset info (supply, mint history, CIP-25/CIP-26 metadata); Blockfrost and Koios only. */
81
85
  getAssetInfo(unit: string): Promise<AssetInfo>;
82
- /** Latest mint and burn events. Prefers Koios, because Blockfrost leaves timestamps null. */
86
+ /** Latest mint and burn events. Koios first, because Blockfrost leaves timestamps null. */
83
87
  getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
84
88
  /** Falls back to a full getAddressTransactions when no backend lists hashes only. */
85
89
  getAddressTransactionHashes(address: string, limit: number): Promise<string[]>;
@@ -92,12 +96,18 @@ export declare class CardanoClient {
92
96
  recoverChainSyncBackend(): Promise<ChainSyncBackend | null>;
93
97
  /** First usable backend that can dump the UTxO set at a point, for the UTxO set import. */
94
98
  getLedgerStateBackend(): LedgerStateBackend | null;
99
+ readLedger(refs: Array<{
100
+ txHash: string;
101
+ outputIndex: number;
102
+ }>): Promise<{
103
+ live: boolean;
104
+ tip: number;
105
+ unspent: boolean[];
106
+ }>;
95
107
  getUnspentOutputs(refs: Array<{
96
108
  txHash: string;
97
109
  outputIndex: number;
98
110
  }>): Promise<UTxO[] | null>;
99
- /** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
100
- private outputLookupBackend;
101
111
  /** True when an initialized backend implements `method` and does not declare it unsupported. */
102
112
  hasBackendFor(method: string): boolean;
103
113
  /** Backend that reads pool, DRep and pot state at a block. Preferred source of epoch snapshots. */