@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) 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/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -1,113 +1,75 @@
1
1
  import type { CardanoClient } from './cardano-client';
2
- import type { TxBuildRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
2
+ import type { UTxO } from '../utils/types';
3
+ import type { TxBuildRequest, TxBuildPlutusRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
3
4
  import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
4
5
  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
- */
6
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
9
7
  export declare class CardanoTransactionBuilder {
10
8
  private client;
11
9
  private txBuilder;
12
10
  private initialized;
13
- /**
14
- * Create a new CardanoTransactionBuilder instance
15
- * @param client - The CardanoClient instance for UTxO fetching
16
- */
11
+ /** @param client UTxO source for coin selection */
17
12
  constructor(client: CardanoClient);
18
- /**
19
- * Initialize the transaction builder
20
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
21
- */
13
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
14
+ private addressUtxoSource;
15
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
16
+ setAddressUtxoSource(source: (address: string) => Promise<UTxO[] | null>): void;
17
+ /** @param protocolParams optional; fetched from the backend when omitted */
22
18
  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
- */
19
+ /** Lazily initialize and return the builder. */
28
20
  private ensureInitialized;
29
- /**
30
- * Reset the transaction builder (useful for testing)
31
- */
21
+ /** Reset the builder (testing). */
32
22
  reset(): void;
33
- /**
34
- * Set the transaction builder directly (for testing)
35
- * @param builder - The builder to set
36
- */
23
+ /** Set the builder directly (testing). */
37
24
  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
- */
25
+ /** Build a simple ADA transfer transaction. */
44
26
  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
- */
27
+ /** Build a transaction with metadata (simple or multi-asset). */
51
28
  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
- */
29
+ /** Build a multi-asset transaction. */
58
30
  buildMultiAssetTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
31
+ /** Build a minting transaction. */
32
+ buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
33
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
34
+ buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
59
35
  /**
60
- * Build a minting transaction
61
- * @param req transaction build request
62
- * @param protocolParameters current protocol parameters
63
- * @returns {Promise<TxBuildResult>} transaction build result
36
+ * Several script inputs in one transaction: resolve every script UTxO and every reference-script
37
+ * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
64
38
  */
65
- buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
39
+ buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
66
40
  /**
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
41
+ * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
42
+ * build fails here with the account named. A provider failure is passed on as it is.
71
43
  */
72
- buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
44
+ private _assertRewardAccountsRegistered;
73
45
  /**
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).
46
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
47
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
48
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
81
49
  */
82
- private _assertUnspent;
50
+ private _resolveScriptUtxo;
83
51
  /**
84
- * Resolve forced-input refs (consumed) to full UTxO records.
85
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
52
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
53
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
86
54
  */
87
- private _resolveForceInputs;
55
+ private _lookupUnspent;
88
56
  /**
89
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
90
- * coin-selection set) to full UTxO records.
57
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
58
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
91
59
  */
60
+ private _assertUnspent;
61
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
62
+ private _resolveForceInputs;
63
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
92
64
  private _resolveReferenceInputs;
93
65
  /**
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
66
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
67
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
68
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
69
+ * deduplicated; order is preserved.
104
70
  */
105
71
  private _resolveInputRefs;
106
- /**
107
- * Fetch UTxOs for a given address
108
- * @param address bech32 address
109
- * @returns {Promise<UTxO[]>} list of UTxOs
110
- */
72
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
111
73
  private _fetchUtxosForAddress;
112
74
  }
113
75
  //# sourceMappingURL=cardano-tx-builder.d.ts.map
@@ -8,26 +8,23 @@ 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
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
22
+ addressUtxoSource = null;
23
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
24
+ setAddressUtxoSource(source) {
25
+ this.addressUtxoSource = source;
26
+ }
27
+ /** @param protocolParams optional; fetched from the backend when omitted */
31
28
  async init(protocolParams) {
32
29
  if (this.initialized && this.txBuilder)
33
30
  return;
@@ -37,42 +34,27 @@ class CardanoTransactionBuilder {
37
34
  this.initialized = true;
38
35
  logger.debug(`Initialized with builder: ${this.txBuilder.name}`);
39
36
  }
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
- */
37
+ /** Lazily initialize and return the builder. */
45
38
  async ensureInitialized() {
46
39
  if (!this.initialized || !this.txBuilder) {
47
40
  await this.init();
48
41
  }
49
42
  return this.txBuilder;
50
43
  }
51
- /**
52
- * Reset the transaction builder (useful for testing)
53
- */
44
+ /** Reset the builder (testing). */
54
45
  reset() {
55
46
  this.txBuilder = undefined;
56
47
  this.initialized = false;
57
48
  logger.debug(`Builder reset`);
58
49
  }
59
- /**
60
- * Set the transaction builder directly (for testing)
61
- * @param builder - The builder to set
62
- */
50
+ /** Set the builder directly (testing). */
63
51
  setBuilder(builder) {
64
52
  this.txBuilder = builder;
65
53
  this.initialized = true;
66
54
  }
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
- */
55
+ /** Build a simple ADA transfer transaction. */
73
56
  async buildSimpleAdaTransaction(req, protocolParameters) {
74
57
  const builder = await this.ensureInitialized();
75
- // prepare the transaction build context
76
58
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
77
59
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
78
60
  const txContext = {
@@ -80,21 +62,13 @@ class CardanoTransactionBuilder {
80
62
  protocolParameters: protocolParameters
81
63
  };
82
64
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
83
- // Build the unsigned transfer transaction
84
65
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
85
66
  logger.debug(`Built simple ADA transaction successfully.`);
86
- // Return the transaction build result
87
67
  return txBuildResult;
88
68
  }
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
- */
69
+ /** Build a transaction with metadata (simple or multi-asset). */
95
70
  async buildTransactionWithMetadata(req, protocolParameters) {
96
71
  const builder = await this.ensureInitialized();
97
- // Prepare the transaction build context
98
72
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
99
73
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
100
74
  const txContext = {
@@ -102,24 +76,16 @@ class CardanoTransactionBuilder {
102
76
  protocolParameters: protocolParameters
103
77
  };
104
78
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
105
- // Build the unsigned transaction with metadata
106
79
  const txBuildResult = await builder.buildUnsignedTransactionWithMetadata(req, txContext);
107
80
  logger.debug(`Built transaction with metadata successfully.`);
108
- // Return the transaction build result
109
81
  return txBuildResult;
110
82
  }
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
- */
83
+ /** Build a multi-asset transaction. */
117
84
  async buildMultiAssetTransaction(req, protocolParameters) {
118
85
  if (!req.assets || req.assets.length === 0) {
119
86
  throw new Error('[CardanoTransactionBuilder] buildMultiAssetTransaction requires assets to be specified');
120
87
  }
121
88
  const builder = await this.ensureInitialized();
122
- // Prepare the transaction build context
123
89
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
124
90
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
125
91
  const txContext = {
@@ -127,30 +93,21 @@ class CardanoTransactionBuilder {
127
93
  protocolParameters: protocolParameters
128
94
  };
129
95
  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
96
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
132
97
  logger.debug(`Built multi-asset transaction successfully.`);
133
98
  return txBuildResult;
134
99
  }
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
- */
100
+ /** Build a minting transaction. */
141
101
  async buildMintTransaction(req, protocolParameters) {
142
- // Validate mint-specific required fields
143
102
  if (!req.mintActions || req.mintActions.length === 0) {
144
103
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintActions to be specified');
145
104
  }
146
105
  if (!req.mintingPolicyScript) {
147
106
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintingPolicyScript to be specified');
148
107
  }
149
- // Type is now narrowed to TxBuildMintRequest
150
108
  const mintReq = req;
151
109
  const builder = await this.ensureInitialized();
152
110
  const cardanoClient = this.client;
153
- // Prepare the transaction build context
154
111
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
155
112
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
156
113
  // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
@@ -159,7 +116,7 @@ class CardanoTransactionBuilder {
159
116
  utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
160
117
  protocolParameters: protocolParameters,
161
118
  // Pass evaluator if Ogmios is available for dynamic execution unit calculation
162
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
119
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
163
120
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
164
121
  : undefined,
165
122
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -171,18 +128,11 @@ class CardanoTransactionBuilder {
171
128
  else {
172
129
  logger.debug(`Ogmios not available - using default execution units`);
173
130
  }
174
- // Build the unsigned minting transaction
175
131
  const txBuildResult = await builder.buildUnsignedMintTransaction(mintReq, txContext);
176
132
  logger.debug(`Built minting transaction successfully.`);
177
- // Return the transaction build result
178
133
  return txBuildResult;
179
134
  }
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
- */
135
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
186
136
  async buildPlutusSpendTransaction(req, protocolParameters) {
187
137
  if (!req.plutusScriptExecution) {
188
138
  throw new Error('[CardanoTransactionBuilder] buildPlutusSpendTransaction requires plutusScriptExecution to be specified');
@@ -192,34 +142,12 @@ class CardanoTransactionBuilder {
192
142
  const cardanoClient = this.client;
193
143
  // Fetch sender UTxOs for fee payment
194
144
  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
145
+ // The script UTxO sits at the script address; add it so the builder can find it
197
146
  const scriptRef = spendReq.plutusScriptExecution.scriptUtxo;
198
147
  const allUtxos = [...senderUtxos];
199
- // Check if the script UTxO is already in sender UTxOs (unlikely but possible)
200
148
  const alreadyIncluded = senderUtxos.some(u => u.txHash === scriptRef.txHash && u.outputIndex === scriptRef.outputIndex);
201
149
  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
- });
150
+ allUtxos.push(await this._resolveScriptUtxo(scriptRef));
223
151
  }
224
152
  // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
225
153
  // The builder itself will skip any forced ref that matches scriptRef.
@@ -230,7 +158,7 @@ class CardanoTransactionBuilder {
230
158
  const txContext = {
231
159
  utxos: mergedUtxos,
232
160
  protocolParameters: protocolParameters,
233
- evaluateTransaction: cardanoClient.hasOgmiosBackend()
161
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
234
162
  ? (cbor) => cardanoClient.evaluateTransaction(cbor)
235
163
  : undefined,
236
164
  referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
@@ -247,13 +175,114 @@ class CardanoTransactionBuilder {
247
175
  return txBuildResult;
248
176
  }
249
177
  /**
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).
178
+ * Several script inputs in one transaction: resolve every script UTxO and every reference-script
179
+ * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
180
+ */
181
+ async buildPlutusTransaction(req, protocolParameters) {
182
+ const builder = await this.ensureInitialized();
183
+ const cardanoClient = this.client;
184
+ const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
185
+ const scriptUtxos = await this._resolveInputRefs(req.scriptInputs.map(s => ({ txHash: s.txHash, outputIndex: s.outputIndex })), senderUtxos, 'scriptInput');
186
+ const allUtxos = mergeUtxosUnique(senderUtxos, scriptUtxos);
187
+ const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
188
+ // Reference-script UTxOs always from the ledger: a known sender UTxO may carry only the script hash
189
+ const refScriptUtxos = await this._resolveInputRefs([
190
+ ...req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])),
191
+ ...(req.withdrawals ?? []).flatMap(w => (w.referenceScript ? [w.referenceScript] : [])),
192
+ ...(req.certificates ?? []).flatMap(c => (c.referenceScript ? [c.referenceScript] : [])),
193
+ ...(req.mintActions ?? []).flatMap(m => (m.referenceScript ? [m.referenceScript] : [])),
194
+ ], [], 'referenceScript');
195
+ const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
196
+ const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
197
+ // A credential this transaction registers is withdrawable in the same transaction
198
+ const registeredHere = new Set((req.certificates ?? []).filter(c => c.type === 'registerStake').map(c => c.stakeAddress.toLowerCase()));
199
+ await this._assertRewardAccountsRegistered(req.withdrawals ?? [], registeredHere);
200
+ const txContext = {
201
+ utxos: mergeUtxosUnique(allUtxos, forcedUtxos),
202
+ protocolParameters,
203
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
204
+ ? (cbor) => cardanoClient.evaluateTransaction(cbor)
205
+ : undefined,
206
+ referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined,
207
+ };
208
+ logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
209
+ return builder.buildUnsignedPlutusTransaction(req, txContext);
210
+ }
211
+ /**
212
+ * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
213
+ * build fails here with the account named. A provider failure is passed on as it is.
214
+ */
215
+ async _assertRewardAccountsRegistered(withdrawals, registeredHere = new Set()) {
216
+ for (const [i, w] of withdrawals.entries()) {
217
+ if (registeredHere.has(w.rewardAddress.toLowerCase()))
218
+ continue;
219
+ let active;
220
+ try {
221
+ active = (await this.client.getAccount(w.rewardAddress)).active;
222
+ }
223
+ catch (err) {
224
+ if (!(err instanceof errors_1.NotFoundError))
225
+ throw err;
226
+ active = false;
227
+ }
228
+ if (!active) {
229
+ throw new errors_1.TransactionValidationError(`withdrawals[${i}] reward account ${w.rewardAddress} is not registered on chain; register the stake credential first`);
230
+ }
231
+ }
232
+ }
233
+ /**
234
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
235
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
236
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
237
+ */
238
+ async _resolveScriptUtxo(scriptRef) {
239
+ const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
240
+ if (by)
241
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} is spent by transaction ${by}, submitted and not yet on chain`);
242
+ const ledger = await this._lookupUnspent([scriptRef]);
243
+ if (ledger) {
244
+ const live = ledger.get(outRefKey(scriptRef));
245
+ if (!live) {
246
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} not found on-chain or already spent`);
247
+ }
248
+ return live;
249
+ }
250
+ logger.debug(`Script UTxO ${outRefKey(scriptRef)} not in sender UTxOs - fetching its transaction`);
251
+ const tx = await this.client.getTransaction(scriptRef.txHash);
252
+ const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
253
+ if (!scriptOutput) {
254
+ throw new errors_1.TransactionValidationError(`Script UTxO output ${outRefKey(scriptRef)} not found in transaction`);
255
+ }
256
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
257
+ return {
258
+ txHash: scriptRef.txHash,
259
+ outputIndex: scriptRef.outputIndex,
260
+ address: scriptOutput.address,
261
+ amount: scriptOutput.amount,
262
+ inlineDatum: scriptOutput.inlineDatum,
263
+ datumHash: scriptOutput.dataHash ?? undefined,
264
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
265
+ };
266
+ }
267
+ /**
268
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
269
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
270
+ */
271
+ async _lookupUnspent(refs) {
272
+ if (refs.length === 0)
273
+ return new Map();
274
+ try {
275
+ const utxos = await this.client.getUnspentOutputs(refs);
276
+ return utxos ? new Map(utxos.map(u => [outRefKey(u), u])) : null;
277
+ }
278
+ catch (err) {
279
+ logger.warn(`Ledger lookup of ${refs.length} output reference(s) failed, falling back to the producing transactions: ${err instanceof Error ? err.message : String(err)}`);
280
+ return null;
281
+ }
282
+ }
283
+ /**
284
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
285
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
257
286
  */
258
287
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
288
  let live;
@@ -276,35 +305,28 @@ class CardanoTransactionBuilder {
276
305
  throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
306
  }
278
307
  }
279
- /**
280
- * Resolve forced-input refs (consumed) to full UTxO records.
281
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
- */
308
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
283
309
  _resolveForceInputs(refs, senderUtxos) {
284
310
  return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
311
  }
286
- /**
287
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
- * coin-selection set) to full UTxO records.
289
- */
312
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
290
313
  _resolveReferenceInputs(refs, knownUtxos) {
291
314
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
292
315
  }
293
316
  /**
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
317
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
318
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
319
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
320
+ * deduplicated; order is preserved.
304
321
  */
305
322
  async _resolveInputRefs(refs, knownUtxos, kind) {
306
323
  if (!refs || refs.length === 0)
307
324
  return [];
325
+ for (const r of refs) {
326
+ const by = this.client.pendingSpends?.spentBy(r.txHash, r.outputIndex);
327
+ if (by)
328
+ throw new errors_1.TransactionValidationError(`${kind} ${r.txHash}#${r.outputIndex} is spent by transaction ${by}, submitted and not yet on chain`);
329
+ }
308
330
  // Dedup by "txHash#index" key
309
331
  const seen = new Set();
310
332
  const dedupedRefs = refs.filter(r => {
@@ -314,6 +336,8 @@ class CardanoTransactionBuilder {
314
336
  seen.add(key);
315
337
  return true;
316
338
  });
339
+ const isKnown = (r) => knownUtxos.some(u => u.txHash === r.txHash && u.outputIndex === r.outputIndex);
340
+ const ledger = await this._lookupUnspent(dedupedRefs.filter(r => !isKnown(r)));
317
341
  const liveUtxoCache = new Map();
318
342
  const resolved = [];
319
343
  for (const ref of dedupedRefs) {
@@ -323,7 +347,16 @@ class CardanoTransactionBuilder {
323
347
  resolved.push(local);
324
348
  continue;
325
349
  }
326
- // 2) Fallback: fetch the producing transaction and look up the output.
350
+ // 2) The node's ledger answers existence and spendability in one lookup
351
+ if (ledger) {
352
+ const live = ledger.get(outRefKey(ref));
353
+ if (!live) {
354
+ throw new errors_1.TransactionValidationError(`${kind} ${outRefKey(ref)} not found on-chain or already spent`);
355
+ }
356
+ resolved.push(live);
357
+ continue;
358
+ }
359
+ // 3) Fallback: fetch the producing transaction and look up the output.
327
360
  let tx;
328
361
  try {
329
362
  tx = await this.client.getTransaction(ref.txHash);
@@ -349,33 +382,45 @@ class CardanoTransactionBuilder {
349
382
  }
350
383
  return resolved;
351
384
  }
352
- /**
353
- * Fetch UTxOs for a given address
354
- * @param address bech32 address
355
- * @returns {Promise<UTxO[]>} list of UTxOs
356
- */
385
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
357
386
  async _fetchUtxosForAddress(address) {
358
387
  logger.debug(`Fetching UTxOs for address: ${address}`);
359
- const utxos = await this.client.getAddressUtxos(address);
388
+ // The crawled set answers with an index lookup; the node's address query scans its whole
389
+ // UTxO set. An empty answer from the set is re-checked there (funded in the last block).
390
+ const local = await this.addressUtxoSource?.(address).catch((err) => {
391
+ logger.warn(`Local UTxO lookup for ${address} failed, asking the node: ${err instanceof Error ? err.message : String(err)}`);
392
+ return null;
393
+ });
394
+ const ledger = local && local.length > 0 ? local : await this.client.getAddressUtxos(address);
395
+ // the ledger view still lists what our own submitted transactions spend while they wait in the mempool
396
+ const all = this.client.pendingSpends?.apply(address, ledger) ?? ledger;
397
+ // A UTxO carrying a reference script is deployed on purpose, not change to spend; only a
398
+ // forced input consumes it (the fee of a spent reference script is also not counted by the builder).
399
+ const utxos = all.filter(u => !u.scriptRef && !u.scriptRefCbor);
400
+ if (utxos.length < all.length)
401
+ logger.debug(`${all.length - utxos.length} UTxO(s) with a reference script left out of coin selection`);
360
402
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
361
403
  if (utxos.length === 0) {
362
- throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
404
+ throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
405
+ ? `address ${address} holds only UTxOs with a reference script — they are not spent as funding; pass one in forceInputsJson to consume it`
406
+ : `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
363
407
  }
364
408
  return utxos;
365
409
  }
366
410
  }
367
411
  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
- */
412
+ /** "txHash#outputIndex" key of an output reference. */
413
+ function outRefKey(ref) {
414
+ return `${ref.txHash}#${ref.outputIndex}`;
415
+ }
416
+ /** Merge two UTxO lists, skipping refs already present in the first. */
372
417
  function mergeUtxosUnique(base, extra) {
373
418
  if (extra.length === 0)
374
419
  return base;
375
- const seen = new Set(base.map(u => `${u.txHash}#${u.outputIndex}`));
420
+ const seen = new Set(base.map(outRefKey));
376
421
  const result = [...base];
377
422
  for (const u of extra) {
378
- const key = `${u.txHash}#${u.outputIndex}`;
423
+ const key = outRefKey(u);
379
424
  if (!seen.has(key)) {
380
425
  seen.add(key);
381
426
  result.push(u);