@odatano/core 2.0.0-rc.18 → 2.0.0-rc.19

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 (35) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +52 -0
  2. package/@cds-models/CardanoIndexerService/index.js +7 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +170 -0
  4. package/@cds-models/CardanoODataService/index.js +21 -0
  5. package/@cds-models/odatano/cardano/index.d.ts +176 -0
  6. package/@cds-models/odatano/cardano/index.js +21 -0
  7. package/README.md +3 -3
  8. package/db/schema.cds +277 -0
  9. package/package.json +179 -179
  10. package/srv/blockchain/backends/cardano-backend.d.ts +16 -0
  11. package/srv/blockchain/backends/cardano-backend.js +4 -0
  12. package/srv/blockchain/backends/koios-backend.d.ts +80 -1
  13. package/srv/blockchain/backends/koios-backend.js +128 -48
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +21 -2
  15. package/srv/blockchain/backends/ogmios-backend.js +120 -16
  16. package/srv/blockchain/cardano-client.d.ts +3 -1
  17. package/srv/blockchain/cardano-client.js +9 -0
  18. package/srv/blockchain/cardano-indexer.d.ts +56 -3
  19. package/srv/blockchain/cardano-indexer.js +124 -3
  20. package/srv/blockchain/crawler/crawler.d.ts +11 -1
  21. package/srv/blockchain/crawler/crawler.js +70 -1
  22. package/srv/blockchain/crawler/sync-state.d.ts +27 -1
  23. package/srv/blockchain/crawler/sync-state.js +83 -1
  24. package/srv/blockchain/crawler/utxo-set-import.d.ts +86 -0
  25. package/srv/blockchain/crawler/utxo-set-import.js +289 -0
  26. package/srv/blockchain/ledger-state.d.ts +89 -0
  27. package/srv/blockchain/ledger-state.js +383 -0
  28. package/srv/cardano-indexer-service.cds +26 -0
  29. package/srv/cardano-indexer-service.js +71 -0
  30. package/srv/cardano-service.cds +35 -0
  31. package/srv/server.js +6 -1
  32. package/srv/utils/db-indexes.js +12 -0
  33. package/srv/utils/mappers.d.ts +43 -3
  34. package/srv/utils/mappers.js +115 -1
  35. package/srv/utils/types.d.ts +38 -0
@@ -228,12 +228,28 @@ export interface ChainSyncBackend extends CardanoBackend {
228
228
  }
229
229
  /** Type guard: does this backend support streamed chain-sync? */
230
230
  export declare function isChainSyncBackend(backend: CardanoBackend): backend is ChainSyncBackend;
231
+ /**
232
+ * A backend that can hand out the whole UTxO set as of a recent chain point (a node via
233
+ * Ogmios `queryLedgerState/utxo` after `acquireLedgerState`). Used once, by the
234
+ * crawler.utxoSet snapshot import; the point must lie inside the node's volatile window.
235
+ */
236
+ export interface LedgerStateBackend extends CardanoBackend {
237
+ queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
238
+ }
239
+ export declare function isLedgerStateBackend(backend: CardanoBackend): backend is LedgerStateBackend;
231
240
  /**
232
241
  * Backend that can walk the chain forward by pagination (no live node). The
233
242
  * crawler's fallback source when no Ogmios chain-sync is available. Reorgs are
234
243
  * detected by the crawler via parent-hash mismatch (not delivered natively).
235
244
  */
236
245
  export interface PaginatingBackend extends CardanoBackend {
246
+ /**
247
+ * Optional: what the crawl wants per block beyond inputs/outputs (crawler.certificates).
248
+ * A backend that pays per payload (Koios `_certs`/`_withdrawals`) only asks when told to.
249
+ */
250
+ configureCrawl?(options: {
251
+ certificates: boolean;
252
+ }): void;
237
253
  /** Fetch a block by its height. */
238
254
  getBlockByHeight(height: number): Promise<BlockData>;
239
255
  /**
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isEvaluatingBackend = isEvaluatingBackend;
4
4
  exports.isChainSyncBackend = isChainSyncBackend;
5
+ exports.isLedgerStateBackend = isLedgerStateBackend;
5
6
  exports.isPaginatingBackend = isPaginatingBackend;
6
7
  exports.isEnumeratingBackend = isEnumeratingBackend;
7
8
  /**
@@ -16,6 +17,9 @@ function isEvaluatingBackend(backend) {
16
17
  function isChainSyncBackend(backend) {
17
18
  return typeof backend.openChainSync === 'function';
18
19
  }
20
+ function isLedgerStateBackend(backend) {
21
+ return typeof backend.queryUtxoSetAt === 'function';
22
+ }
19
23
  /** Type guard: can this backend be walked forward by pagination? */
20
24
  function isPaginatingBackend(backend) {
21
25
  const b = backend;
@@ -1,6 +1,72 @@
1
1
  import { CardanoBackend, PaginatingBackend, EnumeratingBackend } from './cardano-backend';
2
- import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters } from '../../utils/types';
2
+ import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, TxCertificate } from '../../utils/types';
3
3
  import { Network } from '../cardano-client';
4
+ /** Shape of a Koios tx-in/tx-out row from /tx_info */
5
+ interface KoiosTxIO {
6
+ address?: string;
7
+ payment_addr?: {
8
+ bech32?: string;
9
+ };
10
+ tx_hash: string;
11
+ tx_index: number;
12
+ value: string;
13
+ datum_hash?: string | null;
14
+ inline_datum?: unknown;
15
+ reference_script?: unknown;
16
+ asset_list?: Array<{
17
+ policy_id: string;
18
+ asset_name: string;
19
+ quantity: string;
20
+ }>;
21
+ }
22
+ /** Shape of a Koios /tx_info response row */
23
+ interface KoiosTxInfo {
24
+ tx_hash: string;
25
+ block_hash: string;
26
+ block_height: number | string;
27
+ tx_timestamp?: number;
28
+ block_time?: number;
29
+ absolute_slot?: number;
30
+ slot_no?: number;
31
+ tx_block_index?: number;
32
+ fee?: string;
33
+ deposit?: string;
34
+ tx_size: number;
35
+ metadata?: Record<string, unknown> | null;
36
+ inputs: KoiosTxIO[];
37
+ outputs: KoiosTxIO[];
38
+ /** False when the script phase failed (collateral consumed, regular ins/outs not applied). Absent on older Koios. */
39
+ valid_contract?: boolean | null;
40
+ collateral_inputs?: KoiosTxIO[] | null;
41
+ /** Live Koios returns ONE object here (the spec says array); both shapes are accepted. */
42
+ collateral_output?: KoiosTxIO | KoiosTxIO[] | null;
43
+ reference_inputs?: KoiosTxIO[] | null;
44
+ /**
45
+ * Net mint/burn of the transaction (`_assets: true`), quantity signed — negative is a burn.
46
+ * Absent on older Koios versions; the indexer then derives the delta from inputs/outputs,
47
+ * which is exact here because Koios resolves every input's `asset_list`.
48
+ */
49
+ assets_minted?: Array<{
50
+ policy_id?: string;
51
+ asset_name?: string | null;
52
+ quantity?: string | number;
53
+ }> | null;
54
+ /** `_withdrawals: true` only (crawler batch path); null/absent otherwise. */
55
+ withdrawals?: Array<{
56
+ amount?: string | number;
57
+ stake_addr?: string;
58
+ }> | null;
59
+ /**
60
+ * `_certs: true` only (crawler batch path). `type` is Koios' own vocabulary
61
+ * (stake_registration, pool_delegation, vote_delegation, pool_update, pool_retire, …);
62
+ * `info` carries the certificate fields, named per type.
63
+ */
64
+ certificates?: Array<{
65
+ index?: number | null;
66
+ type?: string;
67
+ info?: Record<string, unknown> | null;
68
+ }> | null;
69
+ }
4
70
  /**
5
71
  * KoiosBackend Implementation for CardanoBackend Interface
6
72
  * Implements the CardanoBackend interface using Koios API with Axios
@@ -170,6 +236,11 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
170
236
  * @returns {Promise<string[]>} most recent tx hashes
171
237
  */
172
238
  getAddressTransactionHashes(address: string, limit: number): Promise<string[]>;
239
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
240
+ private crawlCertificates;
241
+ configureCrawl(options: {
242
+ certificates: boolean;
243
+ }): void;
173
244
  /**
174
245
  * Batch fetch multiple transactions by hash using Koios POST /tx_info.
175
246
  * Sends all hashes in one request (chunked at 100 per Koios limit).
@@ -234,4 +305,12 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
234
305
  */
235
306
  private _mapKoiosTx;
236
307
  }
308
+ /**
309
+ * Normalize Koios `/tx_info` certificates (`_certs: true`). Field names inside `info`
310
+ * differ per type (`stake_address`, `pool_id_bech32`, `drep_id`, `deposit`,
311
+ * `retiring_epoch` — spelled `retiring epoch` with a space in current Koios), so every
312
+ * alias is read. Exported for the unit tests.
313
+ */
314
+ export declare function mapKoiosCertificates(certs: NonNullable<KoiosTxInfo['certificates']>): TxCertificate[];
315
+ export {};
237
316
  //# sourceMappingURL=koios-backend.d.ts.map
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.KoiosBackend = void 0;
7
+ exports.mapKoiosCertificates = mapKoiosCertificates;
7
8
  const cds_1 = __importDefault(require("@sap/cds"));
8
9
  const axios_1 = __importDefault(require("axios"));
9
10
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
@@ -827,6 +828,11 @@ class KoiosBackend {
827
828
  .map(tx => tx.tx_hash);
828
829
  }, this.name);
829
830
  }
831
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
832
+ crawlCertificates = false;
833
+ configureCrawl(options) {
834
+ this.crawlCertificates = Boolean(options.certificates);
835
+ }
830
836
  /**
831
837
  * Batch fetch multiple transactions by hash using Koios POST /tx_info.
832
838
  * Sends all hashes in one request (chunked at 100 per Koios limit).
@@ -844,8 +850,10 @@ class KoiosBackend {
844
850
  _inputs: true,
845
851
  _metadata: true,
846
852
  _assets: true,
847
- _withdrawals: false,
848
- _certs: false,
853
+ // crawler coverage (`crawler.certificates`): same request, larger payload —
854
+ // only asked for when the crawl will write them
855
+ _withdrawals: this.crawlCertificates,
856
+ _certs: this.crawlCertificates,
849
857
  _scripts: false,
850
858
  _bytecode: false,
851
859
  });
@@ -1092,54 +1100,126 @@ class KoiosBackend {
1092
1100
  }))
1093
1101
  : undefined,
1094
1102
  size: tx.tx_size,
1095
- inputs: tx.inputs.map((input) => {
1096
- const amount = [
1097
- { unit: 'lovelace', quantity: input.value }
1098
- ];
1099
- if (input.asset_list && Array.isArray(input.asset_list)) {
1100
- for (const asset of input.asset_list) {
1101
- amount.push({
1102
- unit: `${asset.policy_id}${asset.asset_name}`,
1103
- quantity: asset.quantity
1104
- });
1105
- }
1106
- }
1107
- return {
1108
- address: input.payment_addr?.bech32 || input.address || '',
1109
- txHash: input.tx_hash,
1110
- outputIndex: input.tx_index,
1111
- amount: amount,
1112
- dataHash: input.datum_hash || null,
1113
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1114
- referenceScriptHash: koiosRefScriptHash(input.reference_script),
1115
- };
1116
- }),
1117
- outputs: tx.outputs.map((output) => {
1118
- const amount = [
1119
- { unit: 'lovelace', quantity: output.value }
1120
- ];
1121
- if (output.asset_list && Array.isArray(output.asset_list)) {
1122
- for (const asset of output.asset_list) {
1123
- amount.push({
1124
- unit: `${asset.policy_id}${asset.asset_name}`,
1125
- quantity: asset.quantity
1126
- });
1127
- }
1128
- }
1129
- return {
1130
- address: output.payment_addr?.bech32 || output.address || '',
1131
- amount: amount,
1132
- txHash: tx.tx_hash,
1133
- outputIndex: output.tx_index,
1134
- dataHash: output.datum_hash || null,
1135
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1136
- isCollateral: false,
1137
- referenceScriptHash: koiosRefScriptHash(output.reference_script),
1138
- };
1139
- }),
1140
- metadata: labels
1103
+ // Phase-2 validity as db-sync records it; undefined on a Koios without the field, so the
1104
+ // indexer keeps treating such a source as "no phase-2 information".
1105
+ spendsCollaterals: typeof tx.valid_contract === 'boolean' ? tx.valid_contract === false : undefined,
1106
+ inputs: [
1107
+ ...asKoiosList(tx.inputs).map((input) => mapKoiosInput(input)),
1108
+ ...asKoiosList(tx.collateral_inputs).map((input) => mapKoiosInput(input, { isCollateral: true })),
1109
+ ...asKoiosList(tx.reference_inputs).map((input) => mapKoiosInput(input, { isReference: true })),
1110
+ ],
1111
+ outputs: [
1112
+ ...asKoiosList(tx.outputs).map((output) => mapKoiosOutput(tx.tx_hash, output, false)),
1113
+ // CIP-40 collateral return: produced only when the script phase failed
1114
+ ...asKoiosList(tx.collateral_output).map((output) => mapKoiosOutput(tx.tx_hash, output, true)),
1115
+ ],
1116
+ metadata: labels,
1117
+ // undefined (not []) when the call did not ask for them (`_certs: false` on the lazy
1118
+ // path) — the indexer tells "none" from "not reported" by exactly this.
1119
+ certificates: Array.isArray(tx.certificates) ? mapKoiosCertificates(tx.certificates) : undefined,
1120
+ withdrawals: Array.isArray(tx.withdrawals)
1121
+ ? tx.withdrawals
1122
+ .filter((w) => !!w.stake_addr)
1123
+ .map((w) => ({ stakeAddress: String(w.stake_addr), amount: String(w.amount ?? '0') }))
1124
+ : undefined,
1141
1125
  };
1142
1126
  }
1143
1127
  }
1144
1128
  exports.KoiosBackend = KoiosBackend;
1129
+ /**
1130
+ * Koios is loose about shapes: `collateral_output` arrives as one object (the spec says
1131
+ * array) and `asset_list` on it as the JSON STRING "[]". Normalize both before mapping.
1132
+ */
1133
+ function asKoiosList(v) {
1134
+ if (Array.isArray(v))
1135
+ return v;
1136
+ if (typeof v === 'string') {
1137
+ try {
1138
+ const parsed = JSON.parse(v);
1139
+ return Array.isArray(parsed) ? parsed : [];
1140
+ }
1141
+ catch {
1142
+ return [];
1143
+ }
1144
+ }
1145
+ return v && typeof v === 'object' ? [v] : [];
1146
+ }
1147
+ function koiosAmount(io) {
1148
+ const amount = [{ unit: 'lovelace', quantity: io.value }];
1149
+ for (const asset of asKoiosList(io.asset_list)) {
1150
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
1151
+ }
1152
+ return amount;
1153
+ }
1154
+ function mapKoiosInput(input, flags = {}) {
1155
+ return {
1156
+ address: input.payment_addr?.bech32 || input.address || '',
1157
+ txHash: input.tx_hash,
1158
+ outputIndex: input.tx_index,
1159
+ amount: koiosAmount(input),
1160
+ dataHash: input.datum_hash || null,
1161
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1162
+ referenceScriptHash: koiosRefScriptHash(input.reference_script),
1163
+ ...flags,
1164
+ };
1165
+ }
1166
+ function mapKoiosOutput(txHash, output, isCollateral) {
1167
+ return {
1168
+ address: output.payment_addr?.bech32 || output.address || '',
1169
+ amount: koiosAmount(output),
1170
+ txHash,
1171
+ outputIndex: output.tx_index,
1172
+ dataHash: output.datum_hash || null,
1173
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1174
+ isCollateral,
1175
+ referenceScriptHash: koiosRefScriptHash(output.reference_script),
1176
+ };
1177
+ }
1178
+ /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
1179
+ const KOIOS_CERT_KINDS = {
1180
+ stake_registration: 'stake_registration',
1181
+ stake_deregistration: 'stake_deregistration',
1182
+ pool_delegation: 'pool_delegation',
1183
+ // older Koios releases named the pool delegation plainly
1184
+ delegation: 'pool_delegation',
1185
+ vote_delegation: 'vote_delegation',
1186
+ pool_update: 'pool_registration',
1187
+ pool_retire: 'pool_retirement',
1188
+ drep_registration: 'drep_registration',
1189
+ drep_update: 'drep_update',
1190
+ drep_retire: 'drep_retirement',
1191
+ drep_deregistration: 'drep_retirement',
1192
+ committee_hot_auth: 'committee_hot_auth',
1193
+ committee_resign: 'committee_resign',
1194
+ treasury_MIR: 'treasury_mir',
1195
+ reserve_MIR: 'reserve_mir',
1196
+ pot_transfer: 'pot_transfer',
1197
+ param_proposal: 'param_proposal',
1198
+ };
1199
+ /**
1200
+ * Normalize Koios `/tx_info` certificates (`_certs: true`). Field names inside `info`
1201
+ * differ per type (`stake_address`, `pool_id_bech32`, `drep_id`, `deposit`,
1202
+ * `retiring_epoch` — spelled `retiring epoch` with a space in current Koios), so every
1203
+ * alias is read. Exported for the unit tests.
1204
+ */
1205
+ function mapKoiosCertificates(certs) {
1206
+ const str = (v) => (typeof v === 'string' && v.length ? v : null);
1207
+ const num = (v) => {
1208
+ const n = typeof v === 'string' ? Number(v) : v;
1209
+ return typeof n === 'number' && Number.isFinite(n) ? n : null;
1210
+ };
1211
+ return certs.map((c, position) => {
1212
+ const info = c.info ?? {};
1213
+ const deposit = info.deposit;
1214
+ return {
1215
+ certIndex: num(c.index) ?? position,
1216
+ kind: (c.type && KOIOS_CERT_KINDS[c.type]) || c.type || 'other',
1217
+ stakeAddress: str(info.stake_address) ?? str(info.stake_addr),
1218
+ poolId: str(info.pool_id_bech32) ?? str(info.pool),
1219
+ drepId: str(info.drep_id),
1220
+ deposit: deposit != null && deposit !== '' ? String(deposit) : null,
1221
+ epoch: num(info.retiring_epoch) ?? num(info['retiring epoch']),
1222
+ };
1223
+ });
1224
+ }
1145
1225
  //# sourceMappingURL=koios-backend.js.map
@@ -1,5 +1,5 @@
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 } from './cardano-backend';
3
3
  import { Network } from '../cardano-client';
4
4
  /**
5
5
  * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
@@ -21,7 +21,7 @@ export declare function resolveOgmiosTip(tip: 'origin' | {
21
21
  };
22
22
  /** Resolve Ogmios block height which may be 'origin' (genesis block) or a number */
23
23
  export declare function resolveOgmiosHeight(height: 'origin' | number): number;
24
- export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend {
24
+ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend, LedgerStateBackend {
25
25
  readonly name = "ogmios";
26
26
  /**
27
27
  * Capability declaration — the orchestrator skips Ogmios for these without
@@ -157,6 +157,17 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
157
157
  * @returns {Promise<UTxO[]>} address UTxOs
158
158
  */
159
159
  getAddressUtxos(address: string): Promise<UTxO[]>;
160
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
161
+ private mapOgmiosUtxo;
162
+ /**
163
+ * The whole UTxO set as of `point` (LedgerStateBackend — crawler.utxoSet snapshot import).
164
+ * Opens a SEPARATE WebSocket connection for it: the local-state-query protocol keeps one
165
+ * acquired point per connection, so a client on the shared socket would move every live
166
+ * query to the historical anchor for the duration. The point must be inside the node's
167
+ * volatile window (the last 2160 blocks) or the node refuses the acquisition. Whole-set
168
+ * queries are fine on preview/preprod; on mainnet prefer a cardano-cli file.
169
+ */
170
+ queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
160
171
  /**
161
172
  * Get Address Transactions (not supported by Ogmios - use historical backend)
162
173
  * Ogmios is a live state query backend and does not provide historical transaction data
@@ -268,5 +279,13 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
268
279
  * follows that partition too — see the `spendsCollaterals` branch below.
269
280
  */
270
281
  private mapOgmiosTx;
282
+ /**
283
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary.
284
+ * A `stakeDelegation` carrying both a pool and a DRep target is split into two entries
285
+ * with the same index, matching what Koios (db-sync) reports for the Conway combined
286
+ * certificate. Ogmios credentials are bare hashes; they are re-encoded as bech32 here so
287
+ * the rows carry the same identifiers as every other table.
288
+ */
289
+ private mapOgmiosCertificates;
271
290
  }
272
291
  //# sourceMappingURL=ogmios-backend.d.ts.map
@@ -422,22 +422,55 @@ class OgmiosBackend {
422
422
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
423
423
  await this.ensureConnected();
424
424
  const utxos = await this.stateQueryClient.utxo({ addresses: [address] });
425
- return utxos.map((u) => {
426
- // convert Ogmios value format to standard amount array
427
- const amount = this.convertOgmiosValue(u.value);
428
- return {
429
- txHash: u.transaction?.id || '',
430
- outputIndex: u.index || 0,
431
- address: u.address || address,
432
- amount: amount,
433
- blockHash: '',
434
- datumHash: u.datumHash,
435
- // Ogmios delivers the inline datum as CBOR hex in `datum` — it was
436
- // dropped before, breaking inline-datum spends when Ogmios serves UTxOs
437
- inlineDatum: typeof u.datum === 'string' ? u.datum : null,
438
- scriptRef: u.script?.hash
439
- };
440
- });
425
+ return utxos.map((u) => this.mapOgmiosUtxo(u, address));
426
+ }, this.name);
427
+ }
428
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
429
+ mapOgmiosUtxo(u, fallbackAddress = '') {
430
+ return {
431
+ txHash: u.transaction?.id || '',
432
+ outputIndex: u.index || 0,
433
+ address: u.address || fallbackAddress,
434
+ // convert Ogmios value format to standard amount array
435
+ amount: this.convertOgmiosValue(u.value),
436
+ blockHash: '',
437
+ datumHash: u.datumHash,
438
+ // Ogmios delivers the inline datum as CBOR hex in `datum` — it was
439
+ // dropped before, breaking inline-datum spends when Ogmios serves UTxOs
440
+ inlineDatum: typeof u.datum === 'string' ? u.datum : null,
441
+ scriptRef: u.script?.hash,
442
+ };
443
+ }
444
+ /**
445
+ * The whole UTxO set as of `point` (LedgerStateBackend — crawler.utxoSet snapshot import).
446
+ * Opens a SEPARATE WebSocket connection for it: the local-state-query protocol keeps one
447
+ * acquired point per connection, so a client on the shared socket would move every live
448
+ * query to the historical anchor for the duration. The point must be inside the node's
449
+ * volatile window (the last 2160 blocks) or the node refuses the acquisition. Whole-set
450
+ * queries are fine on preview/preprod; on mainnet prefer a cardano-cli file.
451
+ */
452
+ async queryUtxoSetAt(point) {
453
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
454
+ const url = new URL(this.ogmiosUrl);
455
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
456
+ const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] snapshot context error: ${err.message}`), () => { }, { connection });
457
+ let client = null;
458
+ try {
459
+ client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
460
+ const utxos = await client.utxo();
461
+ return utxos.map((u) => this.mapOgmiosUtxo(u));
462
+ }
463
+ finally {
464
+ // shutdown() closes THIS connection only; the backend's own socket is untouched
465
+ if (client) {
466
+ try {
467
+ await client.shutdown();
468
+ }
469
+ catch { /* best effort */ }
470
+ }
471
+ else
472
+ this.forceCloseContext(context);
473
+ }
441
474
  }, this.name);
442
475
  }
443
476
  /**
@@ -1014,7 +1047,78 @@ class OgmiosBackend {
1014
1047
  // undefined (not []) when absent — matches the Blockfrost path so
1015
1048
  // mapTransaction's hasMetadata flag stays false for metadata-less txs
1016
1049
  metadata: metadataEntries.length ? metadataEntries : undefined,
1050
+ certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
1051
+ withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
1052
+ stakeAddress,
1053
+ amount: (value?.ada?.lovelace ?? 0).toString(),
1054
+ })),
1055
+ };
1056
+ }
1057
+ /**
1058
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary.
1059
+ * A `stakeDelegation` carrying both a pool and a DRep target is split into two entries
1060
+ * with the same index, matching what Koios (db-sync) reports for the Conway combined
1061
+ * certificate. Ogmios credentials are bare hashes; they are re-encoded as bech32 here so
1062
+ * the rows carry the same identifiers as every other table.
1063
+ */
1064
+ mapOgmiosCertificates(certs) {
1065
+ const out = [];
1066
+ const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
1067
+ const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
1068
+ const drepId = (d) => {
1069
+ if (!d)
1070
+ return null;
1071
+ if (d.type === 'abstain')
1072
+ return 'drep_always_abstain';
1073
+ if (d.type === 'noConfidence')
1074
+ return 'drep_always_no_confidence';
1075
+ return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
1017
1076
  };
1077
+ certs.forEach((c, certIndex) => {
1078
+ switch (c.type) {
1079
+ case 'stakeCredentialRegistration':
1080
+ out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1081
+ break;
1082
+ case 'stakeCredentialDeregistration':
1083
+ out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1084
+ break;
1085
+ case 'stakeDelegation': {
1086
+ const stakeAddress = stakeAddr(c);
1087
+ if (c.stakePool?.id)
1088
+ out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
1089
+ if (c.delegateRepresentative)
1090
+ out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: drepId(c.delegateRepresentative) });
1091
+ break;
1092
+ }
1093
+ case 'stakePoolRegistration':
1094
+ out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
1095
+ break;
1096
+ case 'stakePoolRetirement':
1097
+ out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
1098
+ break;
1099
+ case 'delegateRepresentativeRegistration':
1100
+ out.push({ certIndex, kind: 'drep_registration', drepId: drepId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1101
+ break;
1102
+ case 'delegateRepresentativeUpdate':
1103
+ out.push({ certIndex, kind: 'drep_update', drepId: drepId(c.delegateRepresentative) });
1104
+ break;
1105
+ case 'delegateRepresentativeRetirement':
1106
+ out.push({ certIndex, kind: 'drep_retirement', drepId: drepId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1107
+ break;
1108
+ case 'constitutionalCommitteeDelegation':
1109
+ out.push({ certIndex, kind: 'committee_hot_auth' });
1110
+ break;
1111
+ case 'constitutionalCommitteeRetirement':
1112
+ out.push({ certIndex, kind: 'committee_resign' });
1113
+ break;
1114
+ case 'genesisDelegation':
1115
+ out.push({ certIndex, kind: 'genesis_delegation' });
1116
+ break;
1117
+ default:
1118
+ out.push({ certIndex, kind: c.type });
1119
+ }
1120
+ });
1121
+ return out;
1018
1122
  }
1019
1123
  }
1020
1124
  exports.OgmiosBackend = OgmiosBackend;
@@ -1,4 +1,4 @@
1
- import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend } from './backends/cardano-backend';
1
+ import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend } from './backends/cardano-backend';
2
2
  import { type CircuitBreakerConfig } from './circuit-breaker';
3
3
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
4
4
  export type Network = 'mainnet' | 'preview' | 'preprod';
@@ -254,6 +254,8 @@ export declare class CardanoClient {
254
254
  * Without this the crawler would stay on pagination for the rest of the process.
255
255
  */
256
256
  recoverChainSyncBackend(): Promise<ChainSyncBackend | null>;
257
+ /** The first usable backend that can dump the UTxO set at a point (Ogmios) — crawler.utxoSet import. */
258
+ getLedgerStateBackend(): LedgerStateBackend | null;
257
259
  /**
258
260
  * Get a backend that can enumerate the full pool/DRep set (Koios), or null. Used by the
259
261
  * crawler's epoch-boundary snapshots; without one they stay off rather than degrade into
@@ -567,6 +567,15 @@ class CardanoClient {
567
567
  }
568
568
  return null;
569
569
  }
570
+ /** The first usable backend that can dump the UTxO set at a point (Ogmios) — crawler.utxoSet import. */
571
+ getLedgerStateBackend() {
572
+ const candidates = [this.liveBackend, ...this.historicalBackends];
573
+ for (const b of candidates) {
574
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isLedgerStateBackend)(b))
575
+ return b;
576
+ }
577
+ return null;
578
+ }
570
579
  /**
571
580
  * Get a backend that can enumerate the full pool/DRep set (Koios), or null. Used by the
572
581
  * crawler's epoch-boundary snapshots; without one they stay off rather than degrade into