@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -0,0 +1,67 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ import type { BlockData, Transaction } from '../../utils/types';
5
+ /**
6
+ * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
7
+ * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
8
+ * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
9
+ * live crawler keeps its own stream. A block the index does not know (rolled back since) is
10
+ * skipped, so no row can point at a transaction that is not there.
11
+ */
12
+ export declare class CertificateBackfillError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ export interface CertificateBackfillProgress {
16
+ /** Slot of the last block handled. */
17
+ atSlot: number;
18
+ blocks: number;
19
+ transactions: number;
20
+ certificates: number;
21
+ withdrawals: number;
22
+ }
23
+ export interface CertificateBackfillOptions {
24
+ client: CardanoClient;
25
+ /** First slot to cover; the stream intersects at the newest indexed block before it. */
26
+ fromSlot: number;
27
+ /** Last slot to cover; the stream ends at the first block past it. */
28
+ toSlot: number;
29
+ /** Rows are written per batch of blocks; smaller batches show progress sooner. */
30
+ batchBlocks?: number;
31
+ onProgress?: (p: CertificateBackfillProgress) => void;
32
+ }
33
+ export interface CertificateBackfillResult extends CertificateBackfillProgress {
34
+ fromSlot: number;
35
+ toSlot: number;
36
+ /** The chain point the stream started after. */
37
+ intersection: ChainPoint | 'origin';
38
+ }
39
+ /**
40
+ * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
41
+ * start point when none is. Lazily indexed blocks below the crawl start are never picked:
42
+ * they may lie far back or on a fork the node no longer knows.
43
+ */
44
+ export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
45
+ /** One streamed block of a backfill, with what the collector took from it. */
46
+ export interface StreamedBlock<T> {
47
+ hash: string;
48
+ slot: number;
49
+ transactions: number;
50
+ payload: T;
51
+ }
52
+ export interface CrawledBlockStreamOptions {
53
+ client: CardanoClient;
54
+ fromSlot: number;
55
+ toSlot: number;
56
+ batchBlocks?: number;
57
+ /** Error class the range and backend checks throw. */
58
+ errorType?: new (message: string) => Error;
59
+ }
60
+ /**
61
+ * Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
62
+ * batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
63
+ * the index does not know (rolled back since) is skipped. Returns the intersection used.
64
+ */
65
+ export declare function streamCrawledBlocks<T>(opts: CrawledBlockStreamOptions, collect: (block: BlockData, txs: Transaction[]) => T, writeBatch: (tx: CapTransaction, blocks: StreamedBlock<T>[]) => Promise<void>, afterBatch: (toSlot: number) => void): Promise<ChainPoint | 'origin'>;
66
+ export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
67
+ //# sourceMappingURL=certificate-backfill.d.ts.map
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CertificateBackfillError = void 0;
7
+ exports.intersectionBefore = intersectionBefore;
8
+ exports.streamCrawledBlocks = streamCrawledBlocks;
9
+ exports.backfillCertificates = backfillCertificates;
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ const mappers_1 = require("../../utils/mappers");
12
+ const sync_state_1 = require("./sync-state");
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
14
+ const { SELECT, UPSERT } = cds_1.default.ql;
15
+ const logger = cds_1.default.log('CertificateBackfill');
16
+ /**
17
+ * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
18
+ * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
19
+ * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
20
+ * live crawler keeps its own stream. A block the index does not know (rolled back since) is
21
+ * skipped, so no row can point at a transaction that is not there.
22
+ */
23
+ class CertificateBackfillError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = 'CertificateBackfillError';
27
+ }
28
+ }
29
+ exports.CertificateBackfillError = CertificateBackfillError;
30
+ /**
31
+ * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
32
+ * start point when none is. Lazily indexed blocks below the crawl start are never picked:
33
+ * they may lie far back or on a fork the node no longer knows.
34
+ */
35
+ async function intersectionBefore(db, slot) {
36
+ const cursor = await (0, sync_state_1.readCursor)(db);
37
+ const floor = cursor?.startSlot ?? null;
38
+ const range = floor != null ? { between: floor, and: slot - 1 } : { '<': slot };
39
+ const row = floor != null && slot - 1 < floor ? null : (await db.run(SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range }).orderBy('slot desc')));
40
+ if (row?.hash && row.slot != null)
41
+ return { slot: Number(row.slot), hash: row.hash, height: row.height == null ? undefined : Number(row.height) };
42
+ if (floor != null && cursor?.startBlockHash)
43
+ return { slot: floor, hash: cursor.startBlockHash };
44
+ return 'origin';
45
+ }
46
+ /**
47
+ * Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
48
+ * batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
49
+ * the index does not know (rolled back since) is skipped. Returns the intersection used.
50
+ */
51
+ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
52
+ const { client, fromSlot, toSlot } = opts;
53
+ const Err = opts.errorType ?? CertificateBackfillError;
54
+ if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
55
+ throw new Err(`Invalid slot range ${fromSlot}..${toSlot}`);
56
+ }
57
+ const backend = client.getChainSyncBackend();
58
+ if (!backend)
59
+ throw new Err('No chain-sync backend available (the backfill streams from Ogmios).');
60
+ const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
61
+ const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
62
+ const points = intersection === 'origin' ? 'origin' : [intersection];
63
+ let pending = [];
64
+ /**
65
+ * Writes a batch: the index's blocks of the batch's slot range are read once (a sequential
66
+ * index range, not one random lookup per block) and only blocks the index holds are passed on.
67
+ */
68
+ const flush = async () => {
69
+ if (!pending.length)
70
+ return;
71
+ const batch = pending;
72
+ pending = [];
73
+ const fromBatch = batch[0].slot, toBatch = batch[batch.length - 1].slot;
74
+ await cds_1.default.tx(async (tx) => {
75
+ const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
76
+ const known = new Set(rows.map((r) => r.hash));
77
+ const held = batch.filter((b) => {
78
+ if (known.has(b.hash))
79
+ return true;
80
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
81
+ return false;
82
+ });
83
+ await writeBatch(tx, held);
84
+ });
85
+ afterBatch(toBatch);
86
+ };
87
+ let handle = null;
88
+ let settled = false;
89
+ const done = new Promise((resolve, reject) => {
90
+ const finish = (err) => {
91
+ if (settled)
92
+ return;
93
+ settled = true;
94
+ if (err)
95
+ reject(err);
96
+ else
97
+ resolve();
98
+ };
99
+ const onBlock = async (block, txs) => {
100
+ if (settled)
101
+ return;
102
+ const slot = block.slot ?? 0;
103
+ if (slot > toSlot) {
104
+ finish();
105
+ return;
106
+ }
107
+ if (slot < fromSlot)
108
+ return; // between the intersection and the range: skipped, not counted
109
+ pending.push({ hash: block.hash, slot, transactions: txs.length, payload: collect(block, txs) });
110
+ if (pending.length >= batchBlocks)
111
+ await flush();
112
+ if (slot === toSlot)
113
+ finish();
114
+ };
115
+ backend.openChainSync(points, {
116
+ rollForward: (block, txs) => onBlock(block, txs).catch(finish),
117
+ // The handshake acknowledges the intersection; a reorg mid-run is the crawler's to undo,
118
+ // it deletes the rows of the rolled-back transactions.
119
+ rollBackward: async () => undefined,
120
+ onError: async (err) => finish(err),
121
+ }).then((h) => { handle = h; if (settled)
122
+ void h.close().catch(() => undefined); }, finish);
123
+ });
124
+ try {
125
+ await done;
126
+ await flush();
127
+ }
128
+ finally {
129
+ const h = handle;
130
+ if (h) {
131
+ try {
132
+ await h.close();
133
+ }
134
+ catch { /* best effort */ }
135
+ }
136
+ }
137
+ return intersection;
138
+ }
139
+ async function backfillCertificates(opts) {
140
+ const { fromSlot, toSlot } = opts;
141
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
142
+ let started = false;
143
+ const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
144
+ certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
145
+ withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
146
+ }), async (tx, blocks) => {
147
+ const certs = blocks.flatMap((b) => b.payload.certs);
148
+ const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
149
+ for (const b of blocks) {
150
+ progress.blocks++;
151
+ progress.transactions += b.transactions;
152
+ }
153
+ progress.certificates += certs.length;
154
+ progress.withdrawals += withdrawals.length;
155
+ if (certs.length)
156
+ await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
157
+ if (withdrawals.length)
158
+ await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
159
+ }, (atSlot) => {
160
+ started = true;
161
+ progress.atSlot = atSlot;
162
+ opts.onProgress?.({ ...progress });
163
+ });
164
+ if (!started)
165
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
166
+ logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals`);
167
+ return { ...progress, fromSlot, toSlot, intersection };
168
+ }
169
+ //# sourceMappingURL=certificate-backfill.js.map
@@ -1,6 +1,8 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { type CrawlSyncStatusValue } from './sync-state';
4
+ /** The source a running crawler is currently ingesting from. */
5
+ export type CrawlSource = 'chain-sync' | 'pagination';
4
6
  /** Runtime configuration for the chain crawler (loaded from cds.requires by the server). */
5
7
  export interface CrawlerConfig {
6
8
  enabled: boolean;
@@ -16,21 +18,37 @@ export interface CrawlerConfig {
16
18
  confirmationDepth: number;
17
19
  /** Poll cadence when caught up / on transient errors (pagination path). */
18
20
  pollIntervalMs: number;
21
+ /** Write mint/burn rows into AssetHistory. Free — no provider call. */
22
+ assetHistory: boolean;
23
+ /**
24
+ * `off` — nothing; `bare` — one Assets row per unit from block data alone (free);
25
+ * `enrich` — additionally resolve supply/registry data in the background, rate limited.
26
+ */
27
+ assetCatalogue: 'off' | 'bare' | 'enrich';
28
+ /** Units per second the background enrichment resolves (`assetCatalogue: 'enrich'` only). */
29
+ assetEnrichRate: number;
30
+ /** Snapshot every pool, DRep and the ada pots at each epoch boundary (Ogmios, or Koios at the tip). */
31
+ epochSnapshots: boolean;
32
+ /**
33
+ * Write TransactionCertificates + TransactionWithdrawals per block (ledger-state
34
+ * coverage). Free on Ogmios chain-sync and Koios; Blockfrost does not report them.
35
+ */
36
+ certificates: boolean;
37
+ /**
38
+ * Maintain the crawler-fed UTxO set (`LedgerUTxOs` / `LedgerAddresses` / `LedgerAccounts`).
39
+ * Needs a one-off snapshot import (`importUtxoSet`) to become active.
40
+ */
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;
19
47
  }
20
48
  /**
21
- * CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
22
- * start block and bulk-indexes Blocks + Transactions (+ inputs/outputs/assets) into the
23
- * DB, so consumers can query local data instead of hitting a backend per request.
24
- *
25
- * Two sources (see CRAWLER_DESIGN.md):
26
- * - **Ogmios chain-sync** (primary): ordered rollForward + native rollBackward (reorg).
27
- * - **Blockfrost/Koios pagination** (fallback): forward walk + parent-hash reorg recovery.
28
- *
29
- * Lifecycle: start() launches the ingest pipeline detached so the HTTP server binds
30
- * immediately, but the pipeline promise is retained — stop() halts the loops (waking
31
- * any pending poll sleep) and AWAITS the pipeline, so shutdown never races in-flight
32
- * block writes. All per-block writes are atomic. The crawler NEVER crawls from genesis
33
- * implicitly — it requires an explicit configured start point or an existing cursor.
49
+ * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
50
+ * Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
51
+ * Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
34
52
  */
35
53
  export declare class CardanoCrawler {
36
54
  private readonly client;
@@ -41,10 +59,32 @@ export declare class CardanoCrawler {
41
59
  private readonly leaseOwner?;
42
60
  /** Transient-failure retries per block before giving up. */
43
61
  private static readonly PERSIST_RETRIES;
62
+ /** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
63
+ private static readonly POISON_BLOCK_THRESHOLD;
64
+ /** Process-wide, survives instance restarts: the block currently failing and how often. */
65
+ private static poison;
66
+ /**
67
+ * Errors deterministic for the block's data — only these count towards the poison latch.
68
+ * Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
69
+ */
70
+ private static readonly DATA_REJECTION_PATTERNS;
44
71
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
45
72
  private static readonly CALL_TIMEOUT_MS;
73
+ /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
74
+ private static readonly SNAPSHOT_TIMEOUT_MS;
75
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
76
+ private static readonly SNAPSHOT_RETRY_BASE_MS;
77
+ private static readonly SNAPSHOT_RETRY_MAX_MS;
78
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
79
+ private static readonly CHAIN_SYNC_RETRY_MS;
46
80
  private running;
47
81
  private chainSyncHandle;
82
+ /** What the ingest loop is currently reading from; null while stopped. */
83
+ private activeSource;
84
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
85
+ private chainSyncProbeTimer;
86
+ private chainSyncProbe;
87
+ private chainSyncRecovered;
48
88
  /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
49
89
  private pipeline;
50
90
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
@@ -54,16 +94,38 @@ export declare class CardanoCrawler {
54
94
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
55
95
  private readonly inFlightCallbacks;
56
96
  private haltPromise;
97
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
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;
103
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
104
+ private streamEnded;
57
105
  private finalStatus;
58
106
  /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
59
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;
110
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
111
+ private snapshotedEpoch;
112
+ private snapshotInFlight;
113
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
114
+ private snapshotFailures;
115
+ private snapshotRetryAfter;
60
116
  private leaseHeld;
61
117
  private leaseHeartbeat;
118
+ /** Last successful lease renewal by a block commit (epoch ms). */
119
+ private leaseRenewedAt;
62
120
  private leaseWake;
63
121
  constructor(client: CardanoClient, indexer: CardanoIndexer, network: string, config: CrawlerConfig,
64
122
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
65
123
  leaseOwner?: string | undefined);
66
124
  isRunning(): boolean;
125
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
126
+ haltedWithError(): boolean;
127
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
128
+ getActiveSource(): CrawlSource | null;
67
129
  /**
68
130
  * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
69
131
  * Refuses to start without a resume point: an explicit configured start block or an
@@ -71,50 +133,64 @@ export declare class CardanoCrawler {
71
133
  */
72
134
  start(): Promise<void>;
73
135
  /**
74
- * Stop crawling and WAIT for the pipeline to finish its in-flight step: halts the
75
- * loops (waking any pending poll sleep), closes the chain-sync stream, records the
76
- * final status, then awaits the detached pipeline so callers (shutdownAppContext)
77
- * can safely tear down backends/DB afterwards.
136
+ * Stop crawling and await the pipeline's in-flight step, so callers can tear down
137
+ * backends/DB afterwards.
78
138
  */
79
139
  stop(finalStatus?: CrawlSyncStatusValue): Promise<void>;
80
140
  /**
81
- * Halt without awaiting the pipeline — the variant safe to call FROM INSIDE the
82
- * pipeline (persistBlock failure, stream onError), where awaiting the pipeline
83
- * would deadlock.
84
- */
85
- /**
86
- * @param latch clears `desiredRunning`, so NO restart brings the crawler back —
87
- * only an operator's resumeCrawler does. Reserved for failures a restart cannot
88
- * fix (misconfiguration, missing resume point). Runtime failures — a dropped
89
- * chain-sync socket, a provider outage, a node restart — must leave it false,
90
- * otherwise a routine node restart silently disables the pre-sync for good.
141
+ * Halt without awaiting the pipeline — safe to call from inside it.
142
+ * @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
143
+ * a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
91
144
  */
92
145
  private halt;
93
- /**
94
- * Start teardown without awaiting it. Internal callers can therefore halt from
95
- * inside a tracked callback/pipeline without waiting on their own promise.
96
- */
146
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
97
147
  private beginHalt;
98
148
  private runIngestPipeline;
149
+ /**
150
+ * Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
151
+ * one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
152
+ * the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
153
+ */
154
+ private startChainSyncProbing;
155
+ private scheduleChainSyncProbe;
156
+ private stopChainSyncProbing;
99
157
  /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
100
158
  private withTimeout;
101
159
  private runChainSync;
160
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
161
+ private takeFrameFailure;
162
+ /**
163
+ * Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
164
+ * backend, and a source not pinned to 'ogmios' (chain-sync only).
165
+ */
166
+ private canDegradeToPagination;
167
+ /**
168
+ * End the chain-sync stream and hand back to the ingest loop, which continues on pagination
169
+ * past the offending block. The error is recorded first so `lastError` names the block.
170
+ */
171
+ private degradeToPagination;
172
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
173
+ private endStream;
102
174
  /**
103
- * Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
104
- * spaced ladder of our own already-crawled ancestors, then the configured start
105
- * block as the deepest anchor.
106
- *
107
- * Why more than the cursor: if the cursor's block was orphaned while the crawler
108
- * was down, a single-point intersection fails outright ("No intersection found")
109
- * and the stream never opens. With ancestors on the list the node intersects at
110
- * the last common block and reports it as a rollBackward — the ordinary reorg path
111
- * that handleReorg already implements. Doubling offsets cover ~32k blocks with 16
112
- * points; anything deeper is past any realistic rollback and should fail loudly.
175
+ * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
176
+ * ancestors, then the configured start block. If the cursor's block was orphaned while the
177
+ * crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
113
178
  */
114
179
  private buildIntersectionPoints;
115
180
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
116
181
  private trackCallback;
182
+ /**
183
+ * @param untilHeight return once the cursor reaches it — walks past a block chain-sync
184
+ * cannot deliver, then hands back.
185
+ * @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
186
+ */
117
187
  private runPagination;
188
+ private paginate;
189
+ /**
190
+ * Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
191
+ * since the probe's wake-up only reaches a sleep that has begun.
192
+ */
193
+ private pollPause;
118
194
  /**
119
195
  * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
120
196
  * our stored one until they agree — that height is the fork point. If the last-indexed
@@ -122,26 +198,35 @@ export declare class CardanoCrawler {
122
198
  */
123
199
  private tryReorgRecovery;
124
200
  /**
125
- * Persist one block atomically and advance the cursor. Transient failures are retried
126
- * a few times (recording the error streak); only repeated failure stops the crawler —
127
- * the cursor is not advanced on failure, so a resume re-syncs cleanly from it.
128
- * Marks the cursor 'synced' when the block is at the reported tip.
201
+ * Persist one block atomically and advance the cursor. Transient failures are retried; the
202
+ * cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
129
203
  * @returns true when the block was persisted, false when the crawler was stopped
130
204
  */
131
205
  private persistBlock;
206
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
207
+ private epochOfSlot;
208
+ /**
209
+ * Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
210
+ * state is read AT the block, which works while the block is inside the node's volatile window
211
+ * (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
212
+ * tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
213
+ * `EpochLedgerSnapshots` (or a pool row written before the marker existed).
214
+ */
215
+ private maybeSnapshotEpoch;
132
216
  /**
133
- * Handle a chain rollback: in one transaction, delete every block after the fork point
134
- * and exactly the transactions belonging to those blocks (plus their child rows), reset
135
- * the cursor to the fork, and write a CardanoReorgLog audit row.
136
- *
137
- * The cut runs on the absolute-slot axis of Blocks (same axis as the fork point), and
138
- * transactions are resolved via their blockHash — so:
139
- * - an unresolvable fork height can never widen the delete (no height-0 fallback), and
140
- * - lazily-indexed transactions of blocks the crawler never wrote are left untouched.
217
+ * Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
218
+ * height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
219
+ * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
141
220
  */
142
221
  private handleReorg;
143
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
222
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
144
223
  private startLeaseHeartbeat;
224
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
225
+ static isDataRejection(err: unknown): boolean;
226
+ /** Count final persist failures per block hash (a different hash resets the count). */
227
+ private static notePersistFailure;
228
+ /** Test seam: forget the poison-block memory (process-wide state). */
229
+ static resetPoisonMemory(): void;
145
230
  /** Record state only while this instance still owns the lease. */
146
231
  private recordCrawlerError;
147
232
  private leaseSleep;