@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
@@ -69,6 +69,11 @@ function ogmiosDrepToId(d) {
69
69
  return 'drep_always_no_confidence';
70
70
  return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
71
71
  }
72
+ // Reward balance of a summary. Ogmios 7.0 answers 0 for an account without a pool delegation,
73
+ // whatever it holds, so that balance is unknown.
74
+ function ogmiosRewardBalance(summary) {
75
+ return summary.stakePool?.id ? ogmiosValueToLovelaceString(summary.rewards) : null;
76
+ }
72
77
  /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
73
78
  function ogmiosValueToLovelaceString(value) {
74
79
  if (value === null || value === undefined)
@@ -191,7 +196,6 @@ function mapOgmiosRedeemers(tx) {
191
196
  };
192
197
  });
193
198
  }
194
- /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
195
199
  class OgmiosBackend {
196
200
  name = 'ogmios';
197
201
  /** Ogmios cannot answer historic queries. The orchestrator skips it for these. */
@@ -515,24 +519,56 @@ class OgmiosBackend {
515
519
  // Runs `fn` on the ledger state at `point` over a separate WebSocket. A connection holds one acquired
516
520
  // point, so the shared socket would pin live queries to the past. `point` must be within k blocks.
517
521
  async withLedgerStateAt(point, label, fn) {
522
+ const session = await this.openLedgerStateAt(point, label);
523
+ try {
524
+ return await fn(session.client);
525
+ }
526
+ finally {
527
+ await session.close();
528
+ }
529
+ }
530
+ /** A connection of its own with the ledger state at `point` acquired. The caller closes it. */
531
+ async openLedgerStateAt(point, label) {
518
532
  const url = new URL(this.ogmiosUrl);
519
533
  const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
520
534
  const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] ${label} context error: ${err.message}`), () => { }, { connection });
521
- let client = null;
522
535
  try {
523
- client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
524
- return await fn(client);
525
- }
526
- finally {
536
+ const client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
527
537
  // shutdown() closes THIS connection only; the backend's own socket is untouched
528
- if (client) {
529
- try {
538
+ return { client, close: async () => { try {
530
539
  await client.shutdown();
531
540
  }
532
- catch { /* best effort */ }
533
- }
534
- else
535
- this.forceCloseContext(context);
541
+ catch { /* best effort */ } } };
542
+ }
543
+ catch (err) {
544
+ this.forceCloseContext(context);
545
+ throw err;
546
+ }
547
+ }
548
+ // Reward accounts at `point`. The node lists an account while it is delegated to a pool or a DRep.
549
+ // Errors of `read` itself pass through unchanged.
550
+ async rewardAccountsAt(point, read) {
551
+ const session = await (0, backend_request_handler_1.handleBackendRequest)(() => this.openLedgerStateAt(point, 'account snapshot'), this.name);
552
+ try {
553
+ return await read((stakeAddresses) => (0, backend_request_handler_1.handleBackendRequest)(async () => {
554
+ if (!stakeAddresses.length)
555
+ return [];
556
+ // the node keeps key and script credentials apart and finds a script only under `scripts`
557
+ const scripts = stakeAddresses.filter(a => (0, mappers_1.decodeShelleyAddress)(a).isScript);
558
+ const keys = scripts.length ? stakeAddresses.filter(a => !scripts.includes(a)) : stakeAddresses;
559
+ const raw = await session.client.rewardAccountSummaries({ ...(keys.length ? { keys } : {}), ...(scripts.length ? { scripts } : {}) });
560
+ const summaries = (Array.isArray(raw) ? raw : Object.values(raw));
561
+ return summaries.flatMap((s) => (s.credential ? [{
562
+ stakeAddress: (0, mappers_1.credentialToStakeAddress)(s.credential, s.from === 'script', this.network),
563
+ withdrawableAmount: ogmiosRewardBalance(s),
564
+ deposit: s.deposit == null ? null : ogmiosValueToLovelaceString(s.deposit),
565
+ poolId: s.stakePool?.id || null,
566
+ drepId: ogmiosDrepToId(s.delegateRepresentative),
567
+ }] : []));
568
+ }, this.name));
569
+ }
570
+ finally {
571
+ await session.close();
536
572
  }
537
573
  }
538
574
  /** Whole UTxO set as of `point` (crawler snapshot import). */
@@ -597,7 +633,10 @@ class OgmiosBackend {
597
633
  pledge: ogmiosValueToLovelaceString(pool.pledge),
598
634
  margin: parseOgmiosRatio(pool.margin),
599
635
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
600
- rewardAccount: pool.rewardAccount || ''
636
+ rewardAccount: pool.rewardAccount || '',
637
+ // the node knows where the file is, not what it says
638
+ metadataUrl: pool.metadata?.url ?? null,
639
+ metadataHash: pool.metadata?.hash ?? null,
601
640
  };
602
641
  }, this.name);
603
642
  }
@@ -624,11 +663,11 @@ class OgmiosBackend {
624
663
  activeEpoch: 0,
625
664
  // reward-account summaries carry no controlled amount and no withdrawal totals
626
665
  controlledAmount: '0',
627
- rewardsSum: ogmiosValueToLovelaceString(account.rewards),
666
+ rewardsSum: ogmiosRewardBalance(account),
628
667
  withdrawalsSum: '0',
629
668
  reservesSum: '0',
630
669
  treasurySum: '0',
631
- withdrawableAmount: ogmiosValueToLovelaceString(account.rewards),
670
+ withdrawableAmount: ogmiosRewardBalance(account),
632
671
  poolId: account.stakePool?.id || null,
633
672
  drepId: ogmiosDrepToId(account.delegateRepresentative),
634
673
  addresses: []
@@ -1132,12 +1171,15 @@ class OgmiosBackend {
1132
1171
  fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1133
1172
  spendsCollaterals,
1134
1173
  totalCollateral,
1135
- deposit: '0',
1174
+ // Only certificates and proposals move deposits, and none applies when the script phase failed.
1175
+ // Null leaves the amount to the indexer, which has the spent inputs.
1176
+ deposit: spendsCollaterals || !(tx.certificates?.length || tx.proposals?.length) ? '0' : null,
1177
+ treasuryDonation: tx.treasury?.donation?.ada?.lovelace?.toString() ?? null,
1136
1178
  // The ledger applies no mint when the script phase failed: the body's mint field is
1137
1179
  // declared but never enacted, so a phase-2 failure must report none at all.
1138
1180
  mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
1139
- // chain-sync has no serialized size, and 0 would look like a real size
1140
- size: null,
1181
+ // null without the bytes: 0 would look like a real size
1182
+ size: tx.cbor ? tx.cbor.length / 2 : null,
1141
1183
  blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
1142
1184
  inputs,
1143
1185
  outputs,
@@ -1,10 +1,9 @@
1
- import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend, TokenRegistryBackend } from './backends/cardano-backend';
1
+ import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend, TokenRegistryBackend, RewardAccountStateBackend } from './backends/cardano-backend';
2
2
  import { PendingSpends } from './pending-spends';
3
3
  import { type CircuitBreakerConfig } from './circuit-breaker';
4
4
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
5
5
  export type Network = 'mainnet' | 'preview' | 'preprod';
6
6
  export type BackendName = 'blockfrost' | 'koios' | 'ogmios' | 'odatano';
7
- export type TransactionBuilderName = 'buildooor';
8
7
  export type CardanoClientConfig = {
9
8
  network: Network;
10
9
  backends: BackendName[];
@@ -16,7 +15,6 @@ export type CardanoClientConfig = {
16
15
  odatanoUrl?: string;
17
16
  /** Key for the remote ODATANO (a gateway `oda_…` key or an agent grant token). */
18
17
  odatanoApiKey?: string;
19
- transactionBuilders: TransactionBuilderName[];
20
18
  primaryTimeoutMs: number;
21
19
  fallbackTimeoutMs: number;
22
20
  indexTtlMs: number;
@@ -39,7 +37,6 @@ export declare class CardanoClient {
39
37
  private protocolParamsFetchPromise;
40
38
  /** Last protocol parameters the live backend (node) answered. */
41
39
  private lastLiveProtocolParams?;
42
- private static readonly PROTOCOL_PARAMS_TTL_MS;
43
40
  private txCoalescer;
44
41
  private addrCoalescer;
45
42
  private credCoalescer;
@@ -105,6 +102,8 @@ export declare class CardanoClient {
105
102
  hasBackendFor(method: string): boolean;
106
103
  /** Backend that reads pool, DRep and pot state at a block. Preferred source of epoch snapshots. */
107
104
  getEpochStateBackend(): EpochStateBackend | null;
105
+ /** Backend that reads reward accounts at a block, for account snapshots. */
106
+ getRewardAccountStateBackend(): RewardAccountStateBackend | null;
108
107
  /** Without one, epoch snapshots stay off instead of making thousands of single requests. */
109
108
  getEnumeratingBackend(): EnumeratingBackend | null;
110
109
  /** Backend that lists the CIP-26 token registry (Koios). Null when none is configured. */
@@ -121,6 +120,8 @@ export declare class CardanoClient {
121
120
  /** True iff the UTxO exists and is unspent. */
122
121
  isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
123
122
  submitTransaction(signedTxCbor: string): Promise<string>;
123
+ /** True when a configured backend can serve the method. */
124
+ supports(methodName: string): boolean;
124
125
  /** True when Ogmios is the live backend. */
125
126
  hasOgmiosBackend(): boolean;
126
127
  /** The backend that evaluates scripts: the live one (Ogmios), else an evaluating historical one (odatano). */
@@ -8,12 +8,16 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const cardano_backend_1 = require("./backends/cardano-backend");
9
9
  const errors_1 = require("../utils/errors");
10
10
  const pending_spends_1 = require("./pending-spends");
11
+ const const_1 = require("../utils/const");
11
12
  const circuit_breaker_1 = require("./circuit-breaker");
12
13
  const request_coalescer_1 = require("./request-coalescer");
13
- const ogmios_backend_1 = require("./backends/ogmios-backend");
14
- const blockfrost_backend_1 = require("./backends/blockfrost-backend");
15
- const koios_backend_1 = require("./backends/koios-backend");
16
- const odatano_backend_1 = require("./backends/odatano-backend");
14
+ // A backend module loads when its backend is configured, and its provider SDK with it.
15
+ const backendModules = {
16
+ ogmios: () => require('./backends/ogmios-backend'),
17
+ blockfrost: () => require('./backends/blockfrost-backend'),
18
+ koios: () => require('./backends/koios-backend'),
19
+ odatano: () => require('./backends/odatano-backend'),
20
+ };
17
21
  const logger = cds_1.default.log('CardanoClient');
18
22
  /** Which backend type to prefer per method. */
19
23
  const METHOD_ROUTING = {
@@ -52,14 +56,13 @@ class CardanoClient {
52
56
  /** Backends whose init failed. They stay in rotation and init is retried per request. */
53
57
  uninitializedBackends = new Set();
54
58
  network;
55
- max_age_ms = 60000; // default 1 minute for temporary caching
59
+ max_age_ms = const_1.DEFAULT_INDEX_TTL_MS;
56
60
  /** Transactions submitted through this client that the ledger view does not show yet. */
57
61
  pendingSpends = new pending_spends_1.PendingSpends();
58
62
  protocolParamsCache;
59
63
  protocolParamsFetchPromise = null;
60
64
  /** Last protocol parameters the live backend (node) answered. */
61
65
  lastLiveProtocolParams;
62
- static PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes
63
66
  // Deduplicate concurrent fetches for the same resource.
64
67
  txCoalescer = new request_coalescer_1.RequestCoalescer();
65
68
  addrCoalescer = new request_coalescer_1.RequestCoalescer();
@@ -69,17 +72,21 @@ class CardanoClient {
69
72
  this.network = clientConfig.network;
70
73
  const backends = clientConfig.backends;
71
74
  if (backends.includes('ogmios')) {
72
- this.liveBackend = new ogmios_backend_1.OgmiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.ogmiosUrl);
75
+ const { OgmiosBackend } = backendModules.ogmios();
76
+ this.liveBackend = new OgmiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.ogmiosUrl);
73
77
  }
74
78
  if (backends.includes('blockfrost')) {
75
- this.historicalBackends.push(new blockfrost_backend_1.BlockfrostBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.blockfrostApiKey, clientConfig.blockfrostCustomBackend));
79
+ const { BlockfrostBackend } = backendModules.blockfrost();
80
+ this.historicalBackends.push(new BlockfrostBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.blockfrostApiKey, clientConfig.blockfrostCustomBackend));
76
81
  }
77
82
  if (backends.includes('koios')) {
78
- this.historicalBackends.push(new koios_backend_1.KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
83
+ const { KoiosBackend } = backendModules.koios();
84
+ this.historicalBackends.push(new KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
79
85
  }
80
86
  if (backends.includes('odatano')) {
81
87
  // A remote ODATANO runs its own failover chain: allow its primary timeout plus the fallback.
82
- this.historicalBackends.push(new odatano_backend_1.OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
88
+ const { OdatanoBackend } = backendModules.odatano();
89
+ this.historicalBackends.push(new OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
83
90
  }
84
91
  if (!this.liveBackend && this.historicalBackends.length === 0) {
85
92
  throw new errors_1.ConfigError('No valid backends configured for CardanoClient');
@@ -334,8 +341,21 @@ class CardanoClient {
334
341
  getDrep(drepId) {
335
342
  return this.route('getDrep', b => b.getDrep(drepId));
336
343
  }
337
- getAccount(stakeAddress) {
338
- return this.route('getAccount', b => b.getAccount(stakeAddress));
344
+ // The node reports no balance for an account without a pool delegation. A provider then
345
+ // answers in its place; without one the node's answer stands, balance unknown.
346
+ async getAccount(stakeAddress) {
347
+ const account = await this.route('getAccount', b => b.getAccount(stakeAddress));
348
+ if (account.withdrawableAmount != null)
349
+ return account;
350
+ for (const provider of this.historicalBackends) {
351
+ try {
352
+ return await this.callWithResilience(provider, () => provider.getAccount(stakeAddress));
353
+ }
354
+ catch (err) {
355
+ logger.debug(`getAccount on ${provider.name} failed, trying the next provider: ${err instanceof Error ? err.message : String(err)}`);
356
+ }
357
+ }
358
+ return account;
339
359
  }
340
360
  // The node lists only delegated credentials, so its absence proves nothing and providers decide.
341
361
  // A provider 404 means not registered. Null when no source could tell.
@@ -478,6 +498,15 @@ class CardanoClient {
478
498
  }
479
499
  return null;
480
500
  }
501
+ /** Backend that reads reward accounts at a block, for account snapshots. */
502
+ getRewardAccountStateBackend() {
503
+ const candidates = [this.liveBackend, ...this.historicalBackends];
504
+ for (const b of candidates) {
505
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isRewardAccountStateBackend)(b))
506
+ return b;
507
+ }
508
+ return null;
509
+ }
481
510
  /** Without one, epoch snapshots stay off instead of making thousands of single requests. */
482
511
  getEnumeratingBackend() {
483
512
  const candidates = [...this.historicalBackends, this.liveBackend];
@@ -512,7 +541,7 @@ class CardanoClient {
512
541
  /** Protocol parameters with a 5-minute in-memory cache and coalesced refresh. */
513
542
  async getProtocolParameters() {
514
543
  const now = Date.now();
515
- if (this.protocolParamsCache && (now - this.protocolParamsCache.fetchedAt) < CardanoClient.PROTOCOL_PARAMS_TTL_MS) {
544
+ if (this.protocolParamsCache && (now - this.protocolParamsCache.fetchedAt) < const_1.PROTOCOL_PARAMS_TTL_MS) {
516
545
  logger.debug('Returning cached protocol parameters');
517
546
  return this.protocolParamsCache.data;
518
547
  }
@@ -595,6 +624,10 @@ class CardanoClient {
595
624
  throw err;
596
625
  }
597
626
  }
627
+ /** True when a configured backend can serve the method. */
628
+ supports(methodName) {
629
+ return [this.liveBackend, ...this.historicalBackends].some((b) => !!b && !b.unsupportedMethods?.has(methodName));
630
+ }
598
631
  /** True when Ogmios is the live backend. */
599
632
  hasOgmiosBackend() {
600
633
  return this.liveBackend?.name === 'ogmios';
@@ -6,6 +6,45 @@ import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTran
6
6
  import { TxBuildRequest, TxBuildPlutusRequest, AssetInfo, AccountData, PoolData, NetworkInformation as ProviderNetworkInformation, Address as ProviderAddress, Transaction as ProviderTransaction, UTxO as OdatanoUtxo, BlockData, AssetHistoryEntry as AssetHistoryEntryProviderData, TransactionConfirmations } from '../utils/types';
7
7
  import { type LedgerAnchor, type LedgerLookup } from './ledger-state';
8
8
  import type { TxCacheTargets } from '../utils/tx-build-helper';
9
+ /** Newest transactions of an address as read: the rows to answer with and what is not stored yet. */
10
+ export interface FetchedAddressTransactions {
11
+ rows: AddressTransaction[];
12
+ newRows: AddressTransaction[];
13
+ transactions: Map<string, ProviderTransaction>;
14
+ }
15
+ /** An address as read; `transactions` is null when their read failed. */
16
+ export interface FetchedAddress {
17
+ address: string;
18
+ data: ProviderAddress;
19
+ transactions: FetchedAddressTransactions | null;
20
+ }
21
+ /** An account as read, with the addresses it controls. */
22
+ export interface FetchedAccount {
23
+ account: AccountData;
24
+ addresses: FetchedAddress[];
25
+ }
26
+ /** A block as read; `epoch` is missing when the backend has no data for its epoch. */
27
+ export interface FetchedBlock {
28
+ block: BlockData;
29
+ epoch?: Epoch;
30
+ }
31
+ /** Metadata of a transaction as the backend reports it. */
32
+ export interface FetchedTransactionMetadata {
33
+ txHash: string;
34
+ metadata: Awaited<ReturnType<CardanoClient['getTransactionMetadata']>>;
35
+ }
36
+ /** Progress of backfillEpochs. */
37
+ export interface EpochBackfillProgress {
38
+ atEpoch: number;
39
+ toEpoch: number;
40
+ updated: number;
41
+ created: number;
42
+ }
43
+ /** Protocol parameters; `fresh` is false when the stored row was still current. */
44
+ export interface FetchedProtocolParameters {
45
+ row: LedgerProtocolParameter;
46
+ fresh: boolean;
47
+ }
9
48
  /** Fetches chain data, maps it to entity rows and UPSERTs them in the caller's transaction. */
10
49
  export declare class CardanoIndexer {
11
50
  private client;
@@ -31,6 +70,8 @@ export declare class CardanoIndexer {
31
70
  private crawlUtxoSet;
32
71
  /** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
33
72
  private crawlAuthoritative;
73
+ /** crawler.inputAssetCopies: every crawled input keeps a copy of its assets and points at no output. */
74
+ private crawlInputAssetCopies;
34
75
  private utxoAnchor;
35
76
  /** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
36
77
  private credentialsReady;
@@ -40,6 +81,10 @@ export declare class CardanoIndexer {
40
81
  private utxoAnchorVerified;
41
82
  /** Kept until the crawler confirms the block commit, so a rolled-back attempt changes nothing. */
42
83
  private ledgerInvalidation;
84
+ /** Load pool metadata files from their registered URL. Off unless configured. */
85
+ private poolMetadataFetch;
86
+ private poolMetadataByHash;
87
+ private static readonly POOL_METADATA_MEMO_CAP;
43
88
  /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
44
89
  private static readonly ASSET_MEMO_CAP;
45
90
  /** Output references per node lookup when checking crawled UTxOs. */
@@ -57,6 +102,7 @@ export declare class CardanoIndexer {
57
102
  certificates?: boolean;
58
103
  utxoSet?: boolean;
59
104
  authoritative?: boolean;
105
+ inputAssetCopies?: boolean;
60
106
  }): void;
61
107
  private localCoverage;
62
108
  private localPoolBlocks;
@@ -70,6 +116,8 @@ export declare class CardanoIndexer {
70
116
  resolveAddressUtxos(tx: CapTransaction, addr: string): Promise<OdatanoUtxo[]>;
71
117
  /** Asset from the crawled chain when it answers, else from the backend. */
72
118
  resolveAssetInfo(tx: CapTransaction, unit: string): Promise<AssetInfo>;
119
+ /** Stored mint/burn rows, newest first. Null when the crawled chain does not answer for them. */
120
+ private crawledAssetHistory;
73
121
  /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
74
122
  resolveAssetHistory(tx: CapTransaction, unit: string, limit: number): Promise<AssetHistoryEntryProviderData[]>;
75
123
  /** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
@@ -79,8 +127,8 @@ export declare class CardanoIndexer {
79
127
  /** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
80
128
  ledgerCoverageActive(tx: CapTransaction): Promise<boolean>;
81
129
  private localAddress;
82
- /** Addresses of a stake key from the crawled UTxO set, with their unspent outputs (one read for all). */
83
- private localAccountAddresses;
130
+ /** Addresses of a stake key in the crawled UTxO set, with their stored unspent outputs (one read for all). */
131
+ private ledgerAccountUtxos;
84
132
  private localAddressTransactions;
85
133
  /** Amount lists (lovelace + assets) of `LedgerUTxOs` rows, keyed `txHash#outputIndex`. */
86
134
  private ledgerAmounts;
@@ -103,43 +151,76 @@ export declare class CardanoIndexer {
103
151
  private crawledEpochTotals;
104
152
  /** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
105
153
  private bareEpochRow;
154
+ backfillEpochs(onProgress?: (p: EpochBackfillProgress) => void): Promise<EpochBackfillProgress>;
106
155
  constructor(client: CardanoClient, txBuilder: CardanoTransactionBuilder);
107
156
  private localAddressUtxos;
157
+ /** A transaction from the backend. 404 when the crawled chain answers for it alone. */
158
+ fetchTransaction(tx: CapTransaction, txHash: string): Promise<ProviderTransaction>;
108
159
  /** All UPSERTs run in the caller's transaction, so everything persists or nothing does. */
160
+ storeTransaction(tx: CapTransaction, providerTx: ProviderTransaction): Promise<CardanoTransaction>;
161
+ /** Reads a transaction from the backend and stores it. */
109
162
  indexTransaction(tx: CapTransaction, txHash: string): Promise<CardanoTransaction>;
110
163
  /** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
111
164
  private writeTransactionChildren;
165
+ fetchAddress(tx: CapTransaction, addr: string, prefetched?: ProviderAddress): Promise<FetchedAddress>;
166
+ /** Reads an address and its newest transactions, then stores them. */
112
167
  indexAddress(tx: CapTransaction, addr: string, prefetched?: ProviderAddress): Promise<Address>;
113
- /** Always fresh from the backend. Rows are written without a parent Addresses row. */
168
+ /** Stores what fetchAddress read: the address, its assets, UTxOs and newest transactions. */
169
+ storeAddress(tx: CapTransaction, fetched: FetchedAddress): Promise<Address>;
170
+ /** UTxOs of a payment credential, always fresh: the crawled set when it answers, else the backend. */
171
+ fetchCredentialUtxos(tx: CapTransaction, credHash: string): Promise<OdatanoUtxo[]>;
172
+ /** Reads the UTxOs of a payment credential and stores them. */
114
173
  indexCredentialUtxos(tx: CapTransaction, credHash: string): Promise<AddressUTxO[]>;
174
+ /** Stores credential UTxOs. Rows are written without a parent Addresses row. */
175
+ storeCredentialUtxos(tx: CapTransaction, utxos: OdatanoUtxo[]): Promise<AddressUTxO[]>;
115
176
  private localCredentialUtxos;
116
- private openLedgerUtxos;
177
+ private unspentAtNode;
117
178
  /** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
118
179
  private ledgerUtxosOf;
119
180
  paymentCredentialsReady(): Promise<boolean>;
120
181
  /** The ledger tables were replaced (re-import): the credential column has to be filled again. */
121
182
  resetPaymentCredentials(): void;
122
183
  indexAddressUtxos(tx: CapTransaction, addr: string): Promise<AddressUTxO[]>;
184
+ /** The UTxOs of an address from the backend. */
185
+ fetchAddressUtxos(addr: string): Promise<OdatanoUtxo[]>;
186
+ /** Stores the UTxOs of an address. Writes no parent Addresses row. */
187
+ storeAddressUtxos(tx: CapTransaction, addr: string, utxos: OdatanoUtxo[]): Promise<AddressUTxO[]>;
123
188
  invalidateUtxoCacheForTx(tx: CapTransaction, targets: TxCacheTargets, extraAddresses?: string[]): Promise<void>;
124
189
  /** Index address transactions (separate from indexAddress for lazy loading). */
125
190
  indexAddressTransactions(tx: CapTransaction, addr: string, limit: number): Promise<AddressTransaction[]>;
191
+ fetchAddressTransactions(tx: CapTransaction, addr: string, limit: number): Promise<FetchedAddressTransactions>;
192
+ storeAddressTransactions(tx: CapTransaction, fetched: FetchedAddressTransactions): Promise<AddressTransaction[]>;
126
193
  /** Link an address to a signing request for address-based queries. */
127
194
  indexAddressSigningRequests(tx: CapTransaction, addr: string, signingRequestId: string): Promise<void>;
128
195
  /** Link an address to a transaction build for address-based queries. */
129
196
  indexAddressTransactionBuilds(tx: CapTransaction, addr: string, buildId: string): Promise<void>;
130
197
  /** Index the metadata rows of a transaction. */
131
198
  indexTransactionMetadata(tx: CapTransaction, tx_hash: string): Promise<TransactionMetadata[]>;
199
+ /** Metadata of a transaction from the backend. Null when the transaction is known to have none. */
200
+ fetchTransactionMetadata(tx: CapTransaction, tx_hash: string): Promise<FetchedTransactionMetadata | null>;
201
+ /** Stores the metadata rows of a transaction and returns them. */
202
+ storeTransactionMetadata(tx: CapTransaction, fetched: FetchedTransactionMetadata | null): Promise<TransactionMetadata[]>;
132
203
  /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
133
204
  indexNetworkInformation(tx: CapTransaction): Promise<NetworkInformation>;
205
+ /** The network information row, read but not stored. */
206
+ fetchNetworkInformation(tx: CapTransaction): Promise<NetworkInformation>;
207
+ storeNetworkInformation(tx: CapTransaction, netEntity: NetworkInformation): Promise<NetworkInformation>;
134
208
  /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
135
209
  resolveNetworkInformation(tx: CapTransaction): Promise<ProviderNetworkInformation>;
136
210
  /** Index a block by hash, with best-effort epoch enrichment. */
137
211
  indexBlock(tx: CapTransaction, blockHash: string): Promise<Block>;
212
+ /** A block and its epoch from the backend. 404 when the crawled chain answers for it alone. */
213
+ fetchBlock(tx: CapTransaction, blockHash: string): Promise<FetchedBlock>;
214
+ private withEpoch;
215
+ /** Stores a block and, when it was read, its epoch. */
216
+ storeBlock(tx: CapTransaction, fetched: FetchedBlock): Promise<Block>;
138
217
  indexBlockFull(tx: CapTransaction, blockData: BlockData, txs: ProviderTransaction[]): Promise<void>;
139
218
  private removeSupersededBlocks;
140
219
  private removeStaleTxSeqs;
141
220
  private warnIfCertificatesUnreported;
142
221
  resolveInputs(tx: CapTransaction, txs: ProviderTransaction[], ledger?: LedgerLookup): Promise<void>;
222
+ private referenceStoredOutputs;
223
+ private applyDeposits;
143
224
  private applyCollateralFees;
144
225
  private buildAssetHistoryRows;
145
226
  private ensureAssetRows;
@@ -161,18 +242,36 @@ export declare class CardanoIndexer {
161
242
  private collectBlockUnits;
162
243
  /** Index an epoch by number. */
163
244
  indexEpoch(tx: CapTransaction, epochNumber: number): Promise<Epoch>;
245
+ /** An epoch row from the backend. */
246
+ fetchEpoch(epochNumber: number): Promise<Epoch>;
247
+ storeEpoch(tx: CapTransaction, epochEntity: Epoch): Promise<Epoch>;
164
248
  /** Index an account by stake address, plus its addresses when it has any. */
165
249
  indexAccount(tx: CapTransaction, stakeAddress: string): Promise<Account>;
250
+ /** An account and the addresses it controls, read but not stored. */
251
+ fetchAccount(tx: CapTransaction, stakeAddress: string): Promise<FetchedAccount>;
252
+ /** Stores what fetchAccount read. */
253
+ storeAccount(tx: CapTransaction, fetched: FetchedAccount): Promise<Account>;
166
254
  /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
167
255
  resolveAccount(tx: CapTransaction, stakeAddress: string): Promise<AccountData>;
168
256
  /** Index a DRep by bech32 id. */
169
257
  indexDrep(tx: CapTransaction, drepId: string): Promise<Drep>;
258
+ /** A DRep row from the backend. */
259
+ fetchDrep(drepId: string): Promise<Drep>;
260
+ storeDrep(tx: CapTransaction, drepEntity: Drep): Promise<Drep>;
170
261
  /** Index a pool by id. */
171
262
  indexPool(tx: CapTransaction, poolId: string): Promise<Pool>;
172
- /** Pool from the backend with crawled block counts and the snapshot's active stake. */
263
+ /** A pool row, read but not stored. */
264
+ fetchPool(tx: CapTransaction, poolId: string): Promise<Pool>;
265
+ storePool(tx: CapTransaction, poolEntity: Pool): Promise<Pool>;
266
+ /** Pool from the backend with crawled block counts, the snapshot's active stake and its metadata file. */
173
267
  resolvePool(tx: CapTransaction, poolId: string): Promise<PoolData>;
268
+ private poolMetadataOf;
269
+ /** Turns the loading of pool metadata files on or off (`poolMetadataFetch`). */
270
+ setPoolMetadataFetch(enabled: boolean): void;
174
271
  /** Index an asset by unit (policyId + assetNameHex). */
175
272
  indexAsset(tx: CapTransaction, unit: string): Promise<Asset>;
273
+ /** Stores an asset read with resolveAssetInfo. */
274
+ storeAsset(tx: CapTransaction, assetInfo: AssetInfo): Promise<Asset>;
176
275
  /** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
177
276
  indexAssetFromBackend(tx: CapTransaction, unit: string): Promise<Asset>;
178
277
  private writeAsset;
@@ -189,6 +288,10 @@ export declare class CardanoIndexer {
189
288
  indexPlutusBuildResult(tx: CapTransaction, buildreq: TxBuildPlutusRequest): Promise<TransactionBuild>;
190
289
  /** Protocol parameters, served from the DB row within a 5-minute TTL. */
191
290
  indexProtocolParameters(tx: CapTransaction): Promise<LedgerProtocolParameter>;
291
+ /** The stored row within its TTL, else the parameters from the backend. Nothing is written. */
292
+ fetchProtocolParameters(tx: CapTransaction): Promise<FetchedProtocolParameters>;
293
+ /** Stores parameters that came from the backend and restarts their TTL. */
294
+ storeProtocolParameters(tx: CapTransaction, fetched: FetchedProtocolParameters): Promise<LedgerProtocolParameter>;
192
295
  /** Persist a transaction submission and flag the build as submitted when linked. */
193
296
  persistTransactionSubmission(tx: CapTransaction, params: {
194
297
  signedTxCbor: string;
@@ -196,8 +299,8 @@ export declare class CardanoIndexer {
196
299
  buildId?: string | null;
197
300
  status?: 'pending' | 'submitted';
198
301
  }): Promise<TransactionSubmission>;
199
- /** Update a submission's status (two-phase submit: pending → submitted or failed). */
200
- updateSubmissionStatus(tx: CapTransaction, submissionId: string, status: TransactionSubmission['status'], errorMessage?: string): Promise<void>;
302
+ /** Update a submission's status. With onlyFrom the row changes only while it has that status. */
303
+ updateSubmissionStatus(tx: CapTransaction, submissionId: string, status: TransactionSubmission['status'], errorMessage?: string, onlyFrom?: TransactionSubmission['status']): Promise<void>;
201
304
  /** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
202
305
  dropDuplicateSubmission(tx: CapTransaction, submissionId: string, txHash: string): Promise<boolean>;
203
306
  /** Persist a new signing request and link it to the build's sender address. */
@@ -285,8 +388,12 @@ export declare class CardanoIndexer {
285
388
  resolveTransactionConfirmations(tx: CapTransaction, txHash: string): Promise<TransactionConfirmations>;
286
389
  /** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
287
390
  private crawledTransactionDepth;
288
- /** Batch-fetches the missing ones and returns only those. */
391
+ /** Batch-fetches the missing ones, stores them and returns only those. */
289
392
  ensureTransactionsIndexed(tx: CapTransaction, txHashes: string[]): Promise<Map<string, ProviderTransaction>>;
290
- private _ensureAddresses;
393
+ /** The hashes among the given ones that have no stored transaction. */
394
+ private unstoredTransactionHashes;
395
+ /** Stores transactions read from a backend, each with its inputs, outputs and metadata. */
396
+ private storeTransactions;
397
+ private fetchAddresses;
291
398
  }
292
399
  //# sourceMappingURL=cardano-indexer.d.ts.map