@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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 (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -0,0 +1,162 @@
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 collections_1 = require("../../utils/collections");
13
+ const sync_state_1 = require("./sync-state");
14
+ const cardano_1 = require("#cds-models/odatano/cardano");
15
+ const { SELECT, UPSERT, DELETE } = cds_1.default.ql;
16
+ const logger = cds_1.default.log('CertificateBackfill');
17
+ // Fill certificates and withdrawals for already crawled blocks from a second chain-sync stream.
18
+ // Only those two tables are written, and a repeat run is idempotent. Unknown blocks are skipped.
19
+ class CertificateBackfillError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'CertificateBackfillError';
23
+ }
24
+ }
25
+ exports.CertificateBackfillError = CertificateBackfillError;
26
+ // Newest crawled block before `slot`, else the crawl start. Lazily indexed blocks below the start
27
+ // are never picked, since they may lie on a fork the node no longer knows.
28
+ async function intersectionBefore(db, slot) {
29
+ const cursor = await (0, sync_state_1.readCursor)(db);
30
+ const floor = cursor?.startSlot ?? null;
31
+ const range = floor != null ? { between: floor, and: slot - 1 } : { '<': slot };
32
+ 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')));
33
+ if (row?.hash && row.slot != null)
34
+ return { slot: Number(row.slot), hash: row.hash, height: row.height == null ? undefined : Number(row.height) };
35
+ if (floor != null && cursor?.startBlockHash)
36
+ return { slot: floor, hash: cursor.startBlockHash };
37
+ return 'origin';
38
+ }
39
+ // Stream `fromSlot..toSlot` over a second chain-sync connection and pass stored blocks to
40
+ // `writeBatch`, one DB transaction per batch. Returns the intersection used.
41
+ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
42
+ const { client, fromSlot, toSlot } = opts;
43
+ const Err = opts.errorType ?? CertificateBackfillError;
44
+ if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
45
+ throw new Err(`Invalid slot range ${fromSlot}..${toSlot}`);
46
+ }
47
+ const backend = client.getChainSyncBackend();
48
+ if (!backend)
49
+ throw new Err('No chain-sync backend available (the backfill streams from Ogmios).');
50
+ const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
51
+ const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
52
+ const points = intersection === 'origin' ? 'origin' : [intersection];
53
+ let pending = [];
54
+ // Read the stored blocks of the batch's slot range in one range query, not one lookup per block.
55
+ const flush = async () => {
56
+ if (!pending.length)
57
+ return;
58
+ const batch = pending;
59
+ pending = [];
60
+ const fromBatch = batch[0].slot, toBatch = batch[batch.length - 1].slot;
61
+ await cds_1.default.tx(async (tx) => {
62
+ const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
63
+ const known = new Set(rows.map((r) => r.hash));
64
+ const held = batch.filter((b) => {
65
+ if (known.has(b.hash))
66
+ return true;
67
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index, skipped`);
68
+ return false;
69
+ });
70
+ await writeBatch(tx, held);
71
+ });
72
+ afterBatch(toBatch);
73
+ };
74
+ let handle = null;
75
+ let settled = false;
76
+ const done = new Promise((resolve, reject) => {
77
+ const finish = (err) => {
78
+ if (settled)
79
+ return;
80
+ settled = true;
81
+ if (err)
82
+ reject(err);
83
+ else
84
+ resolve();
85
+ };
86
+ const onBlock = async (block, txs) => {
87
+ if (settled)
88
+ return;
89
+ const slot = block.slot ?? 0;
90
+ if (slot > toSlot) {
91
+ finish();
92
+ return;
93
+ }
94
+ if (slot < fromSlot)
95
+ return; // between the intersection and the range: skipped, not counted
96
+ pending.push({ hash: block.hash, slot, transactions: txs.length, payload: collect(block, txs) });
97
+ if (pending.length >= batchBlocks)
98
+ await flush();
99
+ if (slot === toSlot)
100
+ finish();
101
+ };
102
+ backend.openChainSync(points, {
103
+ rollForward: (block, txs) => onBlock(block, txs).catch(finish),
104
+ // The handshake acknowledges the intersection; a reorg mid-run is the crawler's to undo,
105
+ // it deletes the rows of the rolled-back transactions.
106
+ rollBackward: async () => undefined,
107
+ onError: async (err) => finish(err),
108
+ }).then((h) => { handle = h; if (settled)
109
+ void h.close().catch(() => undefined); }, finish);
110
+ });
111
+ try {
112
+ await done;
113
+ await flush();
114
+ }
115
+ finally {
116
+ const h = handle;
117
+ if (h) {
118
+ try {
119
+ await h.close();
120
+ }
121
+ catch { /* best effort */ }
122
+ }
123
+ }
124
+ return intersection;
125
+ }
126
+ async function backfillCertificates(opts) {
127
+ const { fromSlot, toSlot } = opts;
128
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0 };
129
+ let started = false;
130
+ const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
131
+ certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
132
+ withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
133
+ failed: txs.filter((t) => t.spendsCollaterals).map((t) => t.hash),
134
+ }), async (tx, blocks) => {
135
+ const certs = blocks.flatMap((b) => b.payload.certs);
136
+ const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
137
+ for (const b of blocks) {
138
+ progress.blocks++;
139
+ progress.transactions += b.transactions;
140
+ }
141
+ progress.certificates += certs.length;
142
+ progress.withdrawals += withdrawals.length;
143
+ if (certs.length)
144
+ await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
145
+ if (withdrawals.length)
146
+ await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
147
+ // the ledger applied neither for a failed script phase; an earlier version stored them
148
+ for (const part of (0, collections_1.chunk)(blocks.flatMap((b) => b.payload.failed), collections_1.IN_CHUNK)) {
149
+ progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: part } }))) || 0;
150
+ progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: part } }))) || 0;
151
+ }
152
+ }, (atSlot) => {
153
+ started = true;
154
+ progress.atSlot = atSlot;
155
+ opts.onProgress?.({ ...progress });
156
+ });
157
+ if (!started)
158
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
159
+ logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals, ${progress.removed} rows of failed transactions removed`);
160
+ return { ...progress, fromSlot, toSlot, intersection };
161
+ }
162
+ //# 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,22 +18,25 @@ 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 and burn rows into AssetHistory. Needs no provider call. */
22
+ assetHistory: boolean;
23
+ /** `bare` writes one Assets row per unit from block data. `enrich` also fetches registry data, rate limited. */
24
+ assetCatalogue: 'off' | 'bare' | 'enrich';
25
+ /** Units per second the background enrichment resolves (`assetCatalogue: 'enrich'` only). */
26
+ assetEnrichRate: number;
27
+ /** Snapshot every pool, DRep and the ada pots at each epoch boundary (Ogmios, or Koios at the tip). */
28
+ epochSnapshots: boolean;
29
+ /** Snapshot the reward accounts with the epoch snapshot. Needs `epochSnapshots` and Ogmios. */
30
+ accountSnapshots?: boolean;
31
+ /** Write certificates and withdrawals per block. Ogmios and Koios report them, Blockfrost does not. */
32
+ certificates: boolean;
33
+ /** Maintain the Ledger* UTxO tables. Inactive until `importUtxoSet` has run once. */
34
+ utxoSet: boolean;
35
+ /** Answer 404 for chain data the database lacks instead of asking a provider. Needs a full synced crawl. */
36
+ authoritative?: boolean;
37
+ /** Store a copy of the assets of every input instead of pointing at the stored output. */
38
+ inputAssetCopies?: boolean;
19
39
  }
20
- /**
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.
34
- */
35
40
  export declare class CardanoCrawler {
36
41
  private readonly client;
37
42
  private readonly indexer;
@@ -41,11 +46,32 @@ export declare class CardanoCrawler {
41
46
  private readonly leaseOwner?;
42
47
  /** Transient-failure retries per block before giving up. */
43
48
  private static readonly PERSIST_RETRIES;
49
+ /** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
50
+ private static readonly POISON_BLOCK_THRESHOLD;
51
+ /** Process-wide, survives instance restarts: the block currently failing and how often. */
52
+ private static poison;
53
+ /** Errors caused by the block's data. Only these count towards the poison latch, outages never do. */
54
+ private static readonly DATA_REJECTION_PATTERNS;
44
55
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
45
56
  private static readonly CALL_TIMEOUT_MS;
57
+ /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
58
+ private static readonly SNAPSHOT_TIMEOUT_MS;
59
+ /** One node request per 2000 known accounts; an hour covers a mainnet-sized set. */
60
+ private static readonly ACCOUNT_SNAPSHOT_TIMEOUT_MS;
61
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
62
+ private static readonly SNAPSHOT_RETRY_BASE_MS;
63
+ private static readonly SNAPSHOT_RETRY_MAX_MS;
64
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
65
+ private static readonly CHAIN_SYNC_RETRY_MS;
46
66
  private running;
47
67
  private chainSyncHandle;
48
- /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
68
+ /** What the ingest loop is currently reading from; null while stopped. */
69
+ private activeSource;
70
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
71
+ private chainSyncProbeTimer;
72
+ private chainSyncProbe;
73
+ private chainSyncRecovered;
74
+ /** The detached ingest pipeline. stop() awaits it so teardown never races it. */
49
75
  private pipeline;
50
76
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
51
77
  private wake;
@@ -54,98 +80,95 @@ export declare class CardanoCrawler {
54
80
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
55
81
  private readonly inFlightCallbacks;
56
82
  private haltPromise;
83
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
84
+ private frameFailure;
85
+ /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
86
+ private reopenStream;
87
+ /** Blocks persisted by the current chain-sync stream. */
88
+ private blocksThisStream;
89
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
90
+ private streamEnded;
91
+ /** An open stream that delivers nothing for this long is taken as dead and reopened at the cursor. */
92
+ private static CHAIN_SYNC_IDLE_MS;
93
+ private idleTimer;
94
+ /** Reopens since the last block, so a chain that stands still warns once. */
95
+ private idleReopens;
57
96
  private finalStatus;
58
- /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
97
+ /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
59
98
  private latchOnHalt;
99
+ /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
100
+ private static readonly SNAPSHOT_WINDOW_MARGIN;
101
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
102
+ private snapshotedEpoch;
103
+ private snapshotInFlight;
104
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
105
+ private snapshotFailures;
106
+ private accountSnapshotWarned;
107
+ private snapshotRetryAfter;
60
108
  private leaseHeld;
61
109
  private leaseHeartbeat;
110
+ /** Last successful lease renewal by a block commit (epoch ms). */
111
+ private leaseRenewedAt;
62
112
  private leaseWake;
63
113
  constructor(client: CardanoClient, indexer: CardanoIndexer, network: string, config: CrawlerConfig,
64
114
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
65
115
  leaseOwner?: string | undefined);
66
116
  isRunning(): boolean;
67
- /**
68
- * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
69
- * Refuses to start without a resume point: an explicit configured start block or an
70
- * existing cursor — never an implicit full-chain sync from genesis.
71
- */
117
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
118
+ haltedWithError(): boolean;
119
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
120
+ getActiveSource(): CrawlSource | null;
121
+ /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
72
122
  start(): Promise<void>;
73
- /**
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.
78
- */
123
+ /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
79
124
  stop(finalStatus?: CrawlSyncStatusValue): Promise<void>;
80
- /**
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.
91
- */
92
125
  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
- */
126
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
97
127
  private beginHalt;
98
128
  private runIngestPipeline;
99
- /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
129
+ private startChainSyncProbing;
130
+ private scheduleChainSyncProbe;
131
+ private stopChainSyncProbing;
132
+ /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
100
133
  private withTimeout;
101
134
  private runChainSync;
102
- /**
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.
113
- */
135
+ private armIdleWatchdog;
136
+ private clearIdleWatchdog;
137
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
138
+ private takeFrameFailure;
139
+ private canDegradeToPagination;
140
+ /** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
141
+ private degradeToPagination;
142
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
143
+ private endStream;
114
144
  private buildIntersectionPoints;
115
145
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
116
146
  private trackCallback;
147
+ /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
117
148
  private runPagination;
118
- /**
119
- * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
120
- * our stored one until they agree — that height is the fork point. If the last-indexed
121
- * block still matches on-chain, there is no reorg (returns false → treat as transient).
122
- */
149
+ private paginate;
150
+ /** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
151
+ private pollPause;
123
152
  private tryReorgRecovery;
124
- /**
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.
129
- * @returns true when the block was persisted, false when the crawler was stopped
130
- */
153
+ /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
131
154
  private persistBlock;
132
- /**
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.
141
- */
155
+ /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
156
+ private epochOfSlot;
157
+ private maybeSnapshotEpoch;
158
+ private maybeSnapshotAccounts;
142
159
  private handleReorg;
143
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
160
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
144
161
  private startLeaseHeartbeat;
162
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
163
+ static isDataRejection(err: unknown): boolean;
164
+ /** Count final persist failures per block hash (a different hash resets the count). */
165
+ private static notePersistFailure;
166
+ /** Test seam: forget the poison-block memory (process-wide state). */
167
+ static resetPoisonMemory(): void;
145
168
  /** Record state only while this instance still owns the lease. */
146
169
  private recordCrawlerError;
147
170
  private leaseSleep;
148
- /** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
171
+ /** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
149
172
  private sleep;
150
173
  }
151
174
  //# sourceMappingURL=crawler.d.ts.map