@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
@@ -4,8 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BuildooorTxBuilder = void 0;
7
- // Coin selection uses this.txBuilder.keepRelevant again since buildooor 0.2.9
8
- // ships the fixed implementation (our PR); the vendored keep-relevant.ts is gone.
9
7
  const buildooor_1 = require("@harmoniclabs/buildooor");
10
8
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
11
9
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
@@ -13,29 +11,18 @@ const errors_1 = require("../../utils/errors");
13
11
  const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
14
12
  const cds_1 = __importDefault(require("@sap/cds"));
15
13
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
16
- // Metadata classes are imported from the DIST paths ON PURPOSE: buildooor's
17
- // AuxiliaryData/TxMetadata do internal `instanceof` checks against these exact
18
- // dist-class identities, which differ from the package-root re-exports. Mixing
19
- // root + dist identities breaks those checks at runtime. (See cbor-parse.test.)
14
+ // Metadata classes come from the DIST paths on purpose: buildooor's AuxiliaryData/TxMetadata
15
+ // run `instanceof` checks against these exact class identities, not the package-root re-exports.
20
16
  const TxMetadata_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadata");
21
17
  const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadatum");
22
18
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
19
+ const caller_datums_1 = require("./caller-datums");
23
20
  const const_1 = require("../../utils/const");
24
21
  const logger = cds_1.default.log('BuildooorTxBuilder');
25
22
  /**
26
- * Build options for script-bearing transactions.
27
- *
28
- * Buildooor evaluates every Plutus script locally during `build()` and unconditionally
29
- * stamps each redeemer with the budget its local CEK run consumed (`onEvaluationResult`
30
- * in TxBuilder) — execution units passed in the build args are never read. Without an
31
- * `onScriptInvalid` handler a local evaluation failure aborts the build; *with* one the
32
- * redeemer is left carrying the partial budget consumed up to the error, which would
33
- * fail phase-2 on-chain and forfeit the collateral if signed and submitted.
34
- *
35
- * We therefore only record local failures here; `_buildScriptTx` decides afterwards:
36
- * an authoritative Ogmios evaluation overrides the local result (so local false
37
- * negatives — e.g. cost-model drift — don't block the build), while a failure without
38
- * Ogmios aborts with a clear error instead of returning an unsubmittable transaction.
23
+ * Build options for script-bearing transactions. Buildooor stamps each redeemer with its
24
+ * local CEK budget and, without `onScriptInvalid`, aborts on a local failure; we only record
25
+ * failures here and let `_buildScriptTx` decide (Ogmios result wins, otherwise abort).
39
26
  */
40
27
  function makeScriptBuildOpts(failures) {
41
28
  return {
@@ -75,10 +62,8 @@ function maxBig(a, b) {
75
62
  return a > b ? a : b;
76
63
  }
77
64
  /**
78
- * Parse a ledger protocol-parameter value (number or decimal string) into a
79
- * non-negative safe integer. Returns undefined for null/undefined/empty/invalid
80
- * input so callers can fall back to library defaults instead of silently
81
- * coercing to 0 (which e.g. disables min-ADA when applied to utxoCostPerByte).
65
+ * Parse a protocol-parameter value (number or decimal string) into a non-negative safe integer;
66
+ * undefined for null/empty/invalid so callers keep library defaults instead of coercing to 0.
82
67
  */
83
68
  function toUInt(value) {
84
69
  if (value === null || value === undefined || value === '')
@@ -93,11 +78,7 @@ function toPositiveNumber(value) {
93
78
  const n = Number(value);
94
79
  return Number.isFinite(n) && n > 0 ? n : undefined;
95
80
  }
96
- /**
97
- * Stable identity of a protocol-parameter set. Params only change at epoch
98
- * boundaries, so network#epoch is sufficient; fall back to full JSON when
99
- * either field is missing.
100
- */
81
+ /** Stable identity of a protocol-parameter set: network#epoch (params change per epoch), else full JSON. */
101
82
  function protocolParamsFingerprint(p) {
102
83
  if (p.network && p.epoch !== undefined && p.epoch !== null)
103
84
  return `${p.network}#${p.epoch}`;
@@ -105,10 +86,7 @@ function protocolParamsFingerprint(p) {
105
86
  }
106
87
  /** Ledger limit for a single text/bytes metadatum (bytes, not characters). */
107
88
  const METADATA_BYTE_LIMIT = 64;
108
- /**
109
- * Split a string into pieces of at most maxBytes UTF-8 bytes each, never
110
- * splitting inside a code point (which would produce invalid UTF-8 on-chain).
111
- */
89
+ /** Split a string into pieces of at most maxBytes UTF-8 bytes without splitting a code point. */
112
90
  function chunkUtf8(str, maxBytes) {
113
91
  const chunks = [];
114
92
  let current = '';
@@ -130,8 +108,19 @@ function chunkUtf8(str, maxBytes) {
130
108
  return chunks;
131
109
  }
132
110
  /**
133
- * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
111
+ * The same script without the CBOR it was parsed from. Script.fromCbor keeps the input bytes (the
112
+ * compiler's bare bytestring) and toCbor() returns them, while an output's script_ref must hold the
113
+ * ledger form [language, bytes]; the hash is the same either way.
134
114
  */
115
+ function ledgerScript(script) {
116
+ return new cardano_ledger_ts_1.Script(script.type, script.bytes);
117
+ }
118
+ // Hash32 inherits Hash.clone(), which returns a plain Hash; TxOut rejects that as datum when
119
+ // Buildooor clones outputs, so a datum-hash output could never be built. Hash28 has its own clone.
120
+ if (!Object.prototype.hasOwnProperty.call(cardano_ledger_ts_1.Hash32.prototype, 'clone')) {
121
+ cardano_ledger_ts_1.Hash32.prototype.clone = function () { return new cardano_ledger_ts_1.Hash32(this.toString()); };
122
+ }
123
+ /** CardanoTxBuilder implementation on top of Buildooor. */
135
124
  class BuildooorTxBuilder {
136
125
  name = 'BuildooorTxBuilder';
137
126
  txBuilder;
@@ -139,16 +128,13 @@ class BuildooorTxBuilder {
139
128
  genesisInfos;
140
129
  paramsFingerprint;
141
130
  /**
142
- * Chain cost-model arrays kept verbatim for language-view hashing. Maintained by
143
- * _mapCostModels (in lockstep with the named-key models the TxBuilder is built
144
- * with); consumed by _languageViewCostModels. Empty when the current parameters
145
- * carry no usable cost models (library defaults in effect).
131
+ * Chain cost-model arrays kept verbatim for language-view hashing; set by _mapCostModels,
132
+ * empty when the current parameters carry no usable cost models.
146
133
  */
147
134
  rawCostModelArrays = {};
148
135
  /**
149
- * Initialize the builder
150
- * @param client - The CardanoClient instance
151
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
136
+ * Initialize the builder.
137
+ * @param protocolParams - optional; fetched from the backend when omitted
152
138
  */
153
139
  async init(client, protocolParams) {
154
140
  this.cardanoClient = client;
@@ -162,11 +148,8 @@ class BuildooorTxBuilder {
162
148
  logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
163
149
  }
164
150
  /**
165
- * Rebuild the TxBuilder when the per-request protocol parameters differ from
166
- * the ones the current TxBuilder was constructed with. Buildooor's TxBuilder
167
- * has no setter for protocol params, but its constructor is cheap, so we
168
- * rebuild on change (effectively once per epoch) instead of staying frozen
169
- * at init-time parameters for the process lifetime.
151
+ * Rebuild the TxBuilder when the per-request protocol parameters differ from the current
152
+ * ones; the TxBuilder has no setter but its constructor is cheap (effectively once per epoch).
170
153
  */
171
154
  _ensureCurrentProtocolParameters(ctx) {
172
155
  const params = ctx.protocolParameters;
@@ -182,23 +165,17 @@ class BuildooorTxBuilder {
182
165
  this.txBuilder = new buildooor_1.TxBuilder(this._mapLedgerParametersToBuildooorParams(params), this.genesisInfos);
183
166
  this.paramsFingerprint = fingerprint;
184
167
  }
185
- /**
186
- * Build unsigned transfer transaction (ADA-only or with native assets).
187
- */
168
+ /** Build an unsigned transfer transaction (ADA-only or with native assets). */
188
169
  buildUnsignedTransfer(req, ctx) {
189
170
  return this._buildSimpleTransfer(req, ctx, 'transfer');
190
171
  }
191
- /**
192
- * Build unsigned transfer transaction with attached metadata.
193
- */
172
+ /** Build an unsigned transfer transaction with attached metadata. */
194
173
  buildUnsignedTransactionWithMetadata(req, ctx) {
195
174
  return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
196
175
  }
197
176
  /**
198
- * Shared non-script transfer build. The two public entry points only differ in
199
- * the optional pieces of the request they carry (assets/outputDatum on the
200
- * plain-transfer path, metadataJson on the metadata path) — all handled here
201
- * conditionally on the field being present, so behaviour matches both.
177
+ * Shared non-script transfer build; assets, outputDatum and metadataJson are each
178
+ * handled only when present in the request.
202
179
  */
203
180
  async _buildSimpleTransfer(req, ctx, label) {
204
181
  try {
@@ -209,15 +186,29 @@ class BuildooorTxBuilder {
209
186
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
210
187
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
211
188
  const amount = BigInt(String(req.lovelaceAmount));
212
- // Build output value (lovelace + optional native assets)
213
- let outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
214
- if (req.assets && req.assets.length > 0) {
215
- outputValue = this._buildLedgerValue(amount, req.assets);
189
+ if (req.outputDatum !== undefined && req.outputDatumCbor !== undefined) {
190
+ throw new errors_1.TransactionValidationError('outputDatum and outputDatumCbor exclude each other; pass one');
216
191
  }
192
+ const callerDatum = req.outputDatumCbor !== undefined ? Buffer.from(req.outputDatumCbor, 'hex') : undefined;
217
193
  const refScript = this._parseReferenceScript(req.referenceScript);
218
- const outputs = [this._buildTxOut(recipientAddress, outputValue, req.outputDatum, refScript)];
194
+ const recipientOut = (lovelace) => {
195
+ const value = this._buildLedgerValue(lovelace, req.assets);
196
+ return callerDatum
197
+ ? new cardano_ledger_ts_1.TxOut({ address: recipientAddress, value, datum: (0, plutus_data_1.dataFromCbor)(callerDatum), ...(refScript && { refScript }) })
198
+ : this._buildTxOut(recipientAddress, value, req.outputDatum, refScript);
199
+ };
200
+ let recipient = recipientOut(amount);
201
+ const minLovelace = this._minOutputLovelace(recipient, callerDatum);
202
+ if (amount < minLovelace) {
203
+ if (!req.ensureMinAda) {
204
+ throw new errors_1.TransactionValidationError(`recipient output needs at least ${minLovelace.toString()} lovelace (has ${amount.toString()}); raise lovelaceAmount or set ensureMinAda`);
205
+ }
206
+ recipient = recipientOut(this._minOutputLovelace(recipient, callerDatum, true));
207
+ }
208
+ const outputValue = recipient.value;
209
+ const outputs = [recipient];
219
210
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
220
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
211
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
221
212
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
222
213
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
223
214
  // Coin selection on candidates only; forced inputs are prepended unconditionally
@@ -228,7 +219,8 @@ class BuildooorTxBuilder {
228
219
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
229
220
  : undefined;
230
221
  const validity = this._resolveValiditySlots(req, 'passthrough');
231
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity });
222
+ const callerDatums = new Map(callerDatum ? [[0, callerDatum]] : []);
223
+ const tx = await this._buildWithCallerDatums({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity }, callerDatums);
232
224
  logger.debug(`Built unsigned transaction successfully.`);
233
225
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
234
226
  }
@@ -237,39 +229,44 @@ class BuildooorTxBuilder {
237
229
  }
238
230
  }
239
231
  async buildUnsignedMintTransaction(req, ctx) {
240
- // Set once the collateral partition is known — an insufficient-funds rejection
241
- // after that point is usually CAUSED by it, and the builder's message can't know.
232
+ // Set once the collateral partition is known: it explains insufficient-funds rejections
233
+ // that the builder's own message cannot attribute.
242
234
  let coinSelectionContext;
243
235
  try {
244
236
  this._ensureCurrentProtocolParameters(ctx);
245
237
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
246
238
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
- // Parse the minting policy script once
248
239
  const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
249
- // Calculate total mint value for output (only positive quantities - mints, not burns)
240
+ // Total mint value for the output (positive quantities only); each action mints under its own policy script.
250
241
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
251
- for (const mintAction of req.mintActions) {
242
+ for (const [index, mintAction] of req.mintActions.entries()) {
252
243
  const quantity = BigInt(mintAction.quantity);
253
244
  if (quantity > 0n) {
245
+ const actionScript = this._mintActionScript(mintAction, script, index);
254
246
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
255
- mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), quantity));
247
+ mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), quantity));
256
248
  }
257
249
  }
258
250
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
259
251
  // collateral and coin selection operate on the remainder only.
260
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
252
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
261
253
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
262
254
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
263
255
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
264
256
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
265
257
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
266
258
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
267
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
268
- const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
259
+ // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
260
+ // demand the mint itself does not cover.
261
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
262
+ if (req.extraOutputs && req.extraOutputs.length > 0) {
263
+ const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
264
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
265
+ }
269
266
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
270
267
  const inputs = [...forcedInputs, ...selectedFunding];
271
268
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
272
- // FR-3: resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum after final input order is known.
269
+ // Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
273
270
  const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
274
271
  ...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
275
272
  ...this._extractFundingRefs(selectedFunding)
@@ -281,27 +278,31 @@ class BuildooorTxBuilder {
281
278
  const resolvedInlineDatum = req.inlineDatum
282
279
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
283
280
  : undefined;
284
- // Build output — recipient gets the minted assets + min ADA
281
+ const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
282
+ // Primary output: minted assets + min ADA. With extra outputs declared, those carry
283
+ // the minted assets and the primary output stays ADA(+datum)-only.
285
284
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
286
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
285
+ if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
286
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
287
+ }
287
288
  const refScript = this._parseReferenceScript(req.referenceScript);
288
289
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
289
- // Mint entries for the build args (uses pre-resolved redeemer). Note: Buildooor
290
- // ignores caller-supplied execution units — the real units are stamped into the
291
- // redeemers post-build by _buildScriptTx.
292
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
290
+ // Append extra outputs, each independently min-ADA checked.
291
+ this._appendExtraOutputs(outputs, resolvedExtraOutputs);
292
+ // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
293
+ // stamped post-build by _buildScriptTx.
294
+ const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
293
295
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
294
296
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
295
297
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
296
298
  // and fee computation stay consistent (a mismatch would force re-evaluation).
297
299
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
298
- // CIP-20 / label-674 etc. auxiliary metadata. Must be identical across eval + final
299
- // passes since auxiliary_data affects both tx size (→ fee) and script data hash (indirectly via tx hash).
300
+ // Auxiliary metadata (CIP-20, label 674, ...) must be identical across eval + final passes:
301
+ // it affects tx size (fee) and the script data hash.
300
302
  const mintMetadata = req.metadataJson
301
303
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
302
304
  : undefined;
303
- // Single set of build args — both internal passes and the Ogmios evaluation share
304
- // validity bounds and metadata so redeemer ExUnits and fee stay consistent.
305
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
305
306
  const buildParams = {
306
307
  inputs, outputs, changeAddress, mints,
307
308
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
@@ -324,14 +325,11 @@ class BuildooorTxBuilder {
324
325
  try {
325
326
  this._ensureCurrentProtocolParameters(ctx);
326
327
  const { plutusScriptExecution } = req;
327
- // Parse the validator script
328
328
  const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
329
329
  if (!plutusScriptExecution.datum) {
330
- // When no explicit datum is provided, the UTxO must have an inline datum.
331
- // If neither exists, the Plutus validator will fail with a cryptic error.
330
+ // Without an explicit datum the script UTxO must carry an inline datum.
332
331
  logger.debug('No datumJson provided — expecting inline datum on script UTxO');
333
332
  }
334
- // Find the specific script UTxO in the provided context UTxOs
335
333
  const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
336
334
  const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
337
335
  if (!scriptOdatanoUtxo) {
@@ -344,15 +342,14 @@ class BuildooorTxBuilder {
344
342
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
345
343
  // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
346
344
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
347
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
345
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
348
346
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
349
347
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
350
348
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
351
349
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
352
350
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
353
- // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
354
- // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
355
- // already provides will net out, so over-requesting is harmless — keepRelevant prefers smaller sets.
351
+ // Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
352
+ // assets the script UTxO already provides net out, so over-requesting is harmless.
356
353
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
357
354
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
358
355
  if (req.extraOutputs && req.extraOutputs.length > 0) {
@@ -362,15 +359,18 @@ class BuildooorTxBuilder {
362
359
  }
363
360
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
364
361
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
365
- // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
366
- // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
367
- const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
362
+ // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
363
+ // in redeemer / datum / output datums BEFORE PlutusData encoding.
364
+ const sortedInputs = this._computeSortedInputs([scriptUtxoRef], forced, this._extractFundingRefs(selectedFundingInputs));
368
365
  const resolveCtx = { sortedInputs };
369
366
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
370
367
  const redeemerData = (0, tx_build_helper_1.jsonToPlutusData)(resolvedRedeemer);
371
368
  const datum = plutusScriptExecution.datum
372
369
  ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.datum, resolveCtx))
373
370
  : "inline";
371
+ if (datum !== "inline") {
372
+ this._checkWitnessDatum(scriptOdatanoUtxo, (0, plutus_data_1.dataToCbor)(datum), 'datumJson', '; BuildPlutusTransaction takes the datum as datumCbor with the bytes the UTxO was locked with');
373
+ }
374
374
  const resolvedPrimaryInlineDatum = req.inlineDatum
375
375
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
376
376
  : undefined;
@@ -378,7 +378,7 @@ class BuildooorTxBuilder {
378
378
  const resolvedMintRedeemer = req.mintRedeemer
379
379
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
380
380
  : undefined;
381
- // FR-1: combined spend+mint flow. When mintActions are present, build mints alongside the spend input.
381
+ // Combined spend+mint: with mintActions present, mints are built alongside the spend input.
382
382
  const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
383
383
  let mintScript;
384
384
  let mintScriptHash;
@@ -394,24 +394,23 @@ class BuildooorTxBuilder {
394
394
  }
395
395
  // If mints are present and no extraOutputs handle the minted assets, attach positive mints to the primary output.
396
396
  if (hasMint && (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0)) {
397
- for (const action of req.mintActions) {
397
+ for (const [index, action] of req.mintActions.entries()) {
398
398
  const qty = BigInt(action.quantity);
399
399
  if (qty > 0n) {
400
+ const actionScript = this._mintActionScript(action, mintScript, index);
400
401
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
401
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), qty));
402
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), qty));
402
403
  }
403
404
  }
404
405
  }
405
406
  const primaryRefScript = this._parseReferenceScript(req.referenceScript);
406
407
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedPrimaryInlineDatum, primaryRefScript)];
407
- // Append extra outputs (FR-2). Each is independently min-ADA checked so consumers
408
- // get a clear, field-attributed error before Buildooor's coin selection runs.
408
+ // Append extra outputs, each independently min-ADA checked.
409
409
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
410
- // Mint entries (FR-1) and inputs for the build args. Note: Buildooor ignores
411
- // caller-supplied execution units — the real units are stamped into the
412
- // redeemers post-build by _buildScriptTx.
410
+ // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
411
+ // units, the real ones are stamped post-build by _buildScriptTx.
413
412
  const mints = hasMint
414
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
413
+ ? this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, mintScript, i) }), resolvedMintRedeemer, resolveCtx)
415
414
  : undefined;
416
415
  const scriptInput = {
417
416
  utxo: scriptLedgerUtxo,
@@ -423,8 +422,7 @@ class BuildooorTxBuilder {
423
422
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
424
423
  // and fee computation stay consistent (a mismatch would force re-evaluation).
425
424
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
426
- // Single set of build args — both internal passes and the Ogmios evaluation share
427
- // validity bounds so redeemer ExUnits and fee stay consistent.
425
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
428
426
  const buildParams = {
429
427
  inputs, outputs, changeAddress,
430
428
  mints,
@@ -446,6 +444,276 @@ class BuildooorTxBuilder {
446
444
  (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
447
445
  }
448
446
  }
447
+ /**
448
+ * Several script inputs in one transaction, each with its own redeemer (inline validator or a
449
+ * reference-script UTxO), the outputs exactly in the given order and change after them.
450
+ */
451
+ async buildUnsignedPlutusTransaction(req, ctx) {
452
+ let coinSelectionContext;
453
+ try {
454
+ this._ensureCurrentProtocolParameters(ctx);
455
+ const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
456
+ const utxoByKey = new Map(ctx.utxos.map(u => [keyOf(u), u]));
457
+ const refUtxoByKey = new Map((ctx.referenceInputUtxos ?? []).map(u => [keyOf(u), u]));
458
+ const scriptKeys = new Set(req.scriptInputs.map(keyOf));
459
+ // Scripts the reference inputs already carry: the ledger rejects the same script again as a
460
+ // witness (ExtraneousScriptWitnesses), so an inline validator with such a hash uses the reference.
461
+ const referencedByHash = new Map();
462
+ for (const u of ctx.referenceInputUtxos ?? []) {
463
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(u);
464
+ const hash = ledgerUtxo.resolved.refScript?.hash.toString();
465
+ if (hash && !referencedByHash.has(hash))
466
+ referencedByHash.set(hash, ledgerUtxo);
467
+ }
468
+ // Script inputs: each UTxO with its script (inline, or the ledger UTxO carrying it)
469
+ const scriptEntries = req.scriptInputs.map((si, i) => {
470
+ const utxo = utxoByKey.get(keyOf(si));
471
+ if (!utxo)
472
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}] ${keyOf(si)} not found on-chain or already spent`);
473
+ if (si.validatorScript) {
474
+ const script = this._parsePlutusV3Script(si.validatorScript, `scriptInputs[${i}].validatorScript`);
475
+ const scriptHash = script.hash.toString();
476
+ const referenced = referencedByHash.get(scriptHash);
477
+ return referenced ? { si, utxo, refLedgerUtxo: referenced, scriptHash } : { si, utxo, script };
478
+ }
479
+ const refKey = keyOf(si.referenceScript);
480
+ const refUtxo = refUtxoByKey.get(refKey);
481
+ if (!refUtxo)
482
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} not found on-chain or already spent`);
483
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
484
+ if (!refLedgerUtxo.resolved.refScript) {
485
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
486
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
487
+ }
488
+ return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
489
+ });
490
+ // Withdrawals: the staking script inline, by reference, or the one a reference input carries
491
+ const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
492
+ w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
493
+ ...this._resolveScriptWitness({ script: w.stakingScript, referenceScript: w.referenceScript }, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
494
+ }));
495
+ // Certificates: the credential from the stake address; a script runs under the Certifying purpose
496
+ const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
497
+ const certEntries = (req.certificates ?? []).map((c, i) => {
498
+ const at = `certificates[${i}]`;
499
+ const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
500
+ const credentialHash = stake.credentials.toString().toLowerCase();
501
+ const witness = this._resolveScriptWitness({ script: c.stakingScript, referenceScript: c.referenceScript }, at, referencedByHash, refUtxoByKey);
502
+ const scripted = Boolean(witness.script || witness.refLedgerUtxo);
503
+ const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
504
+ if (stake.type === 'script') {
505
+ if (scripted && witnessHash !== credentialHash) {
506
+ throw new errors_1.TransactionValidationError(`${at} staking script hash ${witnessHash} is not the credential of ${c.stakeAddress} (${credentialHash})`);
507
+ }
508
+ if (!scripted && c.type === 'deregisterStake') {
509
+ throw new errors_1.TransactionValidationError(`${at} deregisters the script credential ${c.stakeAddress}; its staking script and redeemer are needed`);
510
+ }
511
+ }
512
+ else if (scripted) {
513
+ throw new errors_1.TransactionValidationError(`${at} ${c.stakeAddress} is a key credential; it takes no staking script`);
514
+ }
515
+ const stakeCredential = stake.type === 'script' ? cardano_ledger_ts_1.Credential.script(stake.credentials) : cardano_ledger_ts_1.Credential.keyHash(stake.credentials);
516
+ const deposit = c.deposit ? BigInt(c.deposit) : stakeDeposit;
517
+ // Without a script the witness-free legacy registration; the deposit forms need the witness
518
+ const cert = c.type === 'registerStake'
519
+ ? (scripted ? new cardano_ledger_ts_1.CertRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeRegistration({ stakeCredential }))
520
+ : (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
521
+ return { c, cert, deposit, ...witness };
522
+ });
523
+ // Mints: each policy inline, by reference, or the one a reference input carries
524
+ const mintEntries = (req.mintActions ?? []).map((m, i) => {
525
+ const at = `mintActions[${i}]`;
526
+ const witness = this._resolveScriptWitness({ script: m.mintingPolicyScript, referenceScript: m.referenceScript }, at, referencedByHash, refUtxoByKey, 'mintingPolicyScript');
527
+ const policyId = (witness.script?.hash ?? witness.refLedgerUtxo.resolved.refScript.hash).toString().toLowerCase();
528
+ if (!m.assetUnit.toLowerCase().startsWith(policyId)) {
529
+ throw new errors_1.TransactionValidationError(`${at}.assetUnit ${m.assetUnit} is not under the policy ${policyId} of its script`);
530
+ }
531
+ return { m, policyId, ...witness };
532
+ });
533
+ // one policy runs from one place: once any action of it uses a reference script, all do
534
+ const mintRefByPolicy = new Map();
535
+ for (const e of mintEntries)
536
+ if (e.refLedgerUtxo && !mintRefByPolicy.has(e.policyId))
537
+ mintRefByPolicy.set(e.policyId, e.refLedgerUtxo);
538
+ for (const e of mintEntries) {
539
+ const ref = mintRefByPolicy.get(e.policyId);
540
+ if (ref) {
541
+ e.refLedgerUtxo = ref;
542
+ e.script = undefined;
543
+ }
544
+ }
545
+ const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
546
+ const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
547
+ const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
548
+ if (scriptKeyClash)
549
+ throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
550
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs);
551
+ this._checkForeignForcedInputs(forced, req);
552
+ const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
553
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
554
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
555
+ const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
556
+ // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
557
+ // withdrawals (keepRelevant adds its own lovelace margin for fee and change).
558
+ const need = new Map();
559
+ const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
560
+ for (const o of req.outputs) {
561
+ add('lovelace', BigInt(o.lovelaceAmount));
562
+ for (const a of o.assets ?? [])
563
+ add(a.unit, BigInt(a.quantity));
564
+ }
565
+ for (const u of [...scriptEntries.map(e => e.utxo), ...forced]) {
566
+ for (const a of u.amount)
567
+ add(a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit, -BigInt(a.quantity));
568
+ }
569
+ for (const m of req.mintActions ?? [])
570
+ add(m.assetUnit, -BigInt(m.quantity));
571
+ for (const { w } of withdrawalEntries)
572
+ add('lovelace', -BigInt(w.lovelace));
573
+ // a registration locks the deposit, a deregistration refunds it
574
+ for (const { c, deposit } of certEntries)
575
+ add('lovelace', c.type === 'registerStake' ? deposit : -deposit);
576
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
577
+ for (const [unit, qty] of need) {
578
+ if (qty <= 0n)
579
+ continue;
580
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, unit === 'lovelace'
581
+ ? cardano_ledger_ts_1.Value.lovelaces(qty)
582
+ : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
583
+ }
584
+ const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
585
+ // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
586
+ const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries, ...mintEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
587
+ const callerRefUtxos = (ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u)));
588
+ const readonlyRefInputs = this._mapReferenceInputs(callerRefUtxos);
589
+ const sortedReferenceInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
590
+ ...callerRefUtxos.map(u => ({ txHash: u.txHash.toLowerCase(), outputIndex: u.outputIndex })),
591
+ ...[...refScriptKeys].map(k => { const [txHash, idx] = k.split('#'); return { txHash, outputIndex: Number(idx) }; }),
592
+ ]);
593
+ // Placeholders resolve against the final input, reference-input and withdrawal order
594
+ const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
595
+ const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
596
+ const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
597
+ const witnessDatums = [];
598
+ const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }, i) => {
599
+ const redeemer = si.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(si.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.redeemer, resolveCtx));
600
+ let datum = "inline";
601
+ if (si.datumCbor) {
602
+ const bytes = Buffer.from(si.datumCbor, 'hex');
603
+ this._checkWitnessDatum(utxo, bytes, `scriptInputs[${i}].datumCbor`, '');
604
+ witnessDatums.push(bytes);
605
+ datum = (0, plutus_data_1.dataFromCbor)(bytes);
606
+ }
607
+ else if (si.datum !== undefined) {
608
+ datum = (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx));
609
+ this._checkWitnessDatum(utxo, (0, plutus_data_1.dataToCbor)(datum), `scriptInputs[${i}].datumJson`, '; pass datumCbor with the bytes the UTxO was locked with');
610
+ }
611
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
612
+ return script
613
+ ? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
614
+ : { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
615
+ });
616
+ const outputs = [];
617
+ const callerDatums = this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
618
+ ...o,
619
+ inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
620
+ })));
621
+ const mints = mintEntries.length > 0
622
+ ? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
623
+ : undefined;
624
+ // Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
625
+ const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
626
+ const withdrawal = { rewardAccount, amount: BigInt(w.lovelace) };
627
+ if (!script && !refLedgerUtxo)
628
+ return { withdrawal };
629
+ const redeemer = w.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(w.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(w.redeemer ?? null, resolveCtx));
630
+ return { withdrawal, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
631
+ });
632
+ // Certificates in the given order; a scripted one carries its redeemer under the Cert purpose
633
+ const certificates = certEntries.map(({ c, cert, script, refLedgerUtxo }) => {
634
+ if (!script && !refLedgerUtxo)
635
+ return { cert };
636
+ const redeemer = c.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(c.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(c.redeemer ?? null, resolveCtx));
637
+ return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
638
+ });
639
+ const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
640
+ const buildParams = {
641
+ inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
642
+ outputs, changeAddress, mints,
643
+ collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
644
+ invalidBefore, invalidAfter,
645
+ ...(collateralReturn && { collateralReturn }),
646
+ ...(readonlyRefInputs.length > 0 && { readonlyRefInputs }),
647
+ ...(withdrawals.length > 0 && { withdrawals }),
648
+ ...(certificates.length > 0 && { certificates })
649
+ };
650
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction, callerDatums, witnessDatums);
651
+ const details = this._extractTxDetails(tx);
652
+ const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
653
+ if (details.sizeBytes > maxTxSize) {
654
+ const inline = scriptEntries.filter(e => e.script).length;
655
+ throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
656
+ (inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
657
+ }
658
+ const scriptHashes = scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash);
659
+ logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
660
+ return this._buildResult(req, ctx, details, {
661
+ scriptHash: scriptHashes[0],
662
+ forcedInputsUsed: forcedInputs.length,
663
+ referenceInputsUsed: readonlyRefInputs.length + refScriptKeys.size
664
+ });
665
+ }
666
+ catch (err) {
667
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
668
+ }
669
+ }
670
+ /**
671
+ * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
672
+ * Returns the inline datums given as CBOR, keyed by output index.
673
+ */
674
+ _appendPlutusOutputs(outputs, list) {
675
+ const callerDatums = new Map();
676
+ for (let i = 0; i < list.length; i++) {
677
+ const o = list[i];
678
+ const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
679
+ const refScript = this._parseReferenceScript(o.referenceScript);
680
+ const callerDatum = o.inlineDatumCbor ? Buffer.from(o.inlineDatumCbor, 'hex') : undefined;
681
+ const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : callerDatum ? (0, plutus_data_1.dataFromCbor)(callerDatum) : undefined;
682
+ const txOut = datum
683
+ ? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
684
+ : this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
685
+ const minLovelaces = this._minOutputLovelace(txOut, callerDatum);
686
+ if (BigInt(o.lovelaceAmount) < minLovelaces) {
687
+ throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
688
+ }
689
+ if (callerDatum)
690
+ callerDatums.set(outputs.length, callerDatum);
691
+ outputs.push(txOut);
692
+ }
693
+ return callerDatums;
694
+ }
695
+ /**
696
+ * Min-ADA of an output, counting the caller's datum bytes where they are longer than
697
+ * Buildooor's encoding. `forAnyAmount` sizes the coin field for the largest amount, so the
698
+ * result stays valid once written into the output.
699
+ */
700
+ _minOutputLovelace(txOut, callerDatum, forAnyAmount = false) {
701
+ const base = forAnyAmount
702
+ ? this.txBuilder.minimizeLovelaces(txOut).value.lovelaces
703
+ : this.txBuilder.getMinimumOutputLovelaces(txOut);
704
+ const growth = callerDatum ? Math.max(0, (0, caller_datums_1.callerDatumGrowth)(callerDatum)) : 0;
705
+ return base + BigInt(growth) * BigInt(this.txBuilder.protocolParamters.utxoCostPerByte);
706
+ }
707
+ /** Build, then write the caller's datum bytes; when they are longer, a second build raises the fee. */
708
+ async _buildWithCallerDatums(args, datums) {
709
+ const tx = await this.txBuilder.build(args);
710
+ const growth = (0, caller_datums_1.callerDatumsGrowth)(datums);
711
+ if (growth === 0)
712
+ return (0, caller_datums_1.writeCallerDatums)(tx, datums);
713
+ // Fee floor: the extra bytes plus a pad for change-size wobble
714
+ const fee = BigInt(tx.body.fee.toString()) + BigInt(growth + 10) * this._txFeePerByte();
715
+ return (0, caller_datums_1.writeCallerDatums)(await this.txBuilder.build({ ...args, fee }), datums);
716
+ }
449
717
  //---------------------------------------------------------------------------
450
718
  // Shared Helper Methods
451
719
  //---------------------------------------------------------------------------
@@ -465,6 +733,12 @@ class BuildooorTxBuilder {
465
733
  address: o.address?.toString?.() ?? "",
466
734
  lovelace: o.value?.lovelaces?.toString?.() ?? "0"
467
735
  })),
736
+ redeemers: (tx.witnesses.redeemers ?? []).map((r) => ({
737
+ tag: (0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag),
738
+ index: r.index,
739
+ mem: r.execUnits.mem.toString(),
740
+ steps: r.execUnits.cpu.toString(),
741
+ })),
468
742
  };
469
743
  }
470
744
  /** Build the standard TxBuildResult object */
@@ -488,31 +762,17 @@ class BuildooorTxBuilder {
488
762
  feeLovelace: txDetails.feeLovelace,
489
763
  inputs,
490
764
  outputs: txDetails.outputs,
765
+ ...(txDetails.redeemers.length > 0 ? { redeemers: txDetails.redeemers } : {}),
491
766
  ...extra,
492
767
  warnings: [],
493
768
  };
494
769
  }
495
770
  /**
496
- * Build a script-bearing transaction whose redeemers carry *real* execution units and
497
- * whose fee covers them.
498
- *
499
- * Background (verified against the vendored Buildooor source): `initTxBuild` constructs
500
- * every redeemer with a dummy budget — caller-supplied execution units in the build args
501
- * are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
502
- * the budget the local CEK run consumed, even when the script failed (partial budget).
503
- * So the declared units are whatever the *local* evaluation produced, and any cushion
504
- * passed into the args silently evaporates. This method makes the declared units real:
505
- *
506
- * 1. First pass: build once; redeemers now carry the local CEK budgets.
507
- * 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
508
- * budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
509
- * 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
510
- * without an Ogmios result aborts — see makeScriptBuildOpts).
511
- * 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
512
- * from its own local budgets, so the floor adds the price + encoding-size delta).
513
- * 5. Stamp the target units into the redeemers and recompute scriptDataHash.
771
+ * Build a script-bearing transaction with real execution units: Buildooor stamps local CEK
772
+ * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
773
+ * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
514
774
  */
515
- async _buildScriptTx(buildParams, evaluator) {
775
+ async _buildScriptTx(buildParams, evaluator, callerDatums = new Map(), witnessDatums = []) {
516
776
  const pass1Failures = [];
517
777
  const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
518
778
  if (!tx1) {
@@ -520,12 +780,10 @@ class BuildooorTxBuilder {
520
780
  }
521
781
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
522
782
  if (rdmrs1.length === 0) {
523
- // Defensive — callers always attach a script. Nothing to evaluate or stamp,
524
- // and Buildooor's calcMinFee already budgets the vkey witnesses to come.
525
- return tx1;
783
+ // Defensive: callers always attach a script; nothing to evaluate or stamp.
784
+ return callerDatums.size === 0 ? tx1 : this._buildWithCallerDatums(buildParams, callerDatums);
526
785
  }
527
- // The first-pass CBOR is exactly what a dedicated "evaluation build" would produce
528
- // (identical args ⇒ identical tx, since passed ExUnits are ignored anyway).
786
+ // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
529
787
  const evaluatedUnits = evaluator
530
788
  ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
531
789
  : undefined;
@@ -533,26 +791,23 @@ class BuildooorTxBuilder {
533
791
  logger.debug('No evaluator available — falling back to buffered local execution units');
534
792
  }
535
793
  const targets1 = this._resolveTargetExUnits(rdmrs1, evaluatedUnits, pass1Failures);
536
- // Fee floor: Buildooor's fee covers its local budgets AND the vkey witnesses to
537
- // come (calcMinFee budgets 104 bytes per estimated signer); add only the price
538
- // delta of the stamped units, their (slightly longer) CBOR encoding, and a small
539
- // pad for change-output size wobble between the two passes.
794
+ // Fee floor: Buildooor's fee already covers local budgets and future vkey witnesses; add the
795
+ // price delta of the stamped units, their longer CBOR encoding, and a pad for change-size wobble.
540
796
  const feeFloor = BigInt(tx1.body.fee.toString())
541
797
  + this._exUnitsPriceDelta(rdmrs1, targets1)
542
798
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
799
+ + BigInt((0, caller_datums_1.callerDatumsGrowth)(callerDatums) + (0, caller_datums_1.witnessDatumsGrowth)(witnessDatums)) * this._txFeePerByte()
543
800
  + 10n * this._txFeePerByte();
544
801
  const pass2Failures = [];
545
802
  const tx2 = await this.txBuilder.build({ ...buildParams, fee: feeFloor }, makeScriptBuildOpts(pass2Failures));
546
803
  const rdmrs2 = tx2.witnesses.redeemers ?? [];
547
804
  const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
548
- return this._stampExecUnits(tx2, targets2);
805
+ const tx = (0, caller_datums_1.writeCallerDatums)(this._stampExecUnits(tx2, targets2), callerDatums);
806
+ return (0, caller_datums_1.writeWitnessDatums)(tx, witnessDatums, this._languageViews(tx));
549
807
  }
550
808
  /**
551
- * Evaluate a transaction via Ogmios and return cushioned budgets keyed per redeemer
552
- * (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
553
- * failure, empty result) so callers fall back to buffered local units. A
554
- * TransactionValidationError or ScriptValidationError from the evaluator is
555
- * authoritative (the script really failed on the ledger) and is rethrown.
809
+ * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
810
+ * evaluation is unusable (transient failure, empty result). Validation errors are rethrown.
556
811
  */
557
812
  async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
558
813
  try {
@@ -566,7 +821,7 @@ class BuildooorTxBuilder {
566
821
  let purpose;
567
822
  let index;
568
823
  if (typeof v === 'string') {
569
- // Legacy "purpose:index" form
824
+ // "purpose:index" string form
570
825
  const [p, i] = v.split(':');
571
826
  purpose = p;
572
827
  index = Number(i);
@@ -586,11 +841,8 @@ class BuildooorTxBuilder {
586
841
  }
587
842
  catch (evalError) {
588
843
  if (evalError instanceof errors_1.TransactionValidationError || evalError instanceof errors_1.ScriptValidationError) {
589
- // Authoritative: Ogmios executed the script and the ledger rejected it. This is
590
- // either a TransactionValidationError or, after normalizeBackendError, a
591
- // ScriptValidationError (PlutusFailure / CekError / budget overspend). Falling
592
- // back to local buffered units here would hand back a transaction the node has
593
- // already rejected — so propagate the failure instead.
844
+ // Authoritative: the ledger executed and rejected the script; falling back to local
845
+ // units would hand back a transaction the node has already rejected.
594
846
  throw evalError;
595
847
  }
596
848
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
@@ -599,9 +851,8 @@ class BuildooorTxBuilder {
599
851
  }
600
852
  }
601
853
  /**
602
- * Combined cushion: relative multiplier catches proportional drift on large
603
- * validators, absolute floor catches sub-percent drift on small ones (observed
604
- * when metadata affects the real tx body vs the evaluator's ScriptContext).
854
+ * Cushion: relative multiplier for proportional drift on large validators, absolute floor
855
+ * for sub-percent drift on small ones.
605
856
  */
606
857
  _applyExUnitBuffer(mem, cpu) {
607
858
  return {
@@ -610,12 +861,9 @@ class BuildooorTxBuilder {
610
861
  };
611
862
  }
612
863
  /**
613
- * Decide the execution units each redeemer must declare.
614
- * - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
615
- * - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
616
- * - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
617
- * - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
618
- * collateral of whoever signs and submits the returned CBOR.
864
+ * Execution units each redeemer must declare: max(local, Ogmios) when both exist, buffered
865
+ * local without Ogmios, Ogmios alone after a local failure; a local failure without Ogmios
866
+ * aborts because unreliable units would forfeit the signer's collateral.
619
867
  */
620
868
  _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
621
869
  return rdmrs.map(r => {
@@ -673,15 +921,9 @@ class BuildooorTxBuilder {
673
921
  return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
674
922
  }
675
923
  /**
676
- * Replace the redeemers' execution units and recompute scriptDataHash.
677
- *
678
- * Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
679
- * 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
680
- * builder's named-key cost models, which clamp the chain array to the parameter
681
- * count the library release knows — wrong whenever the on-chain cost model has
682
- * grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
683
- * _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
684
- * is recomputed here even when the target units already match.
924
+ * Replace the redeemers' execution units and recompute scriptDataHash with the raw chain
925
+ * cost-model arrays (TxBuilder.overrideTxRedeemers hashes with clamped named-key models,
926
+ * which mismatches once the on-chain cost model grows). Recomputed even when units match.
685
927
  */
686
928
  _stampExecUnits(tx, targets) {
687
929
  const rdmrs = tx.witnesses.redeemers ?? [];
@@ -693,8 +935,7 @@ class BuildooorTxBuilder {
693
935
  execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
694
936
  }));
695
937
  const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
696
- const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
697
- const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
938
+ const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, this._languageViews(tx)) });
698
939
  const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
699
940
  if (!unchanged) {
700
941
  logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
@@ -702,6 +943,22 @@ class BuildooorTxBuilder {
702
943
  }
703
944
  return finalTx;
704
945
  }
946
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
947
+ _languageViews(tx) {
948
+ return (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
949
+ }
950
+ /**
951
+ * Check a witness datum against the datum hash its script UTxO is locked with: the ledger
952
+ * finds the datum by the hash of its bytes. Inline-datum UTxOs need no witness datum.
953
+ */
954
+ _checkWitnessDatum(utxo, datum, field, hint) {
955
+ if (!utxo.datumHash || utxo.inlineDatum)
956
+ return;
957
+ const hash = (0, caller_datums_1.datumHashOf)(datum);
958
+ if (hash !== utxo.datumHash.toLowerCase()) {
959
+ throw new errors_1.TransactionValidationError(`${field} hashes to ${hash}, but ${utxo.txHash}#${utxo.outputIndex} is locked with datum hash ${utxo.datumHash}${hint}`);
960
+ }
961
+ }
705
962
  /**
706
963
  * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
707
964
  * (which flags the languages of *executed* scripts). This builder only attaches
@@ -719,12 +976,9 @@ class BuildooorTxBuilder {
719
976
  return opts;
720
977
  }
721
978
  /**
722
- * Cost models for language-view hashing. The named-key objects the TxBuilder was
723
- * constructed with clamp the chain array to the parameter count this costmodels-ts
724
- * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
725
- * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
726
- * array form through unclamped, so substitute the raw chain arrays where we have
727
- * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
979
+ * Cost models for language-view hashing: named-key objects clamp the chain array to the
980
+ * parameter count this library release knows, but the ledger hashes every entry served,
981
+ * so raw chain arrays (passed through unclamped) are substituted where available.
728
982
  */
729
983
  _languageViewCostModels() {
730
984
  const models = this.txBuilder.protocolParamters.costModels;
@@ -733,57 +987,217 @@ class BuildooorTxBuilder {
733
987
  return { ...models, ...this.rawCostModelArrays };
734
988
  }
735
989
  /**
736
- * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
737
- * coin selection / collateral). Refs in forceInputs that are not present in utxos are
738
- * silently ignored — the resolver upstream has already validated existence.
990
+ * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
991
+ * refs absent from utxos are ignored (existence is validated upstream).
739
992
  */
740
- _partitionForcedInputs(utxos, forceInputs) {
741
- if (!forceInputs || forceInputs.length === 0)
993
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs) {
994
+ const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
995
+ const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
996
+ const protectedKeys = new Set((protectInputs ?? []).map(key));
997
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(hasRefScript)) {
742
998
  return { forced: [], rest: utxos };
743
- const forcedKeys = new Set(forceInputs.map(r => `${r.txHash}#${r.outputIndex}`));
999
+ }
1000
+ const forcedKeys = new Set((forceInputs ?? []).map(key));
1001
+ // a UTxO cannot be spent and referenced in one transaction
1002
+ const clash = [...forcedKeys].find(k => referenced.has(k));
1003
+ if (clash)
1004
+ throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input — a UTxO cannot be spent and referenced in one transaction`);
1005
+ const protectedClash = [...forcedKeys].find(k => protectedKeys.has(k));
1006
+ if (protectedClash)
1007
+ throw new errors_1.TransactionValidationError(`forceInputs ${protectedClash} is also in protectInputs`);
744
1008
  const forced = [];
745
1009
  const rest = [];
746
1010
  for (const u of utxos) {
747
- if (forcedKeys.has(`${u.txHash}#${u.outputIndex}`))
1011
+ if (forcedKeys.has(key(u)))
748
1012
  forced.push(u);
749
- else
1013
+ // reference inputs, protected UTxOs and UTxOs carrying a reference script stay out of coin
1014
+ // selection and collateral; a deployed script is spent only when forced
1015
+ else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !hasRefScript(u))
750
1016
  rest.push(u);
751
1017
  }
752
1018
  return { forced, rest };
753
1019
  }
754
1020
  /**
755
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
756
- * Returns empty array when no reference inputs are provided.
1021
+ * Script of a withdrawal, certificate or mint: inline (swapped for a reference input that already
1022
+ * carries the same hash), by reference, or none (key witness).
1023
+ */
1024
+ _resolveScriptWitness(w, at, referencedByHash, refUtxoByKey, scriptField = 'stakingScript') {
1025
+ if (w.script) {
1026
+ const script = this._parsePlutusV3Script(w.script, `${at}.${scriptField}`);
1027
+ const referenced = referencedByHash.get(script.hash.toString());
1028
+ return referenced ? { refLedgerUtxo: referenced } : { script };
1029
+ }
1030
+ if (!w.referenceScript)
1031
+ return {};
1032
+ const refKey = `${w.referenceScript.txHash.toLowerCase()}#${w.referenceScript.outputIndex}`;
1033
+ const refUtxo = refUtxoByKey.get(refKey);
1034
+ if (!refUtxo)
1035
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} not found on-chain or already spent`);
1036
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
1037
+ if (!refLedgerUtxo.resolved.refScript) {
1038
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
1039
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
1040
+ }
1041
+ return { refLedgerUtxo };
1042
+ }
1043
+ /**
1044
+ * Withdrawal credential hashes in ledger order, which `__WDRL_IDX__` resolves against. Buildooor
1045
+ * numbers withdrawal redeemers by hash alone, so a scripted withdrawal whose position differs
1046
+ * between the two orders would get the wrong redeemer; such a build is refused.
1047
+ */
1048
+ _ledgerWithdrawalOrder(entries) {
1049
+ const withHash = entries.map(e => ({
1050
+ credentialHash: e.rewardAccount.credentials.toString().toLowerCase(),
1051
+ isScript: e.rewardAccount.type === 'script',
1052
+ scripted: Boolean(e.script || e.refLedgerUtxo),
1053
+ }));
1054
+ const ledger = (0, plutus_placeholders_1.sortWithdrawalsLikeLedger)(withHash).map(e => e.credentialHash);
1055
+ const buildooor = withHash.map(e => e.credentialHash).sort((a, b) => Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')));
1056
+ const misplaced = withHash.find(e => e.scripted && ledger.indexOf(e.credentialHash) !== buildooor.indexOf(e.credentialHash));
1057
+ if (misplaced) {
1058
+ throw new errors_1.TransactionValidationError(`withdrawals: the scripted withdrawal of credential ${misplaced.credentialHash} cannot be indexed correctly, ` +
1059
+ 'because a key-credential withdrawal sorts before it by hash; move that key withdrawal into a separate transaction');
1060
+ }
1061
+ return ledger;
1062
+ }
1063
+ /**
1064
+ * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
1065
+ * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
1066
+ * Script addresses are refused; those UTxOs are script inputs.
757
1067
  */
1068
+ _checkForeignForcedInputs(forced, req) {
1069
+ const sender = req.senderAddress.toLowerCase();
1070
+ const foreign = forced.filter(u => u.address.toLowerCase() !== sender);
1071
+ if (foreign.length === 0)
1072
+ return;
1073
+ const signers = new Set((req.requiredSigners ?? []).map(s => s.toLowerCase()));
1074
+ const keyOf = (u) => `${u.txHash}#${u.outputIndex}`;
1075
+ const byAddress = new Map();
1076
+ for (const u of foreign)
1077
+ byAddress.set(u.address, [...(byAddress.get(u.address) ?? []), u]);
1078
+ for (const [address, utxos] of byAddress) {
1079
+ const creds = cardano_ledger_ts_1.Address.fromString(address).paymentCreds;
1080
+ const refs = utxos.map(keyOf).join(', ');
1081
+ if (creds.type !== cardano_ledger_ts_1.CredentialType.KeyHash) {
1082
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} are at the script address ${address}; spend script UTxOs via scriptInputs`);
1083
+ }
1084
+ const keyHash = creds.hash.toString().toLowerCase();
1085
+ if (!signers.has(keyHash)) {
1086
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} belong to ${address}; its payment key hash ${keyHash} must be in requiredSigners (the owner co-signs)`);
1087
+ }
1088
+ }
1089
+ const brought = new Map();
1090
+ for (const u of foreign) {
1091
+ for (const a of u.amount) {
1092
+ const unit = a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit;
1093
+ brought.set(unit, (brought.get(unit) ?? 0n) + BigInt(a.quantity));
1094
+ }
1095
+ }
1096
+ const spent = new Map();
1097
+ for (const o of req.outputs) {
1098
+ spent.set('lovelace', (spent.get('lovelace') ?? 0n) + BigInt(o.lovelaceAmount));
1099
+ for (const a of o.assets ?? [])
1100
+ spent.set(a.unit, (spent.get(a.unit) ?? 0n) + BigInt(a.quantity));
1101
+ }
1102
+ for (const [unit, qty] of brought) {
1103
+ const out = spent.get(unit) ?? 0n;
1104
+ if (qty > out) {
1105
+ throw new errors_1.TransactionValidationError(`forceInputs of other addresses bring ${qty} ${unit} but the outputs spend only ${out}; ` +
1106
+ `the difference would go to the sender's change, return it to its owner in outputs`);
1107
+ }
1108
+ }
1109
+ }
1110
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
1111
+ _referencedKeys(ctx, ...refs) {
1112
+ const keys = new Set();
1113
+ for (const u of ctx.referenceInputUtxos ?? [])
1114
+ keys.add(`${u.txHash.toLowerCase()}#${u.outputIndex}`);
1115
+ for (const list of refs)
1116
+ for (const r of list ?? [])
1117
+ keys.add(`${r.txHash.toLowerCase()}#${r.outputIndex}`);
1118
+ return keys;
1119
+ }
1120
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
758
1121
  _mapReferenceInputs(referenceInputUtxos) {
759
1122
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
760
1123
  return [];
761
1124
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
762
1125
  }
763
1126
  /**
764
- * Build the Buildooor mint-entry array shared by the mint-only flow and the
765
- * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
766
- * they are stamped into the redeemers post-build by _buildScriptTx).
1127
+ * Funding contributed by extra outputs on a mint build: their summed lovelace plus, per asset
1128
+ * unit, the demand the transaction's own positive mints do not cover.
1129
+ */
1130
+ _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
1131
+ const mintedByUnit = new Map();
1132
+ for (const action of mintActions) {
1133
+ const quantity = BigInt(action.quantity);
1134
+ if (quantity > 0n) {
1135
+ const unit = action.assetUnit.toLowerCase();
1136
+ mintedByUnit.set(unit, (mintedByUnit.get(unit) ?? 0n) + quantity);
1137
+ }
1138
+ }
1139
+ const demandByUnit = new Map();
1140
+ let lovelace = 0n;
1141
+ for (const extra of extraOutputs) {
1142
+ lovelace += BigInt(extra.lovelaceAmount);
1143
+ for (const asset of extra.assets ?? []) {
1144
+ const unit = asset.unit.toLowerCase();
1145
+ demandByUnit.set(unit, (demandByUnit.get(unit) ?? 0n) + BigInt(asset.quantity));
1146
+ }
1147
+ }
1148
+ const assets = [];
1149
+ for (const [unit, demand] of demandByUnit) {
1150
+ const uncovered = demand - (mintedByUnit.get(unit) ?? 0n);
1151
+ if (uncovered > 0n)
1152
+ assets.push({ unit, quantity: uncovered.toString() });
1153
+ }
1154
+ return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
1155
+ }
1156
+ /**
1157
+ * Script a mint action executes under: its per-action policy when set, else the request's
1158
+ * top-level policy script.
1159
+ */
1160
+ _mintActionScript(action, defaultScript, index) {
1161
+ if (!action.mintingPolicyScript)
1162
+ return defaultScript;
1163
+ return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
1164
+ }
1165
+ /**
1166
+ * Buildooor mint entries shared by all mint flows. `scriptFor` gives each action's policy, inline
1167
+ * or as a reference-script UTxO. Each action may carry its own redeemer (falling back to the
1168
+ * request-level one); the ledger holds ONE redeemer per policy, so actions on the same policy must agree.
767
1169
  */
768
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
769
- return mintActions.map(action => {
1170
+ _buildMintEntries(mintActions, scriptFor, resolvedMintRedeemer, resolveCtx) {
1171
+ const redeemerByPolicy = new Map();
1172
+ return mintActions.map((action, index) => {
1173
+ const source = scriptFor(action, index);
1174
+ const policyHash = 'inline' in source ? source.inline.hash : source.ref.resolved.refScript.hash;
1175
+ const actionRedeemer = action.redeemerJson !== undefined
1176
+ ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
1177
+ : resolvedMintRedeemer;
1178
+ const redeemerData = actionRedeemer !== undefined
1179
+ ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
1180
+ : new plutus_data_1.DataI(action.redeemer ?? 0);
1181
+ const policyId = policyHash.toString();
1182
+ // Canonical comparison over the encoded PlutusData: JSON key order must
1183
+ // not matter, and a JSON {int:0} equals the DataI(0) fallback.
1184
+ const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
1185
+ const seen = redeemerByPolicy.get(policyId);
1186
+ if (seen !== undefined && seen !== redeemerFingerprint) {
1187
+ throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
1188
+ 'split them into separate transactions or align the redeemers');
1189
+ }
1190
+ redeemerByPolicy.set(policyId, redeemerFingerprint);
770
1191
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
771
1192
  return {
772
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
773
- script: {
774
- inline: mintScript,
775
- redeemer: resolvedMintRedeemer
776
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
777
- : new plutus_data_1.DataI(action.redeemer ?? 0)
778
- }
1193
+ value: cardano_ledger_ts_1.Value.singleAsset(policyHash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
1194
+ script: { ...source, redeemer: redeemerData }
779
1195
  };
780
1196
  });
781
1197
  }
782
1198
  /**
783
- * Consumer-facing context for insufficient-funds rejections after the
784
- * collateral partition: the builder's own "not enough …" message counts only
785
- * the funding pool, and without this the reservation is invisible ("but the
786
- * address HAS enough ADA").
1199
+ * Context for insufficient-funds rejections after the collateral partition: the builder's
1200
+ * message counts only the funding pool, so the reservation would otherwise be invisible.
787
1201
  */
788
1202
  _collateralPartitionContext(collateralUtxos, fundingUtxos) {
789
1203
  const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
@@ -792,21 +1206,15 @@ class BuildooorTxBuilder {
792
1206
  `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
793
1207
  }
794
1208
  /**
795
- * Pick a collateral UTxO and return remaining funding UTxOs.
796
- * Throws if no ADA-only UTxO is available.
797
- *
798
- * Selection: the SMALLEST ADA-only UTxO that still covers the static
799
- * COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
800
- * The previous "first ADA-only" pick failed both ways: a dust UTxO below
801
- * collateralPercentage × fee is rejected at submit, and a large UTxO is
802
- * fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
803
- * for ADA-only collateral). Everything above the floor is therefore handed
804
- * back via an explicit collateralReturn when the excess satisfies min-ADA.
1209
+ * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
1210
+ * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
1211
+ * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
805
1212
  */
806
1213
  _setupCollateral(utxos) {
807
- const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
1214
+ // ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
1215
+ const adaOnly = utxos.filter(tx_build_helper_1.isCollateralCandidate);
808
1216
  if (adaOnly.length === 0) {
809
- throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
1217
+ throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral; create one with SetCollateral.');
810
1218
  }
811
1219
  const sorted = [...adaOnly].sort((a, b) => {
812
1220
  const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
@@ -829,8 +1237,7 @@ class BuildooorTxBuilder {
829
1237
  if (excess >= minAda) {
830
1238
  collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
831
1239
  }
832
- // excess below min-ADA: no return output possible — whole UTxO stays at risk,
833
- // but by selection it is the smallest sufficient one.
1240
+ // excess below min-ADA: no return output possible, the whole UTxO stays at risk
834
1241
  }
835
1242
  return { collateralUtxos, fundingUtxos, collateralReturn };
836
1243
  }
@@ -861,12 +1268,9 @@ class BuildooorTxBuilder {
861
1268
  return new cardano_ledger_ts_1.TxOut(params);
862
1269
  }
863
1270
  /**
864
- * Parse a consumer-provided, CBOR-wrapped Plutus script and reject UPLC 1.0.0
865
- * code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
866
- * would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
867
- * wrong policy IDs and unspendable script addresses with no error anywhere
868
- * down the line. The UPLC version is the first three flat-encoded naturals
869
- * of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
1271
+ * Parse a CBOR-wrapped Plutus script and reject UPLC 1.0.0 code (V1/V2): Script.fromCbor
1272
+ * defaults to V3 and would hash with the 0x03 prefix, giving a silently wrong script hash.
1273
+ * The UPLC version is the first three flat naturals of the unwrapped script: [1,0,0] vs [1,1,0].
870
1274
  */
871
1275
  _parsePlutusV3Script(hex, field) {
872
1276
  let script;
@@ -888,23 +1292,21 @@ class BuildooorTxBuilder {
888
1292
  _parseReferenceScript(hex) {
889
1293
  if (!hex)
890
1294
  return undefined;
891
- return this._parsePlutusV3Script(hex, 'referenceScript');
1295
+ return ledgerScript(this._parsePlutusV3Script(hex, 'referenceScript'));
892
1296
  }
893
1297
  /**
894
- * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
895
- * UTxO.scriptRef is overloaded across backends: Blockfrost/Ogmios set it to a 28-byte
896
- * hash (56 hex chars), Koios sets it to the full CBOR script bytes. Only full bytes
897
- * are usable here — hash-only entries are preserved only on-chain, not in local eval.
1298
+ * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
1299
+ * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
898
1300
  */
899
1301
  _buildInputRefScript(utxo) {
900
- if (!utxo.scriptRef)
901
- return undefined;
902
- if (utxo.scriptRef.length <= 56) {
903
- logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
1302
+ const cbor = utxo.scriptRefCbor ?? (utxo.scriptRef && utxo.scriptRef.length > 56 ? utxo.scriptRef : undefined);
1303
+ if (!cbor) {
1304
+ if (utxo.scriptRef)
1305
+ logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
904
1306
  return undefined;
905
1307
  }
906
1308
  try {
907
- const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
1309
+ const script = ledgerScript(cardano_ledger_ts_1.Script.fromCbor(Buffer.from(cbor, 'hex')));
908
1310
  // chain data, not consumer input — warn instead of rejecting
909
1311
  const b = script.bytes;
910
1312
  if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
@@ -919,14 +1321,12 @@ class BuildooorTxBuilder {
919
1321
  }
920
1322
  }
921
1323
  /**
922
- * Compute the post-sort input order so __INPUT_IDX__ placeholders (FR-3) resolve to the
923
- * same indices Buildooor will assign during build(). Order: script-input first by convention,
924
- * then forced + funding sorted lexicographically on (txHash, outputIndex).
925
- * Buildooor sorts ALL inputs together; we mirror that exact behaviour via sortInputsLikeBuildooor.
1324
+ * Post-sort input order so __INPUT_IDX__ placeholders resolve to the indices Buildooor assigns
1325
+ * in build(): all inputs (script, forced, funding) sorted lexicographically on (txHash, outputIndex).
926
1326
  */
927
- _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
1327
+ _computeSortedInputs(scriptUtxoRefs, forcedUtxos, fundingRefs) {
928
1328
  const all = [
929
- { txHash: scriptUtxoRef.txHash, outputIndex: scriptUtxoRef.outputIndex },
1329
+ ...scriptUtxoRefs.map(r => ({ txHash: r.txHash, outputIndex: r.outputIndex })),
930
1330
  ...forcedUtxos.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
931
1331
  ...fundingRefs
932
1332
  ];
@@ -939,10 +1339,7 @@ class BuildooorTxBuilder {
939
1339
  outputIndex: i.utxo.utxoRef.index
940
1340
  }));
941
1341
  }
942
- /**
943
- * Resolve __INPUT_IDX__ placeholders (FR-3) inside each extraOutput.inlineDatum.
944
- * Returns a new array with resolved datums; non-datum fields pass through unchanged.
945
- */
1342
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
946
1343
  _resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
947
1344
  if (!extraOutputs || extraOutputs.length === 0)
948
1345
  return extraOutputs;
@@ -954,9 +1351,8 @@ class BuildooorTxBuilder {
954
1351
  }));
955
1352
  }
956
1353
  /**
957
- * Append parsed extraOutputs (FR-2) to the outputs array, enforcing min-ADA per entry.
958
- * Throws TransactionValidationError with the required min-ADA in the message so consumers
959
- * can adjust without having to inspect Buildooor internals.
1354
+ * Append parsed extra outputs, enforcing min-ADA per entry; the rejection names the
1355
+ * required min-ADA so consumers can adjust without inspecting Buildooor internals.
960
1356
  */
961
1357
  _appendExtraOutputs(outputs, extraOutputs) {
962
1358
  if (!extraOutputs || extraOutputs.length === 0)
@@ -977,10 +1373,8 @@ class BuildooorTxBuilder {
977
1373
  // UTxO Mapping & Configuration Helpers
978
1374
  //---------------------------------------------------------------------------
979
1375
  /**
980
- * Resolve the transaction's validity window (slots) from the request.
981
- * Falls back to `now - 2 min` / `now + 1 h` when the request omits bounds.
982
- * Script-validated builds must call this; plain transfers pass their own
983
- * explicit bounds through (no defaulting) so replay behavior is opt-in.
1376
+ * Validity window (slots) from the request. Script builds default to `now - 2 min` / `now + 1 h`;
1377
+ * plain transfers pass explicit bounds through without defaulting.
984
1378
  */
985
1379
  _resolveValiditySlots(req, mode) {
986
1380
  const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
@@ -1004,14 +1398,9 @@ class BuildooorTxBuilder {
1004
1398
  };
1005
1399
  }
1006
1400
  /**
1007
- * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape.
1008
- *
1009
- * Every field is null-guarded: a missing/null source value keeps the library
1010
- * default instead of degrading to 0 (`Number(null) === 0` previously set
1011
- * utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
1012
- * execution-unit prices are mapped because they feed the scriptDataHash
1013
- * (language views) and the fee/ExUnits math — stale defaults there cause
1014
- * PPViewHashesDontMatch or fee underestimation on-chain.
1401
+ * Map LedgerProtocolParameter to Buildooor's ProtocolParameters. Every field is null-guarded so a
1402
+ * missing value keeps the library default instead of degrading to 0 (e.g. utxoCostPerByte = 0
1403
+ * disables min-ADA); cost models and ExUnit prices feed scriptDataHash and the fee math.
1015
1404
  */
1016
1405
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
1017
1406
  const pp = protocolParameters;
@@ -1059,15 +1448,9 @@ class BuildooorTxBuilder {
1059
1448
  return mapped;
1060
1449
  }
1061
1450
  /**
1062
- * Parse the cost-models JSON blob (backend-normalized number arrays, keys
1063
- * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
1064
- * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
1065
- * usable is found, so the caller can keep defaults and warn.
1066
- *
1067
- * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
1068
- * for the versions mapped here — the named-key conversion drops every entry past
1069
- * the parameter count this costmodels-ts release knows, and the scriptDataHash
1070
- * must cover all of them (see _languageViewCostModels).
1451
+ * Parse the cost-models JSON (keys 'PlutusVN', 'plutus:vN' or 'PlutusScriptVN') into Buildooor's
1452
+ * CostModels; undefined when nothing usable is found. Also (re)sets this.rawCostModelArrays with
1453
+ * the unclamped chain arrays, which the scriptDataHash must cover (see _languageViewCostModels).
1071
1454
  */
1072
1455
  _mapCostModels(costModelsJson) {
1073
1456
  this.rawCostModelArrays = {};
@@ -1122,9 +1505,7 @@ class BuildooorTxBuilder {
1122
1505
  this.rawCostModelArrays = rawArrays;
1123
1506
  return result;
1124
1507
  }
1125
- /**
1126
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
1127
- */
1508
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
1128
1509
  _mapOdatanoUtxoToLedgerUtxo(utxos) {
1129
1510
  (0, tx_build_helper_1.assertAdaOnly)(utxos);
1130
1511
  return new cardano_ledger_ts_1.UTxO({
@@ -1137,15 +1518,11 @@ class BuildooorTxBuilder {
1137
1518
  })
1138
1519
  });
1139
1520
  }
1140
- /**
1141
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
1142
- */
1521
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
1143
1522
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
1144
1523
  const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
1145
- // Inline datum wins; otherwise carry the datum HASH into the resolved TxOut —
1146
- // Buildooor only includes a provided datum preimage in the witness set when the
1147
- // spent output is marked with its Hash32 (pushWitDatum). Dropping the hash here
1148
- // silently discards the preimage → MissingRequiredDatums on submit.
1524
+ // Inline datum wins; otherwise carry the datum HASH: Buildooor only puts a provided datum
1525
+ // preimage into the witness set when the spent output is marked with its Hash32.
1149
1526
  const datumValue = utxo.inlineDatum
1150
1527
  ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1151
1528
  : utxo.datumHash
@@ -1161,9 +1538,7 @@ class BuildooorTxBuilder {
1161
1538
  })
1162
1539
  });
1163
1540
  }
1164
- /**
1165
- * Map ODATANO metadata JSON to Ledger TxMetadata
1166
- */
1541
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
1167
1542
  _mapOdatanoMetadataToLedgerMetadata(metadataJson) {
1168
1543
  if (!metadataJson) {
1169
1544
  return new TxMetadata_1.TxMetadata({});
@@ -1178,20 +1553,9 @@ class BuildooorTxBuilder {
1178
1553
  return new TxMetadata_1.TxMetadata(metadata);
1179
1554
  }
1180
1555
  /**
1181
- * Recursively convert JSON value to TxMetadatum.
1182
- *
1183
- * Ledger rules enforced here (instead of a node-side rejection or a raw 500):
1184
- * - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
1185
- * - text and byte values are limited to 64 BYTES per metadatum — longer values
1186
- * are chunked into a list of ≤64-byte pieces (the established convention,
1187
- * e.g. CIP-25 long strings)
1188
- * - strings prefixed with "0x" (even hex length) become byte metadata
1189
- * - map keys are not auto-chunked (readers match on the literal key) — over-long
1190
- * keys are rejected with a clear 400
1191
- *
1192
- * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
1193
- * "1155.result" or "721.files[0].src") — named in every rejection
1194
- * so the consumer can locate the offending value.
1556
+ * Recursively convert a JSON value to TxMetadatum, enforcing ledger rules: integers only, text/bytes
1557
+ * over 64 BYTES chunked into a list, "0x..." strings become bytes, over-long map keys rejected.
1558
+ * @param path label-rooted position of `value` (e.g. "721.files[0].src"), named in every rejection
1195
1559
  */
1196
1560
  _jsonToTxMetadatum(value, path) {
1197
1561
  if (typeof value === 'number' || typeof value === 'bigint') {