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

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 (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -2,112 +2,59 @@ import type { CardanoClient } from './cardano-client';
2
2
  import type { TxBuildRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
3
3
  import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
4
4
  import { LedgerProtocolParameter } from '#cds-models/CardanoODataService';
5
- /**
6
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
7
- * to build various types of Cardano transactions.
8
- */
5
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
9
6
  export declare class CardanoTransactionBuilder {
10
7
  private client;
11
8
  private txBuilder;
12
9
  private initialized;
13
- /**
14
- * Create a new CardanoTransactionBuilder instance
15
- * @param client - The CardanoClient instance for UTxO fetching
16
- */
10
+ /** @param client UTxO source for coin selection */
17
11
  constructor(client: CardanoClient);
18
- /**
19
- * Initialize the transaction builder
20
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
21
- */
12
+ /** @param protocolParams optional; fetched from the backend when omitted */
22
13
  init(protocolParams?: LedgerProtocolParameters): Promise<void>;
23
- /**
24
- * Ensure the builder is initialized and return it (lazy init)
25
- * @returns {Promise<CardanoTxBuilder>} initialized builder
26
- * @throws {Error} if builder cannot be initialized
27
- */
14
+ /** Lazily initialize and return the builder. */
28
15
  private ensureInitialized;
29
- /**
30
- * Reset the transaction builder (useful for testing)
31
- */
16
+ /** Reset the builder (testing). */
32
17
  reset(): void;
33
- /**
34
- * Set the transaction builder directly (for testing)
35
- * @param builder - The builder to set
36
- */
18
+ /** Set the builder directly (testing). */
37
19
  setBuilder(builder: CardanoTxBuilder): void;
38
- /**
39
- * Build a simple ADA transfer transaction
40
- * @param req transaction build request
41
- * @param protocolParameters current protocol parameters
42
- * @returns {Promise<TxBuildResult>} transaction build result
43
- */
20
+ /** Build a simple ADA transfer transaction. */
44
21
  buildSimpleAdaTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
45
- /**
46
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
47
- * @param req transaction build request
48
- * @param protocolParameters current protocol parameters
49
- * @returns {Promise<TxBuildResult>} transaction build result
50
- */
22
+ /** Build a transaction with metadata (simple or multi-asset). */
51
23
  buildTransactionWithMetadata(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
52
- /**
53
- * Build a multi-asset transaction
54
- * @param req transaction build request
55
- * @param protocolParameters current protocol parameters
56
- * @returns {Promise<TxBuildResult>} transaction build result
57
- */
24
+ /** Build a multi-asset transaction. */
58
25
  buildMultiAssetTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
59
- /**
60
- * Build a minting transaction
61
- * @param req transaction build request
62
- * @param protocolParameters current protocol parameters
63
- * @returns {Promise<TxBuildResult>} transaction build result
64
- */
26
+ /** Build a minting transaction. */
65
27
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
66
- /**
67
- * Build a Plutus spending transaction (consume UTxO at script address)
68
- * @param req transaction build request
69
- * @param protocolParameters current protocol parameters
70
- * @returns {Promise<TxBuildResult>} transaction build result
71
- */
28
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
72
29
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
73
30
  /**
74
- * Verify that a transaction output resolved via getTransaction is still unspent,
75
- * by checking the live UTxO set of its address. getTransaction only proves the
76
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
77
- * rejection at submit instead of a clear 400 here.
78
- *
79
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
80
- * build on a flaky backend would be a new failure mode).
31
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
32
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
33
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
81
34
  */
82
- private _assertUnspent;
35
+ private _resolveScriptUtxo;
83
36
  /**
84
- * Resolve forced-input refs (consumed) to full UTxO records.
85
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
37
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
38
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
86
39
  */
87
- private _resolveForceInputs;
40
+ private _lookupUnspent;
88
41
  /**
89
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
90
- * coin-selection set) to full UTxO records.
42
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
43
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
91
44
  */
45
+ private _assertUnspent;
46
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
47
+ private _resolveForceInputs;
48
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
92
49
  private _resolveReferenceInputs;
93
50
  /**
94
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
95
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
96
- * otherwise fetches the producing transaction and verifies the output is
97
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
98
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
99
- *
100
- * @param refs input refs from the request
101
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
102
- * @param kind label used in error messages / the spent-check
103
- * @returns resolved UTxOs, in the same order as the deduped refs
51
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
52
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
53
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
54
+ * deduplicated; order is preserved.
104
55
  */
105
56
  private _resolveInputRefs;
106
- /**
107
- * Fetch UTxOs for a given address
108
- * @param address bech32 address
109
- * @returns {Promise<UTxO[]>} list of UTxOs
110
- */
57
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
111
58
  private _fetchUtxosForAddress;
112
59
  }
113
60
  //# sourceMappingURL=cardano-tx-builder.d.ts.map
@@ -8,26 +8,17 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const buildooor_tx_1 = require("./transaction-building/buildooor-tx");
9
9
  const errors_1 = require("../utils/errors");
10
10
  const logger = cds_1.default.log('CardanoTransactionBuilder');
11
- /**
12
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
13
- * to build various types of Cardano transactions.
14
- */
11
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
15
12
  class CardanoTransactionBuilder {
16
13
  client;
17
14
  txBuilder;
18
15
  initialized = false;
19
- /**
20
- * Create a new CardanoTransactionBuilder instance
21
- * @param client - The CardanoClient instance for UTxO fetching
22
- */
16
+ /** @param client UTxO source for coin selection */
23
17
  constructor(client) {
24
18
  this.client = client;
25
19
  logger.debug('CardanoTransactionBuilder instance created');
26
20
  }
27
- /**
28
- * Initialize the transaction builder
29
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
30
- */
21
+ /** @param protocolParams optional; fetched from the backend when omitted */
31
22
  async init(protocolParams) {
32
23
  if (this.initialized && this.txBuilder)
33
24
  return;
@@ -37,42 +28,27 @@ class CardanoTransactionBuilder {
37
28
  this.initialized = true;
38
29
  logger.debug(`Initialized with builder: ${this.txBuilder.name}`);
39
30
  }
40
- /**
41
- * Ensure the builder is initialized and return it (lazy init)
42
- * @returns {Promise<CardanoTxBuilder>} initialized builder
43
- * @throws {Error} if builder cannot be initialized
44
- */
31
+ /** Lazily initialize and return the builder. */
45
32
  async ensureInitialized() {
46
33
  if (!this.initialized || !this.txBuilder) {
47
34
  await this.init();
48
35
  }
49
36
  return this.txBuilder;
50
37
  }
51
- /**
52
- * Reset the transaction builder (useful for testing)
53
- */
38
+ /** Reset the builder (testing). */
54
39
  reset() {
55
40
  this.txBuilder = undefined;
56
41
  this.initialized = false;
57
42
  logger.debug(`Builder reset`);
58
43
  }
59
- /**
60
- * Set the transaction builder directly (for testing)
61
- * @param builder - The builder to set
62
- */
44
+ /** Set the builder directly (testing). */
63
45
  setBuilder(builder) {
64
46
  this.txBuilder = builder;
65
47
  this.initialized = true;
66
48
  }
67
- /**
68
- * Build a simple ADA transfer transaction
69
- * @param req transaction build request
70
- * @param protocolParameters current protocol parameters
71
- * @returns {Promise<TxBuildResult>} transaction build result
72
- */
49
+ /** Build a simple ADA transfer transaction. */
73
50
  async buildSimpleAdaTransaction(req, protocolParameters) {
74
51
  const builder = await this.ensureInitialized();
75
- // prepare the transaction build context
76
52
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
77
53
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
78
54
  const txContext = {
@@ -80,21 +56,13 @@ class CardanoTransactionBuilder {
80
56
  protocolParameters: protocolParameters
81
57
  };
82
58
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
83
- // Build the unsigned transfer transaction
84
59
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
85
60
  logger.debug(`Built simple ADA transaction successfully.`);
86
- // Return the transaction build result
87
61
  return txBuildResult;
88
62
  }
89
- /**
90
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
91
- * @param req transaction build request
92
- * @param protocolParameters current protocol parameters
93
- * @returns {Promise<TxBuildResult>} transaction build result
94
- */
63
+ /** Build a transaction with metadata (simple or multi-asset). */
95
64
  async buildTransactionWithMetadata(req, protocolParameters) {
96
65
  const builder = await this.ensureInitialized();
97
- // Prepare the transaction build context
98
66
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
99
67
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
100
68
  const txContext = {
@@ -102,24 +70,16 @@ class CardanoTransactionBuilder {
102
70
  protocolParameters: protocolParameters
103
71
  };
104
72
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
105
- // Build the unsigned transaction with metadata
106
73
  const txBuildResult = await builder.buildUnsignedTransactionWithMetadata(req, txContext);
107
74
  logger.debug(`Built transaction with metadata successfully.`);
108
- // Return the transaction build result
109
75
  return txBuildResult;
110
76
  }
111
- /**
112
- * Build a multi-asset transaction
113
- * @param req transaction build request
114
- * @param protocolParameters current protocol parameters
115
- * @returns {Promise<TxBuildResult>} transaction build result
116
- */
77
+ /** Build a multi-asset transaction. */
117
78
  async buildMultiAssetTransaction(req, protocolParameters) {
118
79
  if (!req.assets || req.assets.length === 0) {
119
80
  throw new Error('[CardanoTransactionBuilder] buildMultiAssetTransaction requires assets to be specified');
120
81
  }
121
82
  const builder = await this.ensureInitialized();
122
- // Prepare the transaction build context
123
83
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
124
84
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
125
85
  const txContext = {
@@ -127,30 +87,21 @@ class CardanoTransactionBuilder {
127
87
  protocolParameters: protocolParameters
128
88
  };
129
89
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
130
- // Build the unsigned transfer transaction (unified with simple ADA transfer)
131
90
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
132
91
  logger.debug(`Built multi-asset transaction successfully.`);
133
92
  return txBuildResult;
134
93
  }
135
- /**
136
- * Build a minting transaction
137
- * @param req transaction build request
138
- * @param protocolParameters current protocol parameters
139
- * @returns {Promise<TxBuildResult>} transaction build result
140
- */
94
+ /** Build a minting transaction. */
141
95
  async buildMintTransaction(req, protocolParameters) {
142
- // Validate mint-specific required fields
143
96
  if (!req.mintActions || req.mintActions.length === 0) {
144
97
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintActions to be specified');
145
98
  }
146
99
  if (!req.mintingPolicyScript) {
147
100
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintingPolicyScript to be specified');
148
101
  }
149
- // Type is now narrowed to TxBuildMintRequest
150
102
  const mintReq = req;
151
103
  const builder = await this.ensureInitialized();
152
104
  const cardanoClient = this.client;
153
- // Prepare the transaction build context
154
105
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
155
106
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
156
107
  // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
@@ -171,18 +122,11 @@ class CardanoTransactionBuilder {
171
122
  else {
172
123
  logger.debug(`Ogmios not available - using default execution units`);
173
124
  }
174
- // Build the unsigned minting transaction
175
125
  const txBuildResult = await builder.buildUnsignedMintTransaction(mintReq, txContext);
176
126
  logger.debug(`Built minting transaction successfully.`);
177
- // Return the transaction build result
178
127
  return txBuildResult;
179
128
  }
180
- /**
181
- * Build a Plutus spending transaction (consume UTxO at script address)
182
- * @param req transaction build request
183
- * @param protocolParameters current protocol parameters
184
- * @returns {Promise<TxBuildResult>} transaction build result
185
- */
129
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
186
130
  async buildPlutusSpendTransaction(req, protocolParameters) {
187
131
  if (!req.plutusScriptExecution) {
188
132
  throw new Error('[CardanoTransactionBuilder] buildPlutusSpendTransaction requires plutusScriptExecution to be specified');
@@ -192,34 +136,12 @@ class CardanoTransactionBuilder {
192
136
  const cardanoClient = this.client;
193
137
  // Fetch sender UTxOs for fee payment
194
138
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
195
- // Fetch the script UTxO separately (it's at the script address, not sender address)
196
- // We include it in the UTxO set so the builder can find it
139
+ // The script UTxO sits at the script address; add it so the builder can find it
197
140
  const scriptRef = spendReq.plutusScriptExecution.scriptUtxo;
198
141
  const allUtxos = [...senderUtxos];
199
- // Check if the script UTxO is already in sender UTxOs (unlikely but possible)
200
142
  const alreadyIncluded = senderUtxos.some(u => u.txHash === scriptRef.txHash && u.outputIndex === scriptRef.outputIndex);
201
143
  if (!alreadyIncluded) {
202
- // Fetch script UTxO via transaction lookup - the backend needs to provide it
203
- // For now, we create a minimal UTxO entry from what we know
204
- // The actual UTxO data will be resolved by the backend during tx building
205
- logger.debug(`Script UTxO ${scriptRef.txHash}#${scriptRef.outputIndex} not in sender UTxOs - fetching from backend`);
206
- const tx = await cardanoClient.getTransaction(scriptRef.txHash);
207
- const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
208
- if (!scriptOutput) {
209
- throw new errors_1.TransactionValidationError(`Script UTxO output ${scriptRef.txHash}#${scriptRef.outputIndex} not found in transaction`);
210
- }
211
- // spending an already-consumed script UTxO is the most common replay mistake —
212
- // catch it here with a clear 400 instead of a node-side rejection at submit
213
- await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
214
- allUtxos.push({
215
- txHash: scriptRef.txHash,
216
- outputIndex: scriptRef.outputIndex,
217
- address: scriptOutput.address,
218
- amount: scriptOutput.amount,
219
- inlineDatum: scriptOutput.inlineDatum,
220
- datumHash: scriptOutput.dataHash ?? undefined,
221
- scriptRef: scriptOutput.referenceScriptHash ?? undefined,
222
- });
144
+ allUtxos.push(await this._resolveScriptUtxo(scriptRef));
223
145
  }
224
146
  // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
225
147
  // The builder itself will skip any forced ref that matches scriptRef.
@@ -247,13 +169,55 @@ class CardanoTransactionBuilder {
247
169
  return txBuildResult;
248
170
  }
249
171
  /**
250
- * Verify that a transaction output resolved via getTransaction is still unspent,
251
- * by checking the live UTxO set of its address. getTransaction only proves the
252
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
253
- * rejection at submit instead of a clear 400 here.
254
- *
255
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
256
- * build on a flaky backend would be a new failure mode).
172
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
173
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
174
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
175
+ */
176
+ async _resolveScriptUtxo(scriptRef) {
177
+ const ledger = await this._lookupUnspent([scriptRef]);
178
+ if (ledger) {
179
+ const live = ledger.get(outRefKey(scriptRef));
180
+ if (!live) {
181
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} not found on-chain or already spent`);
182
+ }
183
+ return live;
184
+ }
185
+ logger.debug(`Script UTxO ${outRefKey(scriptRef)} not in sender UTxOs - fetching its transaction`);
186
+ const tx = await this.client.getTransaction(scriptRef.txHash);
187
+ const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
188
+ if (!scriptOutput) {
189
+ throw new errors_1.TransactionValidationError(`Script UTxO output ${outRefKey(scriptRef)} not found in transaction`);
190
+ }
191
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
192
+ return {
193
+ txHash: scriptRef.txHash,
194
+ outputIndex: scriptRef.outputIndex,
195
+ address: scriptOutput.address,
196
+ amount: scriptOutput.amount,
197
+ inlineDatum: scriptOutput.inlineDatum,
198
+ datumHash: scriptOutput.dataHash ?? undefined,
199
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
200
+ };
201
+ }
202
+ /**
203
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
204
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
205
+ */
206
+ async _lookupUnspent(refs) {
207
+ if (refs.length === 0)
208
+ return new Map();
209
+ try {
210
+ const utxos = await this.client.getUnspentOutputs(refs);
211
+ return utxos ? new Map(utxos.map(u => [outRefKey(u), u])) : null;
212
+ }
213
+ catch (err) {
214
+ logger.warn(`Ledger lookup of ${refs.length} output reference(s) failed, falling back to the producing transactions: ${err instanceof Error ? err.message : String(err)}`);
215
+ return null;
216
+ }
217
+ }
218
+ /**
219
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
220
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
257
221
  */
258
222
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
223
  let live;
@@ -276,31 +240,19 @@ class CardanoTransactionBuilder {
276
240
  throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
241
  }
278
242
  }
279
- /**
280
- * Resolve forced-input refs (consumed) to full UTxO records.
281
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
- */
243
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
283
244
  _resolveForceInputs(refs, senderUtxos) {
284
245
  return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
246
  }
286
- /**
287
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
- * coin-selection set) to full UTxO records.
289
- */
247
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
290
248
  _resolveReferenceInputs(refs, knownUtxos) {
291
249
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
292
250
  }
293
251
  /**
294
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
295
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
296
- * otherwise fetches the producing transaction and verifies the output is
297
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
298
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
299
- *
300
- * @param refs input refs from the request
301
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
302
- * @param kind label used in error messages / the spent-check
303
- * @returns resolved UTxOs, in the same order as the deduped refs
252
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
253
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
254
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
255
+ * deduplicated; order is preserved.
304
256
  */
305
257
  async _resolveInputRefs(refs, knownUtxos, kind) {
306
258
  if (!refs || refs.length === 0)
@@ -314,6 +266,8 @@ class CardanoTransactionBuilder {
314
266
  seen.add(key);
315
267
  return true;
316
268
  });
269
+ const isKnown = (r) => knownUtxos.some(u => u.txHash === r.txHash && u.outputIndex === r.outputIndex);
270
+ const ledger = await this._lookupUnspent(dedupedRefs.filter(r => !isKnown(r)));
317
271
  const liveUtxoCache = new Map();
318
272
  const resolved = [];
319
273
  for (const ref of dedupedRefs) {
@@ -323,7 +277,16 @@ class CardanoTransactionBuilder {
323
277
  resolved.push(local);
324
278
  continue;
325
279
  }
326
- // 2) Fallback: fetch the producing transaction and look up the output.
280
+ // 2) The node's ledger answers existence and spendability in one lookup
281
+ if (ledger) {
282
+ const live = ledger.get(outRefKey(ref));
283
+ if (!live) {
284
+ throw new errors_1.TransactionValidationError(`${kind} ${outRefKey(ref)} not found on-chain or already spent`);
285
+ }
286
+ resolved.push(live);
287
+ continue;
288
+ }
289
+ // 3) Fallback: fetch the producing transaction and look up the output.
327
290
  let tx;
328
291
  try {
329
292
  tx = await this.client.getTransaction(ref.txHash);
@@ -349,11 +312,7 @@ class CardanoTransactionBuilder {
349
312
  }
350
313
  return resolved;
351
314
  }
352
- /**
353
- * Fetch UTxOs for a given address
354
- * @param address bech32 address
355
- * @returns {Promise<UTxO[]>} list of UTxOs
356
- */
315
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
357
316
  async _fetchUtxosForAddress(address) {
358
317
  logger.debug(`Fetching UTxOs for address: ${address}`);
359
318
  const utxos = await this.client.getAddressUtxos(address);
@@ -365,17 +324,18 @@ class CardanoTransactionBuilder {
365
324
  }
366
325
  }
367
326
  exports.CardanoTransactionBuilder = CardanoTransactionBuilder;
368
- /**
369
- * Merge two UTxO lists, skipping refs already present in the first.
370
- * Used to add forced UTxOs to a context without duplicating existing entries.
371
- */
327
+ /** "txHash#outputIndex" key of an output reference. */
328
+ function outRefKey(ref) {
329
+ return `${ref.txHash}#${ref.outputIndex}`;
330
+ }
331
+ /** Merge two UTxO lists, skipping refs already present in the first. */
372
332
  function mergeUtxosUnique(base, extra) {
373
333
  if (extra.length === 0)
374
334
  return base;
375
- const seen = new Set(base.map(u => `${u.txHash}#${u.outputIndex}`));
335
+ const seen = new Set(base.map(outRefKey));
376
336
  const result = [...base];
377
337
  for (const u of extra) {
378
- const key = `${u.txHash}#${u.outputIndex}`;
338
+ const key = outRefKey(u);
379
339
  if (!seen.has(key)) {
380
340
  seen.add(key);
381
341
  result.push(u);
@@ -0,0 +1,45 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ /**
5
+ * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
6
+ * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
7
+ * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
8
+ * live crawler keeps its own stream. A block the index does not know (rolled back since) is
9
+ * skipped, so no row can point at a transaction that is not there.
10
+ */
11
+ export declare class CertificateBackfillError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ export interface CertificateBackfillProgress {
15
+ /** Slot of the last block handled. */
16
+ atSlot: number;
17
+ blocks: number;
18
+ transactions: number;
19
+ certificates: number;
20
+ withdrawals: number;
21
+ }
22
+ export interface CertificateBackfillOptions {
23
+ client: CardanoClient;
24
+ /** First slot to cover; the stream intersects at the newest indexed block before it. */
25
+ fromSlot: number;
26
+ /** Last slot to cover; the stream ends at the first block past it. */
27
+ toSlot: number;
28
+ /** Rows are written per batch of blocks; smaller batches show progress sooner. */
29
+ batchBlocks?: number;
30
+ onProgress?: (p: CertificateBackfillProgress) => void;
31
+ }
32
+ export interface CertificateBackfillResult extends CertificateBackfillProgress {
33
+ fromSlot: number;
34
+ toSlot: number;
35
+ /** The chain point the stream started after. */
36
+ intersection: ChainPoint | 'origin';
37
+ }
38
+ /**
39
+ * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
40
+ * start point when none is. Lazily indexed blocks below the crawl start are never picked:
41
+ * they may lie far back or on a fork the node no longer knows.
42
+ */
43
+ export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
44
+ export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
45
+ //# sourceMappingURL=certificate-backfill.d.ts.map