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

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 (239) 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 +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -0,0 +1,149 @@
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.ASSET_SLICE_TABLES = void 0;
7
+ exports.sliceFillStatement = sliceFillStatement;
8
+ exports.backfillAssetSlices = backfillAssetSlices;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const collections_1 = require("../../utils/collections");
12
+ const db_kind_1 = require("../../utils/db-kind");
13
+ const window_plan_1 = require("./window-plan");
14
+ const cardano_1 = require("#cds-models/odatano/cardano");
15
+ const logger = cds_1.default.log('AssetSliceBackfill');
16
+ exports.ASSET_SLICE_TABLES = [
17
+ { name: 'TransactionOutputAssets', table: 'odatano_cardano_TransactionOutputAssets', counter: 'outputs', seqColumn: 'output_txSeq', rangeOf: cardano_1.TransactionOutputs },
18
+ { name: 'TransactionInputAssetCopies', table: 'odatano_cardano_TransactionInputAssetCopies', counter: 'inputs', seqColumn: 'input_txSeq', rangeOf: cardano_1.TransactionInputs },
19
+ { name: 'LedgerUTxOAssets', table: 'odatano_cardano_LedgerUTxOAssets', counter: 'ledgerUtxos' },
20
+ { name: 'LedgerAddressAssets', table: 'odatano_cardano_LedgerAddressAssets', counter: 'ledgerAddresses' },
21
+ { name: 'UTxOAssets', table: 'odatano_cardano_UTxOAssets', counter: 'utxoSlices', addressColumn: 'utxo_address_address' },
22
+ { name: 'AddressAssets', table: 'odatano_cardano_AddressAssets', counter: 'addressSlices', addressColumn: 'address_address' },
23
+ ];
24
+ const SLICE_COLUMNS = ['asset_policyId', 'asset_assetNameHex', 'asset_assetName', 'asset_fingerprint'];
25
+ // One UPDATE that sets the slice columns of every row whose unit, and address on a cached table, is in
26
+ // the bound JSON array and whose columns differ. `bounds` limits it to one txSeq window; they are
27
+ // integers, so they are written inline.
28
+ function sliceFillStatement(kind, spec, bounds) {
29
+ const differs = SLICE_COLUMNS.map((c) => `t.${c} IS DISTINCT FROM v.${c}`).join(' OR ');
30
+ const window = bounds && spec.seqColumn
31
+ ? `t.${spec.seqColumn} >= ${Math.trunc(bounds[0])} AND t.${spec.seqColumn} < ${Math.trunc(bounds[1])} AND `
32
+ : '';
33
+ return (0, db_kind_1.jsonFillUpdate)(kind, {
34
+ table: spec.table,
35
+ keys: spec.addressColumn ? [[spec.addressColumn, 'text'], ['unit', 'text']] : [['unit', 'text']],
36
+ values: SLICE_COLUMNS.map((c) => [c, 'text']),
37
+ set: SLICE_COLUMNS.map((c) => `${c} = v.${c}`).join(', '),
38
+ where: `${window}(${differs})`,
39
+ });
40
+ }
41
+ /** Fill records of `units`, the record fields named after the columns in lower case. */
42
+ function records(units, extra = []) {
43
+ return units.map((unit, i) => {
44
+ const s = (0, mappers_1.assetSlice)(unit, 0);
45
+ return {
46
+ ...extra[i],
47
+ unit,
48
+ asset_policyid: s.asset_policyId,
49
+ asset_assetnamehex: s.asset_assetNameHex,
50
+ asset_assetname: s.asset_assetName,
51
+ asset_fingerprint: s.asset_fingerprint,
52
+ };
53
+ });
54
+ }
55
+ /** Rows a plain statement changed; the drivers answer with their own result object. */
56
+ function changed(result) {
57
+ const r = result;
58
+ return typeof r === 'number' ? r : Number(r?.changes ?? r?.rowCount) || 0;
59
+ }
60
+ async function fillUnits(tx, sql, units, chunkSize) {
61
+ let n = 0;
62
+ for (const part of (0, collections_1.chunk)(units, chunkSize))
63
+ n += changed(await tx.run(sql, [JSON.stringify(records(part))]));
64
+ return n;
65
+ }
66
+ // Walks a cached table along its address index: a page of addresses, then every (address, unit) pair
67
+ // in that address range. One pair stands for all slices of the row, so each slice gets the columns.
68
+ async function fillByAddress(kind, spec, opts, add) {
69
+ const column = spec.addressColumn;
70
+ const chunkSize = opts.chunkSize ?? 1000;
71
+ const sql = sliceFillStatement(kind, spec);
72
+ const [p1, p2] = kind === 'postgres' ? ['$1', '$2'] : ['?', '?'];
73
+ const page = `SELECT DISTINCT ${column} AS address FROM ${spec.table} WHERE ${column} > ${p1} ORDER BY ${column} LIMIT ${chunkSize}`;
74
+ const pairs = `SELECT DISTINCT ${column} AS address, unit FROM ${spec.table} WHERE ${column} >= ${p1} AND ${column} <= ${p2}`;
75
+ for (let after = '';;) {
76
+ if (opts.shouldStop?.())
77
+ return false;
78
+ const addresses = (await cds_1.default.tx((tx) => tx.run(page, [after]))).map((r) => r.address);
79
+ if (!addresses.length)
80
+ return true;
81
+ add(await cds_1.default.tx(async (tx) => {
82
+ const rows = await tx.run(pairs, [addresses[0], addresses[addresses.length - 1]]);
83
+ let n = 0;
84
+ for (const part of (0, collections_1.chunk)(rows, chunkSize)) {
85
+ const fill = records(part.map((r) => r.unit), part.map((r) => ({ [column.toLowerCase()]: r.address })));
86
+ n += changed(await tx.run(sql, [JSON.stringify(fill)]));
87
+ }
88
+ return n;
89
+ }));
90
+ after = addresses[addresses.length - 1];
91
+ if (addresses.length < chunkSize)
92
+ return true;
93
+ }
94
+ }
95
+ /** Walks a transaction asset table window by window. False when stopped. */
96
+ async function fillByWindow(kind, spec, opts, add) {
97
+ const range = await (0, window_plan_1.slotRangeOf)(spec.rangeOf);
98
+ if (!range)
99
+ return true;
100
+ const chunkSize = opts.chunkSize ?? 1000;
101
+ // the fill matches the window's rows against a unit list: a hash join, key lookups take 100 times longer
102
+ return (0, window_plan_1.walkSlotWindows)(range, { slotWindow: opts.slotWindow, shouldStop: opts.shouldStop, plan: 'join' }, async (tx, window) => {
103
+ const rows = await tx.run(`SELECT DISTINCT unit FROM ${spec.table} WHERE ${spec.seqColumn} >= ${Math.trunc(window[0])} AND ${spec.seqColumn} < ${Math.trunc(window[1])}`);
104
+ if (rows.length)
105
+ add(await fillUnits(tx, sliceFillStatement(kind, spec, window), rows.map((r) => r.unit), chunkSize));
106
+ });
107
+ }
108
+ /** Walks a ledger asset table unit by unit along its unit index. False when stopped. */
109
+ async function fillByUnit(kind, spec, opts, add) {
110
+ const chunkSize = opts.chunkSize ?? 1000;
111
+ const sql = sliceFillStatement(kind, spec);
112
+ const page = kind === 'postgres'
113
+ ? `SELECT DISTINCT unit FROM ${spec.table} WHERE unit > $1 ORDER BY unit LIMIT ${chunkSize}`
114
+ : `SELECT DISTINCT unit FROM ${spec.table} WHERE unit > ? ORDER BY unit LIMIT ${chunkSize}`;
115
+ for (let after = '';;) {
116
+ if (opts.shouldStop?.())
117
+ return false;
118
+ const units = (await cds_1.default.tx((tx) => tx.run(page, [after]))).map((r) => r.unit);
119
+ if (!units.length)
120
+ return true;
121
+ add(await cds_1.default.tx((tx) => fillUnits(tx, sql, units, chunkSize)));
122
+ after = units[units.length - 1];
123
+ if (units.length < chunkSize)
124
+ return true;
125
+ }
126
+ }
127
+ async function backfillAssetSlices(opts = {}) {
128
+ const kind = (0, db_kind_1.bulkSqlKind)((0, db_kind_1.connectedDbKind)());
129
+ if (!kind)
130
+ throw new Error(`Asset rows are rewritten on PostgreSQL and SQLite only (database kind: ${(0, db_kind_1.connectedDbKind)() || 'none'})`);
131
+ const progress = { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, ledgerAddresses: 0, utxoSlices: 0, addressSlices: 0 };
132
+ for (const spec of exports.ASSET_SLICE_TABLES) {
133
+ progress.table = spec.name;
134
+ opts.onProgress?.({ ...progress });
135
+ const add = (n) => {
136
+ progress[spec.counter] += n;
137
+ opts.onProgress?.({ ...progress });
138
+ };
139
+ const finished = spec.seqColumn ? await fillByWindow(kind, spec, opts, add)
140
+ : spec.addressColumn ? await fillByAddress(kind, spec, opts, add)
141
+ : await fillByUnit(kind, spec, opts, add);
142
+ if (!finished)
143
+ return progress;
144
+ }
145
+ progress.table = null;
146
+ logger.info(`asset rows rewritten: ${progress.outputs} output, ${progress.inputs} input, ${progress.ledgerUtxos} ledger UTxO, ${progress.ledgerAddresses} ledger address, ${progress.utxoSlices} cached UTxO, ${progress.addressSlices} cached address rows`);
147
+ return progress;
148
+ }
149
+ //# sourceMappingURL=asset-slice-backfill.js.map
@@ -0,0 +1,56 @@
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
+ export declare class CertificateBackfillError extends Error {
6
+ constructor(message: string);
7
+ }
8
+ export interface CertificateBackfillProgress {
9
+ /** Slot of the last block handled. */
10
+ atSlot: number;
11
+ blocks: number;
12
+ transactions: number;
13
+ certificates: number;
14
+ withdrawals: number;
15
+ /** Stored rows removed: certificates and withdrawals of transactions whose script phase failed. */
16
+ removed: number;
17
+ }
18
+ export interface CertificateBackfillOptions {
19
+ client: CardanoClient;
20
+ /** First slot to cover; the stream intersects at the newest indexed block before it. */
21
+ fromSlot: number;
22
+ /** Last slot to cover; the stream ends at the first block past it. */
23
+ toSlot: number;
24
+ /** Rows are written per batch of blocks; smaller batches show progress sooner. */
25
+ batchBlocks?: number;
26
+ onProgress?: (p: CertificateBackfillProgress) => void;
27
+ /** Ends the stream after the current batch. */
28
+ shouldStop?: () => boolean;
29
+ }
30
+ export interface CertificateBackfillResult extends CertificateBackfillProgress {
31
+ fromSlot: number;
32
+ toSlot: number;
33
+ /** The chain point the stream started after. */
34
+ intersection: ChainPoint | 'origin';
35
+ }
36
+ export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
37
+ /** One streamed block of a backfill, with what the collector took from it. */
38
+ export interface StreamedBlock<T> {
39
+ hash: string;
40
+ slot: number;
41
+ transactions: number;
42
+ payload: T;
43
+ }
44
+ export interface CrawledBlockStreamOptions {
45
+ client: CardanoClient;
46
+ fromSlot: number;
47
+ toSlot: number;
48
+ batchBlocks?: number;
49
+ /** Error class the range and backend checks throw. */
50
+ errorType?: new (message: string) => Error;
51
+ /** Ends the stream after the current batch. */
52
+ shouldStop?: () => boolean;
53
+ }
54
+ 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'>;
55
+ export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
56
+ //# sourceMappingURL=certificate-backfill.d.ts.map
@@ -0,0 +1,174 @@
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, UPDATE, 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
+ let row = null;
33
+ if (floor == null || slot - 1 >= floor) {
34
+ const q = SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range });
35
+ // nulls first is the order a plain index on slot is read backwards in; the range excludes null
36
+ q.SELECT.orderBy = [{ ref: ['slot'], sort: 'desc', nulls: 'first' }];
37
+ row = (await db.run(q));
38
+ }
39
+ if (row?.hash && row.slot != null)
40
+ return { slot: Number(row.slot), hash: row.hash, height: row.height == null ? undefined : Number(row.height) };
41
+ if (floor != null && cursor?.startBlockHash)
42
+ return { slot: floor, hash: cursor.startBlockHash };
43
+ return 'origin';
44
+ }
45
+ // Stream `fromSlot..toSlot` over a second chain-sync connection and pass stored blocks to
46
+ // `writeBatch`, one DB transaction per batch. Returns the intersection used.
47
+ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
48
+ const { client, fromSlot, toSlot } = opts;
49
+ const Err = opts.errorType ?? CertificateBackfillError;
50
+ if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
51
+ throw new Err(`Invalid slot range ${fromSlot}..${toSlot}`);
52
+ }
53
+ const backend = client.getChainSyncBackend();
54
+ if (!backend)
55
+ throw new Err('No chain-sync backend available (the backfill streams from Ogmios).');
56
+ const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
57
+ const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
58
+ const points = intersection === 'origin' ? 'origin' : [intersection];
59
+ let pending = [];
60
+ // Read the stored blocks of the batch's slot range in one range query, not one lookup per block.
61
+ const flush = async () => {
62
+ if (!pending.length)
63
+ return;
64
+ const batch = pending;
65
+ pending = [];
66
+ const fromBatch = batch[0].slot, toBatch = batch[batch.length - 1].slot;
67
+ await cds_1.default.tx(async (tx) => {
68
+ const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
69
+ const known = new Set(rows.map((r) => r.hash));
70
+ const held = batch.filter((b) => {
71
+ if (known.has(b.hash))
72
+ return true;
73
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index, skipped`);
74
+ return false;
75
+ });
76
+ await writeBatch(tx, held);
77
+ });
78
+ afterBatch(toBatch);
79
+ };
80
+ let handle = null;
81
+ let settled = false;
82
+ const done = new Promise((resolve, reject) => {
83
+ const finish = (err) => {
84
+ if (settled)
85
+ return;
86
+ settled = true;
87
+ if (err)
88
+ reject(err);
89
+ else
90
+ resolve();
91
+ };
92
+ const onBlock = async (block, txs) => {
93
+ if (settled)
94
+ return;
95
+ const slot = block.slot ?? 0;
96
+ if (slot > toSlot || opts.shouldStop?.()) {
97
+ finish();
98
+ return;
99
+ }
100
+ if (slot < fromSlot)
101
+ return; // between the intersection and the range: skipped, not counted
102
+ pending.push({ hash: block.hash, slot, transactions: txs.length, payload: collect(block, txs) });
103
+ if (pending.length >= batchBlocks)
104
+ await flush();
105
+ if (slot === toSlot)
106
+ finish();
107
+ };
108
+ backend.openChainSync(points, {
109
+ rollForward: (block, txs) => onBlock(block, txs).catch(finish),
110
+ // The handshake acknowledges the intersection; a reorg mid-run is the crawler's to undo,
111
+ // it deletes the rows of the rolled-back transactions.
112
+ rollBackward: async () => undefined,
113
+ onError: async (err) => finish(err),
114
+ }).then((h) => { handle = h; if (settled)
115
+ void h.close().catch(() => undefined); }, finish);
116
+ });
117
+ try {
118
+ await done;
119
+ await flush();
120
+ }
121
+ finally {
122
+ const h = handle;
123
+ if (h) {
124
+ try {
125
+ await h.close();
126
+ }
127
+ catch { /* best effort */ }
128
+ }
129
+ }
130
+ return intersection;
131
+ }
132
+ async function backfillCertificates(opts) {
133
+ const { fromSlot, toSlot } = opts;
134
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0 };
135
+ let started = false;
136
+ const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
137
+ certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
138
+ withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
139
+ failed: txs.filter((t) => t.spendsCollaterals).map((t) => t.hash),
140
+ // the rule of the crawl: every transaction of the block reported its withdrawals
141
+ withdrawalsReported: txs.every((t) => t.withdrawals !== undefined),
142
+ }), async (tx, blocks) => {
143
+ const certs = blocks.flatMap((b) => b.payload.certs);
144
+ const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
145
+ for (const b of blocks) {
146
+ progress.blocks++;
147
+ progress.transactions += b.transactions;
148
+ }
149
+ progress.certificates += certs.length;
150
+ progress.withdrawals += withdrawals.length;
151
+ if (certs.length)
152
+ await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
153
+ if (withdrawals.length)
154
+ await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
155
+ // the ledger applied neither for a failed script phase; an earlier version stored them
156
+ for (const part of (0, collections_1.chunk)(blocks.flatMap((b) => b.payload.failed), collections_1.IN_CHUNK)) {
157
+ progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: part } }))) || 0;
158
+ progress.removed += Number(await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: part } }))) || 0;
159
+ }
160
+ // the account snapshot derives credited amounts only over blocks marked here
161
+ for (const part of (0, collections_1.chunk)(blocks.filter((b) => b.payload.withdrawalsReported).map((b) => b.hash), collections_1.IN_CHUNK)) {
162
+ await tx.run(UPDATE.entity(cardano_1.Block).set({ withdrawalsReported: true }).where({ hash: { in: part } }));
163
+ }
164
+ }, (atSlot) => {
165
+ started = true;
166
+ progress.atSlot = atSlot;
167
+ opts.onProgress?.({ ...progress });
168
+ });
169
+ if (!started)
170
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
171
+ logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals, ${progress.removed} rows of failed transactions removed`);
172
+ return { ...progress, fromSlot, toSlot, intersection };
173
+ }
174
+ //# 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,40 @@ 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
+ /** How long a timed-out snapshot may take to end before the next attempt is allowed. */
62
+ private static readonly SNAPSHOT_ABORT_GRACE_MS;
63
+ /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
64
+ private static readonly SNAPSHOT_RETRY_BASE_MS;
65
+ private static readonly SNAPSHOT_RETRY_MAX_MS;
66
+ /** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
67
+ private static readonly CHAIN_SYNC_RETRY_MS;
68
+ /** Wait before chain-sync is reopened after the node was found behind the cursor. */
69
+ private static readonly NODE_BEHIND_RETRY_MS;
70
+ /** Refused rollbacks that contradict the stored chain before the crawler halts with an error. */
71
+ private static readonly MAX_ROLLBACK_REFUSALS;
72
+ /** At most one node-behind warning per this interval; the rest go to debug. */
73
+ private static readonly NODE_BEHIND_LOG_MS;
46
74
  private running;
47
75
  private chainSyncHandle;
48
- /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
76
+ /** What the ingest loop is currently reading from; null while stopped. */
77
+ private activeSource;
78
+ /** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
79
+ private chainSyncProbeTimer;
80
+ private chainSyncProbe;
81
+ private chainSyncRecovered;
82
+ /** The detached ingest pipeline. stop() awaits it so teardown never races it. */
49
83
  private pipeline;
50
84
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
51
85
  private wake;
@@ -54,98 +88,108 @@ export declare class CardanoCrawler {
54
88
  /** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
55
89
  private readonly inFlightCallbacks;
56
90
  private haltPromise;
91
+ /** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
92
+ private frameFailure;
93
+ /** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
94
+ private reopenStream;
95
+ /** The stream ended on a refused rollback; the ingest loop retries later. */
96
+ private streamRefused;
97
+ private rollbackRefusals;
98
+ private nodeBehindLoggedAt;
99
+ /** Blocks persisted by the current chain-sync stream. */
100
+ private blocksThisStream;
101
+ /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
102
+ private streamEnded;
103
+ /** An open stream that delivers nothing for this long is taken as dead and reopened at the cursor. */
104
+ private static CHAIN_SYNC_IDLE_MS;
105
+ private idleTimer;
106
+ /** Reopens since the last block, so a chain that stands still warns once. */
107
+ private idleReopens;
57
108
  private finalStatus;
58
- /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
109
+ /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
59
110
  private latchOnHalt;
111
+ /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
112
+ private static readonly SNAPSHOT_WINDOW_MARGIN;
113
+ /** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
114
+ private snapshotedEpoch;
115
+ private snapshotInFlight;
116
+ /** The snapshot work itself. It can outlive a timed-out attempt until it sees its abort flag. */
117
+ private snapshotWork;
118
+ /** Consecutive snapshot failures and the earliest time the next attempt may run. */
119
+ private snapshotFailures;
120
+ private accountSnapshotWarned;
121
+ private snapshotRetryAfter;
60
122
  private leaseHeld;
61
123
  private leaseHeartbeat;
124
+ /** Last successful lease renewal by a block commit (epoch ms). */
125
+ private leaseRenewedAt;
62
126
  private leaseWake;
63
127
  constructor(client: CardanoClient, indexer: CardanoIndexer, network: string, config: CrawlerConfig,
64
128
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
65
129
  leaseOwner?: string | undefined);
66
130
  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
- */
131
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
132
+ haltedWithError(): boolean;
133
+ /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
134
+ getActiveSource(): CrawlSource | null;
135
+ /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
72
136
  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
- */
137
+ /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
79
138
  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
139
  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
- */
140
+ /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
97
141
  private beginHalt;
98
142
  private runIngestPipeline;
99
- /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
143
+ private startChainSyncProbing;
144
+ private scheduleChainSyncProbe;
145
+ private stopChainSyncProbing;
146
+ /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
100
147
  private withTimeout;
101
148
  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
- */
149
+ private armIdleWatchdog;
150
+ private clearIdleWatchdog;
151
+ /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
152
+ private takeFrameFailure;
153
+ private canDegradeToPagination;
154
+ /** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
155
+ private degradeToPagination;
156
+ /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
157
+ private endStream;
114
158
  private buildIntersectionPoints;
159
+ private followsByronBoundary;
160
+ /** Blocks the node can roll back at most (Praos `k`). */
161
+ private securityParam;
162
+ private rollbackRefusal;
163
+ private waitForNode;
164
+ private refuseRollback;
115
165
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
116
166
  private trackCallback;
167
+ /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
117
168
  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
- */
169
+ private paginate;
170
+ /** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
171
+ private pollPause;
123
172
  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
- */
173
+ /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
131
174
  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
- */
175
+ /** Epoch a slot belongs to, from the network's Shelley anchor. */
176
+ private epochOfSlot;
177
+ private maybeSnapshotEpoch;
178
+ private maybeSnapshotAccounts;
179
+ private attemptWithTimeout;
142
180
  private handleReorg;
143
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
181
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
144
182
  private startLeaseHeartbeat;
183
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
184
+ static isDataRejection(err: unknown): boolean;
185
+ /** Count final persist failures per block hash (a different hash resets the count). */
186
+ private static notePersistFailure;
187
+ /** Test seam: forget the poison-block memory (process-wide state). */
188
+ static resetPoisonMemory(): void;
145
189
  /** Record state only while this instance still owns the lease. */
146
190
  private recordCrawlerError;
147
191
  private leaseSleep;
148
- /** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
192
+ /** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
149
193
  private sleep;
150
194
  }
151
195
  //# sourceMappingURL=crawler.d.ts.map