@odatano/core 2.0.0-rc.21 → 2.0.0-rc.24

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 (45) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +18 -0
  4. package/@cds-models/CardanoIndexerService/index.js +3 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +37 -0
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/odatano/cardano/index.d.ts +37 -0
  8. package/@cds-models/odatano/cardano/index.js +3 -0
  9. package/db/schema.cds +2226 -2133
  10. package/package.json +182 -181
  11. package/srv/blockchain/backends/cardano-backend.d.ts +23 -0
  12. package/srv/blockchain/backends/cardano-backend.js +5 -0
  13. package/srv/blockchain/backends/odatano-backend.d.ts +59 -0
  14. package/srv/blockchain/backends/odatano-backend.js +154 -0
  15. package/srv/blockchain/backends/ogmios-backend.d.ts +92 -9
  16. package/srv/blockchain/backends/ogmios-backend.js +164 -32
  17. package/srv/blockchain/cardano-client.d.ts +19 -5
  18. package/srv/blockchain/cardano-client.js +53 -12
  19. package/srv/blockchain/cardano-indexer.d.ts +100 -4
  20. package/srv/blockchain/cardano-indexer.js +466 -23
  21. package/srv/blockchain/cardano-tx-builder.js +2 -2
  22. package/srv/blockchain/crawler/crawler.d.ts +20 -5
  23. package/srv/blockchain/crawler/crawler.js +78 -15
  24. package/srv/blockchain/crawler/utxo-set-import.js +3 -0
  25. package/srv/blockchain/ledger-state.d.ts +6 -0
  26. package/srv/blockchain/ledger-state.js +29 -0
  27. package/srv/blockchain/stored-chain.d.ts +30 -0
  28. package/srv/blockchain/stored-chain.js +208 -0
  29. package/srv/cardano-backend-service.cds +52 -0
  30. package/srv/cardano-backend-service.d.ts +2 -0
  31. package/srv/cardano-backend-service.js +217 -0
  32. package/srv/cardano-indexer-service.cds +176 -164
  33. package/srv/cardano-indexer-service.js +30 -0
  34. package/srv/cardano-service.cds +6 -1
  35. package/srv/cardano-service.js +5 -2
  36. package/srv/server.js +19 -2
  37. package/srv/utils/agent-grants.js +7 -0
  38. package/srv/utils/const.d.ts +4 -0
  39. package/srv/utils/const.js +4 -3
  40. package/srv/utils/db-indexes.js +1 -0
  41. package/srv/utils/errors.d.ts +8 -0
  42. package/srv/utils/errors.js +14 -1
  43. package/srv/utils/mappers.d.ts +19 -2
  44. package/srv/utils/mappers.js +25 -7
  45. package/srv/utils/types.d.ts +8 -1
@@ -27,7 +27,7 @@ export interface CrawlerConfig {
27
27
  assetCatalogue: 'off' | 'bare' | 'enrich';
28
28
  /** Units per second the background enrichment resolves (`assetCatalogue: 'enrich'` only). */
29
29
  assetEnrichRate: number;
30
- /** Snapshot every pool and DRep at each epoch boundary. Requires an enumerating backend (Koios). */
30
+ /** Snapshot every pool, DRep and the ada pots at each epoch boundary (Ogmios, or Koios at the tip). */
31
31
  epochSnapshots: boolean;
32
32
  /**
33
33
  * Write TransactionCertificates + TransactionWithdrawals per block (ledger-state
@@ -39,6 +39,11 @@ export interface CrawlerConfig {
39
39
  * Needs a one-off snapshot import (`importUtxoSet`) to become active.
40
40
  */
41
41
  utxoSet: boolean;
42
+ /**
43
+ * Treat the crawled chain as complete: a block, transaction, metadata or asset the database
44
+ * does not hold is answered 404 instead of asking a provider (crawl from Shelley, synced).
45
+ */
46
+ authoritative?: boolean;
42
47
  }
43
48
  /**
44
49
  * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
@@ -89,13 +94,19 @@ export declare class CardanoCrawler {
89
94
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
90
95
  private readonly inFlightCallbacks;
91
96
  private haltPromise;
92
- /** An unparseable chain-sync frame; the ingest loop fetches that block via pagination, then reopens chain-sync. */
97
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
93
98
  private frameFailure;
99
+ /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
100
+ private reopenStream;
101
+ /** Blocks persisted by the current chain-sync stream. */
102
+ private blocksThisStream;
94
103
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
95
104
  private streamEnded;
96
105
  private finalStatus;
97
106
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
98
107
  private latchOnHalt;
108
+ /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
109
+ private static readonly SNAPSHOT_WINDOW_MARGIN;
99
110
  /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
100
111
  private snapshotedEpoch;
101
112
  private snapshotInFlight;
@@ -156,6 +167,8 @@ export declare class CardanoCrawler {
156
167
  * past the offending block. The error is recorded first so `lastError` names the block.
157
168
  */
158
169
  private degradeToPagination;
170
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
171
+ private endStream;
159
172
  /**
160
173
  * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
161
174
  * ancestors, then the configured start block. If the cursor's block was orphaned while the
@@ -191,9 +204,11 @@ export declare class CardanoCrawler {
191
204
  /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
192
205
  private epochOfSlot;
193
206
  /**
194
- * Pool/DRep snapshot once per epoch, detached from the triggering block and ONLY at the tip:
195
- * the enumerating providers report current state (no epoch parameter), so epochs passed
196
- * during a backfill are skipped permanently. Authority is the `PoolEpochSnapshots` row.
207
+ * Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
208
+ * state is read AT the block, which works while the block is inside the node's volatile window
209
+ * (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
210
+ * tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
211
+ * `EpochLedgerSnapshots` (or a pool row written before the marker existed).
197
212
  */
198
213
  private maybeSnapshotEpoch;
199
214
  /**
@@ -80,13 +80,19 @@ class CardanoCrawler {
80
80
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
81
81
  inFlightCallbacks = new Set();
82
82
  haltPromise = null;
83
- /** An unparseable chain-sync frame; the ingest loop fetches that block via pagination, then reopens chain-sync. */
83
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
84
84
  frameFailure = null;
85
+ /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
86
+ reopenStream = false;
87
+ /** Blocks persisted by the current chain-sync stream. */
88
+ blocksThisStream = 0;
85
89
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
86
90
  streamEnded = null;
87
91
  finalStatus = 'stopped';
88
92
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
89
93
  latchOnHalt = false;
94
+ /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
95
+ static SNAPSHOT_WINDOW_MARGIN = 10;
90
96
  /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
91
97
  snapshotedEpoch = null;
92
98
  snapshotInFlight = null;
@@ -152,6 +158,7 @@ class CardanoCrawler {
152
158
  assetEnrichRate: this.config.assetEnrichRate,
153
159
  certificates: this.config.certificates,
154
160
  utxoSet: this.config.utxoSet,
161
+ authoritative: this.config.authoritative ?? false,
155
162
  });
156
163
  // Ledger state is only ever applied from a known anchor — no snapshot, no writes.
157
164
  if (this.config.utxoSet) {
@@ -167,6 +174,7 @@ class CardanoCrawler {
167
174
  }
168
175
  if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
169
176
  this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
177
+ void this.indexer.paymentCredentialsReady();
170
178
  logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
171
179
  }
172
180
  else {
@@ -276,7 +284,13 @@ class CardanoCrawler {
276
284
  return; // open refused, halted, or stop() raced us
277
285
  await streamEnd;
278
286
  const failure = this.takeFrameFailure();
279
- if (!this.running || failure?.height == null)
287
+ if (!this.running)
288
+ return;
289
+ if (this.reopenStream) {
290
+ this.reopenStream = false;
291
+ continue;
292
+ }
293
+ if (failure?.height == null)
280
294
  return;
281
295
  logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
282
296
  await this.runPagination({ untilHeight: failure.height + 1 });
@@ -373,11 +387,13 @@ class CardanoCrawler {
373
387
  await this.halt('error', true); // config error: a restart cannot fix it
374
388
  return;
375
389
  }
390
+ this.blocksThisStream = 0;
376
391
  const handle = await backend.openChainSync(points, {
377
392
  rollForward: (block, txs, tip) => this.trackCallback(async () => {
378
393
  if (!this.running)
379
394
  return;
380
- await this.persistBlock(block, txs, tip);
395
+ if (await this.persistBlock(block, txs, tip))
396
+ this.blocksThisStream++;
381
397
  }),
382
398
  rollBackward: (point) => this.trackCallback(async () => {
383
399
  if (!this.running)
@@ -401,6 +417,21 @@ class CardanoCrawler {
401
417
  await this.degradeToPagination(err);
402
418
  return;
403
419
  }
420
+ // The server dropped the socket. After progress: reopen at the cursor. Without progress
421
+ // the server fails on the next block itself (e.g. a header it cannot decode): fetch that
422
+ // block over pagination, then chain-sync takes over again.
423
+ if (err instanceof errors_1.ChainSyncClosedError) {
424
+ if (this.blocksThisStream > 0) {
425
+ logger.warn(`${err.message} after ${this.blocksThisStream} block(s) — reopening chain-sync at the cursor`);
426
+ await this.endStream(() => { this.reopenStream = true; });
427
+ return;
428
+ }
429
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
430
+ if (cursor && this.config.source !== 'ogmios' && this.client.getPaginatingBackend()) {
431
+ await this.degradeToPagination(new errors_1.ChainSyncStalledError(cursor.lastHeight + 1, err.message));
432
+ return;
433
+ }
434
+ }
404
435
  // The stream is stalled (mapping/callback failure) — record and halt cleanly
405
436
  // so the cursor status shows 'error' instead of a healthy-looking hang.
406
437
  const streak = await this.recordCrawlerError(err);
@@ -445,8 +476,12 @@ class CardanoCrawler {
445
476
  await this.halt('stopped');
446
477
  return;
447
478
  }
448
- logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
449
- this.frameFailure = err;
479
+ logger.error('Chain-sync cannot deliver a block — continuing on pagination:', err.message);
480
+ await this.endStream(() => { this.frameFailure = err; });
481
+ }
482
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
483
+ async endStream(mark) {
484
+ mark();
450
485
  const handle = this.chainSyncHandle;
451
486
  this.chainSyncHandle = null;
452
487
  if (handle) {
@@ -777,9 +812,11 @@ class CardanoCrawler {
777
812
  return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
778
813
  }
779
814
  /**
780
- * Pool/DRep snapshot once per epoch, detached from the triggering block and ONLY at the tip:
781
- * the enumerating providers report current state (no epoch parameter), so epochs passed
782
- * during a backfill are skipped permanently. Authority is the `PoolEpochSnapshots` row.
815
+ * Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
816
+ * state is read AT the block, which works while the block is inside the node's volatile window
817
+ * (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
818
+ * tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
819
+ * `EpochLedgerSnapshots` (or a pool row written before the marker existed).
783
820
  */
784
821
  maybeSnapshotEpoch(block, tip) {
785
822
  if (!this.config.epochSnapshots || block.epoch == null)
@@ -791,20 +828,38 @@ class CardanoCrawler {
791
828
  logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
792
829
  return;
793
830
  }
794
- const tipEpoch = this.epochOfSlot(tip.slot);
795
- if (block.epoch !== tipEpoch) {
796
- logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
797
- `the pool/DRep set can only be observed as it is now, never as it was`);
798
- return;
831
+ const fromLedger = this.client.getEpochStateBackend() != null && !!block.hash;
832
+ if (fromLedger) {
833
+ const k = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]?.securityParam
834
+ ?? const_1.EPOCH_CONFIG_BY_NETWORK.mainnet.securityParam;
835
+ const behind = tip.height != null && block.height != null ? tip.height - block.height : null;
836
+ if (behind == null || behind >= k - CardanoCrawler.SNAPSHOT_WINDOW_MARGIN) {
837
+ logger.debug(`epoch ${block.epoch} snapshot skipped at height ${block.height}: ${behind ?? '?'} blocks behind the tip, outside the node's volatile window (k=${k})`);
838
+ return;
839
+ }
840
+ }
841
+ else {
842
+ const tipEpoch = this.epochOfSlot(tip.slot);
843
+ if (block.epoch !== tipEpoch) {
844
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
845
+ `the provider reports the pool/DRep set as it is now, never as it was`);
846
+ return;
847
+ }
799
848
  }
800
849
  if (Date.now() < this.snapshotRetryAfter)
801
850
  return;
802
851
  const epoch = block.epoch;
803
- const at = { slot: block.slot ?? 0, time: block.time ?? 0 };
852
+ const at = { slot: block.slot ?? 0, time: block.time ?? 0, hash: fromLedger ? block.hash : null };
804
853
  this.snapshotInFlight = this.trackCallback(async () => {
805
- const existing = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch })));
854
+ const existing = await cds_1.default.tx(async (tx) => (await tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch').where({ epoch })))
855
+ ?? (await tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch }))));
806
856
  if (!existing) {
807
857
  await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
858
+ const previous = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('max(epoch) as e').where({ epoch: { '<': epoch } })));
859
+ const last = previous?.e == null ? null : Number(previous.e);
860
+ if (last != null && epoch > last + 1) {
861
+ logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1} — passed outside the snapshot window`);
862
+ }
808
863
  }
809
864
  this.snapshotedEpoch = epoch;
810
865
  this.snapshotFailures = 0;
@@ -870,6 +925,12 @@ class CardanoCrawler {
870
925
  await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
871
926
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
872
927
  }
928
+ // Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
929
+ if (blocksRolledBack > 0) {
930
+ for (const entity of [cardano_1.PoolEpochSnapshots, cardano_1.DrepEpochSnapshots, cardano_1.EpochLedgerSnapshots]) {
931
+ await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
932
+ }
933
+ }
873
934
  // Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
874
935
  // progress marker follows the cursor back; a fork before the anchor invalidates the set.
875
936
  const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
@@ -916,6 +977,8 @@ class CardanoCrawler {
916
977
  }
917
978
  // Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
918
979
  // the rollback commit.
980
+ // The rollback may have removed this epoch's snapshot; the next block re-checks it.
981
+ this.snapshotedEpoch = null;
919
982
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
920
983
  logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
921
984
  }
@@ -244,6 +244,9 @@ async function importUtxoSet(opts) {
244
244
  await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
245
245
  });
246
246
  opts.indexer.setUtxoAnchor(anchor);
247
+ // The aggregation leaves paymentCredential empty; filled in the background.
248
+ opts.indexer.resetPaymentCredentials();
249
+ void opts.indexer.paymentCredentialsReady();
247
250
  logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
248
251
  return { utxos: imported, anchor };
249
252
  }
@@ -77,4 +77,10 @@ export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes:
77
77
  export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
78
78
  /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
79
79
  export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
80
+ /**
81
+ * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
82
+ * aggregation, or written before the column existed). One transaction per chunk, idempotent.
83
+ * @returns rows updated
84
+ */
85
+ export declare function backfillPaymentCredentials(chunkSize?: number): Promise<number>;
80
86
  //# sourceMappingURL=ledger-state.d.ts.map
@@ -8,6 +8,7 @@ exports.applyBlockToLedger = applyBlockToLedger;
8
8
  exports.undoLedgerForTransactions = undoLedgerForTransactions;
9
9
  exports.recountLedgerAddresses = recountLedgerAddresses;
10
10
  exports.recountLedgerAccounts = recountLedgerAccounts;
11
+ exports.backfillPaymentCredentials = backfillPaymentCredentials;
11
12
  const cds_1 = __importDefault(require("@sap/cds"));
12
13
  const cardano_1 = require("#cds-models/odatano/cardano");
13
14
  const mappers_1 = require("../utils/mappers");
@@ -208,6 +209,7 @@ async function applyBlockToLedger(tx, block, txs) {
208
209
  addressRows.push({
209
210
  address,
210
211
  stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
212
+ paymentCredential: (0, mappers_1.decodeShelleyAddress)(address).paymentCredential,
211
213
  addressType: prev?.addressType ?? d.addressType,
212
214
  isScript: prev ? Boolean(prev.isScript) : d.isScript,
213
215
  totalLovelace: total.toString(),
@@ -325,6 +327,7 @@ async function recountLedgerAddresses(tx, addresses) {
325
327
  await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
326
328
  address,
327
329
  stakeAddress,
330
+ paymentCredential: decoded.paymentCredential,
328
331
  addressType: prev?.addressType ?? decoded.type,
329
332
  isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
330
333
  totalLovelace: total.toString(),
@@ -380,4 +383,30 @@ async function recountLedgerAccounts(tx, stakeAddresses) {
380
383
  await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
381
384
  }
382
385
  }
386
+ /** Address types that carry a payment credential. */
387
+ const CREDENTIAL_ADDRESS_TYPES = ['base', 'pointer', 'enterprise'];
388
+ /**
389
+ * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
390
+ * aggregation, or written before the column existed). One transaction per chunk, idempotent.
391
+ * @returns rows updated
392
+ */
393
+ async function backfillPaymentCredentials(chunkSize = 1000) {
394
+ let updated = 0;
395
+ for (;;) {
396
+ const n = await cds_1.default.tx(async (tx) => {
397
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('address')
398
+ .where({ paymentCredential: null, addressType: { in: CREDENTIAL_ADDRESS_TYPES } })
399
+ .limit(chunkSize));
400
+ for (const { address } of rows ?? []) {
401
+ // '' marks an address that decodes without a credential, so it is not picked again
402
+ const credential = (0, mappers_1.decodeShelleyAddress)(address).paymentCredential ?? '';
403
+ await tx.run(UPDATE.entity(cardano_1.LedgerAddresses).set({ paymentCredential: credential }).where({ address }));
404
+ }
405
+ return (rows ?? []).length;
406
+ });
407
+ updated += n;
408
+ if (n < chunkSize)
409
+ return updated;
410
+ }
411
+ }
383
412
  //# sourceMappingURL=ledger-state.js.map
@@ -0,0 +1,30 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
+ /**
4
+ * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
+ * serving other ODATANO instances from what this one has indexed. Not stored, so absent: the
6
+ * phase-2 flag (`spendsCollaterals`), `totalCollateral` and `outputAmount`.
7
+ */
8
+ type Row = Record<string, unknown>;
9
+ /** `Blocks` row -> BlockData. */
10
+ export declare function blockRowToData(row: Row): BlockData;
11
+ /** A stored block by hash; null when not indexed. */
12
+ export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
13
+ /** A stored block by height; null when not indexed. */
14
+ export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
15
+ /**
16
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
17
+ * the first missing height, so a caller never walks over a gap.
18
+ */
19
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
20
+ /** Stored transactions by hash (missing hashes are absent from the map). */
21
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
22
+ /**
23
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
24
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
25
+ */
26
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
27
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
28
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
29
+ export {};
30
+ //# sourceMappingURL=stored-chain.d.ts.map
@@ -0,0 +1,208 @@
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.blockRowToData = blockRowToData;
7
+ exports.readBlock = readBlock;
8
+ exports.readBlockByHeight = readBlockByHeight;
9
+ exports.readNextBlocks = readNextBlocks;
10
+ exports.readTransactionsByHash = readTransactionsByHash;
11
+ exports.readBlockTransactions = readBlockTransactions;
12
+ exports.readTransactionMetadata = readTransactionMetadata;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const client_1 = require("@cardano-ogmios/client");
15
+ const cardano_1 = require("#cds-models/odatano/cardano");
16
+ const collections_1 = require("../utils/collections");
17
+ const { SELECT } = cds_1.default.ql;
18
+ const num = (v) => Number(v ?? 0);
19
+ const numOrNull = (v) => (v == null ? null : Number(v));
20
+ const str = (v) => (v == null ? '' : String(v));
21
+ /** `Blocks` row -> BlockData. */
22
+ function blockRowToData(row) {
23
+ return {
24
+ time: Math.floor(Date.parse(str(row.time)) / 1000),
25
+ height: numOrNull(row.height),
26
+ hash: str(row.hash),
27
+ slot: numOrNull(row.slot),
28
+ slotLeader: str(row.slotLeader),
29
+ epoch: numOrNull(row.epochNumber),
30
+ epochSlot: numOrNull(row.epochSlot),
31
+ size: num(row.size),
32
+ txCount: num(row.txCount),
33
+ fees: row.fees == null ? null : String(row.fees),
34
+ };
35
+ }
36
+ /** A stored block by hash; null when not indexed. */
37
+ async function readBlock(db, hash) {
38
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ hash }));
39
+ return row ? blockRowToData(row) : null;
40
+ }
41
+ /** A stored block by height; null when not indexed. */
42
+ async function readBlockByHeight(db, height) {
43
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
44
+ return row ? blockRowToData(row) : null;
45
+ }
46
+ /**
47
+ * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
48
+ * the first missing height, so a caller never walks over a gap.
49
+ */
50
+ async function readNextBlocks(db, afterHeight, count) {
51
+ const rows = await db.run(SELECT.from(cardano_1.Blocks).where({ height: { '>': afterHeight, '<=': afterHeight + count } }).orderBy('height asc'));
52
+ const out = [];
53
+ let expected = afterHeight + 1;
54
+ for (const row of rows ?? []) {
55
+ if (num(row.height) !== expected)
56
+ break;
57
+ out.push(blockRowToData(row));
58
+ expected++;
59
+ }
60
+ return out;
61
+ }
62
+ /** Stored transactions by hash (missing hashes are absent from the map). */
63
+ async function readTransactionsByHash(db, hashes) {
64
+ const rows = [];
65
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
66
+ rows.push(...((await db.run(SELECT.from(cardano_1.Transactions).where({ hash: { in: hashChunk } }))) ?? []));
67
+ }
68
+ const txs = await assembleTransactions(db, rows);
69
+ return new Map(txs.map(t => [t.hash, t]));
70
+ }
71
+ /**
72
+ * Stored transactions of a block in block order; null when the block is not stored with all of its
73
+ * transactions (a lazily indexed block may hold only the ones somebody asked for).
74
+ */
75
+ async function readBlockTransactions(db, blockHash) {
76
+ const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
77
+ if (!block)
78
+ return null;
79
+ const rows = await db.run(SELECT.from(cardano_1.Transactions).where({ blockHash }).orderBy('txIndex asc'));
80
+ if ((rows ?? []).length !== num(block.txCount))
81
+ return null;
82
+ return assembleTransactions(db, rows ?? []);
83
+ }
84
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
85
+ async function readTransactionMetadata(db, txHash) {
86
+ const known = await db.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ hash: txHash }));
87
+ if (!known)
88
+ return null;
89
+ const rows = await db.run(SELECT.from(cardano_1.TransactionMetadata_).where({ tx_hash: txHash }));
90
+ return (rows ?? []).map(metadataRow);
91
+ }
92
+ function metadataRow(r) {
93
+ return {
94
+ txHash: str(r.tx_hash),
95
+ label: str(r.label),
96
+ json: r.payload == null ? undefined : client_1.safeJSON.parse(String(r.payload)),
97
+ };
98
+ }
99
+ /** Amount list with lovelace first, as the providers deliver it. */
100
+ function amounts(assets) {
101
+ const list = assets.map(a => ({ unit: str(a.unit), quantity: str(a.asset_quantity) }));
102
+ return [...list.filter(a => a.unit === 'lovelace'), ...list.filter(a => a.unit !== 'lovelace')];
103
+ }
104
+ function groupBy(rows, key) {
105
+ const out = new Map();
106
+ for (const r of rows) {
107
+ const k = key(r);
108
+ const list = out.get(k);
109
+ if (list)
110
+ list.push(r);
111
+ else
112
+ out.set(k, [r]);
113
+ }
114
+ return out;
115
+ }
116
+ /** Transactions rows + their child tables -> provider transactions, in the order of `rows`. */
117
+ async function assembleTransactions(db, rows) {
118
+ if (rows.length === 0)
119
+ return [];
120
+ const seqs = rows.map(r => r.txSeq);
121
+ const hashes = rows.map(r => str(r.hash));
122
+ const fetchIn = async (entity, column, keys) => {
123
+ const out = [];
124
+ for (const c of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
125
+ out.push(...((await db.run(SELECT.from(entity).where({ [column]: { in: c } }))) ?? []));
126
+ }
127
+ return out;
128
+ };
129
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints] = await Promise.all([
130
+ fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
131
+ fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
132
+ fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
133
+ fetchIn(cardano_1.TransactionOutputAssets, 'output_txSeq', seqs),
134
+ fetchIn(cardano_1.TransactionMetadata_, 'tx_hash', hashes),
135
+ fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
136
+ fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
137
+ fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
138
+ ]);
139
+ const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
140
+ const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
141
+ const outputsBySeq = groupBy(outputs, r => str(r.txSeq));
142
+ const outputAssetsByKey = groupBy(outputAssets, r => `${r.output_txSeq}#${r.output_outputIndex}`);
143
+ const metadataByHash = groupBy(metadata, r => str(r.tx_hash));
144
+ const certsByHash = groupBy(certificates, r => str(r.tx_hash));
145
+ const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
146
+ const mintsByHash = groupBy(mints, r => str(r.txHash));
147
+ return rows.map((t) => {
148
+ const seq = str(t.txSeq);
149
+ const hash = str(t.hash);
150
+ const txInputs = (inputsBySeq.get(seq) ?? [])
151
+ .sort((a, b) => num(a.inputIndex) - num(b.inputIndex))
152
+ .map(i => ({
153
+ address: str(i.address_address),
154
+ amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
155
+ txHash: str(i.spentTxHash),
156
+ outputIndex: num(i.spentOutputIndex),
157
+ dataHash: i.utxoData_dataHash ?? null,
158
+ inlineDatum: i.utxoData_inlineDatum ?? null,
159
+ referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
160
+ isCollateral: Boolean(i.isCollateral),
161
+ isReference: Boolean(i.isReference),
162
+ }));
163
+ const txOutputs = (outputsBySeq.get(seq) ?? [])
164
+ .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
165
+ .map(o => ({
166
+ address: str(o.address_address),
167
+ amount: amounts(outputAssetsByKey.get(`${seq}#${o.outputIndex}`) ?? []),
168
+ txHash: hash,
169
+ outputIndex: num(o.outputIndex),
170
+ dataHash: o.utxo_dataHash ?? null,
171
+ inlineDatum: o.utxo_inlineDatum ?? null,
172
+ isCollateral: false,
173
+ referenceScriptHash: o.utxo_referenceScriptHash ?? null,
174
+ }));
175
+ const certs = certsByHash.get(hash);
176
+ const withdrawn = withdrawalsByHash.get(hash);
177
+ const minted = mintsByHash.get(hash);
178
+ return {
179
+ hash,
180
+ blockHash: str(t.blockHash),
181
+ blockHeight: num(t.blockHeight),
182
+ slot: num(t.slot),
183
+ index: num(t.txIndex),
184
+ fee: str(t.fee ?? '0'),
185
+ deposit: str(t.deposit ?? '0'),
186
+ size: numOrNull(t.size),
187
+ blockTime: num(t.blockTime),
188
+ mint: minted?.map(m => ({
189
+ unit: str(m.unit),
190
+ quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
191
+ })),
192
+ inputs: txInputs,
193
+ outputs: txOutputs,
194
+ metadata: (metadataByHash.get(hash) ?? []).map(metadataRow),
195
+ certificates: certs?.map((c) => ({
196
+ certIndex: num(c.certIndex),
197
+ kind: str(c.kind),
198
+ stakeAddress: c.stakeAddress ?? null,
199
+ poolId: c.poolId ?? null,
200
+ drepId: c.drepId ?? null,
201
+ deposit: c.deposit == null ? null : String(c.deposit),
202
+ epoch: numOrNull(c.epoch),
203
+ })),
204
+ withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
205
+ };
206
+ });
207
+ }
208
+ //# sourceMappingURL=stored-chain.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Cardano Backend Service
3
+ *
4
+ * The data a CardanoBackend needs, for another ODATANO instance that uses this one as its
5
+ * backend (`backends: ["odatano"]`). Every operation answers the provider shape as a JSON
6
+ * string (`value`), so the caller maps it exactly like a Koios or Blockfrost answer.
7
+ * Stored blocks and transactions come from this instance's index; everything else goes
8
+ * through its own backends and crawled data, as the read service does. Nothing is persisted
9
+ * for the caller.
10
+ */
11
+ @requires: 'authenticated-user'
12
+ service CardanoBackendService @(impl: './cardano-backend-service') {
13
+
14
+ // --- blocks and transactions -------------------------------------------------------------
15
+ action GetTransaction(hash: String) returns LargeString;
16
+ action GetTransactionsBatch(hashes: LargeString) returns LargeString;
17
+ action GetTransactionMetadata(hash: String) returns LargeString;
18
+ action GetBlock(hash: String) returns LargeString;
19
+ action GetBlockByHeight(height: Integer64) returns LargeString;
20
+ action GetNextBlocks(afterHash: String, count: Integer, afterHeight: Integer64) returns LargeString;
21
+ action GetBlockTransactions(blockHash: String) returns LargeString;
22
+ action GetLatestBlock() returns LargeString;
23
+ action GetCurrentSlot() returns LargeString;
24
+ action GetEpoch(epoch: Integer) returns LargeString;
25
+ action GetLatestEpoch() returns LargeString;
26
+
27
+ // --- addresses and UTxOs ------------------------------------------------------------------
28
+ action GetAddress(address: String) returns LargeString;
29
+ action GetAddressUtxos(address: String) returns LargeString;
30
+ action GetAddressTransactions(address: String, limit: Integer) returns LargeString;
31
+ action GetAddressTransactionHashes(address: String, limit: Integer) returns LargeString;
32
+ action GetCredentialUtxos(credential: String) returns LargeString;
33
+ action IsUtxoUnspent(txHash: String, outputIndex: Integer) returns LargeString;
34
+ action GetUnspentOutputs(refs: LargeString) returns LargeString;
35
+
36
+ // --- stake, governance, assets, network ------------------------------------------------
37
+ action GetAccount(stakeAddress: String) returns LargeString;
38
+ action GetPool(poolId: String) returns LargeString;
39
+ action GetPoolIds() returns LargeString;
40
+ action GetPools(ids: LargeString) returns LargeString;
41
+ action GetDrep(drepId: String) returns LargeString;
42
+ action GetDrepIds() returns LargeString;
43
+ action GetDreps(ids: LargeString) returns LargeString;
44
+ action GetAssetInfo(unit: String) returns LargeString;
45
+ action GetAssetHistory(unit: String, limit: Integer) returns LargeString;
46
+ action GetNetworkInformation() returns LargeString;
47
+ action GetProtocolParameters() returns LargeString;
48
+
49
+ // --- transactions in flight ------------------------------------------------------------
50
+ action EvaluateTransaction(cbor: LargeString) returns LargeString;
51
+ action SubmitTransaction(cbor: LargeString) returns LargeString;
52
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-backend-service.d.ts.map