@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) 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 +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -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 +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -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 +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  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 +376 -235
  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 +556 -201
  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 +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -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 +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  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 +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  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 +18 -23
  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 +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -1,113 +1,76 @@
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. When no
43
+ * backend can tell, the build goes on and the node decides at submit.
71
44
  */
72
- buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
45
+ private _assertRewardAccountsRegistered;
73
46
  /**
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).
47
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
48
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
49
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
81
50
  */
82
- private _assertUnspent;
51
+ private _resolveScriptUtxo;
83
52
  /**
84
- * Resolve forced-input refs (consumed) to full UTxO records.
85
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
53
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
54
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
86
55
  */
87
- private _resolveForceInputs;
56
+ private _lookupUnspent;
88
57
  /**
89
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
90
- * coin-selection set) to full UTxO records.
58
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
59
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
91
60
  */
61
+ private _assertUnspent;
62
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
63
+ private _resolveForceInputs;
64
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
92
65
  private _resolveReferenceInputs;
93
66
  /**
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
67
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
68
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
69
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
70
+ * deduplicated; order is preserved.
104
71
  */
105
72
  private _resolveInputRefs;
106
- /**
107
- * Fetch UTxOs for a given address
108
- * @param address bech32 address
109
- * @returns {Promise<UTxO[]>} list of UTxOs
110
- */
73
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
111
74
  private _fetchUtxosForAddress;
112
75
  }
113
76
  //# 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,110 @@ 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. When no
214
+ * backend can tell, the build goes on and the node decides at submit.
215
+ */
216
+ async _assertRewardAccountsRegistered(withdrawals, registeredHere = new Set()) {
217
+ for (const [i, w] of withdrawals.entries()) {
218
+ if (registeredHere.has(w.rewardAddress.toLowerCase()))
219
+ continue;
220
+ const registered = await this.client.isRewardAccountRegistered(w.rewardAddress);
221
+ if (registered === false) {
222
+ throw new errors_1.TransactionValidationError(`withdrawals[${i}] reward account ${w.rewardAddress} is not registered on chain; register the stake credential first`);
223
+ }
224
+ if (registered === null) {
225
+ logger.warn(`withdrawals[${i}] reward account ${w.rewardAddress}: registration not verifiable (the node lists delegated accounts only, no provider answered); the node checks it at submit`);
226
+ }
227
+ }
228
+ }
229
+ /**
230
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
231
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
232
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
233
+ */
234
+ async _resolveScriptUtxo(scriptRef) {
235
+ const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
236
+ if (by)
237
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} is spent by transaction ${by}, submitted and not yet on chain`);
238
+ const ledger = await this._lookupUnspent([scriptRef]);
239
+ if (ledger) {
240
+ const live = ledger.get(outRefKey(scriptRef));
241
+ if (!live) {
242
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} not found on-chain or already spent`);
243
+ }
244
+ return live;
245
+ }
246
+ logger.debug(`Script UTxO ${outRefKey(scriptRef)} not in sender UTxOs - fetching its transaction`);
247
+ const tx = await this.client.getTransaction(scriptRef.txHash);
248
+ const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
249
+ if (!scriptOutput) {
250
+ throw new errors_1.TransactionValidationError(`Script UTxO output ${outRefKey(scriptRef)} not found in transaction`);
251
+ }
252
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
253
+ return {
254
+ txHash: scriptRef.txHash,
255
+ outputIndex: scriptRef.outputIndex,
256
+ address: scriptOutput.address,
257
+ amount: scriptOutput.amount,
258
+ inlineDatum: scriptOutput.inlineDatum,
259
+ datumHash: scriptOutput.dataHash ?? undefined,
260
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
261
+ };
262
+ }
263
+ /**
264
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
265
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
266
+ */
267
+ async _lookupUnspent(refs) {
268
+ if (refs.length === 0)
269
+ return new Map();
270
+ try {
271
+ const utxos = await this.client.getUnspentOutputs(refs);
272
+ return utxos ? new Map(utxos.map(u => [outRefKey(u), u])) : null;
273
+ }
274
+ catch (err) {
275
+ logger.warn(`Ledger lookup of ${refs.length} output reference(s) failed, falling back to the producing transactions: ${err instanceof Error ? err.message : String(err)}`);
276
+ return null;
277
+ }
278
+ }
279
+ /**
280
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
281
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
257
282
  */
258
283
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
284
  let live;
@@ -276,35 +301,28 @@ class CardanoTransactionBuilder {
276
301
  throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
302
  }
278
303
  }
279
- /**
280
- * Resolve forced-input refs (consumed) to full UTxO records.
281
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
- */
304
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
283
305
  _resolveForceInputs(refs, senderUtxos) {
284
306
  return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
307
  }
286
- /**
287
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
- * coin-selection set) to full UTxO records.
289
- */
308
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
290
309
  _resolveReferenceInputs(refs, knownUtxos) {
291
310
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
292
311
  }
293
312
  /**
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
313
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
314
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
315
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
316
+ * deduplicated; order is preserved.
304
317
  */
305
318
  async _resolveInputRefs(refs, knownUtxos, kind) {
306
319
  if (!refs || refs.length === 0)
307
320
  return [];
321
+ for (const r of refs) {
322
+ const by = this.client.pendingSpends?.spentBy(r.txHash, r.outputIndex);
323
+ if (by)
324
+ throw new errors_1.TransactionValidationError(`${kind} ${r.txHash}#${r.outputIndex} is spent by transaction ${by}, submitted and not yet on chain`);
325
+ }
308
326
  // Dedup by "txHash#index" key
309
327
  const seen = new Set();
310
328
  const dedupedRefs = refs.filter(r => {
@@ -314,6 +332,8 @@ class CardanoTransactionBuilder {
314
332
  seen.add(key);
315
333
  return true;
316
334
  });
335
+ const isKnown = (r) => knownUtxos.some(u => u.txHash === r.txHash && u.outputIndex === r.outputIndex);
336
+ const ledger = await this._lookupUnspent(dedupedRefs.filter(r => !isKnown(r)));
317
337
  const liveUtxoCache = new Map();
318
338
  const resolved = [];
319
339
  for (const ref of dedupedRefs) {
@@ -323,7 +343,16 @@ class CardanoTransactionBuilder {
323
343
  resolved.push(local);
324
344
  continue;
325
345
  }
326
- // 2) Fallback: fetch the producing transaction and look up the output.
346
+ // 2) The node's ledger answers existence and spendability in one lookup
347
+ if (ledger) {
348
+ const live = ledger.get(outRefKey(ref));
349
+ if (!live) {
350
+ throw new errors_1.TransactionValidationError(`${kind} ${outRefKey(ref)} not found on-chain or already spent`);
351
+ }
352
+ resolved.push(live);
353
+ continue;
354
+ }
355
+ // 3) Fallback: fetch the producing transaction and look up the output.
327
356
  let tx;
328
357
  try {
329
358
  tx = await this.client.getTransaction(ref.txHash);
@@ -349,33 +378,45 @@ class CardanoTransactionBuilder {
349
378
  }
350
379
  return resolved;
351
380
  }
352
- /**
353
- * Fetch UTxOs for a given address
354
- * @param address bech32 address
355
- * @returns {Promise<UTxO[]>} list of UTxOs
356
- */
381
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
357
382
  async _fetchUtxosForAddress(address) {
358
383
  logger.debug(`Fetching UTxOs for address: ${address}`);
359
- const utxos = await this.client.getAddressUtxos(address);
384
+ // The crawled set answers with an index lookup; the node's address query scans its whole
385
+ // UTxO set. An empty answer from the set is re-checked there (funded in the last block).
386
+ const local = await this.addressUtxoSource?.(address).catch((err) => {
387
+ logger.warn(`Local UTxO lookup for ${address} failed, asking the node: ${err instanceof Error ? err.message : String(err)}`);
388
+ return null;
389
+ });
390
+ const ledger = local && local.length > 0 ? local : await this.client.getAddressUtxos(address);
391
+ // the ledger view still lists what our own submitted transactions spend while they wait in the mempool
392
+ const all = this.client.pendingSpends?.apply(address, ledger) ?? ledger;
393
+ // A UTxO carrying a reference script is deployed on purpose, not change to spend; only a
394
+ // forced input consumes it (the fee of a spent reference script is also not counted by the builder).
395
+ const utxos = all.filter(u => !u.scriptRef && !u.scriptRefCbor);
396
+ if (utxos.length < all.length)
397
+ logger.debug(`${all.length - utxos.length} UTxO(s) with a reference script left out of coin selection`);
360
398
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
361
399
  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`);
400
+ throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
401
+ ? `address ${address} holds only UTxOs with a reference script — they are not spent as funding; pass one in forceInputsJson to consume it`
402
+ : `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
363
403
  }
364
404
  return utxos;
365
405
  }
366
406
  }
367
407
  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
- */
408
+ /** "txHash#outputIndex" key of an output reference. */
409
+ function outRefKey(ref) {
410
+ return `${ref.txHash}#${ref.outputIndex}`;
411
+ }
412
+ /** Merge two UTxO lists, skipping refs already present in the first. */
372
413
  function mergeUtxosUnique(base, extra) {
373
414
  if (extra.length === 0)
374
415
  return base;
375
- const seen = new Set(base.map(u => `${u.txHash}#${u.outputIndex}`));
416
+ const seen = new Set(base.map(outRefKey));
376
417
  const result = [...base];
377
418
  for (const u of extra) {
378
- const key = `${u.txHash}#${u.outputIndex}`;
419
+ const key = outRefKey(u);
379
420
  if (!seen.has(key)) {
380
421
  seen.add(key);
381
422
  result.push(u);