@odatano/core 2.0.0-rc.49 → 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 (120) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +6 -12
  2. package/@cds-models/CardanoIndexerService/index.d.ts +200 -2
  3. package/@cds-models/CardanoIndexerService/index.js +24 -0
  4. package/@cds-models/CardanoODataService/index.d.ts +49 -6
  5. package/@cds-models/CardanoODataService/index.js +4 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -3
  7. package/@cds-models/CardanoWorkerService/index.d.ts +4 -3
  8. package/@cds-models/index.d.ts +9 -1
  9. package/@cds-models/index.js +2 -1
  10. package/@cds-models/odatano/cardano/index.d.ts +59 -5
  11. package/@cds-models/odatano/cardano/index.js +6 -0
  12. package/README.md +29 -17
  13. package/db/schema.cds +117 -24
  14. package/db/types.cds +8 -0
  15. package/package.json +17 -15
  16. package/scripts/migrate-schema.mjs +334 -0
  17. package/src/index.d.ts +7 -5
  18. package/src/index.js +12 -10
  19. package/src/plugin.js +6 -7
  20. package/srv/blockchain/backends/blockfrost-backend.js +9 -1
  21. package/srv/blockchain/backends/cardano-backend.d.ts +15 -0
  22. package/srv/blockchain/backends/cardano-backend.js +5 -0
  23. package/srv/blockchain/backends/koios-backend.js +16 -10
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +9 -3
  25. package/srv/blockchain/backends/ogmios-backend.js +60 -18
  26. package/srv/blockchain/cardano-client.d.ts +5 -4
  27. package/srv/blockchain/cardano-client.js +46 -13
  28. package/srv/blockchain/cardano-indexer.d.ts +116 -9
  29. package/srv/blockchain/cardano-indexer.js +436 -189
  30. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  31. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  32. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +23 -1
  33. package/srv/blockchain/crawler/asset-registry-backfill.js +91 -1
  34. package/srv/blockchain/crawler/certificate-backfill.d.ts +2 -0
  35. package/srv/blockchain/crawler/certificate-backfill.js +10 -3
  36. package/srv/blockchain/crawler/crawler.d.ts +15 -0
  37. package/srv/blockchain/crawler/crawler.js +68 -3
  38. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  39. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  40. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  41. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  42. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  43. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  44. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  45. package/srv/blockchain/crawler/transaction-backfill.js +12 -8
  46. package/srv/blockchain/pool-metadata.d.ts +15 -0
  47. package/srv/blockchain/pool-metadata.js +132 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +3 -1
  49. package/srv/blockchain/signing/cose-verifier.js +144 -56
  50. package/srv/blockchain/signing/hsm-signer.js +2 -1
  51. package/srv/blockchain/signing/submission-finalizer.d.ts +15 -4
  52. package/srv/blockchain/signing/submission-finalizer.js +201 -69
  53. package/srv/blockchain/stored-chain.js +1 -1
  54. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +1 -3
  55. package/srv/blockchain/transaction-building/buildooor-tx.js +34 -54
  56. package/srv/blockchain/transaction-presence.d.ts +5 -0
  57. package/srv/blockchain/transaction-presence.js +29 -0
  58. package/srv/blockchain/transaction-rows.js +1 -1
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -1
  60. package/srv/blockchain/wallet-worker/build-request.js +25 -0
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.js +1 -1
  62. package/srv/blockchain/wallet-worker/job-store.d.ts +17 -7
  63. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  64. package/srv/blockchain/wallet-worker/signers.d.ts +2 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +2 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +42 -32
  67. package/srv/cardano-agent-service.cds +11 -12
  68. package/srv/cardano-agent-service.js +2 -0
  69. package/srv/cardano-backend-service.cds +34 -1
  70. package/srv/cardano-backend-service.js +20 -17
  71. package/srv/cardano-indexer-service.cds +153 -12
  72. package/srv/cardano-indexer-service.js +175 -29
  73. package/srv/cardano-service.cds +67 -3
  74. package/srv/cardano-service.js +132 -67
  75. package/srv/cardano-sign-service.cds +30 -20
  76. package/srv/cardano-sign-service.js +13 -10
  77. package/srv/cardano-tx-service.cds +15 -1
  78. package/srv/cardano-tx-service.js +4 -1
  79. package/srv/cardano-worker-service.cds +16 -7
  80. package/srv/cardano-worker-service.js +31 -22
  81. package/srv/cbor/parse.js +11 -34
  82. package/srv/config.d.ts +113 -0
  83. package/srv/config.js +409 -0
  84. package/srv/server.d.ts +9 -14
  85. package/srv/server.js +32 -316
  86. package/srv/utils/agent-access.d.ts +9 -0
  87. package/srv/utils/agent-access.js +67 -0
  88. package/srv/utils/agent-grants-config.d.ts +0 -17
  89. package/srv/utils/agent-grants-config.js +6 -81
  90. package/srv/utils/agent-grants.d.ts +6 -19
  91. package/srv/utils/agent-grants.js +69 -130
  92. package/srv/utils/const.d.ts +4 -0
  93. package/srv/utils/const.js +5 -1
  94. package/srv/utils/db-indexes.js +11 -3
  95. package/srv/utils/error-codes.d.ts +4 -0
  96. package/srv/utils/error-codes.js +4 -0
  97. package/srv/utils/errors.d.ts +6 -0
  98. package/srv/utils/errors.js +23 -1
  99. package/srv/utils/liveness.js +2 -5
  100. package/srv/utils/mappers.d.ts +5 -7
  101. package/srv/utils/mappers.js +22 -9
  102. package/srv/utils/pg-order-nulls.js +4 -3
  103. package/srv/utils/readiness.d.ts +12 -0
  104. package/srv/utils/readiness.js +29 -0
  105. package/srv/utils/result-numbers.d.ts +15 -0
  106. package/srv/utils/result-numbers.js +61 -0
  107. package/srv/utils/tx-request-parsers.d.ts +1 -1
  108. package/srv/utils/tx-request-parsers.js +3 -3
  109. package/srv/utils/tx-utils.d.ts +3 -0
  110. package/srv/utils/tx-utils.js +17 -3
  111. package/srv/utils/types.d.ts +16 -3
  112. package/scripts/migrate-txseq.mjs +0 -138
  113. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -13
  114. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +0 -71
  115. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -15
  116. package/srv/blockchain/transaction-building/caller-datums.js +0 -133
  117. package/srv/cbor/redeemer-tag-patch.d.ts +0 -3
  118. package/srv/cbor/redeemer-tag-patch.js +0 -61
  119. package/srv/utils/legacy-service-paths.d.ts +0 -11
  120. package/srv/utils/legacy-service-paths.js +0 -58
@@ -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
@@ -7,8 +7,12 @@ export interface RegistryBackfillProgress {
7
7
  processed: number;
8
8
  /** Units whose Assets rows received the registry values. */
9
9
  filled: number;
10
- /** Units the backend did not resolve. */
10
+ /** Units the backend did not resolve, or entry files that could not be read. */
11
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;
12
16
  }
13
17
  export interface RegistryBackfillOptions {
14
18
  client: CardanoClient;
@@ -18,4 +22,22 @@ export interface RegistryBackfillOptions {
18
22
  onProgress?: (p: RegistryBackfillProgress) => void;
19
23
  }
20
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>;
21
43
  //# sourceMappingURL=asset-registry-backfill.d.ts.map
@@ -4,9 +4,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.backfillAssetRegistry = backfillAssetRegistry;
7
+ exports.parseRegistryEntry = parseRegistryEntry;
8
+ exports.registryEntryFiles = registryEntryFiles;
9
+ exports.backfillAssetRegistryFromFiles = backfillAssetRegistryFromFiles;
7
10
  const cds_1 = __importDefault(require("@sap/cds"));
11
+ const fs_1 = require("fs");
12
+ const path_1 = __importDefault(require("path"));
8
13
  const cardano_1 = require("#cds-models/odatano/cardano");
9
14
  const errors_1 = require("../../utils/errors");
15
+ const collections_1 = require("../../utils/collections");
16
+ const validators_1 = require("../../utils/validators");
10
17
  const { UPDATE } = cds_1.default.ql;
11
18
  const logger = cds_1.default.log('RegistryBackfill');
12
19
  /** The run stops when this many units in a row fail: the backend is down, not the units. */
@@ -19,7 +26,8 @@ async function backfillAssetRegistry(opts) {
19
26
  throw new errors_1.ProviderUnavailableError('No backend lists the token registry (needs Koios)');
20
27
  const units = await backend.getTokenRegistryUnits();
21
28
  const intervalMs = 1000 / Math.max(1, opts.unitsPerSecond ?? 4);
22
- const progress = { units: units.length, processed: 0, filled: 0, failed: 0 };
29
+ const progress = { units: units.length, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 };
30
+ const failuresByError = new Map();
23
31
  let consecutiveFailures = 0;
24
32
  for (const unit of units) {
25
33
  const started = Date.now();
@@ -45,6 +53,8 @@ async function backfillAssetRegistry(opts) {
45
53
  catch (err) {
46
54
  progress.failed++;
47
55
  consecutiveFailures++;
56
+ const errorName = err instanceof Error ? err.name : typeof err;
57
+ failuresByError.set(errorName, (failuresByError.get(errorName) ?? 0) + 1);
48
58
  logger.debug(`registry fill for ${unit} failed:`, err);
49
59
  if (!(err instanceof errors_1.NotFoundError) && consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
50
60
  const last = err instanceof Error ? err.message : String(err);
@@ -58,6 +68,86 @@ async function backfillAssetRegistry(opts) {
58
68
  await new Promise((r) => setTimeout(r, wait));
59
69
  }
60
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`);
61
151
  return progress;
62
152
  }
63
153
  //# sourceMappingURL=asset-registry-backfill.js.map
@@ -12,6 +12,8 @@ export interface CertificateBackfillProgress {
12
12
  transactions: number;
13
13
  certificates: number;
14
14
  withdrawals: number;
15
+ /** Stored rows removed: certificates and withdrawals of transactions whose script phase failed. */
16
+ removed: number;
15
17
  }
16
18
  export interface CertificateBackfillOptions {
17
19
  client: CardanoClient;
@@ -9,9 +9,10 @@ exports.streamCrawledBlocks = streamCrawledBlocks;
9
9
  exports.backfillCertificates = backfillCertificates;
10
10
  const cds_1 = __importDefault(require("@sap/cds"));
11
11
  const mappers_1 = require("../../utils/mappers");
12
+ const collections_1 = require("../../utils/collections");
12
13
  const sync_state_1 = require("./sync-state");
13
14
  const cardano_1 = require("#cds-models/odatano/cardano");
14
- const { SELECT, UPSERT } = cds_1.default.ql;
15
+ const { SELECT, UPSERT, DELETE } = cds_1.default.ql;
15
16
  const logger = cds_1.default.log('CertificateBackfill');
16
17
  // Fill certificates and withdrawals for already crawled blocks from a second chain-sync stream.
17
18
  // Only those two tables are written, and a repeat run is idempotent. Unknown blocks are skipped.
@@ -124,11 +125,12 @@ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
124
125
  }
125
126
  async function backfillCertificates(opts) {
126
127
  const { fromSlot, toSlot } = opts;
127
- const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
128
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0 };
128
129
  let started = false;
129
130
  const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
130
131
  certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
131
132
  withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
133
+ failed: txs.filter((t) => t.spendsCollaterals).map((t) => t.hash),
132
134
  }), async (tx, blocks) => {
133
135
  const certs = blocks.flatMap((b) => b.payload.certs);
134
136
  const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
@@ -142,6 +144,11 @@ async function backfillCertificates(opts) {
142
144
  await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
143
145
  if (withdrawals.length)
144
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
+ }
145
152
  }, (atSlot) => {
146
153
  started = true;
147
154
  progress.atSlot = atSlot;
@@ -149,7 +156,7 @@ async function backfillCertificates(opts) {
149
156
  });
150
157
  if (!started)
151
158
  progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
152
- logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals`);
159
+ logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals, ${progress.removed} rows of failed transactions removed`);
153
160
  return { ...progress, fromSlot, toSlot, intersection };
154
161
  }
155
162
  //# sourceMappingURL=certificate-backfill.js.map
@@ -26,12 +26,16 @@ export interface CrawlerConfig {
26
26
  assetEnrichRate: number;
27
27
  /** Snapshot every pool, DRep and the ada pots at each epoch boundary (Ogmios, or Koios at the tip). */
28
28
  epochSnapshots: boolean;
29
+ /** Snapshot the reward accounts with the epoch snapshot. Needs `epochSnapshots` and Ogmios. */
30
+ accountSnapshots?: boolean;
29
31
  /** Write certificates and withdrawals per block. Ogmios and Koios report them, Blockfrost does not. */
30
32
  certificates: boolean;
31
33
  /** Maintain the Ledger* UTxO tables. Inactive until `importUtxoSet` has run once. */
32
34
  utxoSet: boolean;
33
35
  /** Answer 404 for chain data the database lacks instead of asking a provider. Needs a full synced crawl. */
34
36
  authoritative?: boolean;
37
+ /** Store a copy of the assets of every input instead of pointing at the stored output. */
38
+ inputAssetCopies?: boolean;
35
39
  }
36
40
  export declare class CardanoCrawler {
37
41
  private readonly client;
@@ -52,6 +56,8 @@ export declare class CardanoCrawler {
52
56
  private static readonly CALL_TIMEOUT_MS;
53
57
  /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
54
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;
55
61
  /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
56
62
  private static readonly SNAPSHOT_RETRY_BASE_MS;
57
63
  private static readonly SNAPSHOT_RETRY_MAX_MS;
@@ -82,6 +88,11 @@ export declare class CardanoCrawler {
82
88
  private blocksThisStream;
83
89
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
84
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;
85
96
  private finalStatus;
86
97
  /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
87
98
  private latchOnHalt;
@@ -92,6 +103,7 @@ export declare class CardanoCrawler {
92
103
  private snapshotInFlight;
93
104
  /** Consecutive snapshot failures and the earliest time the next attempt may run. */
94
105
  private snapshotFailures;
106
+ private accountSnapshotWarned;
95
107
  private snapshotRetryAfter;
96
108
  private leaseHeld;
97
109
  private leaseHeartbeat;
@@ -120,6 +132,8 @@ export declare class CardanoCrawler {
120
132
  /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
121
133
  private withTimeout;
122
134
  private runChainSync;
135
+ private armIdleWatchdog;
136
+ private clearIdleWatchdog;
123
137
  /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
124
138
  private takeFrameFailure;
125
139
  private canDegradeToPagination;
@@ -141,6 +155,7 @@ export declare class CardanoCrawler {
141
155
  /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
142
156
  private epochOfSlot;
143
157
  private maybeSnapshotEpoch;
158
+ private maybeSnapshotAccounts;
144
159
  private handleReorg;
145
160
  /** Renew the lease while no block commits; block writes renew it transactionally. */
146
161
  private startLeaseHeartbeat;
@@ -12,6 +12,7 @@ const hooks_1 = require("./hooks");
12
12
  const ledger_state_1 = require("../ledger-state");
13
13
  const transaction_rows_1 = require("../transaction-rows");
14
14
  const cardano_1 = require("#cds-models/odatano/cardano");
15
+ const account_snapshots_1 = require("./account-snapshots");
15
16
  const sync_state_1 = require("./sync-state");
16
17
  const { SELECT, DELETE, INSERT } = cds_1.default.ql;
17
18
  const logger = cds_1.default.log('CardanoCrawler');
@@ -52,6 +53,8 @@ class CardanoCrawler {
52
53
  static CALL_TIMEOUT_MS = 60_000;
53
54
  /** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
54
55
  static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
56
+ /** One node request per 2000 known accounts; an hour covers a mainnet-sized set. */
57
+ static ACCOUNT_SNAPSHOT_TIMEOUT_MS = 60 * 60_000;
55
58
  /** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
56
59
  static SNAPSHOT_RETRY_BASE_MS = 30_000;
57
60
  static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
@@ -82,6 +85,11 @@ class CardanoCrawler {
82
85
  blocksThisStream = 0;
83
86
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
84
87
  streamEnded = null;
88
+ /** An open stream that delivers nothing for this long is taken as dead and reopened at the cursor. */
89
+ static CHAIN_SYNC_IDLE_MS = 5 * 60 * 1000;
90
+ idleTimer = null;
91
+ /** Reopens since the last block, so a chain that stands still warns once. */
92
+ idleReopens = 0;
85
93
  finalStatus = 'stopped';
86
94
  /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
87
95
  latchOnHalt = false;
@@ -92,6 +100,7 @@ class CardanoCrawler {
92
100
  snapshotInFlight = null;
93
101
  /** Consecutive snapshot failures and the earliest time the next attempt may run. */
94
102
  snapshotFailures = 0;
103
+ accountSnapshotWarned = false;
95
104
  snapshotRetryAfter = 0;
96
105
  leaseHeld = false;
97
106
  leaseHeartbeat = null;
@@ -151,6 +160,7 @@ class CardanoCrawler {
151
160
  certificates: this.config.certificates,
152
161
  utxoSet: this.config.utxoSet,
153
162
  authoritative: this.config.authoritative ?? false,
163
+ inputAssetCopies: this.config.inputAssetCopies ?? false,
154
164
  });
155
165
  // Ledger state is only applied after an imported snapshot.
156
166
  if (this.config.utxoSet) {
@@ -213,6 +223,7 @@ class CardanoCrawler {
213
223
  // Background asset enrichment belongs to the crawl and must not outlive it.
214
224
  this.indexer.stopAssetEnrichment();
215
225
  this.wake?.(); // cancel a pending poll sleep so the loop exits now
226
+ this.clearIdleWatchdog();
216
227
  this.stopChainSyncProbing();
217
228
  this.streamEnded?.(); // release the ingest loop, the pipeline is awaited below
218
229
  this.leaseWake?.();
@@ -372,20 +383,27 @@ class CardanoCrawler {
372
383
  rollForward: (block, txs, tip) => this.trackCallback(async () => {
373
384
  if (!this.running)
374
385
  return;
375
- if (await this.persistBlock(block, txs, tip))
386
+ this.clearIdleWatchdog();
387
+ if (await this.persistBlock(block, txs, tip)) {
376
388
  this.blocksThisStream++;
389
+ this.idleReopens = 0;
390
+ }
391
+ this.armIdleWatchdog();
377
392
  }),
378
393
  rollBackward: (point) => this.trackCallback(async () => {
379
394
  if (!this.running)
380
395
  return;
396
+ this.clearIdleWatchdog();
381
397
  // Ogmios always opens the stream with a rollBackward to the intersection. That is the
382
398
  // handshake, not a reorg, so only roll back when the point differs from the cursor.
383
399
  const current = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
384
400
  if (point !== 'origin' && current?.lastBlockHash === point.hash) {
385
401
  logger.debug(`chain-sync intersection acknowledged at slot ${point.slot}, no reorg`);
386
- return;
387
402
  }
388
- await this.handleReorg(point);
403
+ else {
404
+ await this.handleReorg(point);
405
+ }
406
+ this.armIdleWatchdog();
389
407
  }),
390
408
  onError: (err) => this.trackCallback(async () => {
391
409
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
@@ -425,8 +443,34 @@ class CardanoCrawler {
425
443
  }
426
444
  this.chainSyncHandle = handle;
427
445
  this.activeSource = 'chain-sync';
446
+ this.armIdleWatchdog();
428
447
  logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
429
448
  }
449
+ // Starts the silence timer of the open stream. It runs only between frames, so a block that
450
+ // takes long to store never counts as silence. A half-open socket sends neither frames nor a close.
451
+ armIdleWatchdog() {
452
+ this.clearIdleWatchdog();
453
+ if (!this.running || !this.chainSyncHandle)
454
+ return;
455
+ const idleMs = CardanoCrawler.CHAIN_SYNC_IDLE_MS;
456
+ this.idleTimer = setTimeout(() => {
457
+ this.idleTimer = null;
458
+ if (!this.running || !this.chainSyncHandle)
459
+ return;
460
+ const message = `chain-sync delivered nothing for ${Math.round(idleMs / 1000)} s, reopening at the cursor`;
461
+ if (this.idleReopens++ === 0)
462
+ logger.warn(message);
463
+ else
464
+ logger.debug(message);
465
+ void this.trackCallback(() => this.endStream(() => { this.reopenStream = true; }));
466
+ }, idleMs);
467
+ this.idleTimer.unref?.();
468
+ }
469
+ clearIdleWatchdog() {
470
+ if (this.idleTimer)
471
+ clearTimeout(this.idleTimer);
472
+ this.idleTimer = null;
473
+ }
430
474
  /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
431
475
  takeFrameFailure() {
432
476
  const failure = this.frameFailure;
@@ -451,6 +495,7 @@ class CardanoCrawler {
451
495
  /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
452
496
  async endStream(mark) {
453
497
  mark();
498
+ this.clearIdleWatchdog();
454
499
  const handle = this.chainSyncHandle;
455
500
  this.chainSyncHandle = null;
456
501
  if (handle) {
@@ -797,6 +842,7 @@ class CardanoCrawler {
797
842
  logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1}: passed outside the snapshot window`);
798
843
  }
799
844
  }
845
+ await this.maybeSnapshotAccounts(epoch, at);
800
846
  this.snapshotedEpoch = epoch;
801
847
  this.snapshotFailures = 0;
802
848
  this.snapshotRetryAfter = 0;
@@ -811,6 +857,24 @@ class CardanoCrawler {
811
857
  })
812
858
  .finally(() => { this.snapshotInFlight = null; });
813
859
  }
860
+ // The account snapshot of an epoch, after its pool snapshot. Skipped with one warning without a
861
+ // backend that reads the ledger at a block.
862
+ async maybeSnapshotAccounts(epoch, at) {
863
+ if (!this.config.accountSnapshots)
864
+ return;
865
+ const backend = at.hash ? this.client.getRewardAccountStateBackend() : null;
866
+ if (!backend || !at.hash) {
867
+ if (!this.accountSnapshotWarned)
868
+ logger.warn('account snapshots need Ogmios (the ledger at the snapshot block); none is taken');
869
+ this.accountSnapshotWarned = true;
870
+ return;
871
+ }
872
+ await this.withTimeout((0, account_snapshots_1.snapshotAccounts)({
873
+ backend, epoch, at: { slot: at.slot, hash: at.hash },
874
+ withdrawals: this.config.certificates,
875
+ shouldStop: () => !this.running,
876
+ }), `snapshotAccounts(${epoch})`, CardanoCrawler.ACCOUNT_SNAPSHOT_TIMEOUT_MS);
877
+ }
814
878
  // Roll back in one transaction. Deletes blocks after the fork slot, never by height, and their transactions.
815
879
  // Lazily indexed transactions of other blocks stay. Resets the cursor and logs the reorg.
816
880
  async handleReorg(point) {
@@ -857,6 +921,7 @@ class CardanoCrawler {
857
921
  }
858
922
  // Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
859
923
  if (blocksRolledBack > 0) {
924
+ await (0, account_snapshots_1.dropAccountSnapshotsAfter)(tx, forkSlot);
860
925
  for (const entity of [cardano_1.PoolEpochSnapshots, cardano_1.DrepEpochSnapshots, cardano_1.EpochLedgerSnapshots]) {
861
926
  await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
862
927
  }
@@ -0,0 +1,34 @@
1
+ /** Columns of an asset row besides its key, the same in the copies and in the output assets. */
2
+ export declare const ASSET_COLUMNS: string[];
3
+ export interface InputCopyPruneProgress {
4
+ atSlot: number;
5
+ toSlot: number;
6
+ referenced: number;
7
+ kept: number;
8
+ deleted: number;
9
+ }
10
+ export interface InputCopyRestoreProgress {
11
+ atSlot: number;
12
+ toSlot: number;
13
+ restored: number;
14
+ rows: number;
15
+ }
16
+ export interface SlotWalkOptions<P> {
17
+ fromSlot: number;
18
+ toSlot: number;
19
+ slotWindow?: number;
20
+ onProgress?: (p: P) => void;
21
+ }
22
+ export declare function referenceStatement(kind: string): string | null;
23
+ /** Deletes the copies of the inputs of a window that have a reference. */
24
+ export declare function deleteCopiesStatement(kind: string): string | null;
25
+ /** Counts the inputs of a window that have no reference. */
26
+ export declare function keptStatement(kind: string): string | null;
27
+ /** Writes the copies of the inputs of a window that have a reference, from the outputs they spent. */
28
+ export declare function restoreCopiesStatement(kind: string): string | null;
29
+ /** Takes the reference from the inputs of a window, once their copies are written. */
30
+ export declare function dropReferenceStatement(kind: string): string | null;
31
+ export declare function bothStatement(kind: string): string | null;
32
+ export declare function pruneInputAssetCopies(opts: SlotWalkOptions<InputCopyPruneProgress>): Promise<InputCopyPruneProgress>;
33
+ export declare function restoreInputAssetCopies(opts: SlotWalkOptions<InputCopyRestoreProgress>): Promise<InputCopyRestoreProgress>;
34
+ //# sourceMappingURL=input-asset-copies.d.ts.map