@odatano/core 2.0.0-rc.21 → 2.0.0-rc.24

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 (45) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +18 -0
  4. package/@cds-models/CardanoIndexerService/index.js +3 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +37 -0
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/odatano/cardano/index.d.ts +37 -0
  8. package/@cds-models/odatano/cardano/index.js +3 -0
  9. package/db/schema.cds +2226 -2133
  10. package/package.json +182 -181
  11. package/srv/blockchain/backends/cardano-backend.d.ts +23 -0
  12. package/srv/blockchain/backends/cardano-backend.js +5 -0
  13. package/srv/blockchain/backends/odatano-backend.d.ts +59 -0
  14. package/srv/blockchain/backends/odatano-backend.js +154 -0
  15. package/srv/blockchain/backends/ogmios-backend.d.ts +92 -9
  16. package/srv/blockchain/backends/ogmios-backend.js +164 -32
  17. package/srv/blockchain/cardano-client.d.ts +19 -5
  18. package/srv/blockchain/cardano-client.js +53 -12
  19. package/srv/blockchain/cardano-indexer.d.ts +100 -4
  20. package/srv/blockchain/cardano-indexer.js +466 -23
  21. package/srv/blockchain/cardano-tx-builder.js +2 -2
  22. package/srv/blockchain/crawler/crawler.d.ts +20 -5
  23. package/srv/blockchain/crawler/crawler.js +78 -15
  24. package/srv/blockchain/crawler/utxo-set-import.js +3 -0
  25. package/srv/blockchain/ledger-state.d.ts +6 -0
  26. package/srv/blockchain/ledger-state.js +29 -0
  27. package/srv/blockchain/stored-chain.d.ts +30 -0
  28. package/srv/blockchain/stored-chain.js +208 -0
  29. package/srv/cardano-backend-service.cds +52 -0
  30. package/srv/cardano-backend-service.d.ts +2 -0
  31. package/srv/cardano-backend-service.js +217 -0
  32. package/srv/cardano-indexer-service.cds +176 -164
  33. package/srv/cardano-indexer-service.js +30 -0
  34. package/srv/cardano-service.cds +6 -1
  35. package/srv/cardano-service.js +5 -2
  36. package/srv/server.js +19 -2
  37. package/srv/utils/agent-grants.js +7 -0
  38. package/srv/utils/const.d.ts +4 -0
  39. package/srv/utils/const.js +4 -3
  40. package/srv/utils/db-indexes.js +1 -0
  41. package/srv/utils/errors.d.ts +8 -0
  42. package/srv/utils/errors.js +14 -1
  43. package/srv/utils/mappers.d.ts +19 -2
  44. package/srv/utils/mappers.js +25 -7
  45. package/srv/utils/types.d.ts +8 -1
@@ -12,6 +12,7 @@ const CardanoSignService_1 = require("#cds-models/CardanoSignService");
12
12
  // service projection carries (see ensureAssetRows).
13
13
  const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const mappers_1 = require("../utils/mappers");
15
+ const errors_1 = require("../utils/errors");
15
16
  const collections_1 = require("../utils/collections");
16
17
  const transaction_rows_1 = require("./transaction-rows");
17
18
  const ledger_state_1 = require("./ledger-state");
@@ -56,7 +57,13 @@ class CardanoIndexer {
56
57
  * Ledger* tables; no anchor means configured but inactive.
57
58
  */
58
59
  crawlUtxoSet = false;
60
+ /** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
61
+ crawlAuthoritative = false;
59
62
  utxoAnchor = null;
63
+ /** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
64
+ credentialsReady = false;
65
+ credentialFill = null;
66
+ credentialGeneration = 0;
60
67
  /** The anchor block was found in the crawled chain (checked once, before the first apply). */
61
68
  utxoAnchorVerified = false;
62
69
  /**
@@ -77,6 +84,7 @@ class CardanoIndexer {
77
84
  enrichRate = 2;
78
85
  /** Adopt the crawler's coverage settings; the lazy request path never touches these. */
79
86
  configureCrawlCoverage(coverage) {
87
+ this.crawlAuthoritative = coverage.authoritative ?? false;
80
88
  this.crawlAssetHistory = coverage.assetHistory;
81
89
  this.crawlAssetCatalogue = coverage.assetCatalogue;
82
90
  this.crawlCertificates = coverage.certificates ?? false;
@@ -116,6 +124,235 @@ class CardanoIndexer {
116
124
  counts.blocksMinted = await countSince(0);
117
125
  return counts;
118
126
  }
127
+ /**
128
+ * The crawled chain answers `method` on its own: live crawler at the tip, crawl from the Shelley
129
+ * start, and either crawler.authoritative or no configured backend can serve the method.
130
+ */
131
+ async crawlAnswers(tx, method) {
132
+ const coverage = await this.localCoverage(tx);
133
+ if (!coverage || coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
134
+ return null;
135
+ if (!this.crawlAuthoritative && this.client.hasBackendFor(method))
136
+ return null;
137
+ return { lastSlot: coverage.lastSlot };
138
+ }
139
+ /** 404 for a lookup the crawled chain answers on its own (the caller already missed in the DB). */
140
+ async refuseOutsideCrawl(tx, method, what) {
141
+ const coverage = await this.crawlAnswers(tx, method);
142
+ if (coverage)
143
+ throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
144
+ }
145
+ /**
146
+ * Asset from crawled mint/burn rows: supply = mints − burns, first mint, CIP-25 payload (label 721)
147
+ * of the latest mint. Registry fields stay null. null = the crawled chain does not answer.
148
+ */
149
+ async localAssetInfo(tx, unit) {
150
+ if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
151
+ return null;
152
+ const events = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).columns('txHash', 'action', 'quantity', 'blockTime', 'blockHeight').where({ unit }));
153
+ if (!events?.length)
154
+ throw new errors_1.NotFoundError(`Asset ${unit} (never minted in the crawled chain)`);
155
+ const ordered = [...events].sort((a, b) => Number(a.blockHeight ?? 0) - Number(b.blockHeight ?? 0));
156
+ let supply = 0n;
157
+ for (const e of ordered)
158
+ supply += (e.action === 'burn' ? -1n : 1n) * BigInt(String(e.quantity ?? '0'));
159
+ const mints = ordered.filter(e => e.action !== 'burn');
160
+ const first = mints[0];
161
+ const latest = mints[mints.length - 1];
162
+ let onchainMetadata = null;
163
+ if (latest) {
164
+ const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
165
+ if (meta?.payload) {
166
+ try {
167
+ onchainMetadata = JSON.parse(meta.payload);
168
+ }
169
+ catch { /* unparseable payload: leave empty */ }
170
+ }
171
+ }
172
+ const policyId = unit.slice(0, 56);
173
+ const assetNameHex = unit.slice(56);
174
+ return {
175
+ unit,
176
+ policyId,
177
+ assetNameHex,
178
+ assetName: assetNameHex ? (0, mappers_1.decodeAssetName)(assetNameHex) : null,
179
+ fingerprint: (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex),
180
+ totalSupply: supply.toString(),
181
+ mintOrBurnCount: ordered.length,
182
+ initialMintTxHash: first?.txHash ?? null,
183
+ initialMintTime: first?.blockTime == null ? null : Number(first.blockTime),
184
+ onchainMetadata,
185
+ registryName: null,
186
+ registryTicker: null,
187
+ registryDecimals: null,
188
+ registryDescription: null,
189
+ registryUrl: null,
190
+ registryLogo: null,
191
+ };
192
+ }
193
+ /** Address from the crawled UTxO set when it answers, else from the backend. */
194
+ async resolveAddress(tx, addr) {
195
+ return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
196
+ }
197
+ /** UTxOs of an address: the crawled set (outputs from the node at the tip) when it answers, else the backend. */
198
+ async resolveAddressUtxos(tx, addr) {
199
+ return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
200
+ }
201
+ /** Asset from the crawled chain when it answers, else from the backend. */
202
+ async resolveAssetInfo(tx, unit) {
203
+ return (await this.localAssetInfo(tx, unit)) ?? await this.client.getAssetInfo(unit);
204
+ }
205
+ /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
206
+ async resolveAssetHistory(tx, unit, limit) {
207
+ if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
208
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
209
+ return (rows ?? []).map(r => ({
210
+ unit: String(r.unit),
211
+ txHash: String(r.txHash),
212
+ action: r.action === 'burn' ? 'burn' : 'mint',
213
+ quantity: String(r.quantity),
214
+ blockTime: r.blockTime == null ? null : Number(r.blockTime),
215
+ blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
216
+ }));
217
+ }
218
+ return this.client.getAssetHistory(unit, limit);
219
+ }
220
+ /** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
221
+ async resolveCredentialUtxos(tx, credHash) {
222
+ return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
223
+ }
224
+ /** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
225
+ async resolveAddressTransactionHashes(tx, addr, limit) {
226
+ const local = await this.localAddressTransactions(tx, addr, limit);
227
+ if (local && (local.complete || local.rows.length >= limit)) {
228
+ return local.rows.map(r => String(r.tx_hash));
229
+ }
230
+ try {
231
+ return await this.client.getAddressTransactionHashes(addr, limit);
232
+ }
233
+ catch (err) {
234
+ if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
235
+ return local.rows.map(r => String(r.tx_hash));
236
+ }
237
+ throw err;
238
+ }
239
+ }
240
+ /** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
241
+ async ledgerCoverageActive(tx) {
242
+ return Boolean((await this.localCoverage(tx))?.ledger);
243
+ }
244
+ /**
245
+ * Address from the crawled UTxO set: outputs from the node at the tip (Ogmios) or the unspent
246
+ * `LedgerUTxOs`, type and stake address decoded from the address. An address the set has never
247
+ * seen is an empty address, not an error. null = the set cannot answer.
248
+ */
249
+ async localAddress(tx, addr) {
250
+ if (!(await this.localCoverage(tx))?.ledger)
251
+ return null;
252
+ let utxos = null;
253
+ try {
254
+ utxos = await this.client.getUtxosByAddresses([addr]);
255
+ }
256
+ catch (err) {
257
+ logger.warn(`address ${addr}: node UTxO query failed, answering from the crawled set: ${err?.message ?? err}`);
258
+ }
259
+ utxos ??= await this.ledgerUtxosOf(tx, [addr]);
260
+ const decoded = (0, mappers_1.decodeShelleyAddress)(addr);
261
+ return {
262
+ address: addr,
263
+ stakeAddress: decoded.stakeAddress,
264
+ type: decoded.type,
265
+ isScript: decoded.isScript,
266
+ amount: (0, mappers_1.sumUtxoAmounts)(utxos),
267
+ utxos,
268
+ };
269
+ }
270
+ /**
271
+ * Latest transactions of an address from the crawled UTxO set: the outputs it received
272
+ * (`LedgerUTxOs.txHash`) and spent (`spentTxHash`) since the anchor. `complete` = the address was
273
+ * first seen after the anchor, so nothing older exists. null = the set cannot answer.
274
+ */
275
+ async localAddressTransactions(tx, addr, limit) {
276
+ if (!(await this.localCoverage(tx))?.ledger)
277
+ return null;
278
+ const known = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('firstSeenSlot').where({ address: addr }));
279
+ if (!known)
280
+ return { rows: [], complete: false };
281
+ const complete = known.firstSeenSlot != null;
282
+ // Candidate transactions by slot; a transaction can touch the address with several outputs.
283
+ const scan = Math.min(limit * 20, 2000);
284
+ const [created, spent] = await Promise.all([
285
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'createdSlot')
286
+ .where({ address: addr, createdSlot: { '>=': 0 } }).orderBy('createdSlot desc').limit(scan)),
287
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('spentTxHash', 'spentSlot')
288
+ .where({ address: addr, spentSlot: { '>=': 0 } }).orderBy('spentSlot desc').limit(scan)),
289
+ ]);
290
+ const slotOf = new Map();
291
+ for (const r of created ?? [])
292
+ slotOf.set(r.txHash, Number(r.createdSlot));
293
+ for (const r of spent ?? [])
294
+ slotOf.set(r.spentTxHash, Number(r.spentSlot));
295
+ const selected = [...slotOf].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([hash]) => hash);
296
+ if (selected.length === 0)
297
+ return { rows: [], complete };
298
+ const [outRows, inRows] = await Promise.all([
299
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, txHash: { in: selected } })),
300
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, spentTxHash: { in: selected } })),
301
+ ]);
302
+ const amounts = await this.ledgerAmounts(tx, [...(outRows ?? []), ...(inRows ?? [])]);
303
+ const amountOf = (r) => amounts.get(`${r.txHash}#${Number(r.outputIndex)}`) ?? [];
304
+ const txs = selected.map((hash) => ({
305
+ hash,
306
+ blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, slotOf.get(hash)),
307
+ inputs: (inRows ?? []).filter(r => r.spentTxHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
308
+ outputs: (outRows ?? []).filter(r => r.txHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
309
+ }));
310
+ const rows = (0, mappers_1.mapAddressTransactions)(addr, txs);
311
+ rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0));
312
+ return { rows: rows, complete };
313
+ }
314
+ /** Amount lists (lovelace + assets) of `LedgerUTxOs` rows, keyed `txHash#outputIndex`. */
315
+ async ledgerAmounts(tx, rows) {
316
+ const out = new Map();
317
+ for (const r of rows)
318
+ out.set(`${r.txHash}#${Number(r.outputIndex)}`, [{ unit: 'lovelace', quantity: String(r.lovelace ?? '0') }]);
319
+ const withAssets = [...new Set(rows.filter(r => r.hasAssets).map(r => String(r.txHash)))];
320
+ for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
321
+ const assetRows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).columns('utxo_txHash', 'utxo_outputIndex', 'unit', 'asset_quantity')
322
+ .where({ utxo_txHash: { in: hashChunk } }));
323
+ for (const a of assetRows ?? []) {
324
+ out.get(`${a.utxo_txHash}#${Number(a.utxo_outputIndex)}`)?.push({ unit: a.unit, quantity: String(a.asset_quantity) });
325
+ }
326
+ }
327
+ return out;
328
+ }
329
+ /**
330
+ * Active stake of a pool from the Ogmios epoch snapshot of the running epoch (constant within
331
+ * an epoch). Empty when the crawler is not at the tip or the epoch has no such snapshot.
332
+ */
333
+ async snapshotActiveStake(tx, poolId) {
334
+ const coverage = await this.localCoverage(tx);
335
+ if (!coverage)
336
+ return {};
337
+ const epoch = (0, epoch_slots_1.epochOfSlot)(this.client.network, coverage.lastSlot);
338
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.PoolEpochSnapshots).columns('activeStake', 'activeSize').where({ poolId, epoch, source: 'ogmios' }));
339
+ if (!row || row.activeStake == null)
340
+ return {};
341
+ return { activeStake: lovelaceSum(row.activeStake), activeSize: Number(row.activeSize ?? 0) };
342
+ }
343
+ /**
344
+ * Lifetime withdrawals of a stake key from crawled withdrawals — only when certificates are
345
+ * crawled and the crawl covers the chain since Shelley; null otherwise.
346
+ */
347
+ async localWithdrawalsSum(tx, stakeAddress) {
348
+ const coverage = await this.localCoverage(tx);
349
+ if (!coverage || !this.crawlCertificates)
350
+ return null;
351
+ if (coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
352
+ return null;
353
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionWithdrawals).columns('sum(lovelace) as total').where({ stakeAddress }));
354
+ return lovelaceSum(row?.total);
355
+ }
119
356
  /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
120
357
  setUtxoAnchor(anchor) {
121
358
  this.utxoAnchor = anchor;
@@ -288,6 +525,7 @@ class CardanoIndexer {
288
525
  * transaction, so either everything persists or nothing does.
289
526
  */
290
527
  async indexTransaction(tx, txHash) {
528
+ await this.refuseOutsideCrawl(tx, 'getTransaction', `Transaction ${txHash}`);
291
529
  const providerTx = await this.client.getTransaction(txHash);
292
530
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
293
531
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
@@ -323,7 +561,7 @@ class CardanoIndexer {
323
561
  * indexAddressTransactions().
324
562
  */
325
563
  async indexAddress(tx, addr) {
326
- const addrData = await this.client.getAddress(addr);
564
+ const addrData = await this.resolveAddress(tx, addr);
327
565
  logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
328
566
  const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
329
567
  const now = new Date().toISOString();
@@ -384,8 +622,9 @@ class CardanoIndexer {
384
622
  * rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
385
623
  */
386
624
  async indexCredentialUtxos(tx, credHash) {
387
- const utxos = await this.client.getCredentialUtxos(credHash);
388
- logger.debug(`indexCredentialUtxos: provider returned ${utxos.length} utxos for credential ${credHash}`);
625
+ const local = await this.localCredentialUtxos(tx, credHash);
626
+ const utxos = local ?? await this.client.getCredentialUtxos(credHash);
627
+ logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
389
628
  if (utxos.length === 0)
390
629
  return [];
391
630
  // Group by bech32 address — Koios returns UTxOs across all bech32 forms
@@ -421,6 +660,79 @@ class CardanoIndexer {
421
660
  logger.debug(`indexCredentialUtxos: indexed ${allRows.length} utxos across ${byAddress.size} addresses`);
422
661
  return allRows;
423
662
  }
663
+ /**
664
+ * UTxOs of a payment credential without a provider: addresses from the crawled UTxO set, outputs
665
+ * from the node at the tip (Ogmios) or, without one, the unspent `LedgerUTxOs` as of the cursor.
666
+ * null = the crawled set cannot answer (not synced, no set, credential column still filling).
667
+ * An address first used in the last `confirmationDepth` blocks is not in the set yet.
668
+ */
669
+ async localCredentialUtxos(tx, credHash) {
670
+ if (!(await this.localCoverage(tx))?.ledger || !(await this.paymentCredentialsReady()))
671
+ return null;
672
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
673
+ const addresses = (rows ?? []).map(r => r.address);
674
+ if (addresses.length === 0)
675
+ return [];
676
+ try {
677
+ const live = await this.client.getUtxosByAddresses(addresses);
678
+ if (live)
679
+ return live;
680
+ }
681
+ catch (err) {
682
+ logger.warn(`credential ${credHash}: node UTxO query failed, answering from the crawled set: ${err?.message ?? err}`);
683
+ }
684
+ return this.ledgerUtxosOf(tx, addresses);
685
+ }
686
+ /** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
687
+ async ledgerUtxosOf(tx, addresses) {
688
+ const out = [];
689
+ for (const addrChunk of (0, collections_1.chunk)(addresses, collections_1.IN_CHUNK)) {
690
+ const utxos = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: { in: addrChunk }, spentTxHash: null }));
691
+ const amounts = await this.ledgerAmounts(tx, utxos ?? []);
692
+ for (const u of utxos ?? []) {
693
+ const txHash = String(u.txHash);
694
+ const outputIndex = Number(u.outputIndex);
695
+ out.push({
696
+ txHash,
697
+ outputIndex,
698
+ address: String(u.address),
699
+ amount: amounts.get(`${txHash}#${outputIndex}`) ?? [],
700
+ blockHash: '',
701
+ datumHash: u.utxo_dataHash ?? undefined,
702
+ inlineDatum: u.utxo_inlineDatum ?? null,
703
+ scriptRef: u.utxo_referenceScriptHash ?? undefined,
704
+ });
705
+ }
706
+ }
707
+ return out;
708
+ }
709
+ /**
710
+ * True once every Shelley-type `LedgerAddresses` row carries its payment credential. Until then
711
+ * the fill runs in the background (started once per process) and callers use the provider.
712
+ */
713
+ async paymentCredentialsReady() {
714
+ if (this.credentialsReady)
715
+ return true;
716
+ if (!this.credentialFill) {
717
+ const generation = this.credentialGeneration;
718
+ this.credentialFill = (0, ledger_state_1.backfillPaymentCredentials)()
719
+ .then((n) => {
720
+ if (generation !== this.credentialGeneration)
721
+ return;
722
+ this.credentialsReady = true;
723
+ if (n > 0)
724
+ logger.info(`payment credentials filled for ${n} ledger addresses`);
725
+ })
726
+ .catch((err) => logger.error('payment credential fill failed (retried on the next lookup):', err))
727
+ .finally(() => { this.credentialFill = null; });
728
+ }
729
+ return false;
730
+ }
731
+ /** The ledger tables were replaced (re-import): the credential column has to be filled again. */
732
+ resetPaymentCredentials() {
733
+ this.credentialGeneration++;
734
+ this.credentialsReady = false;
735
+ }
424
736
  /**
425
737
  * Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
426
738
  * backends without address aggregation such as Ogmios. Writes no parent Addresses row.
@@ -472,8 +784,25 @@ class CardanoIndexer {
472
784
  /** Index address transactions (separate from indexAddress for lazy loading). */
473
785
  async indexAddressTransactions(tx, addr, limit) {
474
786
  logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
787
+ const local = await this.localAddressTransactions(tx, addr, limit);
788
+ const keepLocal = async () => {
789
+ if (local.rows.length)
790
+ await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(local.rows));
791
+ return local.rows;
792
+ };
793
+ if (local && (local.complete || local.rows.length >= limit))
794
+ return keepLocal();
475
795
  // Hash-only listing (one API call)
476
- const txHashes = await this.client.getAddressTransactionHashes(addr, limit);
796
+ let txHashes;
797
+ try {
798
+ txHashes = await this.client.getAddressTransactionHashes(addr, limit);
799
+ }
800
+ catch (err) {
801
+ // No backend with address history: what the crawled set holds is the best answer there is.
802
+ if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError))
803
+ return keepLocal();
804
+ throw err;
805
+ }
477
806
  logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
478
807
  if (txHashes.length === 0)
479
808
  return [];
@@ -527,6 +856,13 @@ class CardanoIndexer {
527
856
  }
528
857
  /** Index the metadata rows of a transaction. */
529
858
  async indexTransactionMetadata(tx, tx_hash) {
859
+ // A crawled transaction without metadata rows has no metadata.
860
+ if (await this.crawlAnswers(tx, 'getTransactionMetadata')) {
861
+ const known = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
862
+ if (known)
863
+ return [];
864
+ await this.refuseOutsideCrawl(tx, 'getTransactionMetadata', `Transaction ${tx_hash}`);
865
+ }
530
866
  const metadata = await this.client.getTransactionMetadata(tx_hash);
531
867
  const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
532
868
  if (rows.length) {
@@ -536,16 +872,21 @@ class CardanoIndexer {
536
872
  }
537
873
  /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
538
874
  async indexNetworkInformation(tx) {
875
+ const netEntity = (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
876
+ await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
877
+ return netEntity;
878
+ }
879
+ /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
880
+ async resolveNetworkInformation(tx) {
539
881
  const netInfo = await this.client.getNetworkInformation();
540
882
  const circulating = (await this.localCoverage(tx))?.ledger
541
883
  ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
542
884
  : null;
543
- const netEntity = (0, mappers_1.mapNetworkInfo)(circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } }, this.client.max_age_ms, this.client.network);
544
- await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
545
- return netEntity;
885
+ return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
546
886
  }
547
887
  /** Index a block by hash, with best-effort epoch enrichment. */
548
888
  async indexBlock(tx, blockHash) {
889
+ await this.refuseOutsideCrawl(tx, 'getBlock', `Block ${blockHash}`);
549
890
  const blockInfo = await this.client.getBlock(blockHash);
550
891
  let epoch;
551
892
  try {
@@ -918,15 +1259,20 @@ class CardanoIndexer {
918
1259
  this.assetMemo.add(unit);
919
1260
  }
920
1261
  /**
921
- * Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit):
922
- * dated snapshot rows plus a refresh of the live `Pools` / `Dreps` rows. Needs Koios, else a no-op.
923
- * @returns counts written
1262
+ * Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit), plus
1263
+ * one EpochLedgerSnapshots row that marks the epoch as observed. With a block hash and an Ogmios
1264
+ * backend the node's ledger state AT that block is read; otherwise Koios reports current state
1265
+ * (and the live `Pools` / `Dreps` rows are refreshed). Neither available: no-op.
1266
+ * @returns counts written and the source used (null = skipped)
924
1267
  */
925
1268
  async snapshotEpoch(epoch, at) {
1269
+ const epochState = at.hash ? this.client.getEpochStateBackend() : null;
1270
+ if (epochState && at.hash)
1271
+ return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash });
926
1272
  const backend = this.client.getEnumeratingBackend();
927
1273
  if (!backend) {
928
- logger.warn(`epoch ${epoch} snapshot skipped: no backend can enumerate pools/DReps (Koios required)`);
929
- return { pools: 0, dreps: 0 };
1274
+ logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
1275
+ return { pools: 0, dreps: 0, source: null };
930
1276
  }
931
1277
  // Network first, DB second — the provider round-trips must not run with a write lock held.
932
1278
  const [poolData, drepData] = await Promise.all([
@@ -937,6 +1283,11 @@ class CardanoIndexer {
937
1283
  const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
938
1284
  const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
939
1285
  const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
1286
+ const ledgerRow = {
1287
+ epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: null, source: 'koios',
1288
+ liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
1289
+ poolCount: poolData.length, drepCount: drepData.length,
1290
+ };
940
1291
  await cds_1.default.tx(async (tx) => {
941
1292
  // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
942
1293
  for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
@@ -947,9 +1298,81 @@ class CardanoIndexer {
947
1298
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
948
1299
  for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
949
1300
  await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
1301
+ await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
950
1302
  });
951
- logger.info(`epoch ${epoch} snapshot: ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
952
- return { pools: poolSnapshots.length, dreps: drepSnapshots.length };
1303
+ logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1304
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
1305
+ }
1306
+ /**
1307
+ * Epoch snapshot from the node's ledger state at block `at`. The live `Pools` / `Dreps` rows are
1308
+ * NOT refreshed: the acquired state may be hours old. `blocksMinted` counts crawled blocks up to
1309
+ * `at`, only when the crawl covers the chain since Shelley.
1310
+ */
1311
+ async snapshotEpochFromLedger(backend, epoch, at) {
1312
+ const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
1313
+ if (state.epoch !== epoch) {
1314
+ logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch} — stored as ${epoch}`);
1315
+ }
1316
+ const minted = await this.crawledBlocksByPool(at.slot);
1317
+ const previous = await this.previousLiveStake(epoch);
1318
+ const activeTotal = previous ? [...previous.values()].reduce((a, b) => a + b, 0n) : 0n;
1319
+ const origin = { source: 'ogmios', hash: at.hash };
1320
+ const poolSnapshots = state.pools.map(p => {
1321
+ const active = previous?.get(p.poolId);
1322
+ return {
1323
+ ...(0, mappers_1.mapPoolSnapshot)(p, epoch, at, origin),
1324
+ blocksMinted: minted ? (minted.get(p.poolId) ?? 0) : null,
1325
+ activeStake: active == null ? null : active.toString(),
1326
+ activeSize: active == null || activeTotal === 0n ? null : Number((active * 1000000n) / activeTotal) / 1_000_000,
1327
+ };
1328
+ });
1329
+ const drepSnapshots = state.dreps.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at, origin));
1330
+ const reserves = state.reserves == null ? null : BigInt(state.reserves);
1331
+ const ledgerRow = {
1332
+ epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: at.hash, source: 'ogmios',
1333
+ treasury: state.treasury,
1334
+ reserves: state.reserves,
1335
+ totalSupply: reserves == null ? null : (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves).toString(),
1336
+ liveStake: state.pools.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
1337
+ activeStake: previous ? activeTotal.toString() : null,
1338
+ poolCount: state.pools.length,
1339
+ drepCount: state.dreps.length,
1340
+ drepAbstainStake: state.drepAbstainStake,
1341
+ drepNoConfidenceStake: state.drepNoConfidenceStake,
1342
+ };
1343
+ await cds_1.default.tx(async (tx) => {
1344
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
1345
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
1346
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
1347
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
1348
+ await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
1349
+ });
1350
+ logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1351
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
1352
+ }
1353
+ /**
1354
+ * Active stake of epoch E = the stake distribution taken at the E-1 boundary, which is the live
1355
+ * stake the Ogmios snapshot of E-1 recorded at its first block. null without that snapshot.
1356
+ */
1357
+ async previousLiveStake(epoch) {
1358
+ const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
1359
+ if (!rows?.length)
1360
+ return null;
1361
+ return new Map(rows.map(r => [r.poolId, BigInt(lovelaceSum(r.liveStake))]));
1362
+ }
1363
+ /** Crawled blocks per pool up to `slot`; null unless the crawl started at or before Shelley. */
1364
+ async crawledBlocksByPool(slot) {
1365
+ const db = cds_1.default.db;
1366
+ const cursor = await (0, sync_state_1.readCursor)(db);
1367
+ const shelley = const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot;
1368
+ if (cursor?.startSlot == null || cursor.startSlot > shelley)
1369
+ return null;
1370
+ const rows = await db.run(SELECT.from(CardanoODataService_1.Blocks).columns('slotLeader', 'count(*) as n').where({ slot: { '<=': slot } }).groupBy('slotLeader'));
1371
+ const out = new Map();
1372
+ for (const r of rows ?? [])
1373
+ if (r.slotLeader)
1374
+ out.set(r.slotLeader, Number(r.n));
1375
+ return out;
953
1376
  }
954
1377
  /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
955
1378
  collectBlockUnits(txs, assetHistoryRows) {
@@ -980,12 +1403,7 @@ class CardanoIndexer {
980
1403
  }
981
1404
  /** Index an account by stake address, plus its addresses when it has any. */
982
1405
  async indexAccount(tx, stakeAddress) {
983
- const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
984
- // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
985
- if ((await this.localCoverage(tx))?.ledger) {
986
- const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
987
- accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
988
- }
1406
+ const accountInfo = await this.resolveAccount(tx, stakeAddress);
989
1407
  const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
990
1408
  await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
991
1409
  const addresses = accountInfo.addresses.map(a => a.address);
@@ -994,6 +1412,21 @@ class CardanoIndexer {
994
1412
  }
995
1413
  return accountEntity;
996
1414
  }
1415
+ /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
1416
+ async resolveAccount(tx, stakeAddress) {
1417
+ const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
1418
+ // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
1419
+ if ((await this.localCoverage(tx))?.ledger) {
1420
+ const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
1421
+ accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
1422
+ }
1423
+ if (accountInfo.withdrawalsSum === '0') {
1424
+ const local = await this.localWithdrawalsSum(tx, stakeAddress);
1425
+ if (local != null)
1426
+ accountInfo.withdrawalsSum = local;
1427
+ }
1428
+ return accountInfo;
1429
+ }
997
1430
  /** Index a DRep by bech32 id. */
998
1431
  async indexDrep(tx, drepId) {
999
1432
  const drepInfo = await this.client.getDrep(drepId);
@@ -1003,14 +1436,21 @@ class CardanoIndexer {
1003
1436
  }
1004
1437
  /** Index a pool by id. */
1005
1438
  async indexPool(tx, poolId) {
1006
- const poolInfo = await this.client.getPool(poolId);
1007
- const poolEntity = (0, mappers_1.mapPool)({ ...poolInfo, ...(await this.localPoolBlocks(tx, poolId)) }, this.client.max_age_ms);
1439
+ const poolEntity = (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
1008
1440
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
1009
1441
  return poolEntity;
1010
1442
  }
1443
+ /** Pool from the backend with crawled block counts and the snapshot's active stake. */
1444
+ async resolvePool(tx, poolId) {
1445
+ const poolInfo = { ...(await this.client.getPool(poolId)), ...(await this.localPoolBlocks(tx, poolId)) };
1446
+ // The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
1447
+ if (poolInfo.activeStake === '0')
1448
+ Object.assign(poolInfo, await this.snapshotActiveStake(tx, poolId));
1449
+ return poolInfo;
1450
+ }
1011
1451
  /** Index an asset by unit (policyId + assetNameHex). */
1012
1452
  async indexAsset(tx, unit) {
1013
- const assetInfo = await this.client.getAssetInfo(unit);
1453
+ const assetInfo = await this.resolveAssetInfo(tx, unit);
1014
1454
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1015
1455
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
1016
1456
  return assetEntity;
@@ -1020,6 +1460,9 @@ class CardanoIndexer {
1020
1460
  * refetch refreshes the recent cap and older cached entries persist.
1021
1461
  */
1022
1462
  async indexAssetHistory(tx, unit, limit = 100) {
1463
+ if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
1464
+ return await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
1465
+ }
1023
1466
  const events = await this.client.getAssetHistory(unit, limit);
1024
1467
  if (events.length === 0)
1025
1468
  return [];
@@ -110,7 +110,7 @@ class CardanoTransactionBuilder {
110
110
  utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
111
111
  protocolParameters: protocolParameters,
112
112
  // Pass evaluator if Ogmios is available for dynamic execution unit calculation
113
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
113
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
114
114
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
115
115
  : undefined,
116
116
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -152,7 +152,7 @@ class CardanoTransactionBuilder {
152
152
  const txContext = {
153
153
  utxos: mergedUtxos,
154
154
  protocolParameters: protocolParameters,
155
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
155
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
156
156
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
157
157
  : undefined,
158
158
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined