@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
@@ -11,25 +11,15 @@ const DEFAULT_CONFIG = {
11
11
  successThreshold: 2,
12
12
  resetTimeoutMs: 30_000,
13
13
  };
14
- /**
15
- * Circuit Breaker for backend failover.
16
- * Tracks per-backend failure counts and prevents hammering unhealthy backends.
17
- *
18
- * States:
19
- * closed → normal operation, requests pass through
20
- * open → backend is unhealthy, requests are skipped
21
- * half-open → probe period, limited requests allowed to test recovery
22
- */
14
+ // Per-backend circuit breaker. Closed passes requests, open skips the backend.
15
+ // Half-open lets a few probe requests through to test recovery.
23
16
  class CircuitBreakerManager {
24
17
  circuits = new Map();
25
18
  config;
26
19
  constructor(config) {
27
20
  this.config = { ...DEFAULT_CONFIG, ...config };
28
21
  }
29
- /**
30
- * Check if a backend should be attempted.
31
- * Transitions open → half-open if reset timeout has elapsed.
32
- */
22
+ /** Moves an open circuit to half-open once the reset timeout has elapsed. */
33
23
  shouldAttempt(backendName) {
34
24
  const entry = this.circuits.get(backendName);
35
25
  if (!entry)
@@ -47,8 +37,8 @@ class CircuitBreakerManager {
47
37
  }
48
38
  return false;
49
39
  }
50
- // half-open: cap in-flight probes at successThreshold — previously a burst
51
- // of concurrent requests all probed a barely-recovering backend at once
40
+ // half-open: cap in-flight probes at successThreshold, so a burst of
41
+ // concurrent requests does not all probe a barely-recovering backend
52
42
  if (entry.halfOpenProbes >= this.config.successThreshold) {
53
43
  return false;
54
44
  }
@@ -0,0 +1,29 @@
1
+ import cds from '@sap/cds';
2
+ import type { RewardAccountStateBackend } from '../backends/cardano-backend';
3
+ export interface AccountSnapshotOptions {
4
+ backend: RewardAccountStateBackend;
5
+ epoch: number;
6
+ at: {
7
+ slot: number;
8
+ hash: string;
9
+ };
10
+ withdrawals: boolean;
11
+ pageSize?: number;
12
+ shouldStop?: () => boolean;
13
+ }
14
+ export interface AccountSnapshotResult {
15
+ taken: boolean;
16
+ asked: number;
17
+ accounts: number;
18
+ }
19
+ /** Where the crawl learns which accounts exist: the UTxO set and the crawled certificates. */
20
+ declare const SOURCES: readonly ["ledger", "certificates"];
21
+ type Source = (typeof SOURCES)[number];
22
+ /** The page query as an opaque value, for a test that renders its SQL. */
23
+ export declare function accountPageQuery(source: Source, after: string, limit: number): object;
24
+ export declare function creditedAmount(now: string | null, before: bigint | undefined, withdrawn: bigint): string | null;
25
+ export declare function snapshotAccounts(opts: AccountSnapshotOptions): Promise<AccountSnapshotResult>;
26
+ /** Removes the account snapshots read at a block after `forkSlot`. Part of the reorg transaction. */
27
+ export declare function dropAccountSnapshotsAfter(tx: cds.Transaction, forkSlot: number): Promise<void>;
28
+ export {};
29
+ //# sourceMappingURL=account-snapshots.d.ts.map
@@ -0,0 +1,153 @@
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.accountPageQuery = accountPageQuery;
7
+ exports.creditedAmount = creditedAmount;
8
+ exports.snapshotAccounts = snapshotAccounts;
9
+ exports.dropAccountSnapshotsAfter = dropAccountSnapshotsAfter;
10
+ // Reward account snapshot of one epoch. Asks the node, at the snapshot block, about every
11
+ // account the crawl knows and stores the ones it reports. Runs after the pool snapshot.
12
+ const cds_1 = __importDefault(require("@sap/cds"));
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
14
+ const collections_1 = require("../../utils/collections");
15
+ const logger = cds_1.default.log('AccountSnapshots');
16
+ const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
17
+ /** Where the crawl learns which accounts exist: the UTxO set and the crawled certificates. */
18
+ const SOURCES = ['ledger', 'certificates'];
19
+ const lovelace = (value) => {
20
+ if (value === null || value === undefined || value === '')
21
+ return 0n;
22
+ return BigInt(typeof value === 'number' ? Math.trunc(value) : String(value).split('.')[0]);
23
+ };
24
+ /** Page query of one source: stake addresses after `after`, in the order of the column's index. */
25
+ function pageQuery(source, after, limit) {
26
+ const q = source === 'ledger'
27
+ ? SELECT.from(cardano_1.LedgerAccounts).columns('stakeAddress').where({ stakeAddress: { '>': after } }).limit(limit)
28
+ : SELECT.distinct.from(cardano_1.TransactionCertificates).columns('stakeAddress').where({ stakeAddress: { '>': after } }).limit(limit);
29
+ // nulls last is the order of a plain index; without it PostgreSQL sorts the range on every page
30
+ q.SELECT.orderBy = [{ ref: ['stakeAddress'], sort: 'asc', nulls: 'last' }];
31
+ return q;
32
+ }
33
+ /** The page query as an opaque value, for a test that renders its SQL. */
34
+ function accountPageQuery(source, after, limit) {
35
+ return pageQuery(source, after, limit);
36
+ }
37
+ async function accountPage(source, after, limit) {
38
+ const rows = await cds_1.default.tx((tx) => tx.run(pageQuery(source, after, limit)));
39
+ return rows.map(r => r.stakeAddress);
40
+ }
41
+ /** The accounts of `page` that the UTxO set does not list; those were asked in the first pass. */
42
+ async function notInLedger(page) {
43
+ const known = new Set();
44
+ await cds_1.default.tx(async (tx) => {
45
+ for (const part of (0, collections_1.chunk)(page, collections_1.IN_CHUNK)) {
46
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerAccounts).columns('stakeAddress').where({ stakeAddress: { in: part } }));
47
+ for (const r of rows)
48
+ known.add(r.stakeAddress);
49
+ }
50
+ });
51
+ return known.size ? page.filter(a => !known.has(a)) : page;
52
+ }
53
+ /** Slot of the account snapshot of `epoch`, or null when that epoch has none. */
54
+ async function accountSnapshotSlot(epoch) {
55
+ const row = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('accountCount', 'accountSnapshotSlot').where({ epoch })));
56
+ return row?.accountCount == null || row.accountSnapshotSlot == null ? null : Number(row.accountSnapshotSlot);
57
+ }
58
+ // Balance difference to the previous snapshot plus what was withdrawn in between.
59
+ // Below zero means a withdrawal the crawl did not store, so the amount is unknown.
60
+ function creditedAmount(now, before, withdrawn) {
61
+ if (now === null || before === undefined)
62
+ return null;
63
+ const credited = BigInt(now) - before + withdrawn;
64
+ return credited < 0n ? null : credited.toString();
65
+ }
66
+ async function storePage(tx, reported, opts, previousSlot) {
67
+ const before = new Map();
68
+ const withdrawn = new Map();
69
+ if (previousSlot != null && opts.withdrawals) {
70
+ for (const part of (0, collections_1.chunk)(reported.map(a => a.stakeAddress), collections_1.IN_CHUNK)) {
71
+ const balances = await tx.run(SELECT.from(cardano_1.AccountEpochSnapshots).columns('stakeAddress', 'withdrawableAmount').where({ epoch: opts.epoch - 1, stakeAddress: { in: part } }));
72
+ for (const r of balances)
73
+ if (r.withdrawableAmount != null)
74
+ before.set(r.stakeAddress, lovelace(r.withdrawableAmount));
75
+ const sums = await tx.run(SELECT.from(cardano_1.TransactionWithdrawals).columns('stakeAddress', 'sum(lovelace) as total')
76
+ .where({ stakeAddress: { in: part }, 'tx.slot': { between: previousSlot + 1, and: opts.at.slot } })
77
+ .groupBy('stakeAddress'));
78
+ for (const r of sums)
79
+ withdrawn.set(r.stakeAddress, lovelace(r.total));
80
+ }
81
+ }
82
+ const rows = reported.map(a => ({
83
+ epoch: opts.epoch,
84
+ stakeAddress: a.stakeAddress,
85
+ withdrawableAmount: a.withdrawableAmount,
86
+ creditedAmount: creditedAmount(a.withdrawableAmount, before.get(a.stakeAddress), withdrawn.get(a.stakeAddress) ?? 0n),
87
+ deposit: a.deposit,
88
+ poolId: a.poolId,
89
+ drepId: a.drepId,
90
+ }));
91
+ for (const part of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK))
92
+ await tx.run(UPSERT.into(cardano_1.AccountEpochSnapshots).entries(part));
93
+ }
94
+ // Takes the account snapshot of `epoch` unless it has one. The marker on EpochLedgerSnapshots is
95
+ // written last, and only while the snapshot block is still on the stored chain.
96
+ async function snapshotAccounts(opts) {
97
+ const { backend, epoch, at } = opts;
98
+ const pageSize = opts.pageSize ?? 2000;
99
+ const marker = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch', 'accountCount').where({ epoch })));
100
+ if (!marker)
101
+ return { taken: false, asked: 0, accounts: 0 };
102
+ if (marker.accountCount != null)
103
+ return { taken: false, asked: 0, accounts: Number(marker.accountCount) };
104
+ // rows of an attempt that did not finish were read at another block
105
+ await cds_1.default.tx((tx) => tx.run(DELETE.from(cardano_1.AccountEpochSnapshots).where({ epoch })));
106
+ const previousSlot = await accountSnapshotSlot(epoch - 1);
107
+ let asked = 0;
108
+ await backend.rewardAccountsAt({ slot: at.slot, hash: at.hash }, async (ask) => {
109
+ let ledgerHasAccounts = false;
110
+ for (const source of SOURCES) {
111
+ for (let after = '';;) {
112
+ if (opts.shouldStop?.())
113
+ throw new Error(`account snapshot of epoch ${epoch} stopped`);
114
+ const page = await accountPage(source, after, pageSize);
115
+ if (!page.length)
116
+ break;
117
+ after = page[page.length - 1];
118
+ if (source === 'ledger')
119
+ ledgerHasAccounts = true;
120
+ const unasked = source === 'certificates' && ledgerHasAccounts ? await notInLedger(page) : page;
121
+ if (!unasked.length)
122
+ continue;
123
+ asked += unasked.length;
124
+ const reported = await ask(unasked);
125
+ if (reported.length)
126
+ await cds_1.default.tx((tx) => storePage(tx, reported, opts, previousSlot));
127
+ }
128
+ }
129
+ });
130
+ const accounts = await cds_1.default.tx(async (tx) => {
131
+ const block = await tx.run(SELECT.one.from(cardano_1.Blocks).columns('hash').where({ hash: at.hash }));
132
+ if (!block) {
133
+ await tx.run(DELETE.from(cardano_1.AccountEpochSnapshots).where({ epoch }));
134
+ return null;
135
+ }
136
+ const counted = await tx.run(SELECT.one.from(cardano_1.AccountEpochSnapshots).columns('count(*) as n').where({ epoch }));
137
+ await tx.run(UPDATE.entity(cardano_1.EpochLedgerSnapshots).set({ accountCount: Number(counted.n), accountSnapshotSlot: at.slot }).where({ epoch }));
138
+ return Number(counted.n);
139
+ });
140
+ if (accounts == null)
141
+ throw new Error(`account snapshot of epoch ${epoch}: block ${at.hash} is no longer on the stored chain`);
142
+ logger.info(`epoch ${epoch} account snapshot (ogmios @ slot ${at.slot}): ${accounts} accounts, ${asked} asked`);
143
+ return { taken: true, asked, accounts };
144
+ }
145
+ /** Removes the account snapshots read at a block after `forkSlot`. Part of the reorg transaction. */
146
+ async function dropAccountSnapshotsAfter(tx, forkSlot) {
147
+ const stale = await tx.run(SELECT.from(cardano_1.EpochLedgerSnapshots).columns('epoch').where({ accountSnapshotSlot: { '>': forkSlot } }));
148
+ for (const { epoch } of stale) {
149
+ await tx.run(DELETE.from(cardano_1.AccountEpochSnapshots).where({ epoch }));
150
+ await tx.run(UPDATE.entity(cardano_1.EpochLedgerSnapshots).set({ accountCount: null, accountSnapshotSlot: null }).where({ epoch }));
151
+ }
152
+ }
153
+ //# sourceMappingURL=account-snapshots.js.map
@@ -0,0 +1,15 @@
1
+ export interface DecimalsBackfillProgress {
2
+ /** Catalogue rows read. */
3
+ scanned: number;
4
+ /** Units with label 333 or 444. */
5
+ candidates: number;
6
+ /** Units that received a decimals value. */
7
+ filled: number;
8
+ }
9
+ export interface DecimalsBackfillOptions {
10
+ /** Rows per page. */
11
+ chunkSize?: number;
12
+ onProgress?: (p: DecimalsBackfillProgress) => void;
13
+ }
14
+ export declare function backfillAssetDecimals(opts?: DecimalsBackfillOptions): Promise<DecimalsBackfillProgress>;
15
+ //# sourceMappingURL=asset-decimals-backfill.d.ts.map
@@ -0,0 +1,56 @@
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.backfillAssetDecimals = backfillAssetDecimals;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const cardano_1 = require("#cds-models/odatano/cardano");
9
+ const cip68_1 = require("../../cbor/cip68");
10
+ const asset_decimals_1 = require("../asset-decimals");
11
+ const { SELECT } = cds_1.default.ql;
12
+ const logger = cds_1.default.log('DecimalsBackfill');
13
+ // Fill Assets.decimals from the CIP-68 reference datum for label 333 and 444 units. Pages by unit
14
+ // only, so the query plan never depends on column statistics. A repeat run refreshes the values.
15
+ async function backfillAssetDecimals(opts = {}) {
16
+ const chunkSize = opts.chunkSize ?? 5000;
17
+ const progress = { scanned: 0, candidates: 0, filled: 0 };
18
+ let cursor = null;
19
+ for (;;) {
20
+ const done = await cds_1.default.tx(async (tx) => {
21
+ const rows = (await tx.run(SELECT.from(cardano_1.Assets).columns('unit', 'initialMintTxHash').where(cursor ? { unit: { '>': cursor } } : {}).orderBy('unit').limit(chunkSize))) ?? [];
22
+ if (!rows.length)
23
+ return true;
24
+ const full = rows.length === chunkSize;
25
+ const lastUnit = rows[rows.length - 1].unit;
26
+ const allSame = rows.every((r) => r.unit === lastUnit);
27
+ // The slices of a unit are adjacent. The last unit of a full page may continue on the next
28
+ // one, so its rows wait there; a page holding one unit only is resolved as a whole.
29
+ const complete = full && !allSame ? rows.filter((r) => r.unit !== lastUnit) : rows;
30
+ const mints = new Map();
31
+ for (const r of complete) {
32
+ if (!(0, cip68_1.cip68ReferenceUnit)(r.unit))
33
+ continue;
34
+ if (!mints.has(r.unit) || r.initialMintTxHash)
35
+ mints.set(r.unit, r.initialMintTxHash ?? null);
36
+ }
37
+ for (const [unit, mintTxHash] of mints) {
38
+ const decimals = await (0, asset_decimals_1.cip68Decimals)(tx, unit, mintTxHash);
39
+ if (decimals == null)
40
+ continue;
41
+ await (0, asset_decimals_1.setAssetDecimals)(tx, unit, decimals);
42
+ progress.filled++;
43
+ }
44
+ progress.scanned += complete.length;
45
+ progress.candidates += mints.size;
46
+ cursor = complete[complete.length - 1].unit;
47
+ return !full;
48
+ });
49
+ opts.onProgress?.({ ...progress });
50
+ if (done)
51
+ break;
52
+ }
53
+ logger.info(`asset decimals filled: ${progress.filled} of ${progress.candidates} CIP-68 units, ${progress.scanned} catalogue rows read`);
54
+ return progress;
55
+ }
56
+ //# sourceMappingURL=asset-decimals-backfill.js.map
@@ -0,0 +1,43 @@
1
+ import type { CardanoClient } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ export interface RegistryBackfillProgress {
4
+ /** Units with a CIP-26 registry entry. */
5
+ units: number;
6
+ /** Units handled so far, filled or failed. */
7
+ processed: number;
8
+ /** Units whose Assets rows received the registry values. */
9
+ filled: number;
10
+ /** Units the backend did not resolve, or entry files that could not be read. */
11
+ failed: number;
12
+ /** Source file: registry units the database has no Assets row for. */
13
+ absent: number;
14
+ /** Source file: entries that describe no native asset. */
15
+ skipped: number;
16
+ }
17
+ export interface RegistryBackfillOptions {
18
+ client: CardanoClient;
19
+ indexer: CardanoIndexer;
20
+ /** Backend calls per second; one unit is one call. */
21
+ unitsPerSecond?: number;
22
+ onProgress?: (p: RegistryBackfillProgress) => void;
23
+ }
24
+ export declare function backfillAssetRegistry(opts: RegistryBackfillOptions): Promise<RegistryBackfillProgress>;
25
+ /** The registry values of one unit, as the Assets columns hold them. */
26
+ export interface RegistryEntry {
27
+ unit: string;
28
+ registryName: string | null;
29
+ registryTicker: string | null;
30
+ registryDecimals: number | null;
31
+ registryDescription: string | null;
32
+ registryUrl: string | null;
33
+ registryLogo: string | null;
34
+ }
35
+ export declare function parseRegistryEntry(json: string): RegistryEntry | null;
36
+ export interface RegistryFileOptions {
37
+ directory: string;
38
+ onProgress?: (p: RegistryBackfillProgress) => void;
39
+ }
40
+ /** The entry files of `directory`; refuses a path that holds none. */
41
+ export declare function registryEntryFiles(directory: string): Promise<string[]>;
42
+ export declare function backfillAssetRegistryFromFiles(opts: RegistryFileOptions): Promise<RegistryBackfillProgress>;
43
+ //# sourceMappingURL=asset-registry-backfill.d.ts.map
@@ -0,0 +1,153 @@
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.backfillAssetRegistry = backfillAssetRegistry;
7
+ exports.parseRegistryEntry = parseRegistryEntry;
8
+ exports.registryEntryFiles = registryEntryFiles;
9
+ exports.backfillAssetRegistryFromFiles = backfillAssetRegistryFromFiles;
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ const fs_1 = require("fs");
12
+ const path_1 = __importDefault(require("path"));
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
14
+ const errors_1 = require("../../utils/errors");
15
+ const collections_1 = require("../../utils/collections");
16
+ const validators_1 = require("../../utils/validators");
17
+ const { UPDATE } = cds_1.default.ql;
18
+ const logger = cds_1.default.log('RegistryBackfill');
19
+ /** The run stops when this many units in a row fail: the backend is down, not the units. */
20
+ const MAX_CONSECUTIVE_FAILURES = 25;
21
+ // Fill the CIP-26 registry fields of every Assets slice for the units the registry lists. The
22
+ // registry is off-chain, so each unit is read from the backend; a repeat run refreshes the values.
23
+ async function backfillAssetRegistry(opts) {
24
+ const backend = opts.client.getTokenRegistryBackend();
25
+ if (!backend)
26
+ throw new errors_1.ProviderUnavailableError('No backend lists the token registry (needs Koios)');
27
+ const units = await backend.getTokenRegistryUnits();
28
+ const intervalMs = 1000 / Math.max(1, opts.unitsPerSecond ?? 4);
29
+ const progress = { units: units.length, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 };
30
+ const failuresByError = new Map();
31
+ let consecutiveFailures = 0;
32
+ for (const unit of units) {
33
+ const started = Date.now();
34
+ try {
35
+ await cds_1.default.tx(async (tx) => {
36
+ const row = await opts.indexer.indexAssetFromBackend(tx, unit);
37
+ // Every slice of the unit carries the registry values, the bare catalogue row included.
38
+ await tx.run(UPDATE.entity(cardano_1.Assets).set({
39
+ registryName: row.registryName ?? null,
40
+ registryTicker: row.registryTicker ?? null,
41
+ registryDecimals: row.registryDecimals ?? null,
42
+ registryDescription: row.registryDescription ?? null,
43
+ registryUrl: row.registryUrl ?? null,
44
+ registryLogo: row.registryLogo ?? null,
45
+ }).where({ unit }));
46
+ if (row.decimals != null) {
47
+ await tx.run(UPDATE.entity(cardano_1.Assets).set({ decimals: row.decimals }).where({ unit, decimals: null }));
48
+ }
49
+ });
50
+ progress.filled++;
51
+ consecutiveFailures = 0;
52
+ }
53
+ catch (err) {
54
+ progress.failed++;
55
+ consecutiveFailures++;
56
+ const errorName = err instanceof Error ? err.name : typeof err;
57
+ failuresByError.set(errorName, (failuresByError.get(errorName) ?? 0) + 1);
58
+ logger.debug(`registry fill for ${unit} failed:`, err);
59
+ if (!(err instanceof errors_1.NotFoundError) && consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
60
+ const last = err instanceof Error ? err.message : String(err);
61
+ throw new errors_1.ProviderUnavailableError(`${consecutiveFailures} units in a row failed, last: ${last}`);
62
+ }
63
+ }
64
+ progress.processed++;
65
+ opts.onProgress?.({ ...progress });
66
+ const wait = intervalMs - (Date.now() - started);
67
+ if (wait > 0)
68
+ await new Promise((r) => setTimeout(r, wait));
69
+ }
70
+ logger.info(`asset registry filled: ${progress.filled} of ${progress.units} registered units, ${progress.failed} failed`);
71
+ if (failuresByError.size > 0) {
72
+ const counts = [...failuresByError].map(([name, count]) => `${name} ${count}`).join(', ');
73
+ logger.warn(`asset registry: units not filled, by error: ${counts}`);
74
+ }
75
+ return progress;
76
+ }
77
+ // One entry file of the registry repository. Null for an entry whose subject is no asset unit, or
78
+ // that carries a preimage: the registry also describes scripts. A value too long for its column is left out.
79
+ function parseRegistryEntry(json) {
80
+ const entry = JSON.parse(json);
81
+ const unit = typeof entry.subject === 'string' ? entry.subject.toLowerCase() : '';
82
+ if (!(0, validators_1.isAssetUnit)(unit) || entry.preImage !== undefined)
83
+ return null;
84
+ const text = (name, max) => {
85
+ const value = entry[name]?.value;
86
+ return typeof value === 'string' && value.length > 0 && value.length <= max ? value : null;
87
+ };
88
+ const decimals = entry.decimals?.value;
89
+ return {
90
+ unit,
91
+ registryName: text('name', 128),
92
+ registryTicker: text('ticker', 16),
93
+ registryDecimals: typeof decimals === 'number' && Number.isInteger(decimals) && decimals >= 0 && decimals <= 255 ? decimals : null,
94
+ registryDescription: text('description', 5000),
95
+ registryUrl: text('url', 256),
96
+ registryLogo: text('logo', 500_000),
97
+ };
98
+ }
99
+ /** The entry files of `directory`; refuses a path that holds none. */
100
+ async function registryEntryFiles(directory) {
101
+ let names;
102
+ try {
103
+ names = await fs_1.promises.readdir(directory);
104
+ }
105
+ catch (err) {
106
+ throw new errors_1.TransactionValidationError(`path is not a readable folder: ${err instanceof Error ? err.message : String(err)}`);
107
+ }
108
+ const files = names.filter(n => n.endsWith('.json')).sort();
109
+ if (!files.length) {
110
+ throw new errors_1.TransactionValidationError('path holds no entry files (*.json). Name the folder mappings of cardano-token-registry, or registry of metadata-registry-testnet.');
111
+ }
112
+ return files;
113
+ }
114
+ // Fill the registry fields from the entry files of a checkout of the registry repository. Only
115
+ // units that have an Assets row are written; no backend is asked and no row is created.
116
+ async function backfillAssetRegistryFromFiles(opts) {
117
+ const files = await registryEntryFiles(opts.directory);
118
+ const progress = { units: files.length, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 };
119
+ for (const batch of (0, collections_1.chunk)(files, 200)) {
120
+ const entries = [];
121
+ for (const name of batch) {
122
+ try {
123
+ const entry = parseRegistryEntry(await fs_1.promises.readFile(path_1.default.join(opts.directory, name), 'utf8'));
124
+ if (entry)
125
+ entries.push(entry);
126
+ else
127
+ progress.skipped++;
128
+ }
129
+ catch (err) {
130
+ progress.failed++;
131
+ logger.debug(`registry entry ${name} not read:`, err);
132
+ }
133
+ }
134
+ await cds_1.default.tx(async (tx) => {
135
+ for (const { unit, ...values } of entries) {
136
+ const rows = Number(await tx.run(UPDATE.entity(cardano_1.Assets).set(values).where({ unit })));
137
+ if (!rows) {
138
+ progress.absent++;
139
+ continue;
140
+ }
141
+ progress.filled++;
142
+ if (values.registryDecimals != null) {
143
+ await tx.run(UPDATE.entity(cardano_1.Assets).set({ decimals: values.registryDecimals }).where({ unit, decimals: null }));
144
+ }
145
+ }
146
+ });
147
+ progress.processed += batch.length;
148
+ opts.onProgress?.({ ...progress });
149
+ }
150
+ logger.info(`asset registry filled from ${opts.directory}: ${progress.filled} of ${progress.units} entries, ${progress.absent} without an asset row, ${progress.skipped} not an asset, ${progress.failed} failed`);
151
+ return progress;
152
+ }
153
+ //# sourceMappingURL=asset-registry-backfill.js.map
@@ -0,0 +1,52 @@
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
+ }
28
+ export interface CertificateBackfillResult extends CertificateBackfillProgress {
29
+ fromSlot: number;
30
+ toSlot: number;
31
+ /** The chain point the stream started after. */
32
+ intersection: ChainPoint | 'origin';
33
+ }
34
+ export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
35
+ /** One streamed block of a backfill, with what the collector took from it. */
36
+ export interface StreamedBlock<T> {
37
+ hash: string;
38
+ slot: number;
39
+ transactions: number;
40
+ payload: T;
41
+ }
42
+ export interface CrawledBlockStreamOptions {
43
+ client: CardanoClient;
44
+ fromSlot: number;
45
+ toSlot: number;
46
+ batchBlocks?: number;
47
+ /** Error class the range and backend checks throw. */
48
+ errorType?: new (message: string) => Error;
49
+ }
50
+ 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'>;
51
+ export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
52
+ //# sourceMappingURL=certificate-backfill.d.ts.map