@odatano/core 2.0.0-rc.10 → 2.0.0-rc.12

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 (32) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +54 -0
  2. package/@cds-models/CardanoODataService/index.js +6 -0
  3. package/@cds-models/odatano/cardano/index.d.ts +54 -0
  4. package/@cds-models/odatano/cardano/index.js +6 -0
  5. package/db/schema.cds +1844 -1738
  6. package/package.json +1 -1
  7. package/srv/blockchain/backends/blockfrost-backend.js +7 -2
  8. package/srv/blockchain/backends/cardano-backend.d.ts +22 -0
  9. package/srv/blockchain/backends/cardano-backend.js +9 -0
  10. package/srv/blockchain/backends/koios-backend.d.ts +34 -2
  11. package/srv/blockchain/backends/koios-backend.js +133 -39
  12. package/srv/blockchain/backends/ogmios-backend.d.ts +6 -1
  13. package/srv/blockchain/backends/ogmios-backend.js +27 -2
  14. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  15. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  16. package/srv/blockchain/cardano-client.d.ts +8 -1
  17. package/srv/blockchain/cardano-client.js +14 -0
  18. package/srv/blockchain/cardano-indexer.d.ts +127 -0
  19. package/srv/blockchain/cardano-indexer.js +345 -3
  20. package/srv/blockchain/crawler/crawler.d.ts +88 -0
  21. package/srv/blockchain/crawler/crawler.js +180 -2
  22. package/srv/cardano-service.cds +10 -0
  23. package/srv/server.js +26 -1
  24. package/srv/utils/const.d.ts +1 -1
  25. package/srv/utils/const.js +1 -1
  26. package/srv/utils/errors.d.ts +18 -0
  27. package/srv/utils/errors.js +24 -1
  28. package/srv/utils/mappers.d.ts +54 -1
  29. package/srv/utils/mappers.js +111 -0
  30. package/srv/utils/types.d.ts +27 -0
  31. package/srv/utils/validators.d.ts +1 -1
  32. package/srv/utils/validators.js +2 -2
@@ -7,6 +7,7 @@ exports.CardanoCrawler = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const errors_1 = require("../../utils/errors");
9
9
  const collections_1 = require("../../utils/collections");
10
+ const const_1 = require("../../utils/const");
10
11
  const hooks_1 = require("./hooks");
11
12
  const cardano_1 = require("#cds-models/odatano/cardano");
12
13
  const sync_state_1 = require("./sync-state");
@@ -71,6 +72,18 @@ class CardanoCrawler {
71
72
  ];
72
73
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
73
74
  static CALL_TIMEOUT_MS = 60_000;
75
+ /**
76
+ * Epoch snapshots are ~100 batched provider requests on mainnet, so they get a wider
77
+ * bound than an ordinary call — still bounded, and cancelled by beginHalt.
78
+ */
79
+ static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
80
+ /**
81
+ * Backoff after a failed snapshot attempt, doubling up to the cap. Without it a provider
82
+ * outage would re-trigger a full pool/DRep enumeration on every single block for the rest
83
+ * of the epoch — the marker is only set on success, by design.
84
+ */
85
+ static SNAPSHOT_RETRY_BASE_MS = 30_000;
86
+ static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
74
87
  running = false;
75
88
  chainSyncHandle = null;
76
89
  /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
@@ -82,9 +95,23 @@ class CardanoCrawler {
82
95
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
83
96
  inFlightCallbacks = new Set();
84
97
  haltPromise = null;
98
+ /**
99
+ * Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
100
+ * block, so the ingest loop takes it through the paginating backend and then reopens
101
+ * chain-sync — see runIngestPipeline().
102
+ */
103
+ frameFailure = null;
104
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
105
+ streamEnded = null;
85
106
  finalStatus = 'stopped';
86
107
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
87
108
  latchOnHalt = false;
109
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
110
+ snapshotedEpoch = null;
111
+ snapshotInFlight = null;
112
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
113
+ snapshotFailures = 0;
114
+ snapshotRetryAfter = 0;
88
115
  leaseHeld = false;
89
116
  leaseHeartbeat = null;
90
117
  leaseWake = null;
@@ -133,6 +160,12 @@ class CardanoCrawler {
133
160
  }
134
161
  }
135
162
  this.running = true;
163
+ // Hand the analytics coverage to the indexer before the first block is written.
164
+ this.indexer.configureCrawlCoverage({
165
+ assetHistory: this.config.assetHistory,
166
+ assetCatalogue: this.config.assetCatalogue,
167
+ assetEnrichRate: this.config.assetEnrichRate,
168
+ });
136
169
  this.startLeaseHeartbeat();
137
170
  // A pipeline crash (e.g. chain-sync intersection not found after downtime) must
138
171
  // surface on the cursor — otherwise the crawler looks healthy while doing nothing.
@@ -184,7 +217,10 @@ class CardanoCrawler {
184
217
  if (this.finalStatus !== 'error' || finalStatus === 'error')
185
218
  this.finalStatus = finalStatus;
186
219
  this.running = false;
220
+ // Background asset enrichment belongs to the crawl — it must not outlive it.
221
+ this.indexer.stopAssetEnrichment();
187
222
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
223
+ this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
188
224
  this.leaseWake?.();
189
225
  for (const cancel of [...this.callCancels])
190
226
  cancel();
@@ -226,7 +262,22 @@ class CardanoCrawler {
226
262
  async runIngestPipeline() {
227
263
  const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
228
264
  if (chainSync) {
229
- await this.runChainSync(chainSync);
265
+ // One pass per chain-sync stream. A frame the client's parser cannot turn into an
266
+ // object ends the stream without ending the crawler: pagination fetches that one
267
+ // block over HTTP, and chain-sync takes over again as soon as it is behind the
268
+ // cursor. Any other stream error still halts, as it always did.
269
+ while (this.running) {
270
+ const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
271
+ await this.runChainSync(chainSync);
272
+ if (!this.chainSyncHandle)
273
+ return; // open refused, halted, or stop() raced us
274
+ await streamEnd;
275
+ const failure = this.takeFrameFailure();
276
+ if (!this.running || failure?.height == null)
277
+ return;
278
+ logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
279
+ await this.runPagination(failure.height + 1);
280
+ }
230
281
  return;
231
282
  }
232
283
  if (this.config.source === 'ogmios') {
@@ -293,6 +344,12 @@ class CardanoCrawler {
293
344
  onError: (err) => this.trackCallback(async () => {
294
345
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
295
346
  return;
347
+ // A frame the client's parser cannot handle is a fault of that one block, not of the
348
+ // crawler or the node — pagination can still fetch it, so degrade instead of halting.
349
+ if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
350
+ await this.degradeToPagination(err);
351
+ return;
352
+ }
296
353
  // The stream is stalled (mapping/callback failure) — record and halt cleanly
297
354
  // so the cursor status shows 'error' instead of a healthy-looking hang.
298
355
  const streak = await this.recordCrawlerError(err);
@@ -311,6 +368,49 @@ class CardanoCrawler {
311
368
  this.chainSyncHandle = handle;
312
369
  logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
313
370
  }
371
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
372
+ takeFrameFailure() {
373
+ const failure = this.frameFailure;
374
+ this.frameFailure = null;
375
+ return failure;
376
+ }
377
+ /**
378
+ * Can this unparseable frame be worked around by fetching the block over HTTP instead?
379
+ *
380
+ * Requires a height to walk to, a paginating backend to walk with, and an operator who has
381
+ * not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
382
+ * degrading to the weaker pagination reorg handling would defeat the point of it.
383
+ */
384
+ canDegradeToPagination(err) {
385
+ return err.height != null
386
+ && this.config.source !== 'ogmios'
387
+ && !!this.client.getPaginatingBackend();
388
+ }
389
+ /**
390
+ * End the chain-sync stream and hand control back to the ingest loop, which continues on
391
+ * pagination past the offending block. Records the error first, so `lastError` names the
392
+ * block rather than leaving the empty status a crashed process used to leave behind.
393
+ */
394
+ async degradeToPagination(err) {
395
+ const streak = await this.recordCrawlerError(err);
396
+ if (streak < 0) {
397
+ await this.halt('stopped');
398
+ return;
399
+ }
400
+ logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
401
+ this.frameFailure = err;
402
+ const handle = this.chainSyncHandle;
403
+ this.chainSyncHandle = null;
404
+ if (handle) {
405
+ try {
406
+ await handle.close();
407
+ }
408
+ catch (e) {
409
+ logger.warn('chain-sync close failed:', e);
410
+ }
411
+ }
412
+ this.streamEnded?.();
413
+ }
314
414
  /**
315
415
  * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
316
416
  * spaced ladder of our own already-crawled ancestors, then the configured start
@@ -370,7 +470,13 @@ class CardanoCrawler {
370
470
  // ---------------------------------------------------------------------------
371
471
  // Pagination (Blockfrost/Koios) — fallback
372
472
  // ---------------------------------------------------------------------------
373
- async runPagination() {
473
+ /**
474
+ * @param untilHeight when set, return as soon as the cursor has reached it instead of
475
+ * looping forever. Used to walk past a block the chain-sync stream cannot deliver and
476
+ * then hand back to it — pagination is roughly seven times slower, so staying on it
477
+ * for the rest of a backfill would be a poor trade.
478
+ */
479
+ async runPagination(untilHeight) {
374
480
  const backend = this.client.getPaginatingBackend();
375
481
  if (!backend) {
376
482
  logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
@@ -391,6 +497,10 @@ class CardanoCrawler {
391
497
  await this.halt('error', true); // broken precondition: a restart cannot fix it
392
498
  return;
393
499
  }
500
+ if (untilHeight != null && cursor.lastHeight >= untilHeight) {
501
+ logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
502
+ return;
503
+ }
394
504
  if (!tip || cursor.lastHeight >= target) {
395
505
  tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
396
506
  target = (tip.height ?? 0) - this.config.confirmationDepth;
@@ -549,6 +659,7 @@ class CardanoCrawler {
549
659
  tipSlot: tip?.slot ?? null,
550
660
  tipHeight: tip?.height ?? null,
551
661
  });
662
+ this.maybeSnapshotEpoch(block, tip);
552
663
  return true;
553
664
  }
554
665
  catch (err) {
@@ -589,6 +700,73 @@ class CardanoCrawler {
589
700
  }
590
701
  }
591
702
  }
703
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
704
+ epochOfSlot(slot) {
705
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
706
+ ?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
707
+ return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
708
+ }
709
+ /**
710
+ * Take the epoch snapshot of pools and DReps once per epoch, detached from the block that
711
+ * triggered it (v2.0 analytics coverage, opt-in via `epochSnapshots`).
712
+ *
713
+ * ONLY AT THE TIP. The providers that can enumerate the pool and DRep set report their
714
+ * CURRENT state — Koios `/pool_info` and `/drep_info` take no epoch parameter. Snapshotting
715
+ * while the crawl is still backfilling would therefore write today's stake and vote power
716
+ * under every historical epoch number it passes: a table that reads as a time series but is
717
+ * a constant. So the block's epoch must be the epoch the reported tip is in; otherwise the
718
+ * epoch is skipped, permanently and by design. Backfilled ranges have no snapshots, live
719
+ * ones do.
720
+ *
721
+ * Detached on purpose: the snapshot is a few thousand rows plus ~100 provider requests, and
722
+ * the crawl must not wait for it or fail because of it. It is tracked as an in-flight
723
+ * callback, so a shutdown still drains it, and bounded by a timeout that beginHalt cancels.
724
+ *
725
+ * "Once per epoch" survives a restart: the process-local marker only skips work, the
726
+ * authority is a `PoolEpochSnapshots` row for that epoch — so a crawler restarted right
727
+ * after a boundary still records the epoch, and one restarted mid-epoch does not redo it.
728
+ * A failed attempt leaves the marker unset and backs off (see SNAPSHOT_RETRY_BASE_MS).
729
+ */
730
+ maybeSnapshotEpoch(block, tip) {
731
+ if (!this.config.epochSnapshots || block.epoch == null)
732
+ return;
733
+ if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
734
+ return;
735
+ // No tip reported = we cannot prove we are live, so we do not pretend to be.
736
+ if (tip == null) {
737
+ logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
738
+ return;
739
+ }
740
+ const tipEpoch = this.epochOfSlot(tip.slot);
741
+ if (block.epoch !== tipEpoch) {
742
+ logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
743
+ `the pool/DRep set can only be observed as it is now, never as it was`);
744
+ return;
745
+ }
746
+ if (Date.now() < this.snapshotRetryAfter)
747
+ return;
748
+ const epoch = block.epoch;
749
+ const at = { slot: block.slot ?? 0, time: block.time ?? 0 };
750
+ this.snapshotInFlight = this.trackCallback(async () => {
751
+ const existing = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch })));
752
+ if (!existing) {
753
+ await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
754
+ }
755
+ this.snapshotedEpoch = epoch;
756
+ this.snapshotFailures = 0;
757
+ this.snapshotRetryAfter = 0;
758
+ })
759
+ .catch((err) => {
760
+ // Never fatal: the crawl keeps its data, the epoch is retried on a later block —
761
+ // but not on the very next one, or an outage would re-enumerate per block.
762
+ this.snapshotFailures++;
763
+ const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
764
+ this.snapshotRetryAfter = Date.now() + backoff;
765
+ if (this.running)
766
+ logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
767
+ })
768
+ .finally(() => { this.snapshotInFlight = null; });
769
+ }
592
770
  /**
593
771
  * Handle a chain rollback: in one transaction, delete every block after the fork point
594
772
  * and exactly the transactions belonging to those blocks (plus their child rows), reset
@@ -62,6 +62,16 @@ service CardanoODataService @(impl: './cardano-service') {
62
62
  @description: 'Projection for Dreps'
63
63
  entity Dreps as projection on db.Dreps;
64
64
 
65
+ @readonly
66
+ @title : 'Pool Epoch Snapshots'
67
+ @description: 'Projection for per-epoch stake-pool snapshots written by the chain crawler'
68
+ entity PoolEpochSnapshots as projection on db.PoolEpochSnapshots;
69
+
70
+ @readonly
71
+ @title : 'DRep Epoch Snapshots'
72
+ @description: 'Projection for per-epoch DRep snapshots written by the chain crawler'
73
+ entity DrepEpochSnapshots as projection on db.DrepEpochSnapshots;
74
+
65
75
  @readonly
66
76
  @title : 'Assets'
67
77
  @description: 'Projection for Native-Asset Information'
package/srv/server.js CHANGED
@@ -39,7 +39,19 @@ const CRAWLER_LIMITS = {
39
39
  batchSize: { min: 1, max: 100 },
40
40
  confirmationDepth: { min: 0, max: 2160 },
41
41
  pollIntervalMs: { min: 1000, max: 3_600_000 },
42
+ assetEnrichRate: { min: 1, max: 20 },
42
43
  };
44
+ const VALID_ASSET_CATALOGUE_MODES = ['off', 'bare', 'enrich'];
45
+ /** Parse a boolean crawler flag that defaults to `fallback` when unset. */
46
+ function crawlerBoolean(raw, name, fallback) {
47
+ if (raw === undefined || raw === null)
48
+ return fallback;
49
+ if (raw === true || raw === 'true')
50
+ return true;
51
+ if (raw === false || raw === 'false')
52
+ return false;
53
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be true or false.`);
54
+ }
43
55
  /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
44
56
  function crawlerInteger(raw, name, min, max, defaultValue) {
45
57
  if (raw == null)
@@ -406,7 +418,20 @@ function loadCrawlerConfigFromEnv() {
406
418
  if (!['ogmios', 'pagination', 'auto'].includes(source)) {
407
419
  throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
408
420
  }
409
- return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
421
+ // Analytics coverage. Mint/burn and the bare catalogue are on by default: both are
422
+ // by-products of a block the crawler already holds and add no provider traffic. The two
423
+ // that do cost network — background enrichment and the epoch snapshots — are opt-in.
424
+ const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
425
+ const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
426
+ if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
427
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ASSET_CATALOGUE "${assetCatalogue}". Must be one of: ${VALID_ASSET_CATALOGUE_MODES.join(', ')}.`);
428
+ }
429
+ const assetEnrichRate = crawlerInteger(c.assetEnrichRate ?? process_1.env.CRAWLER_ASSET_ENRICH_RATE, 'CRAWLER_ASSET_ENRICH_RATE', CRAWLER_LIMITS.assetEnrichRate.min, CRAWLER_LIMITS.assetEnrichRate.max, 2);
430
+ const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
431
+ return {
432
+ enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
433
+ assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots,
434
+ };
410
435
  }
411
436
  /**
412
437
  * Start the chain crawler if it is enabled and the app context is ready. Never throws
@@ -169,7 +169,7 @@ export declare const HEX_56_REGEX: RegExp;
169
169
  */
170
170
  export declare const TX_HASH_REGEX: RegExp;
171
171
  /**
172
- * Asset unit Regex - policy ID (56 hex chars) + asset name (0-128 hex chars)
172
+ * Asset unit Regex - policy ID (56 hex chars) + asset name (0-64 hex chars)
173
173
  */
174
174
  export declare const ASSET_UNIT_REGEX: RegExp;
175
175
  /**
@@ -139,7 +139,7 @@ exports.HEX_56_REGEX = /^[a-f0-9]{56}$/;
139
139
  */
140
140
  exports.TX_HASH_REGEX = /^[a-f0-9]{64}$/;
141
141
  /**
142
- * Asset unit Regex - policy ID (56 hex chars) + asset name (0-128 hex chars)
142
+ * Asset unit Regex - policy ID (56 hex chars) + asset name (0-64 hex chars)
143
143
  */
144
144
  exports.ASSET_UNIT_REGEX = /^[a-f0-9]{56}([a-f0-9]{2}){0,32}$/; // policy ID (56) + asset name (0-32 bytes per ledger rules -> 0-64 hex chars, even length; total ≤ 120 = String(120) key column)
145
145
  /**
@@ -222,6 +222,24 @@ export declare class HsmError extends BackendError {
222
222
  export declare class ConfigError extends Error {
223
223
  constructor(message: string);
224
224
  }
225
+ /**
226
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
227
+ *
228
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
229
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
230
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
231
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
232
+ */
233
+ export declare class ChainSyncFrameError extends BackendError {
234
+ readonly height: number | null;
235
+ readonly id: string | null;
236
+ /** Constructor
237
+ * @param height block height the frame belonged to, when it could be read off the raw text
238
+ * @param id block hash, when readable
239
+ * @param reason why the frame could not be parsed
240
+ */
241
+ constructor(height: number | null, id: string | null, reason: string);
242
+ }
225
243
  /**
226
244
  * BackendInitError - Error initializing a specific backend
227
245
  * Captures backend name and original error
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
3
+ exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ChainSyncFrameError = exports.ConfigError = exports.HsmError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
4
4
  exports.isNotFoundOnAllBackends = isNotFoundOnAllBackends;
5
5
  exports.isPostgrestServerErrorCode = isPostgrestServerErrorCode;
6
6
  exports.getErrorStatus = getErrorStatus;
@@ -442,6 +442,29 @@ class ConfigError extends Error {
442
442
  }
443
443
  }
444
444
  exports.ConfigError = ConfigError;
445
+ /**
446
+ * ChainSyncFrameError - Ogmios delivered a frame the client cannot turn into an object.
447
+ *
448
+ * Raised by the frame guard (see `backends/ogmios-frame-guard.ts`) once the client's parser
449
+ * and the depth-safe fallback have both failed. The block is named so `lastError` points at
450
+ * it instead of leaving an empty status behind, and so the crawler can take that one block
451
+ * through the paginating backend instead of waiting on a stream that will never deliver it.
452
+ */
453
+ class ChainSyncFrameError extends BackendError {
454
+ height;
455
+ id;
456
+ /** Constructor
457
+ * @param height block height the frame belonged to, when it could be read off the raw text
458
+ * @param id block hash, when readable
459
+ * @param reason why the frame could not be parsed
460
+ */
461
+ constructor(height, id, reason) {
462
+ super(`Ogmios chain-sync frame for block ${height ?? '?'} ${id ?? ''} could not be parsed: ${reason}`, 503, error_codes_1.ERROR_CODES.PROVIDER_UNAVAILABLE, 'ogmios');
463
+ this.height = height;
464
+ this.id = id;
465
+ }
466
+ }
467
+ exports.ChainSyncFrameError = ChainSyncFrameError;
445
468
  /**
446
469
  * BackendInitError - Error initializing a specific backend
447
470
  * Captures backend name and original error
@@ -1,5 +1,5 @@
1
1
  import { Transaction as TransactionProviderData, Address as AddressProviderData, UTxO as UtxosProviderData, TxInputLine as TxInputProviderData, TxOutputLine as TxOutputProviderData, Amount as AmountProviderData, NetworkInformation as NetworkInfoProviderData, BlockData as BlockProviderData, EpochData as EpochProviderData, MetadataLabelTx as MetadataLabelTxProviderData, PoolData as PoolProviderData, DrepData as DrepProviderData, AccountData as AccountProviderData, AssetInfo as AssetInfoProviderData, AssetHistoryEntry as AssetHistoryEntryProviderData, TxBuildResult as TransactionBuildResult, LedgerProtocolParameters as ProtocolParameters } from './types';
2
- import { Address as AddressRow, AddressAsset as AddressAssetRow, AddressUTxO as AddressUTxORow, UTxOAsset as UTxOAssetRow, Transaction as TransactionRow, TransactionInput as TransactionInputRow, TransactionInputAsset as TransactionInputAssetRow, TransactionOutput as TransactionOutputRow, TransactionOutputAsset as TransactionOutputAssetRow, NetworkInformation as NetworkInfoRow, TransactionMetadata as TransactionMetadataRow, Block as BlockRow, Epoch as EpochRow, Pool as PoolRow, Drep as DrepRow, Asset as AssetRow, AssetHistory as AssetHistoryRow, Account as AccountRow, LedgerProtocolParameter as ProtocolParameterRow, AddressTransaction as AddressTransactionRow } from '#cds-models/CardanoODataService';
2
+ import { Address as AddressRow, AddressAsset as AddressAssetRow, AddressUTxO as AddressUTxORow, UTxOAsset as UTxOAssetRow, Transaction as TransactionRow, TransactionInput as TransactionInputRow, TransactionInputAsset as TransactionInputAssetRow, TransactionOutput as TransactionOutputRow, TransactionOutputAsset as TransactionOutputAssetRow, NetworkInformation as NetworkInfoRow, TransactionMetadata as TransactionMetadataRow, Block as BlockRow, Epoch as EpochRow, Pool as PoolRow, Drep as DrepRow, PoolEpochSnapshot as PoolEpochSnapshotRow, DrepEpochSnapshot as DrepEpochSnapshotRow, Asset as AssetRow, AssetHistory as AssetHistoryRow, Account as AccountRow, LedgerProtocolParameter as ProtocolParameterRow, AddressTransaction as AddressTransactionRow } from '#cds-models/CardanoODataService';
3
3
  import type { TransactionBuild as TransactionBuildRow, TransactionBuildInput as TransactionBuildInputRow, TransactionBuildOutput as TransactionBuildOutputRow, TransactionSubmission as TransactionSubmissionRow, AddressTransactionBuild as AddressTransactionBuildRow } from '#cds-models/CardanoTransactionService';
4
4
  import type { AddressSigningRequest as AddressSigningRequestRow } from '#cds-models/CardanoSignService';
5
5
  import type { Request } from '@sap/cds';
@@ -131,6 +131,31 @@ export declare function mapTransactionMetadata(providerLabels: MetadataLabelTxPr
131
131
  * (the caller skips the row — a NaN key would fail the whole bulk write)
132
132
  */
133
133
  export declare function metadataIdFor(label: string | number): number | string | null;
134
+ /**
135
+ * Map a pool observation at an epoch boundary into a snapshot row. Unlike mapPool() this
136
+ * carries no temporal validity: the row is dated by (epoch, snapshotSlot) and stays valid
137
+ * forever, because it states what was true then, not what is cached now.
138
+ * @param providerPoolData pool data from provider
139
+ * @param epoch epoch the snapshot belongs to
140
+ * @param at slot and block time of the block that triggered the snapshot
141
+ * @returns {PoolEpochSnapshotRow} mapped snapshot row
142
+ */
143
+ export declare function mapPoolSnapshot(providerPoolData: PoolProviderData, epoch: number, at: {
144
+ slot: number;
145
+ time: number;
146
+ }): PoolEpochSnapshotRow;
147
+ /**
148
+ * Map a DRep observation at an epoch boundary into a snapshot row. Non-temporal, same
149
+ * reasoning as mapPoolSnapshot().
150
+ * @param providerDrepData drep data from provider
151
+ * @param epoch epoch the snapshot belongs to
152
+ * @param at slot and block time of the block that triggered the snapshot
153
+ * @returns {DrepEpochSnapshotRow} mapped snapshot row
154
+ */
155
+ export declare function mapDrepSnapshot(providerDrepData: DrepProviderData, epoch: number, at: {
156
+ slot: number;
157
+ time: number;
158
+ }): DrepEpochSnapshotRow;
134
159
  /**
135
160
  * Map Pool Data
136
161
  * Converts provider pool data into PoolRow format
@@ -148,6 +173,34 @@ export declare function mapPool(providerPoolData: PoolProviderData, max_age: num
148
173
  * @returns {AssetRow} mapped asset row
149
174
  */
150
175
  export declare function mapAsset(providerAssetInfo: AssetInfoProviderData, max_age: number): AssetRow;
176
+ /**
177
+ * Fixed validity stamp for a crawler-written bare `Assets` row. Epoch zero, so the row is
178
+ * born expired (hidden by CAP's temporal filter) and its `(validFrom, unit)` key can never
179
+ * collide with a real, wall-clock-stamped slice from mapAsset().
180
+ */
181
+ export declare const BARE_ASSET_STAMP = "1970-01-01T00:00:00.000Z";
182
+ /**
183
+ * Map a bare asset row from an asset unit alone — everything derivable without a provider
184
+ * call: policyId, assetNameHex, the decoded name and the CIP-14 fingerprint. Used by the
185
+ * crawler to keep the `Assets` catalogue complete for units it meets in a block, at zero
186
+ * network cost (FR "crawler coverage for analytics").
187
+ *
188
+ * The row is stamped as ALREADY EXPIRED (`validTo === validFrom`). That is deliberate: CAP's
189
+ * temporal filter hides it from OData reads, so the first keyed read still counts as a miss
190
+ * and the existing lazy path enriches it through indexAsset() with supply and registry data —
191
+ * while an analytics consumer reading the database directly already sees the full catalogue
192
+ * (and can exclude the placeholders with `validTo > validFrom`).
193
+ *
194
+ * Both stamps are the FIXED epoch sentinel, not `now`. `Assets` is temporal, so its primary
195
+ * key is `(validFrom, unit)`: a wall-clock stamp would make the same unit a new row on every
196
+ * sighting and could collide with a slice the lazy path writes in the same millisecond, which
197
+ * inside the crawler's block transaction means a failed block. With the sentinel the bare row
198
+ * is one fixed, idempotent row per unit that no `mapAsset()` slice can ever alias.
199
+ *
200
+ * @param unit asset unit (policyId + assetNameHex)
201
+ * @returns {AssetRow | null} bare row, or null when the unit is not a native asset unit
202
+ */
203
+ export declare function mapBareAsset(unit: string): AssetRow | null;
151
204
  /**
152
205
  * Map Asset History entries to row format. No temporal stamping — mint/burn
153
206
  * events are immutable; UPSERT keyed on (unit, txHash) is idempotent.
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BARE_ASSET_STAMP = void 0;
6
7
  exports.mapTransaction = mapTransaction;
7
8
  exports.mapTransactionInputs = mapTransactionInputs;
8
9
  exports.mapTransactionInputAssets = mapTransactionInputAssets;
@@ -18,8 +19,11 @@ exports.mapBlock = mapBlock;
18
19
  exports.mapEpoch = mapEpoch;
19
20
  exports.mapTransactionMetadata = mapTransactionMetadata;
20
21
  exports.metadataIdFor = metadataIdFor;
22
+ exports.mapPoolSnapshot = mapPoolSnapshot;
23
+ exports.mapDrepSnapshot = mapDrepSnapshot;
21
24
  exports.mapPool = mapPool;
22
25
  exports.mapAsset = mapAsset;
26
+ exports.mapBareAsset = mapBareAsset;
23
27
  exports.mapAssetHistory = mapAssetHistory;
24
28
  exports.mapDrep = mapDrep;
25
29
  exports.mapAccount = mapAccount;
@@ -43,6 +47,7 @@ const client_1 = require("@cardano-ogmios/client");
43
47
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
44
48
  const logger = cds_1.default.log('mappers');
45
49
  const errors_1 = require("./errors");
50
+ const const_1 = require("./const");
46
51
  /**
47
52
  * Maximum age for cached/indexed data in milliseconds
48
53
  */
@@ -514,6 +519,55 @@ function metadataIdFor(label) {
514
519
  const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
515
520
  return safe ? Number(wrapped) : wrapped.toString();
516
521
  }
522
+ /**
523
+ * Map a pool observation at an epoch boundary into a snapshot row. Unlike mapPool() this
524
+ * carries no temporal validity: the row is dated by (epoch, snapshotSlot) and stays valid
525
+ * forever, because it states what was true then, not what is cached now.
526
+ * @param providerPoolData pool data from provider
527
+ * @param epoch epoch the snapshot belongs to
528
+ * @param at slot and block time of the block that triggered the snapshot
529
+ * @returns {PoolEpochSnapshotRow} mapped snapshot row
530
+ */
531
+ function mapPoolSnapshot(providerPoolData, epoch, at) {
532
+ return {
533
+ poolId: providerPoolData.poolId,
534
+ epoch,
535
+ snapshotSlot: at.slot,
536
+ snapshotTime: at.time,
537
+ blocksMinted: providerPoolData.blocksMinted,
538
+ blocksEpoch: providerPoolData.blocksEpoch,
539
+ liveStake: providerPoolData.liveStake,
540
+ liveSize: Number(providerPoolData.liveSize),
541
+ liveSaturation: Number(providerPoolData.liveSaturation),
542
+ liveDelegators: providerPoolData.liveDelegators,
543
+ activeStake: providerPoolData.activeStake,
544
+ activeSize: Number(providerPoolData.activeSize),
545
+ pledge: providerPoolData.pledge,
546
+ margin: Number(providerPoolData.margin),
547
+ fixedCost: providerPoolData.fixedCost,
548
+ };
549
+ }
550
+ /**
551
+ * Map a DRep observation at an epoch boundary into a snapshot row. Non-temporal, same
552
+ * reasoning as mapPoolSnapshot().
553
+ * @param providerDrepData drep data from provider
554
+ * @param epoch epoch the snapshot belongs to
555
+ * @param at slot and block time of the block that triggered the snapshot
556
+ * @returns {DrepEpochSnapshotRow} mapped snapshot row
557
+ */
558
+ function mapDrepSnapshot(providerDrepData, epoch, at) {
559
+ return {
560
+ drepId: providerDrepData.drepId,
561
+ epoch,
562
+ snapshotSlot: at.slot,
563
+ snapshotTime: at.time,
564
+ amount: providerDrepData.amount,
565
+ hasScript: providerDrepData.hasScript,
566
+ lastActiveEpoch: providerDrepData.lastActiveEpoch,
567
+ retired: providerDrepData.retired,
568
+ expired: providerDrepData.expired,
569
+ };
570
+ }
517
571
  /**
518
572
  * Map Pool Data
519
573
  * Converts provider pool data into PoolRow format
@@ -584,6 +638,63 @@ function mapAsset(providerAssetInfo, max_age) {
584
638
  validTo,
585
639
  };
586
640
  }
641
+ /**
642
+ * Fixed validity stamp for a crawler-written bare `Assets` row. Epoch zero, so the row is
643
+ * born expired (hidden by CAP's temporal filter) and its `(validFrom, unit)` key can never
644
+ * collide with a real, wall-clock-stamped slice from mapAsset().
645
+ */
646
+ exports.BARE_ASSET_STAMP = '1970-01-01T00:00:00.000Z';
647
+ /**
648
+ * Map a bare asset row from an asset unit alone — everything derivable without a provider
649
+ * call: policyId, assetNameHex, the decoded name and the CIP-14 fingerprint. Used by the
650
+ * crawler to keep the `Assets` catalogue complete for units it meets in a block, at zero
651
+ * network cost (FR "crawler coverage for analytics").
652
+ *
653
+ * The row is stamped as ALREADY EXPIRED (`validTo === validFrom`). That is deliberate: CAP's
654
+ * temporal filter hides it from OData reads, so the first keyed read still counts as a miss
655
+ * and the existing lazy path enriches it through indexAsset() with supply and registry data —
656
+ * while an analytics consumer reading the database directly already sees the full catalogue
657
+ * (and can exclude the placeholders with `validTo > validFrom`).
658
+ *
659
+ * Both stamps are the FIXED epoch sentinel, not `now`. `Assets` is temporal, so its primary
660
+ * key is `(validFrom, unit)`: a wall-clock stamp would make the same unit a new row on every
661
+ * sighting and could collide with a slice the lazy path writes in the same millisecond, which
662
+ * inside the crawler's block transaction means a failed block. With the sentinel the bare row
663
+ * is one fixed, idempotent row per unit that no `mapAsset()` slice can ever alias.
664
+ *
665
+ * @param unit asset unit (policyId + assetNameHex)
666
+ * @returns {AssetRow | null} bare row, or null when the unit is not a native asset unit
667
+ */
668
+ function mapBareAsset(unit) {
669
+ // The canonical definition of a unit — 56 hex policy + 0..32 bytes of name, even length.
670
+ // Reusing it keeps the catalogue from inventing a second, looser notion of "asset unit"
671
+ // than isAssetUnit() enforces on the API surface.
672
+ if (!const_1.ASSET_UNIT_REGEX.test(unit))
673
+ return null;
674
+ const policyId = unit.slice(0, 56);
675
+ const assetNameHex = unit.slice(56);
676
+ return {
677
+ unit,
678
+ policyId,
679
+ assetNameHex,
680
+ // decodeAssetName falls back to the hex string for non-text and NUL-bearing names
681
+ assetName: assetNameHex.length > 0 ? decodeAssetName(assetNameHex) : '',
682
+ fingerprint: computeCip14Fingerprint(policyId, assetNameHex),
683
+ totalSupply: null,
684
+ mintOrBurnCount: null,
685
+ initialMintTxHash: null,
686
+ initialMintTime: null,
687
+ onchainMetadata: null,
688
+ registryName: null,
689
+ registryTicker: null,
690
+ registryDecimals: null,
691
+ registryDescription: null,
692
+ registryUrl: null,
693
+ registryLogo: null,
694
+ validFrom: exports.BARE_ASSET_STAMP,
695
+ validTo: exports.BARE_ASSET_STAMP,
696
+ };
697
+ }
587
698
  /**
588
699
  * Map Asset History entries to row format. No temporal stamping — mint/burn
589
700
  * events are immutable; UPSERT keyed on (unit, txHash) is idempotent.