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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -0,0 +1,54 @@
1
+ import { CardanoBackend, EvaluatingBackend, PaginatingBackend, EnumeratingBackend } from './cardano-backend';
2
+ import type { Transaction, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, BlockData, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
3
+ import { Network } from '../cardano-client';
4
+ /** Public ODATANO API per network; mainnet has no default and needs `odatanoUrl`. */
5
+ export declare const ODATANO_API_URLS: Partial<Record<Network, string>>;
6
+ export declare class OdatanoBackend implements CardanoBackend, EvaluatingBackend, PaginatingBackend, EnumeratingBackend {
7
+ readonly name = "odatano";
8
+ private readonly api;
9
+ /** Units left on the key, from the gateway's `x-access-units-left` header; null when not reported. */
10
+ unitsLeft: number | null;
11
+ constructor(network: Network, timeoutMs: number, url: string | undefined, apiKey: string | undefined);
12
+ /** Probe the remote instance with its cheapest call. */
13
+ init(): Promise<boolean>;
14
+ getTransaction(txHash: string): Promise<Transaction>;
15
+ getAddress(address: string): Promise<Address>;
16
+ getAddressUtxos(address: string): Promise<UTxO[]>;
17
+ getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
18
+ getAddressTransactionHashes(address: string, limit: number): Promise<string[]>;
19
+ getTransactionsBatch(txHashes: string[]): Promise<Map<string, Transaction>>;
20
+ getCredentialUtxos(credHash: string): Promise<UTxO[]>;
21
+ /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
22
+ getUnspentOutputs(refs: Array<{
23
+ txHash: string;
24
+ outputIndex: number;
25
+ }>): Promise<UTxO[]>;
26
+ getNetworkInformation(): Promise<NetworkInformation>;
27
+ getTransactionMetadata(txHash: string): Promise<MetadataLabelTx[]>;
28
+ getBlock(blockHash: string): Promise<BlockData>;
29
+ getEpoch(epochNumber: number): Promise<EpochData>;
30
+ getLatestEpoch(): Promise<EpochData>;
31
+ getLatestBlock(): Promise<BlockData>;
32
+ getCurrentSlot(): Promise<number>;
33
+ isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
34
+ getPool(poolId: string): Promise<PoolData>;
35
+ getDrep(drepId: string): Promise<DrepData>;
36
+ getAccount(stakeAddress: string): Promise<AccountData>;
37
+ getAssetInfo(unit: string): Promise<AssetInfo>;
38
+ getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
39
+ getProtocolParameters(): Promise<LedgerProtocolParameters>;
40
+ submitTransaction(signedTxCbor: string): Promise<string>;
41
+ evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
42
+ getBlockByHeight(height: number): Promise<BlockData>;
43
+ getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
44
+ getBlockTransactions(blockHash: string): Promise<Transaction[]>;
45
+ getPoolIds(): Promise<string[]>;
46
+ getPools(poolIds: string[]): Promise<PoolData[]>;
47
+ getDrepIds(): Promise<string[]>;
48
+ getDreps(drepIds: string[]): Promise<DrepData[]>;
49
+ shutdown(): Promise<void>;
50
+ private batched;
51
+ private call;
52
+ private mapError;
53
+ }
54
+ //# sourceMappingURL=odatano-backend.d.ts.map
@@ -0,0 +1,169 @@
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 deep_json_1 = require("../../utils/deep-json");
10
+ const errors_1 = require("../../utils/errors");
11
+ const error_codes_1 = require("../../utils/error-codes");
12
+ const logger = cds_1.default.log('OdatanoBackend');
13
+ /** Public ODATANO API per network; mainnet has no default and needs `odatanoUrl`. */
14
+ exports.ODATANO_API_URLS = {
15
+ preview: 'https://api.preview.odatano.dev',
16
+ preprod: 'https://api.preprod.odatano.dev',
17
+ };
18
+ const SERVICE_PATH = '/odata/v4/cardano-backend';
19
+ /** Ids per GetPools / GetDreps call, below the service's list cap. */
20
+ const ENUMERATION_BATCH = 200;
21
+ // Backend over another ODATANO instance via its `CardanoBackendService`.
22
+ // Answers arrive in the provider shape, so callers treat it like Koios.
23
+ class OdatanoBackend {
24
+ name = 'odatano';
25
+ api;
26
+ /** Units left on the key, from the gateway's `x-access-units-left` header; null when not reported. */
27
+ unitsLeft = null;
28
+ constructor(network, timeoutMs, url, apiKey) {
29
+ const baseURL = (url || exports.ODATANO_API_URLS[network] || '').replace(/\/+$/, '');
30
+ if (!baseURL) {
31
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl is required on ${network}`));
32
+ }
33
+ if (!/^https?:\/\//i.test(baseURL)) {
34
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl must be an http(s) URL, got "${baseURL}"`));
35
+ }
36
+ this.api = axios_1.default.create({
37
+ baseURL: baseURL + SERVICE_PATH,
38
+ timeout: timeoutMs,
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
42
+ },
43
+ });
44
+ }
45
+ /** Probe the remote instance with its cheapest call. */
46
+ async init() {
47
+ await this.call('GetCurrentSlot');
48
+ return true;
49
+ }
50
+ // --- CardanoBackend ------------------------------------------------------------------------
51
+ getTransaction(txHash) { return this.call('GetTransaction', { hash: txHash }); }
52
+ getAddress(address) { return this.call('GetAddress', { address }); }
53
+ getAddressUtxos(address) { return this.call('GetAddressUtxos', { address }); }
54
+ getAddressTransactions(address, limit) {
55
+ return this.call('GetAddressTransactions', { address, limit });
56
+ }
57
+ getAddressTransactionHashes(address, limit) {
58
+ return this.call('GetAddressTransactionHashes', { address, limit });
59
+ }
60
+ async getTransactionsBatch(txHashes) {
61
+ const out = new Map();
62
+ for (let i = 0; i < txHashes.length; i += ENUMERATION_BATCH) {
63
+ const found = await this.call('GetTransactionsBatch', {
64
+ hashes: JSON.stringify(txHashes.slice(i, i + ENUMERATION_BATCH)),
65
+ });
66
+ for (const [hash, tx] of Object.entries(found ?? {}))
67
+ out.set(hash, tx);
68
+ }
69
+ return out;
70
+ }
71
+ getCredentialUtxos(credHash) { return this.call('GetCredentialUtxos', { credential: credHash }); }
72
+ /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
73
+ async getUnspentOutputs(refs) {
74
+ const out = [];
75
+ 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)) }));
77
+ }
78
+ return out;
79
+ }
80
+ getNetworkInformation() { return this.call('GetNetworkInformation'); }
81
+ getTransactionMetadata(txHash) { return this.call('GetTransactionMetadata', { hash: txHash }); }
82
+ getBlock(blockHash) { return this.call('GetBlock', { hash: blockHash }); }
83
+ getEpoch(epochNumber) { return this.call('GetEpoch', { epoch: epochNumber }); }
84
+ getLatestEpoch() { return this.call('GetLatestEpoch'); }
85
+ getLatestBlock() { return this.call('GetLatestBlock'); }
86
+ getCurrentSlot() { return this.call('GetCurrentSlot'); }
87
+ isUtxoUnspent(txHash, outputIndex) {
88
+ return this.call('IsUtxoUnspent', { txHash, outputIndex });
89
+ }
90
+ getPool(poolId) { return this.call('GetPool', { poolId }); }
91
+ getDrep(drepId) { return this.call('GetDrep', { drepId }); }
92
+ getAccount(stakeAddress) { return this.call('GetAccount', { stakeAddress }); }
93
+ getAssetInfo(unit) { return this.call('GetAssetInfo', { unit }); }
94
+ getAssetHistory(unit, limit = 100) { return this.call('GetAssetHistory', { unit, limit }); }
95
+ getProtocolParameters() { return this.call('GetProtocolParameters'); }
96
+ submitTransaction(signedTxCbor) { return this.call('SubmitTransaction', { cbor: signedTxCbor }); }
97
+ // --- EvaluatingBackend -----------------------------------------------------------------------
98
+ evaluateTransaction(unsignedTxCbor) {
99
+ return this.call('EvaluateTransaction', { cbor: unsignedTxCbor });
100
+ }
101
+ // --- PaginatingBackend (crawler source) ------------------------------------------------------
102
+ getBlockByHeight(height) { return this.call('GetBlockByHeight', { height }); }
103
+ getNextBlocks(afterHash, count, afterHeight) {
104
+ return this.call('GetNextBlocks', { afterHash, count, afterHeight: afterHeight ?? null });
105
+ }
106
+ getBlockTransactions(blockHash) { return this.call('GetBlockTransactions', { blockHash }); }
107
+ // --- EnumeratingBackend (epoch snapshots) -----------------------------------------------------
108
+ getPoolIds() { return this.call('GetPoolIds'); }
109
+ getPools(poolIds) { return this.batched('GetPools', poolIds); }
110
+ getDrepIds() { return this.call('GetDrepIds'); }
111
+ getDreps(drepIds) { return this.batched('GetDreps', drepIds); }
112
+ async shutdown() { }
113
+ async batched(operation, ids) {
114
+ const out = [];
115
+ for (let i = 0; i < ids.length; i += ENUMERATION_BATCH) {
116
+ out.push(...await this.call(operation, { ids: JSON.stringify(ids.slice(i, i + ENUMERATION_BATCH)) }));
117
+ }
118
+ return out;
119
+ }
120
+ // POSTs one operation and parses the JSON answer with exact big integers.
121
+ // The remote error message stays verbatim, so `CHAIN_POINT_MISMATCH:` reaches the crawler.
122
+ async call(operation, body = {}) {
123
+ try {
124
+ const res = await this.api.post(`/${operation}`, body);
125
+ const left = Number(res.headers?.['x-access-units-left']);
126
+ if (Number.isFinite(left))
127
+ this.unitsLeft = left;
128
+ const value = res.data?.value;
129
+ return (typeof value === 'string' ? (0, deep_json_1.parseJson)(value) : value);
130
+ }
131
+ catch (err) {
132
+ throw this.mapError(operation, err);
133
+ }
134
+ }
135
+ mapError(operation, err) {
136
+ const ax = err;
137
+ if (!ax?.isAxiosError)
138
+ return err instanceof Error ? err : new Error(String(err));
139
+ const status = ax.response?.status;
140
+ const message = ax.response?.data?.error?.message ?? ax.message;
141
+ // older instances carry the code only as a `[CODE]` prefix of the message
142
+ const code = ax.response?.data?.error?.code ?? message;
143
+ // the remote prefixes `[CODE] Operation: `; the crawler recognises the reorg marker at the start
144
+ const marker = message.indexOf('CHAIN_POINT_MISMATCH:');
145
+ if (marker >= 0)
146
+ return new errors_1.ProviderUnavailableError(message.slice(marker), this.name);
147
+ // NotFoundError appends " not found" itself; the remote message already ends with it
148
+ if (status === 404)
149
+ return new errors_1.NotFoundError(message.replace(/ not found$/, ''), this.name);
150
+ if (status === 429) {
151
+ const retryAfter = Number(ax.response?.headers?.['retry-after']);
152
+ return new errors_1.RateLimitError(message, this.name, Number.isFinite(retryAfter) ? retryAfter : undefined);
153
+ }
154
+ if (status === 409 && code.includes(error_codes_1.ERROR_CODES.TX_ALREADY_SUBMITTED)) {
155
+ return new errors_1.TransactionAlreadySubmittedError(/[0-9a-f]{64}/.exec(message)?.[0] ?? '', message);
156
+ }
157
+ 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);
161
+ }
162
+ if (status === 401 || status === 402 || status === 403) {
163
+ logger.error(`${operation}: the remote ODATANO refused the key (${status}): ${message}`);
164
+ }
165
+ return new errors_1.ProviderUnavailableError(message, this.name);
166
+ }
167
+ }
168
+ exports.OdatanoBackend = OdatanoBackend;
169
+ //# sourceMappingURL=odatano-backend.js.map
@@ -1,6 +1,85 @@
1
1
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
2
- import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint } from './cardano-backend';
2
+ import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint, LedgerStateBackend, EpochStateBackend, EpochLedgerState, RewardAccountStateBackend, AskRewardAccounts } from './cardano-backend';
3
3
  import { Network } from '../cardano-client';
4
+ /** Ogmios response shapes not fully typed in @cardano-ogmios/client. */
5
+ interface OgmiosStakePool {
6
+ vrfVerificationKeyHash?: string;
7
+ stake?: {
8
+ ada?: {
9
+ lovelace?: number | bigint;
10
+ };
11
+ };
12
+ pledge?: {
13
+ ada?: {
14
+ lovelace?: number | bigint;
15
+ };
16
+ } | number | bigint;
17
+ margin?: number | string;
18
+ cost?: {
19
+ ada?: {
20
+ lovelace?: number | bigint;
21
+ };
22
+ } | number | bigint;
23
+ rewardAccount?: string;
24
+ metadata?: {
25
+ url?: string;
26
+ hash?: string;
27
+ };
28
+ }
29
+ /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
30
+ export declare function ogmiosScriptHash(script: unknown): string | null;
31
+ /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
32
+ export declare function ogmiosPlutusScriptCbor(script: unknown): string | null;
33
+ /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
34
+ export declare function issuerKeyToPoolId(verificationKeyHex: string): string;
35
+ /** Ogmios `queryLedgerState/delegateRepresentatives` entry. Only the `registered` variant has an id. */
36
+ interface OgmiosDrepSummary {
37
+ type: 'registered' | 'noConfidence' | 'abstain';
38
+ id?: string;
39
+ from?: 'verificationKey' | 'script';
40
+ mandate?: {
41
+ epoch?: number;
42
+ };
43
+ stake?: {
44
+ ada?: {
45
+ lovelace?: number | bigint;
46
+ };
47
+ };
48
+ deposit?: {
49
+ ada?: {
50
+ lovelace?: number | bigint;
51
+ };
52
+ };
53
+ delegators?: unknown[];
54
+ }
55
+ /** Ogmios `stakePoolsPerformances`. Only nOpt is used, because its stake figures are live, not active. */
56
+ interface OgmiosStakePoolsPerformances {
57
+ desiredNumberOfStakePools?: number;
58
+ }
59
+ /** Raw Ogmios answers for one epoch snapshot, all read at the same acquired block. */
60
+ export interface OgmiosEpochStateRaw {
61
+ epoch: number;
62
+ stakePools: Record<string, OgmiosStakePool>;
63
+ performances: OgmiosStakePoolsPerformances | null;
64
+ dreps: OgmiosDrepSummary[];
65
+ pots: {
66
+ treasury?: {
67
+ ada?: {
68
+ lovelace?: number | bigint;
69
+ };
70
+ };
71
+ reserves?: {
72
+ ada?: {
73
+ lovelace?: number | bigint;
74
+ };
75
+ };
76
+ } | null;
77
+ }
78
+ export declare function mapOgmiosEpochState(raw: OgmiosEpochStateRaw): EpochLedgerState;
79
+ export declare function decodeDrepId(drepId: string): {
80
+ hashHex: string;
81
+ isScript: boolean;
82
+ };
4
83
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
5
84
  export declare function resolveOgmiosTip(tip: 'origin' | {
6
85
  slot: number;
@@ -11,237 +90,91 @@ export declare function resolveOgmiosTip(tip: 'origin' | {
11
90
  };
12
91
  /** Resolve Ogmios block height which may be 'origin' (genesis block) or a number */
13
92
  export declare function resolveOgmiosHeight(height: 'origin' | number): number;
14
- export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend {
93
+ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend, LedgerStateBackend, EpochStateBackend, RewardAccountStateBackend {
15
94
  readonly name = "ogmios";
16
- /**
17
- * Capability declaration — the orchestrator skips Ogmios for these without
18
- * counting circuit failures. Historic queries are out of protocol scope;
19
- * getAddress/getNetworkInformation previously FABRICATED placeholder data
20
- * (type:'base'/isScript:false/stakeAddress:null resp. maxSupply as
21
- * total/circulating) which preferLive routing then preferred over correct
22
- * Blockfrost/Koios data.
23
- */
95
+ /** Ogmios cannot answer historic queries. The orchestrator skips it for these. */
24
96
  readonly unsupportedMethods: ReadonlySet<string>;
25
97
  private stateQueryClient;
26
98
  private txSubmissionClient;
27
99
  private context;
100
+ /** Second connection for address queries (see scanQueryClient). */
101
+ private scanClient;
102
+ private scanContext;
103
+ private scanConnecting;
28
104
  private isShutdown;
29
105
  private reconnectPromise;
30
106
  private network;
31
107
  private timeoutMs;
32
108
  private ogmiosUrl;
33
- /**
34
- * Constructor
35
- */
36
109
  constructor(network: Network, timeoutMs: number, ogmiosUrl: string);
37
- /**
38
- * Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
39
- *
40
- * createInteractionContext() opens the WebSocket, but FIRST probes
41
- * `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
42
- * → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
43
- * keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
44
- * server on Node 22/24 a reused socket the server has already half-closed
45
- * yields "Invalid response body … Premature close" the instant the body is
46
- * read — deterministically (Node 20's older http client tolerated it; `curl`
47
- * does too, so the /health response itself is well-formed and the node is
48
- * healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
49
- * an agent into that internal fetch, so we neutralise keep-alive process-wide
50
- * for `http://`. Blast radius is tiny: the only `http://` consumer is the local
51
- * Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
52
- * and are unaffected. Runs once, lazily, only when Ogmios is actually used.
53
- */
54
110
  private static keepAliveDisabled;
55
111
  private static disableHttpKeepAlive;
56
112
  /** Validate Ogmios URL scheme and reject dangerous protocols */
57
113
  private static validateOgmiosUrl;
58
- /**
59
- * Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
60
- * node is alive but too busy catching up to answer) would otherwise block
61
- * forever — there is no built-in connect timeout — hanging the whole
62
- * app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
63
- * with a message containing "timeout" so the orchestrator's transient-error
64
- * retry picks it up instead of dying.
65
- */
66
114
  private withInitTimeout;
67
- /**
68
- * Force-release an Ogmios interaction socket after a failed/expired open or
69
- * close step. The runtime uses `ws` (and therefore supports `terminate`), but
70
- * the close fallback keeps the helper compatible with the public structural
71
- * InteractionContext type and lightweight test doubles.
72
- */
115
+ /** Force-release a socket after a failed open or close. Test doubles without `terminate` get `close`. */
73
116
  private forceCloseContext;
74
- /**
75
- * Initialize the Ogmios backend connection
76
- */
117
+ /** Open the interaction context and the query/submission clients. */
77
118
  init(): Promise<boolean>;
78
- /**
79
- * Reconnect when the WebSocket has died since the last successful init.
80
- * No-op when never initialized (test-injected clients) — startup-init
81
- * recovery is the orchestrator's job (lazy init retry in CardanoClient).
82
- * Concurrent callers share one reconnect attempt.
83
- */
119
+ private scanQueryClient;
120
+ /** Reconnect a dead WebSocket. Concurrent callers share one attempt. No-op before the first init. */
84
121
  private ensureConnected;
85
- /**
86
- * Get specific Block Data (not supported)
87
- * @param _hash block hash (hex)
88
- * @returns {Promise<BlockData>} block data
89
- */
90
122
  getBlock(_hash: string): Promise<BlockData>;
91
- /**
92
- * Get specific Epoch Data (not supported)
93
- * @param _epochNumber epoch number
94
- * @returns {Promise<EpochData>} epoch data
95
- */
123
+ /** Only the current epoch. */
96
124
  getEpoch(epochNumber: number): Promise<EpochData>;
97
- /**
98
- * Get specific Transaction Data (not supported)
99
- * @param _hash transaction hash (hex)
100
- * @returns {Promise<Transaction>} transaction data
101
- */
102
125
  getTransaction(_hash: string): Promise<Transaction>;
103
- /**
104
- * Get specific Transaction Metadata (not supported)
105
- * @param _tx_hash transaction hash (hex)
106
- * @returns {Promise<MetadataLabelTx[]>} transaction metadata list
107
- */
108
126
  getTransactionMetadata(_tx_hash: string): Promise<MetadataLabelTx[]>;
109
- /**
110
- * Get specific Drep Data (not supported for Ogmios)
111
- * @param _drepId drep id
112
- * @returns {Promise<DrepData>} drep data
113
- */
114
- getDrep(_drepId: string): Promise<DrepData>;
115
- /**
116
- * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
117
- * @param _unit asset unit (policyId + assetNameHex)
118
- * @returns {Promise<AssetInfo>} asset info
119
- */
127
+ getDrep(drepId: string): Promise<DrepData>;
128
+ /** Not supported. The protocol has no aggregate-supply query. */
120
129
  getAssetInfo(_unit: string): Promise<AssetInfo>;
121
- /**
122
- * Get specific Network Information (not supported — Ogmios state queries
123
- * expose no supply/stake aggregates; the previous implementation fabricated
124
- * maxSupply as total/circulating, which preferLive routing then preferred
125
- * over correct Blockfrost/Koios data)
126
- */
130
+ /** Total supply is max supply minus reserves. Circulating, locked and stake totals stay '0'. */
127
131
  getNetworkInformation(): Promise<NetworkInformation>;
128
- /**
129
- * Get current specific Address Data (not supported — address type, script
130
- * flag and stake address are not derivable from Ogmios state queries; the
131
- * previous implementation fabricated type:'base'/isScript:false/
132
- * stakeAddress:null. UTxOs remain available via getAddressUtxos.)
133
- */
134
- getAddress(_address: string): Promise<Address>;
135
- /** get current specific Address UTxOs
136
- * @param address bech32 address
137
- * @returns {Promise<UTxO[]>} address UTxOs
138
- */
132
+ /** Address at the tip, decoded locally, with UTxOs and balance from the ledger. No tx history. */
133
+ getAddress(address: string): Promise<Address>;
139
134
  getAddressUtxos(address: string): Promise<UTxO[]>;
140
- /**
141
- * Get Address Transactions (not supported by Ogmios - use historical backend)
142
- * Ogmios is a live state query backend and does not provide historical transaction data
143
- * @param _address bech32 address
144
- * @returns {Promise<Transaction[]>} always throws - use historical backend instead
145
- */
135
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
136
+ private mapOgmiosUtxo;
137
+ private withLedgerStateAt;
138
+ /** A connection of its own with the ledger state at `point` acquired. The caller closes it. */
139
+ private openLedgerStateAt;
140
+ rewardAccountsAt<T>(point: ChainPoint, read: (ask: AskRewardAccounts) => Promise<T>): Promise<T>;
141
+ /** Whole UTxO set as of `point` (crawler snapshot import). */
142
+ queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
143
+ /** Pools, DReps and pots at `point` from one ledger state. Without nOpt saturation stays 0. */
144
+ epochStateAt(point: ChainPoint): Promise<EpochLedgerState>;
145
+ /** Not supported. Ogmios only queries live state. */
146
146
  getAddressTransactions(_address: string): Promise<Transaction[]>;
147
- /**
148
- * Get current specific Pool Data
149
- * @param poolId pool id
150
- * @returns {Promise<PoolData>} pool data
151
- */
152
147
  getPool(poolId: string): Promise<PoolData>;
153
- /**
154
- * Get Account Data for specified stake address
155
- * @param stakeAddress stake address
156
- * @returns {Promise<AccountData>} account data
157
- */
158
148
  getAccount(stakeAddress: string): Promise<AccountData>;
159
- /**
160
- * Submit Transaction to the network
161
- * @param signedTxCbor signed transaction in CBOR hex format
162
- * @returns {Promise<string>} transaction hash
163
- */
164
149
  submitTransaction(signedTxCbor: string): Promise<string>;
165
- /**
166
- * Evaluate transaction script execution units
167
- * @param unsignedTxCbor unsigned transaction in CBOR hex format
168
- * @returns {Promise<ScriptEvaluationResult[]>} evaluation results
169
- */
150
+ /** Hash of a signed transaction, or null when the CBOR does not parse. */
151
+ private txHashOrNull;
152
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. */
153
+ private isKnownTransaction;
154
+ /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
155
+ private mempoolHas;
170
156
  evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
171
- /**
172
- * Get current Protocol Parameters
173
- * @returns {Promise<LedgerProtocolParameters>} protocol parameters
174
- */
175
157
  getProtocolParameters(): Promise<LedgerProtocolParameters>;
176
- /**
177
- * Get Latest Epoch Data
178
- * @returns {Promise<EpochData>} latest epoch data
179
- */
180
158
  getLatestEpoch(): Promise<EpochData>;
181
- /**
182
- * Get current Latest Block Data
183
- * @returns {Promise<BlockData>} latest block data
184
- */
185
159
  getLatestBlock(): Promise<BlockData>;
186
- /**
187
- * Get the latest chain tip slot.
188
- * @returns {Promise<number>} current chain slot
189
- */
190
160
  getCurrentSlot(): Promise<number>;
191
- /**
192
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
193
- * with an outputReferences filter. Empty result means spent or nonexistent.
194
- * @param txHash 64-char lowercase hex
195
- * @param outputIndex non-negative integer
196
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
197
- */
161
+ /** Unspent check via `queryLedgerState/utxo`. An empty answer means spent or unknown. */
198
162
  isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
199
- /**
200
- * Shutdown the Ogmios Backend
201
- * Closes all connections and marks as shutdown
202
- */
163
+ /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
164
+ getUnspentOutputs(refs: Array<{
165
+ txHash: string;
166
+ outputIndex: number;
167
+ }>): Promise<UTxO[]>;
168
+ /** Close the WebSocket and mark the backend as shut down. */
203
169
  shutdown(): Promise<void>;
204
- /**
205
- * Check if backend is connected
206
- */
207
170
  isConnected(): boolean;
208
- /**
209
- * Ensure the client is not shutdown before operations
210
- */
211
171
  private ensureNotShutdown;
212
- /**
213
- * Convert Ogmios value format to odatano amount array
214
- * Ogmios: { ada: { lovelace: 1000000 }, policyId: { assetName: quantity } }
215
- * Standard: [{ unit: 'lovelace', quantity: '1000000' }, { unit: 'policyId.assetName', quantity: 'N' }]
216
- */
172
+ /** Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` to a list of units and quantities. */
217
173
  private convertOgmiosValue;
218
- /**
219
- * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
220
- * (a separate WebSocket) from the query/submission clients, because it is a
221
- * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
222
- * time in order, which the crawler needs for reorg detection and serial persist.
223
- *
224
- * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
225
- * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
226
- * references ({txId,index}); the indexer resolves them from already-indexed
227
- * outputs (indexBlockFull, C3).
228
- * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
229
- * - Output `referenceScriptHash` is not derived from the inline script yet.
230
- */
231
174
  openChainSync(from: ChainPoint[] | 'origin', callbacks: ChainSyncCallbacks): Promise<ChainSyncHandle>;
232
- /**
233
- * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
234
- * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
235
- * the network's Shelley anchor (same config the tx-builder uses).
236
- */
237
175
  private mapOgmiosBlock;
238
- /**
239
- * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
240
- * and metadata are mapped fully; inputs are kept as bare references (address/amount
241
- * resolved downstream by the indexer). `spends` selects the ledger-applied
242
- * partition: a phase-2-invalid transaction consumes collaterals and creates only
243
- * its collateral-return output, never its declared regular inputs/outputs.
244
- */
245
176
  private mapOgmiosTx;
177
+ private mapOgmiosCertificates;
246
178
  }
179
+ export {};
247
180
  //# sourceMappingURL=ogmios-backend.d.ts.map