@odatano/core 2.0.0-rc.23 → 2.0.0-rc.25

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 (80) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +27 -2
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +23 -1
  8. package/@cds-models/CardanoSignService/index.js +3 -0
  9. package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
  10. package/@cds-models/CardanoTransactionService/index.js +4 -0
  11. package/@cds-models/index.d.ts +18 -0
  12. package/@cds-models/index.js +3 -0
  13. package/@cds-models/odatano/cardano/index.d.ts +49 -2
  14. package/@cds-models/odatano/cardano/index.js +6 -0
  15. package/db/schema.cds +74 -3
  16. package/db/types.cds +27 -0
  17. package/package.json +182 -181
  18. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  19. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  20. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  21. package/srv/blockchain/backends/koios-backend.js +61 -14
  22. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  23. package/srv/blockchain/backends/odatano-backend.js +166 -0
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  25. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  26. package/srv/blockchain/cardano-client.d.ts +23 -9
  27. package/srv/blockchain/cardano-client.js +77 -25
  28. package/srv/blockchain/cardano-indexer.d.ts +61 -15
  29. package/srv/blockchain/cardano-indexer.js +248 -79
  30. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  31. package/srv/blockchain/cardano-tx-builder.js +59 -4
  32. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  33. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  34. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  35. package/srv/blockchain/crawler/crawler.js +12 -7
  36. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  37. package/srv/blockchain/crawler/sync-state.js +15 -2
  38. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  39. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  40. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  41. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  42. package/srv/blockchain/ledger-state.d.ts +16 -1
  43. package/srv/blockchain/ledger-state.js +38 -18
  44. package/srv/blockchain/pending-spends.d.ts +28 -0
  45. package/srv/blockchain/pending-spends.js +89 -0
  46. package/srv/blockchain/stored-chain.d.ts +33 -0
  47. package/srv/blockchain/stored-chain.js +234 -0
  48. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  49. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  50. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  51. package/srv/blockchain/transaction-rows.d.ts +1 -1
  52. package/srv/blockchain/transaction-rows.js +2 -1
  53. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  54. package/srv/cardano-backend-service.cds +52 -0
  55. package/srv/cardano-backend-service.d.ts +2 -0
  56. package/srv/cardano-backend-service.js +244 -0
  57. package/srv/cardano-indexer-service.cds +201 -176
  58. package/srv/cardano-indexer-service.js +104 -10
  59. package/srv/cardano-service.cds +5 -0
  60. package/srv/cardano-tx-service.cds +39 -0
  61. package/srv/cardano-tx-service.js +88 -14
  62. package/srv/server.js +20 -2
  63. package/srv/utils/agent-grants.js +8 -0
  64. package/srv/utils/const.d.ts +5 -0
  65. package/srv/utils/const.js +6 -1
  66. package/srv/utils/error-codes.d.ts +2 -0
  67. package/srv/utils/error-codes.js +2 -0
  68. package/srv/utils/errors.d.ts +7 -0
  69. package/srv/utils/errors.js +11 -1
  70. package/srv/utils/mappers.d.ts +24 -2
  71. package/srv/utils/mappers.js +49 -0
  72. package/srv/utils/pg-inline-json.d.ts +8 -0
  73. package/srv/utils/pg-inline-json.js +63 -0
  74. package/srv/utils/tx-build-helper.d.ts +2 -0
  75. package/srv/utils/tx-build-helper.js +12 -0
  76. package/srv/utils/tx-request-parsers.d.ts +46 -5
  77. package/srv/utils/tx-request-parsers.js +227 -16
  78. package/srv/utils/types.d.ts +59 -0
  79. package/srv/utils/validators.d.ts +5 -1
  80. package/srv/utils/validators.js +19 -9
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OdatanoBackend = exports.ODATANO_API_URLS = void 0;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const client_1 = require("@cardano-ogmios/client");
10
+ const errors_1 = require("../../utils/errors");
11
+ const logger = cds_1.default.log('OdatanoBackend');
12
+ /** Public ODATANO API per network (ACCESS gateway); mainnet has no default and needs `odatanoUrl`. */
13
+ exports.ODATANO_API_URLS = {
14
+ preview: 'https://api.preview.odatano.dev',
15
+ preprod: 'https://api.preprod.odatano.dev',
16
+ };
17
+ const SERVICE_PATH = '/odata/v4/cardano-backend';
18
+ /** Ids per GetPools / GetDreps call, below the service's list cap. */
19
+ const ENUMERATION_BATCH = 200;
20
+ /**
21
+ * Backend over another ODATANO instance (typically the hosted API behind the ACCESS gateway),
22
+ * speaking its `CardanoBackendService`. Answers arrive in the provider shape, so everything above
23
+ * this class treats it like Koios. The key goes as `Authorization: Bearer`.
24
+ */
25
+ class OdatanoBackend {
26
+ name = 'odatano';
27
+ api;
28
+ /** Units left on the key, from the gateway's `x-access-units-left` header; null when not reported. */
29
+ unitsLeft = null;
30
+ constructor(network, timeoutMs, url, apiKey) {
31
+ const baseURL = (url || exports.ODATANO_API_URLS[network] || '').replace(/\/+$/, '');
32
+ if (!baseURL) {
33
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl is required on ${network}`));
34
+ }
35
+ if (!/^https?:\/\//i.test(baseURL)) {
36
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl must be an http(s) URL, got "${baseURL}"`));
37
+ }
38
+ this.api = axios_1.default.create({
39
+ baseURL: baseURL + SERVICE_PATH,
40
+ timeout: timeoutMs,
41
+ headers: {
42
+ 'Content-Type': 'application/json',
43
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
44
+ },
45
+ });
46
+ }
47
+ /** Probe the remote instance with its cheapest call. */
48
+ async init() {
49
+ await this.call('GetCurrentSlot');
50
+ return true;
51
+ }
52
+ // --- CardanoBackend ------------------------------------------------------------------------
53
+ getTransaction(txHash) { return this.call('GetTransaction', { hash: txHash }); }
54
+ getAddress(address) { return this.call('GetAddress', { address }); }
55
+ getAddressUtxos(address) { return this.call('GetAddressUtxos', { address }); }
56
+ getAddressTransactions(address, limit) {
57
+ return this.call('GetAddressTransactions', { address, limit });
58
+ }
59
+ getAddressTransactionHashes(address, limit) {
60
+ return this.call('GetAddressTransactionHashes', { address, limit });
61
+ }
62
+ async getTransactionsBatch(txHashes) {
63
+ const out = new Map();
64
+ for (let i = 0; i < txHashes.length; i += ENUMERATION_BATCH) {
65
+ const found = await this.call('GetTransactionsBatch', {
66
+ hashes: JSON.stringify(txHashes.slice(i, i + ENUMERATION_BATCH)),
67
+ });
68
+ for (const [hash, tx] of Object.entries(found ?? {}))
69
+ out.set(hash, tx);
70
+ }
71
+ return out;
72
+ }
73
+ getCredentialUtxos(credHash) { return this.call('GetCredentialUtxos', { credential: credHash }); }
74
+ /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
75
+ async getUnspentOutputs(refs) {
76
+ const out = [];
77
+ for (let i = 0; i < refs.length; i += ENUMERATION_BATCH) {
78
+ out.push(...await this.call('GetUnspentOutputs', { refs: JSON.stringify(refs.slice(i, i + ENUMERATION_BATCH)) }));
79
+ }
80
+ return out;
81
+ }
82
+ getNetworkInformation() { return this.call('GetNetworkInformation'); }
83
+ getTransactionMetadata(txHash) { return this.call('GetTransactionMetadata', { hash: txHash }); }
84
+ getBlock(blockHash) { return this.call('GetBlock', { hash: blockHash }); }
85
+ getEpoch(epochNumber) { return this.call('GetEpoch', { epoch: epochNumber }); }
86
+ getLatestEpoch() { return this.call('GetLatestEpoch'); }
87
+ getLatestBlock() { return this.call('GetLatestBlock'); }
88
+ getCurrentSlot() { return this.call('GetCurrentSlot'); }
89
+ isUtxoUnspent(txHash, outputIndex) {
90
+ return this.call('IsUtxoUnspent', { txHash, outputIndex });
91
+ }
92
+ getPool(poolId) { return this.call('GetPool', { poolId }); }
93
+ getDrep(drepId) { return this.call('GetDrep', { drepId }); }
94
+ getAccount(stakeAddress) { return this.call('GetAccount', { stakeAddress }); }
95
+ getAssetInfo(unit) { return this.call('GetAssetInfo', { unit }); }
96
+ getAssetHistory(unit, limit = 100) { return this.call('GetAssetHistory', { unit, limit }); }
97
+ getProtocolParameters() { return this.call('GetProtocolParameters'); }
98
+ submitTransaction(signedTxCbor) { return this.call('SubmitTransaction', { cbor: signedTxCbor }); }
99
+ // --- EvaluatingBackend -----------------------------------------------------------------------
100
+ evaluateTransaction(unsignedTxCbor) {
101
+ return this.call('EvaluateTransaction', { cbor: unsignedTxCbor });
102
+ }
103
+ // --- PaginatingBackend (crawler source) ------------------------------------------------------
104
+ getBlockByHeight(height) { return this.call('GetBlockByHeight', { height }); }
105
+ getNextBlocks(afterHash, count, afterHeight) {
106
+ return this.call('GetNextBlocks', { afterHash, count, afterHeight: afterHeight ?? null });
107
+ }
108
+ getBlockTransactions(blockHash) { return this.call('GetBlockTransactions', { blockHash }); }
109
+ // --- EnumeratingBackend (epoch snapshots) -----------------------------------------------------
110
+ getPoolIds() { return this.call('GetPoolIds'); }
111
+ getPools(poolIds) { return this.batched('GetPools', poolIds); }
112
+ getDrepIds() { return this.call('GetDrepIds'); }
113
+ getDreps(drepIds) { return this.batched('GetDreps', drepIds); }
114
+ async shutdown() { }
115
+ async batched(operation, ids) {
116
+ const out = [];
117
+ for (let i = 0; i < ids.length; i += ENUMERATION_BATCH) {
118
+ out.push(...await this.call(operation, { ids: JSON.stringify(ids.slice(i, i + ENUMERATION_BATCH)) }));
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * POST one operation, parse the JSON string it answers (safeJSON keeps big integers) and map
124
+ * HTTP failures to the backend error classes. The remote message is kept verbatim, so markers
125
+ * such as `CHAIN_POINT_MISMATCH:` reach the crawler unchanged.
126
+ */
127
+ async call(operation, body = {}) {
128
+ try {
129
+ const res = await this.api.post(`/${operation}`, body);
130
+ const left = Number(res.headers?.['x-access-units-left']);
131
+ if (Number.isFinite(left))
132
+ this.unitsLeft = left;
133
+ const value = res.data?.value;
134
+ return (typeof value === 'string' ? client_1.safeJSON.parse(value) : value);
135
+ }
136
+ catch (err) {
137
+ throw this.mapError(operation, err);
138
+ }
139
+ }
140
+ mapError(operation, err) {
141
+ const ax = err;
142
+ if (!ax?.isAxiosError)
143
+ return err instanceof Error ? err : new Error(String(err));
144
+ const status = ax.response?.status;
145
+ const message = ax.response?.data?.error?.message ?? ax.message;
146
+ // the remote prefixes `[CODE] Operation: `; the crawler recognises the reorg marker at the start
147
+ const marker = message.indexOf('CHAIN_POINT_MISMATCH:');
148
+ if (marker >= 0)
149
+ return new errors_1.ProviderUnavailableError(message.slice(marker), this.name);
150
+ // NotFoundError appends " not found" itself; the remote message already ends with it
151
+ if (status === 404)
152
+ return new errors_1.NotFoundError(message.replace(/ not found$/, ''), this.name);
153
+ if (status === 429) {
154
+ const retryAfter = Number(ax.response?.headers?.['retry-after']);
155
+ return new errors_1.RateLimitError(message, this.name, Number.isFinite(retryAfter) ? retryAfter : undefined);
156
+ }
157
+ if (status === 400)
158
+ return new errors_1.TransactionValidationError(message);
159
+ if (status === 401 || status === 402 || status === 403) {
160
+ logger.error(`${operation}: the remote ODATANO refused the key (${status}): ${message}`);
161
+ }
162
+ return new errors_1.ProviderUnavailableError(message, this.name);
163
+ }
164
+ }
165
+ exports.OdatanoBackend = OdatanoBackend;
166
+ //# sourceMappingURL=odatano-backend.js.map
@@ -24,6 +24,8 @@ interface OgmiosStakePool {
24
24
  }
25
25
  /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
26
26
  export declare function ogmiosScriptHash(script: unknown): string | null;
27
+ /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
28
+ export declare function ogmiosPlutusScriptCbor(script: unknown): string | null;
27
29
  /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
28
30
  export declare function issuerKeyToPoolId(verificationKeyHex: string): string;
29
31
  /**
@@ -108,6 +110,10 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
108
110
  private stateQueryClient;
109
111
  private txSubmissionClient;
110
112
  private context;
113
+ /** Second connection for address queries (see scanQueryClient). */
114
+ private scanClient;
115
+ private scanContext;
116
+ private scanConnecting;
111
117
  private isShutdown;
112
118
  private reconnectPromise;
113
119
  private network;
@@ -136,6 +142,12 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
136
142
  private forceCloseContext;
137
143
  /** Open the interaction context and the query/submission clients. */
138
144
  init(): Promise<boolean>;
145
+ /**
146
+ * Query client for address queries. The node answers them by scanning its whole UTxO set (seconds
147
+ * each), and Ogmios serves the queries of one connection in order; on their own connection they no
148
+ * longer hold up tip, epoch and protocol parameters. Opened on first use, reopened after a close.
149
+ */
150
+ private scanQueryClient;
139
151
  /**
140
152
  * Reconnect when the WebSocket died since the last init. No-op when never initialized
141
153
  * (test-injected clients); concurrent callers share one reconnect attempt.
@@ -260,8 +272,6 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
260
272
  * @param outputIndex non-negative integer
261
273
  */
262
274
  isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
263
- /** Unspent outputs of several addresses in the live ledger (one query per 100 addresses). */
264
- getUtxosByAddresses(addresses: string[]): Promise<UTxO[]>;
265
275
  /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
266
276
  getUnspentOutputs(refs: Array<{
267
277
  txHash: string;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OgmiosBackend = void 0;
7
7
  exports.ogmiosScriptHash = ogmiosScriptHash;
8
+ exports.ogmiosPlutusScriptCbor = ogmiosPlutusScriptCbor;
8
9
  exports.issuerKeyToPoolId = issuerKeyToPoolId;
9
10
  exports.mapOgmiosEpochState = mapOgmiosEpochState;
10
11
  exports.decodeDrepId = decodeDrepId;
@@ -46,6 +47,11 @@ function ogmiosScriptHash(script) {
46
47
  const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
47
48
  return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
48
49
  }
50
+ /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
51
+ function ogmiosPlutusScriptCbor(script) {
52
+ const s = script;
53
+ return s?.language?.startsWith('plutus:') && typeof s.cbor === 'string' && s.cbor.length > 0 ? s.cbor : null;
54
+ }
49
55
  /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
50
56
  function issuerKeyToPoolId(verificationKeyHex) {
51
57
  const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
@@ -169,6 +175,28 @@ function resolveOgmiosTip(tip) {
169
175
  function resolveOgmiosHeight(height) {
170
176
  return height === 'origin' ? 0 : height;
171
177
  }
178
+ /**
179
+ * Redeemers of a chain-sync tx. A spend index points into the body inputs sorted by
180
+ * (txHash, index), a mint index into the sorted policy ids; both are resolved here.
181
+ */
182
+ function mapOgmiosRedeemers(tx) {
183
+ const sortedInputs = [...(tx.inputs ?? [])].sort((a, b) => (0, mappers_1.compareOutRef)({ txHash: a.transaction.id, outputIndex: a.index }, { txHash: b.transaction.id, outputIndex: b.index }));
184
+ const sortedPolicies = Object.keys(tx.mint ?? {}).sort();
185
+ return (tx.redeemers ?? []).map((r) => {
186
+ const { purpose, index } = r.validator;
187
+ const spent = purpose === 'spend' ? sortedInputs[index] : undefined;
188
+ return {
189
+ purpose,
190
+ index,
191
+ data: r.redeemer,
192
+ mem: r.executionUnits.memory.toString(),
193
+ steps: r.executionUnits.cpu.toString(),
194
+ txHash: spent?.transaction.id ?? null,
195
+ outputIndex: spent?.index ?? null,
196
+ policyId: purpose === 'mint' ? (sortedPolicies[index] ?? null) : null,
197
+ };
198
+ });
199
+ }
172
200
  /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
173
201
  class OgmiosBackend {
174
202
  name = 'ogmios';
@@ -190,6 +218,10 @@ class OgmiosBackend {
190
218
  stateQueryClient = null;
191
219
  txSubmissionClient = null;
192
220
  context = null;
221
+ /** Second connection for address queries (see scanQueryClient). */
222
+ scanClient = null;
223
+ scanContext = null;
224
+ scanConnecting = null;
193
225
  isShutdown = false;
194
226
  reconnectPromise = null;
195
227
  network;
@@ -302,6 +334,38 @@ class OgmiosBackend {
302
334
  this.context = context;
303
335
  return true;
304
336
  }
337
+ /**
338
+ * Query client for address queries. The node answers them by scanning its whole UTxO set (seconds
339
+ * each), and Ogmios serves the queries of one connection in order; on their own connection they no
340
+ * longer hold up tip, epoch and protocol parameters. Opened on first use, reopened after a close.
341
+ */
342
+ async scanQueryClient() {
343
+ this.ensureNotShutdown();
344
+ // never initialized (test-injected clients): the shared client
345
+ if (!this.context)
346
+ return this.stateQueryClient;
347
+ const socket = this.scanContext?.socket;
348
+ if (this.scanClient && socket && socket.readyState === (socket.OPEN ?? 1))
349
+ return this.scanClient;
350
+ if (!this.scanConnecting) {
351
+ this.scanConnecting = (async () => {
352
+ const url = new URL(this.ogmiosUrl);
353
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
354
+ const context = await this.withInitTimeout((0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] address-query context error: ${err.message}`), () => { this.scanClient = null; }, { connection }), 'scan/createInteractionContext');
355
+ try {
356
+ const client = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'scan/ledgerStateQueryClient');
357
+ this.scanContext = context;
358
+ this.scanClient = client;
359
+ return client;
360
+ }
361
+ catch (err) {
362
+ this.forceCloseContext(context);
363
+ throw err;
364
+ }
365
+ })().finally(() => { this.scanConnecting = null; });
366
+ }
367
+ return this.scanConnecting;
368
+ }
305
369
  /**
306
370
  * Reconnect when the WebSocket died since the last init. No-op when never initialized
307
371
  * (test-injected clients); concurrent callers share one reconnect attempt.
@@ -468,7 +532,7 @@ class OgmiosBackend {
468
532
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
469
533
  await this.ensureConnected();
470
534
  const decoded = (0, mappers_1.decodeShelleyAddress)(address);
471
- const raw = await this.stateQueryClient.utxo({ addresses: [address] });
535
+ const raw = await (await this.scanQueryClient()).utxo({ addresses: [address] });
472
536
  const utxos = raw.map((u) => this.mapOgmiosUtxo(u, address));
473
537
  return {
474
538
  address,
@@ -487,7 +551,7 @@ class OgmiosBackend {
487
551
  async getAddressUtxos(address) {
488
552
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
489
553
  await this.ensureConnected();
490
- const utxos = await this.stateQueryClient.utxo({ addresses: [address] });
554
+ const utxos = await (await this.scanQueryClient()).utxo({ addresses: [address] });
491
555
  return utxos.map((u) => this.mapOgmiosUtxo(u, address));
492
556
  }, this.name);
493
557
  }
@@ -503,6 +567,7 @@ class OgmiosBackend {
503
567
  // Ogmios delivers the inline datum as CBOR hex in `datum`
504
568
  inlineDatum: typeof u.datum === 'string' ? u.datum : null,
505
569
  scriptRef: ogmiosScriptHash(u.script) ?? undefined,
570
+ scriptRefCbor: ogmiosPlutusScriptCbor(u.script),
506
571
  };
507
572
  }
508
573
  /**
@@ -649,8 +714,22 @@ class OgmiosBackend {
649
714
  async submitTransaction(signedTxCbor) {
650
715
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
651
716
  await this.ensureConnected();
652
- const txHash = await this.txSubmissionClient.submitTransaction(signedTxCbor);
653
- return txHash;
717
+ try {
718
+ return await this.txSubmissionClient.submitTransaction(signedTxCbor);
719
+ }
720
+ catch (err) {
721
+ // JSON-RPC 3000-3999: the node rejected the transaction. Known kinds keep their class
722
+ // (already submitted = 409, script failure = 400); anything else becomes a 400 with its reason.
723
+ const known = (0, errors_1.normalizeBackendError)(err, this.name);
724
+ if (known.statusCode >= 400 && known.statusCode < 500)
725
+ throw known;
726
+ const e = err;
727
+ if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
728
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
729
+ throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
730
+ }
731
+ throw err;
732
+ }
654
733
  }, this.name);
655
734
  }
656
735
  /**
@@ -804,21 +883,6 @@ class OgmiosBackend {
804
883
  return Array.isArray(result) && result.length > 0;
805
884
  }, this.name);
806
885
  }
807
- /** Unspent outputs of several addresses in the live ledger (one query per 100 addresses). */
808
- async getUtxosByAddresses(addresses) {
809
- if (addresses.length === 0)
810
- return [];
811
- return (0, backend_request_handler_1.handleBackendRequest)(async () => {
812
- await this.ensureConnected();
813
- const out = [];
814
- for (let i = 0; i < addresses.length; i += 100) {
815
- const utxos = await this.stateQueryClient.utxo({ addresses: addresses.slice(i, i + 100) });
816
- for (const u of utxos)
817
- out.push(this.mapOgmiosUtxo(u));
818
- }
819
- return out;
820
- }, this.name);
821
- }
822
886
  /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
823
887
  async getUnspentOutputs(refs) {
824
888
  if (refs.length === 0)
@@ -850,9 +914,13 @@ class OgmiosBackend {
850
914
  });
851
915
  }
852
916
  }
917
+ if (this.scanContext)
918
+ this.forceCloseContext(this.scanContext);
853
919
  this.stateQueryClient = null;
854
920
  this.txSubmissionClient = null;
855
921
  this.context = null;
922
+ this.scanClient = null;
923
+ this.scanContext = null;
856
924
  }
857
925
  isConnected() {
858
926
  if (this.isShutdown || !this.context?.socket) {
@@ -1106,7 +1174,8 @@ class OgmiosBackend {
1106
1174
  // so the indexer derives the rest from the resolved collateral inputs later.
1107
1175
  const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
1108
1176
  const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
1109
- return {
1177
+ // the same ledger view the pagination sources produce (ordering; the partition is already applied)
1178
+ return (0, mappers_1.ledgerView)({
1110
1179
  hash: tx.id,
1111
1180
  blockHash: block.id,
1112
1181
  blockHeight: block.height,
@@ -1133,7 +1202,8 @@ class OgmiosBackend {
1133
1202
  stakeAddress,
1134
1203
  amount: (value?.ada?.lovelace ?? 0).toString(),
1135
1204
  })),
1136
- };
1205
+ redeemers: mapOgmiosRedeemers(tx),
1206
+ });
1137
1207
  }
1138
1208
  /**
1139
1209
  * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
@@ -1,8 +1,9 @@
1
1
  import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend } from './backends/cardano-backend';
2
+ import { PendingSpends } from './pending-spends';
2
3
  import { type CircuitBreakerConfig } from './circuit-breaker';
3
4
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
4
5
  export type Network = 'mainnet' | 'preview' | 'preprod';
5
- export type BackendName = 'blockfrost' | 'koios' | 'ogmios';
6
+ export type BackendName = 'blockfrost' | 'koios' | 'ogmios' | 'odatano';
6
7
  export type TransactionBuilderName = 'buildooor';
7
8
  export type CardanoClientConfig = {
8
9
  network: Network;
@@ -11,6 +12,10 @@ export type CardanoClientConfig = {
11
12
  blockfrostCustomBackend?: string;
12
13
  koiosApiKey: string;
13
14
  ogmiosUrl: string;
15
+ /** Remote ODATANO for the `odatano` backend; defaults to the public API of the network. */
16
+ odatanoUrl?: string;
17
+ /** Key for the remote ODATANO (a gateway `oda_…` key or an agent grant token). */
18
+ odatanoApiKey?: string;
14
19
  transactionBuilders: TransactionBuilderName[];
15
20
  primaryTimeoutMs: number;
16
21
  fallbackTimeoutMs: number;
@@ -32,8 +37,12 @@ export declare class CardanoClient {
32
37
  private uninitializedBackends;
33
38
  network: Network;
34
39
  max_age_ms: number;
40
+ /** Transactions submitted through this client that the ledger view does not show yet. */
41
+ readonly pendingSpends: PendingSpends;
35
42
  private protocolParamsCache?;
36
43
  private protocolParamsFetchPromise;
44
+ /** Last protocol parameters the live backend (node) answered. */
45
+ private lastLiveProtocolParams?;
37
46
  private static readonly PROTOCOL_PARAMS_TTL_MS;
38
47
  private txCoalescer;
39
48
  private addrCoalescer;
@@ -70,7 +79,7 @@ export declare class CardanoClient {
70
79
  private ensureBackendInitialized;
71
80
  /** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
72
81
  private withTimeout;
73
- /** Per-backend timeout: Koios gets the fallback timeout, everything else the primary one. */
82
+ /** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
74
83
  private getTimeoutForBackend;
75
84
  /**
76
85
  * Single-backend call with the executeWithPriority resilience contract (breaker gate, timeout,
@@ -88,7 +97,7 @@ export declare class CardanoClient {
88
97
  getAddressUtxos(address: string): Promise<UTxO[]>;
89
98
  /**
90
99
  * UTxOs by 28-byte payment credential (56-char hex), across all bech32 forms sharing it.
91
- * Koios-only: no other backend has a credential-keyed endpoint, so this throws without Koios.
100
+ * Needs a credential-keyed backend (Koios, or another ODATANO); Blockfrost has none.
92
101
  */
93
102
  getCredentialUtxos(credHash: string): Promise<UTxO[]>;
94
103
  getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
@@ -128,15 +137,16 @@ export declare class CardanoClient {
128
137
  /** The first usable backend that can dump the UTxO set at a point (Ogmios) — crawler.utxoSet import. */
129
138
  getLedgerStateBackend(): LedgerStateBackend | null;
130
139
  /**
131
- * Outputs among `refs` that are unspent at the tip, read from the node's ledger; null when no
132
- * ledger-state backend is usable (the caller then resolves via the producing transaction).
140
+ * Outputs among `refs` that are unspent at the tip, read from the node's ledger (Ogmios, or a remote
141
+ * ODATANO that asks its node); null when no backend can (the caller then resolves via the producing
142
+ * transaction, which carries no reference-script bytes).
133
143
  */
134
144
  getUnspentOutputs(refs: Array<{
135
145
  txHash: string;
136
146
  outputIndex: number;
137
147
  }>): Promise<UTxO[] | null>;
138
- /** Unspent outputs of several addresses from the node's ledger; null when no ledger-state backend can do it. */
139
- getUtxosByAddresses(addresses: string[]): Promise<UTxO[] | null>;
148
+ /** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
149
+ private outputLookupBackend;
140
150
  /** True when an initialized backend implements `method` and does not declare it unsupported. */
141
151
  hasBackendFor(method: string): boolean;
142
152
  /** A backend that reads pool/DRep/pot state at a block (Ogmios) — preferred source of epoch snapshots. */
@@ -165,9 +175,13 @@ export declare class CardanoClient {
165
175
  * the next backend may answer 409 "already submitted" — callers treat that as success.
166
176
  */
167
177
  submitTransaction(signedTxCbor: string): Promise<string>;
168
- /** True when Ogmios is the live backend (script evaluation available). */
178
+ /** True when Ogmios is the live backend. */
169
179
  hasOgmiosBackend(): boolean;
170
- /** Evaluate script execution units of an unsigned transaction (Ogmios only). */
180
+ /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
181
+ private evaluatingBackend;
182
+ /** True when some backend can evaluate script execution units. */
183
+ hasEvaluatingBackend(): boolean;
184
+ /** Evaluate script execution units of an unsigned transaction. */
171
185
  evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
172
186
  }
173
187
  //# sourceMappingURL=cardano-client.d.ts.map