@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -0,0 +1,64 @@
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 (ACCESS gateway); mainnet has no default and needs `odatanoUrl`. */
5
+ export declare const ODATANO_API_URLS: Partial<Record<Network, string>>;
6
+ /**
7
+ * Backend over another ODATANO instance (typically the hosted API behind the ACCESS gateway),
8
+ * speaking its `CardanoBackendService`. Answers arrive in the provider shape, so everything above
9
+ * this class treats it like Koios. The key goes as `Authorization: Bearer`.
10
+ */
11
+ export declare class OdatanoBackend implements CardanoBackend, EvaluatingBackend, PaginatingBackend, EnumeratingBackend {
12
+ readonly name = "odatano";
13
+ private readonly api;
14
+ /** Units left on the key, from the gateway's `x-access-units-left` header; null when not reported. */
15
+ unitsLeft: number | null;
16
+ constructor(network: Network, timeoutMs: number, url: string | undefined, apiKey: string | undefined);
17
+ /** Probe the remote instance with its cheapest call. */
18
+ init(): Promise<boolean>;
19
+ getTransaction(txHash: string): Promise<Transaction>;
20
+ getAddress(address: string): Promise<Address>;
21
+ getAddressUtxos(address: string): Promise<UTxO[]>;
22
+ getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
23
+ getAddressTransactionHashes(address: string, limit: number): Promise<string[]>;
24
+ getTransactionsBatch(txHashes: string[]): Promise<Map<string, Transaction>>;
25
+ getCredentialUtxos(credHash: string): Promise<UTxO[]>;
26
+ /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
27
+ getUnspentOutputs(refs: Array<{
28
+ txHash: string;
29
+ outputIndex: number;
30
+ }>): Promise<UTxO[]>;
31
+ getNetworkInformation(): Promise<NetworkInformation>;
32
+ getTransactionMetadata(txHash: string): Promise<MetadataLabelTx[]>;
33
+ getBlock(blockHash: string): Promise<BlockData>;
34
+ getEpoch(epochNumber: number): Promise<EpochData>;
35
+ getLatestEpoch(): Promise<EpochData>;
36
+ getLatestBlock(): Promise<BlockData>;
37
+ getCurrentSlot(): Promise<number>;
38
+ isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
39
+ getPool(poolId: string): Promise<PoolData>;
40
+ getDrep(drepId: string): Promise<DrepData>;
41
+ getAccount(stakeAddress: string): Promise<AccountData>;
42
+ getAssetInfo(unit: string): Promise<AssetInfo>;
43
+ getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
44
+ getProtocolParameters(): Promise<LedgerProtocolParameters>;
45
+ submitTransaction(signedTxCbor: string): Promise<string>;
46
+ evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
47
+ getBlockByHeight(height: number): Promise<BlockData>;
48
+ getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
49
+ getBlockTransactions(blockHash: string): Promise<Transaction[]>;
50
+ getPoolIds(): Promise<string[]>;
51
+ getPools(poolIds: string[]): Promise<PoolData[]>;
52
+ getDrepIds(): Promise<string[]>;
53
+ getDreps(drepIds: string[]): Promise<DrepData[]>;
54
+ shutdown(): Promise<void>;
55
+ private batched;
56
+ /**
57
+ * POST one operation, parse the JSON string it answers (safeJSON keeps big integers) and map
58
+ * HTTP failures to the backend error classes. The remote message is kept verbatim, so markers
59
+ * such as `CHAIN_POINT_MISMATCH:` reach the crawler unchanged.
60
+ */
61
+ private call;
62
+ private mapError;
63
+ }
64
+ //# sourceMappingURL=odatano-backend.d.ts.map
@@ -0,0 +1,170 @@
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 error_codes_1 = require("../../utils/error-codes");
12
+ const logger = cds_1.default.log('OdatanoBackend');
13
+ /** Public ODATANO API per network (ACCESS gateway); 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
+ /**
22
+ * Backend over another ODATANO instance (typically the hosted API behind the ACCESS gateway),
23
+ * speaking its `CardanoBackendService`. Answers arrive in the provider shape, so everything above
24
+ * this class treats it like Koios. The key goes as `Authorization: Bearer`.
25
+ */
26
+ class OdatanoBackend {
27
+ name = 'odatano';
28
+ api;
29
+ /** Units left on the key, from the gateway's `x-access-units-left` header; null when not reported. */
30
+ unitsLeft = null;
31
+ constructor(network, timeoutMs, url, apiKey) {
32
+ const baseURL = (url || exports.ODATANO_API_URLS[network] || '').replace(/\/+$/, '');
33
+ if (!baseURL) {
34
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl is required on ${network}`));
35
+ }
36
+ if (!/^https?:\/\//i.test(baseURL)) {
37
+ throw new errors_1.BackendInitError('odatano', new Error(`odatanoUrl must be an http(s) URL, got "${baseURL}"`));
38
+ }
39
+ this.api = axios_1.default.create({
40
+ baseURL: baseURL + SERVICE_PATH,
41
+ timeout: timeoutMs,
42
+ headers: {
43
+ 'Content-Type': 'application/json',
44
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
45
+ },
46
+ });
47
+ }
48
+ /** Probe the remote instance with its cheapest call. */
49
+ async init() {
50
+ await this.call('GetCurrentSlot');
51
+ return true;
52
+ }
53
+ // --- CardanoBackend ------------------------------------------------------------------------
54
+ getTransaction(txHash) { return this.call('GetTransaction', { hash: txHash }); }
55
+ getAddress(address) { return this.call('GetAddress', { address }); }
56
+ getAddressUtxos(address) { return this.call('GetAddressUtxos', { address }); }
57
+ getAddressTransactions(address, limit) {
58
+ return this.call('GetAddressTransactions', { address, limit });
59
+ }
60
+ getAddressTransactionHashes(address, limit) {
61
+ return this.call('GetAddressTransactionHashes', { address, limit });
62
+ }
63
+ async getTransactionsBatch(txHashes) {
64
+ const out = new Map();
65
+ for (let i = 0; i < txHashes.length; i += ENUMERATION_BATCH) {
66
+ const found = await this.call('GetTransactionsBatch', {
67
+ hashes: JSON.stringify(txHashes.slice(i, i + ENUMERATION_BATCH)),
68
+ });
69
+ for (const [hash, tx] of Object.entries(found ?? {}))
70
+ out.set(hash, tx);
71
+ }
72
+ return out;
73
+ }
74
+ getCredentialUtxos(credHash) { return this.call('GetCredentialUtxos', { credential: credHash }); }
75
+ /** Unspent outputs among `refs`, from the remote's node (with reference-script bytes). */
76
+ async getUnspentOutputs(refs) {
77
+ const out = [];
78
+ for (let i = 0; i < refs.length; i += ENUMERATION_BATCH) {
79
+ out.push(...await this.call('GetUnspentOutputs', { refs: JSON.stringify(refs.slice(i, i + ENUMERATION_BATCH)) }));
80
+ }
81
+ return out;
82
+ }
83
+ getNetworkInformation() { return this.call('GetNetworkInformation'); }
84
+ getTransactionMetadata(txHash) { return this.call('GetTransactionMetadata', { hash: txHash }); }
85
+ getBlock(blockHash) { return this.call('GetBlock', { hash: blockHash }); }
86
+ getEpoch(epochNumber) { return this.call('GetEpoch', { epoch: epochNumber }); }
87
+ getLatestEpoch() { return this.call('GetLatestEpoch'); }
88
+ getLatestBlock() { return this.call('GetLatestBlock'); }
89
+ getCurrentSlot() { return this.call('GetCurrentSlot'); }
90
+ isUtxoUnspent(txHash, outputIndex) {
91
+ return this.call('IsUtxoUnspent', { txHash, outputIndex });
92
+ }
93
+ getPool(poolId) { return this.call('GetPool', { poolId }); }
94
+ getDrep(drepId) { return this.call('GetDrep', { drepId }); }
95
+ getAccount(stakeAddress) { return this.call('GetAccount', { stakeAddress }); }
96
+ getAssetInfo(unit) { return this.call('GetAssetInfo', { unit }); }
97
+ getAssetHistory(unit, limit = 100) { return this.call('GetAssetHistory', { unit, limit }); }
98
+ getProtocolParameters() { return this.call('GetProtocolParameters'); }
99
+ submitTransaction(signedTxCbor) { return this.call('SubmitTransaction', { cbor: signedTxCbor }); }
100
+ // --- EvaluatingBackend -----------------------------------------------------------------------
101
+ evaluateTransaction(unsignedTxCbor) {
102
+ return this.call('EvaluateTransaction', { cbor: unsignedTxCbor });
103
+ }
104
+ // --- PaginatingBackend (crawler source) ------------------------------------------------------
105
+ getBlockByHeight(height) { return this.call('GetBlockByHeight', { height }); }
106
+ getNextBlocks(afterHash, count, afterHeight) {
107
+ return this.call('GetNextBlocks', { afterHash, count, afterHeight: afterHeight ?? null });
108
+ }
109
+ getBlockTransactions(blockHash) { return this.call('GetBlockTransactions', { blockHash }); }
110
+ // --- EnumeratingBackend (epoch snapshots) -----------------------------------------------------
111
+ getPoolIds() { return this.call('GetPoolIds'); }
112
+ getPools(poolIds) { return this.batched('GetPools', poolIds); }
113
+ getDrepIds() { return this.call('GetDrepIds'); }
114
+ getDreps(drepIds) { return this.batched('GetDreps', drepIds); }
115
+ async shutdown() { }
116
+ async batched(operation, ids) {
117
+ const out = [];
118
+ for (let i = 0; i < ids.length; i += ENUMERATION_BATCH) {
119
+ out.push(...await this.call(operation, { ids: JSON.stringify(ids.slice(i, i + ENUMERATION_BATCH)) }));
120
+ }
121
+ return out;
122
+ }
123
+ /**
124
+ * POST one operation, parse the JSON string it answers (safeJSON keeps big integers) and map
125
+ * HTTP failures to the backend error classes. The remote message is kept verbatim, so markers
126
+ * such as `CHAIN_POINT_MISMATCH:` reach the crawler unchanged.
127
+ */
128
+ async call(operation, body = {}) {
129
+ try {
130
+ const res = await this.api.post(`/${operation}`, body);
131
+ const left = Number(res.headers?.['x-access-units-left']);
132
+ if (Number.isFinite(left))
133
+ this.unitsLeft = left;
134
+ const value = res.data?.value;
135
+ return (typeof value === 'string' ? client_1.safeJSON.parse(value) : value);
136
+ }
137
+ catch (err) {
138
+ throw this.mapError(operation, err);
139
+ }
140
+ }
141
+ mapError(operation, err) {
142
+ const ax = err;
143
+ if (!ax?.isAxiosError)
144
+ return err instanceof Error ? err : new Error(String(err));
145
+ const status = ax.response?.status;
146
+ const message = ax.response?.data?.error?.message ?? ax.message;
147
+ // the remote prefixes `[CODE] Operation: `; the crawler recognises the reorg marker at the start
148
+ const marker = message.indexOf('CHAIN_POINT_MISMATCH:');
149
+ if (marker >= 0)
150
+ return new errors_1.ProviderUnavailableError(message.slice(marker), this.name);
151
+ // NotFoundError appends " not found" itself; the remote message already ends with it
152
+ if (status === 404)
153
+ return new errors_1.NotFoundError(message.replace(/ not found$/, ''), this.name);
154
+ if (status === 429) {
155
+ const retryAfter = Number(ax.response?.headers?.['retry-after']);
156
+ return new errors_1.RateLimitError(message, this.name, Number.isFinite(retryAfter) ? retryAfter : undefined);
157
+ }
158
+ if (status === 400) {
159
+ return message.includes(error_codes_1.ERROR_CODES.SCRIPT_VALIDATION_FAILURE)
160
+ ? new errors_1.ScriptValidationError(message)
161
+ : new errors_1.TransactionValidationError(message);
162
+ }
163
+ if (status === 401 || status === 402 || status === 403) {
164
+ logger.error(`${operation}: the remote ODATANO refused the key (${status}): ${message}`);
165
+ }
166
+ return new errors_1.ProviderUnavailableError(message, this.name);
167
+ }
168
+ }
169
+ exports.OdatanoBackend = OdatanoBackend;
170
+ //# sourceMappingURL=odatano-backend.js.map
@@ -1,6 +1,94 @@
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 } 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
+ }
25
+ /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
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;
29
+ /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
30
+ export declare function issuerKeyToPoolId(verificationKeyHex: string): string;
31
+ /**
32
+ * Ogmios v6 `queryLedgerState/delegateRepresentatives` summary (local wire type; the schema
33
+ * package is only a transitive dependency). Only the `registered` variant carries an id.
34
+ */
35
+ interface OgmiosDrepSummary {
36
+ type: 'registered' | 'noConfidence' | 'abstain';
37
+ id?: string;
38
+ from?: 'verificationKey' | 'script';
39
+ mandate?: {
40
+ epoch?: number;
41
+ };
42
+ stake?: {
43
+ ada?: {
44
+ lovelace?: number | bigint;
45
+ };
46
+ };
47
+ deposit?: {
48
+ ada?: {
49
+ lovelace?: number | bigint;
50
+ };
51
+ };
52
+ delegators?: unknown[];
53
+ }
54
+ /** Ogmios `stakePoolsPerformances`: only nOpt is used — its stake figures are live, not active. */
55
+ interface OgmiosStakePoolsPerformances {
56
+ desiredNumberOfStakePools?: number;
57
+ }
58
+ /** Raw Ogmios answers for one epoch snapshot, all read at the same acquired block. */
59
+ export interface OgmiosEpochStateRaw {
60
+ epoch: number;
61
+ stakePools: Record<string, OgmiosStakePool>;
62
+ performances: OgmiosStakePoolsPerformances | null;
63
+ dreps: OgmiosDrepSummary[];
64
+ pots: {
65
+ treasury?: {
66
+ ada?: {
67
+ lovelace?: number | bigint;
68
+ };
69
+ };
70
+ reserves?: {
71
+ ada?: {
72
+ lovelace?: number | bigint;
73
+ };
74
+ };
75
+ } | null;
76
+ }
77
+ /**
78
+ * Ogmios ledger answers -> EpochLedgerState. Saturation follows the ledger: live stake over
79
+ * (max supply - reserves) / nOpt. Figures the ledger view does not carry stay 0 / null: active
80
+ * stake (the indexer derives it from the previous snapshot), block counts, delegator counts,
81
+ * DRep last activity.
82
+ */
83
+ export declare function mapOgmiosEpochState(raw: OgmiosEpochStateRaw): EpochLedgerState;
84
+ /**
85
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
86
+ * high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
87
+ */
88
+ export declare function decodeDrepId(drepId: string): {
89
+ hashHex: string;
90
+ isScript: boolean;
91
+ };
4
92
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
5
93
  export declare function resolveOgmiosTip(tip: 'origin' | {
6
94
  slot: number;
@@ -11,75 +99,58 @@ export declare function resolveOgmiosTip(tip: 'origin' | {
11
99
  };
12
100
  /** Resolve Ogmios block height which may be 'origin' (genesis block) or a number */
13
101
  export declare function resolveOgmiosHeight(height: 'origin' | number): number;
14
- export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend {
102
+ /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
103
+ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend, LedgerStateBackend, EpochStateBackend {
15
104
  readonly name = "ogmios";
16
105
  /**
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.
106
+ * Capability declaration — the orchestrator skips Ogmios for these without counting
107
+ * circuit failures. Historic queries are out of protocol scope.
23
108
  */
24
109
  readonly unsupportedMethods: ReadonlySet<string>;
25
110
  private stateQueryClient;
26
111
  private txSubmissionClient;
27
112
  private context;
113
+ /** Second connection for address queries (see scanQueryClient). */
114
+ private scanClient;
115
+ private scanContext;
116
+ private scanConnecting;
28
117
  private isShutdown;
29
118
  private reconnectPromise;
30
119
  private network;
31
120
  private timeoutMs;
32
121
  private ogmiosUrl;
33
- /**
34
- * Constructor
35
- */
36
122
  constructor(network: Network, timeoutMs: number, ogmiosUrl: string);
37
123
  /**
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.
124
+ * Force non-keep-alive HTTP for the Ogmios `/health` probe: node-fetch v2 uses `http.globalAgent`,
125
+ * whose pooled sockets (kept alive since Node 19) fail with "Premature close" once Ogmios' Warp server
126
+ * half-closes them. No agent hook exists, so keep-alive is disabled process-wide for `http://` only.
53
127
  */
54
128
  private static keepAliveDisabled;
55
129
  private static disableHttpKeepAlive;
56
130
  /** Validate Ogmios URL scheme and reject dangerous protocols */
57
131
  private static validateOgmiosUrl;
58
132
  /**
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.
133
+ * Bound an init step in time: the WebSocket connect/handshake has no built-in timeout and
134
+ * can hang when the node is busy. The rejection message contains "timeout" so the
135
+ * orchestrator's transient-error retry picks it up.
65
136
  */
66
137
  private withInitTimeout;
67
138
  /**
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.
139
+ * Force-release an interaction socket after a failed/expired open or close. The runtime
140
+ * socket is `ws` (has `terminate`); the `close` fallback keeps test doubles working.
72
141
  */
73
142
  private forceCloseContext;
143
+ /** Open the interaction context and the query/submission clients. */
144
+ init(): Promise<boolean>;
74
145
  /**
75
- * Initialize the Ogmios backend connection
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.
76
149
  */
77
- init(): Promise<boolean>;
150
+ private scanQueryClient;
78
151
  /**
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.
152
+ * Reconnect when the WebSocket died since the last init. No-op when never initialized
153
+ * (test-injected clients); concurrent callers share one reconnect attempt.
83
154
  */
84
155
  private ensureConnected;
85
156
  /**
@@ -107,11 +178,12 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
107
178
  */
108
179
  getTransactionMetadata(_tx_hash: string): Promise<MetadataLabelTx[]>;
109
180
  /**
110
- * Get specific Drep Data (not supported for Ogmios)
111
- * @param _drepId drep id
112
- * @returns {Promise<DrepData>} drep data
181
+ * DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`) via the
182
+ * raw `Method()` primitive, since the client ships no wrapper. Ogmios lists only REGISTERED
183
+ * DReps: retired/unknown → NotFoundError; `expired` is derived from the mandate epoch.
184
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
113
185
  */
114
- getDrep(_drepId: string): Promise<DrepData>;
186
+ getDrep(drepId: string): Promise<DrepData>;
115
187
  /**
116
188
  * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
117
189
  * @param _unit asset unit (policyId + assetNameHex)
@@ -119,30 +191,36 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
119
191
  */
120
192
  getAssetInfo(_unit: string): Promise<AssetInfo>;
121
193
  /**
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)
194
+ * Supply figures from `queryLedgerState/treasuryAndReserves`: total = max − reserves.
195
+ * Circulating, locked and stake totals are not in the ledger state and stay '0'.
126
196
  */
127
197
  getNetworkInformation(): Promise<NetworkInformation>;
128
198
  /**
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.)
199
+ * Address at the tip: type, script flag and stake address decoded from the address itself,
200
+ * UTxOs from the ledger, balance summed over them. No transaction history (getAddressTransactions).
133
201
  */
134
- getAddress(_address: string): Promise<Address>;
202
+ getAddress(address: string): Promise<Address>;
135
203
  /** get current specific Address UTxOs
136
204
  * @param address bech32 address
137
205
  * @returns {Promise<UTxO[]>} address UTxOs
138
206
  */
139
207
  getAddressUtxos(address: string): Promise<UTxO[]>;
208
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
209
+ private mapOgmiosUtxo;
140
210
  /**
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
211
+ * Run `fn` against the ledger state acquired at `point` on a SEPARATE WebSocket: local-state-query
212
+ * holds one acquired point per connection, so the shared socket would pin live queries to the past.
213
+ * The point must be inside the node's volatile window (k blocks) or acquisition is refused.
145
214
  */
215
+ private withLedgerStateAt;
216
+ /** Whole UTxO set as of `point` (crawler snapshot import). */
217
+ queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
218
+ /**
219
+ * Pools, DReps and pots as of `point` (crawler epoch snapshot), all read from one acquired
220
+ * ledger state. Performances are optional: without them (no nOpt) saturation stays 0.
221
+ */
222
+ epochStateAt(point: ChainPoint): Promise<EpochLedgerState>;
223
+ /** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
146
224
  getAddressTransactions(_address: string): Promise<Transaction[]>;
147
225
  /**
148
226
  * Get current specific Pool Data
@@ -189,59 +267,49 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
189
267
  */
190
268
  getCurrentSlot(): Promise<number>;
191
269
  /**
192
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
193
- * with an outputReferences filter. Empty result means spent or nonexistent.
270
+ * Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
194
271
  * @param txHash 64-char lowercase hex
195
272
  * @param outputIndex non-negative integer
196
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
197
273
  */
198
274
  isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
199
- /**
200
- * Shutdown the Ogmios Backend
201
- * Closes all connections and marks as shutdown
202
- */
275
+ /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
276
+ getUnspentOutputs(refs: Array<{
277
+ txHash: string;
278
+ outputIndex: number;
279
+ }>): Promise<UTxO[]>;
280
+ /** Close the WebSocket and mark the backend as shut down. */
203
281
  shutdown(): Promise<void>;
204
- /**
205
- * Check if backend is connected
206
- */
207
282
  isConnected(): boolean;
208
- /**
209
- * Ensure the client is not shutdown before operations
210
- */
211
283
  private ensureNotShutdown;
212
284
  /**
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' }]
285
+ * Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` →
286
+ * `[{ unit: 'lovelace', quantity }, { unit: policyId+assetName, quantity }]`.
216
287
  */
217
288
  private convertOgmiosValue;
218
289
  /**
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.
290
+ * Open a long-lived chain-sync stream on its own WebSocket. `sequential: true` + `inFlight: 1`
291
+ * deliver blocks strictly in order (required by reorg detection and serial persist). Inputs arrive
292
+ * as bare references (resolved by the indexer from indexed outputs); per-tx size/deposit are not surfaced.
230
293
  */
231
294
  openChainSync(from: ChainPoint[] | 'origin', callbacks: ChainSyncCallbacks): Promise<ChainSyncHandle>;
232
295
  /**
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).
296
+ * Map an Ogmios Praos block to BlockData + transactions. Block fees are the sum of per-tx
297
+ * fees; epoch/epochSlot derive from the slot via the Shelley anchor. A phase-2 failure without
298
+ * `total_collateral` still carries its declared fee here; applyCollateralFees() corrects it.
236
299
  */
237
300
  private mapOgmiosBlock;
238
301
  /**
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.
302
+ * Map one chain-sync transaction. Inputs stay bare references (resolved by the indexer).
303
+ * `spends` selects the ledger-applied partition: a phase-2-invalid tx consumes collaterals
304
+ * and creates only its collateral-return output; the fee follows that partition too.
244
305
  */
245
306
  private mapOgmiosTx;
307
+ /**
308
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
309
+ * with both pool and DRep target is split into two entries with the same index (as db-sync
310
+ * reports it); bare credential hashes are re-encoded as bech32 to match the other tables.
311
+ */
312
+ private mapOgmiosCertificates;
246
313
  }
314
+ export {};
247
315
  //# sourceMappingURL=ogmios-backend.d.ts.map