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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -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,26 +219,27 @@ 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
  }
235
227
  catch (err) {
236
- (0, tx_build_helper_1.mapBuilderError)(err);
228
+ // one requested output; Buildooor appends the change after it
229
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, undefined, 1);
237
230
  }
238
231
  }
239
232
  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.
233
+ // Set once the collateral partition is known: it explains insufficient-funds rejections
234
+ // that the builder's own message cannot attribute.
242
235
  let coinSelectionContext;
236
+ let requestedOutputs;
243
237
  try {
244
238
  this._ensureCurrentProtocolParameters(ctx);
245
239
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
246
240
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
- // Parse the minting policy script once
248
241
  const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
249
- // Calculate total mint value for output (only positive quantities - mints, not burns).
250
- // Multi-policy mint FR: each action mints under ITS script (own or top-level).
242
+ // Total mint value for the output (positive quantities only); each action mints under its own policy script.
251
243
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
252
244
  for (const [index, mintAction] of req.mintActions.entries()) {
253
245
  const quantity = BigInt(mintAction.quantity);
@@ -258,27 +250,25 @@ class BuildooorTxBuilder {
258
250
  }
259
251
  }
260
252
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
261
- // collateral and coin selection operate on the remainder only.
262
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
253
+ // coin selection operates on the remainder only.
254
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
263
255
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
264
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
265
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
266
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
267
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
268
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
269
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
270
- // thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
271
- // demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
272
- // from the wallet).
256
+ // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
257
+ // demand the mint itself does not cover.
273
258
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
274
259
  if (req.extraOutputs && req.extraOutputs.length > 0) {
275
260
  const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
276
261
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
277
262
  }
263
+ // Collateral + funding separation from the candidates; a forced input is collateral only as a fallback
264
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress);
265
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
266
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
267
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
278
268
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
279
269
  const inputs = [...forcedInputs, ...selectedFunding];
280
270
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
281
- // FR-3: resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum after final input order is known.
271
+ // Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
282
272
  const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
283
273
  ...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
284
274
  ...this._extractFundingRefs(selectedFunding)
@@ -291,10 +281,8 @@ class BuildooorTxBuilder {
291
281
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
292
282
  : undefined;
293
283
  const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
294
- // Build output — recipient gets the minted assets + min ADA. When extra
295
- // outputs are declared (FR-2 on mint) THEY carry the minted assets (each
296
- // token on its own output with its own datum, e.g. datum-bound predicate
297
- // tokens), so the primary output stays ADA(+datum)-only.
284
+ // Primary output: minted assets + min ADA. With extra outputs declared, those carry
285
+ // the minted assets and the primary output stays ADA(+datum)-only.
298
286
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
299
287
  if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
300
288
  outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
@@ -303,23 +291,21 @@ class BuildooorTxBuilder {
303
291
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
304
292
  // Append extra outputs, each independently min-ADA checked.
305
293
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
306
- // Mint entries for the build args (uses pre-resolved redeemers; per-action
307
- // redeemers resolve their own placeholders). Note: Buildooor ignores
308
- // caller-supplied execution units — the real units are stamped into the
309
- // redeemers post-build by _buildScriptTx.
310
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
294
+ requestedOutputs = outputs.length;
295
+ // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
296
+ // stamped post-build by _buildScriptTx.
297
+ const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
311
298
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
312
299
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
313
300
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
314
301
  // and fee computation stay consistent (a mismatch would force re-evaluation).
315
302
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
316
- // CIP-20 / label-674 etc. auxiliary metadata. Must be identical across eval + final
317
- // passes since auxiliary_data affects both tx size (→ fee) and script data hash (indirectly via tx hash).
303
+ // Auxiliary metadata (CIP-20, label 674, ...) must be identical across eval + final passes:
304
+ // it affects tx size (fee) and the script data hash.
318
305
  const mintMetadata = req.metadataJson
319
306
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
320
307
  : undefined;
321
- // Single set of build args — both internal passes and the Ogmios evaluation share
322
- // validity bounds and metadata so redeemer ExUnits and fee stay consistent.
308
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
323
309
  const buildParams = {
324
310
  inputs, outputs, changeAddress, mints,
325
311
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
@@ -333,23 +319,21 @@ class BuildooorTxBuilder {
333
319
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
334
320
  }
335
321
  catch (err) {
336
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
322
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
337
323
  }
338
324
  }
339
325
  async buildUnsignedPlutusSpendTransaction(req, ctx) {
340
326
  // See buildUnsignedMintTransaction — same collateral-partition context for rejections.
341
327
  let coinSelectionContext;
328
+ let requestedOutputs;
342
329
  try {
343
330
  this._ensureCurrentProtocolParameters(ctx);
344
331
  const { plutusScriptExecution } = req;
345
- // Parse the validator script
346
332
  const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
347
333
  if (!plutusScriptExecution.datum) {
348
- // When no explicit datum is provided, the UTxO must have an inline datum.
349
- // If neither exists, the Plutus validator will fail with a cryptic error.
334
+ // Without an explicit datum the script UTxO must carry an inline datum.
350
335
  logger.debug('No datumJson provided — expecting inline datum on script UTxO');
351
336
  }
352
- // Find the specific script UTxO in the provided context UTxOs
353
337
  const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
354
338
  const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
355
339
  if (!scriptOdatanoUtxo) {
@@ -362,33 +346,37 @@ class BuildooorTxBuilder {
362
346
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
363
347
  // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
364
348
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
365
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
349
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
366
350
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
367
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
368
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
369
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
370
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
371
- // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
372
- // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
373
- // already provides will net out, so over-requesting is harmless — keepRelevant prefers smaller sets.
374
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
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.
375
353
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
376
354
  if (req.extraOutputs && req.extraOutputs.length > 0) {
377
355
  for (const extra of req.extraOutputs) {
378
356
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
379
357
  }
380
358
  }
359
+ // Collateral + funding separation from the candidates; a forced input is collateral only as a fallback.
360
+ // The script UTxO pays its part of the outputs, so the collateral check counts only the rest.
361
+ const fundingGap = requiredFundingValue.lovelaces - (0, tx_build_helper_1.getLovelace)(scriptOdatanoUtxo);
362
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, fundingGap > 0n ? fundingGap : 0n, forced, req.senderAddress);
363
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
364
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
365
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
381
366
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
382
367
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
383
- // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
384
- // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
385
- const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
368
+ // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
369
+ // in redeemer / datum / output datums BEFORE PlutusData encoding.
370
+ const sortedInputs = this._computeSortedInputs([scriptUtxoRef], forced, this._extractFundingRefs(selectedFundingInputs));
386
371
  const resolveCtx = { sortedInputs };
387
372
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
388
373
  const redeemerData = (0, tx_build_helper_1.jsonToPlutusData)(resolvedRedeemer);
389
374
  const datum = plutusScriptExecution.datum
390
375
  ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.datum, resolveCtx))
391
376
  : "inline";
377
+ if (datum !== "inline") {
378
+ this._checkWitnessDatum(scriptOdatanoUtxo, (0, plutus_data_1.dataToCbor)(datum), 'datumJson', '; BuildPlutusTransaction takes the datum as datumCbor with the bytes the UTxO was locked with');
379
+ }
392
380
  const resolvedPrimaryInlineDatum = req.inlineDatum
393
381
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
394
382
  : undefined;
@@ -396,7 +384,7 @@ class BuildooorTxBuilder {
396
384
  const resolvedMintRedeemer = req.mintRedeemer
397
385
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
398
386
  : undefined;
399
- // FR-1: combined spend+mint flow. When mintActions are present, build mints alongside the spend input.
387
+ // Combined spend+mint: with mintActions present, mints are built alongside the spend input.
400
388
  const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
401
389
  let mintScript;
402
390
  let mintScriptHash;
@@ -423,14 +411,13 @@ class BuildooorTxBuilder {
423
411
  }
424
412
  const primaryRefScript = this._parseReferenceScript(req.referenceScript);
425
413
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedPrimaryInlineDatum, primaryRefScript)];
426
- // Append extra outputs (FR-2). Each is independently min-ADA checked so consumers
427
- // get a clear, field-attributed error before Buildooor's coin selection runs.
414
+ // Append extra outputs, each independently min-ADA checked.
428
415
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
429
- // Mint entries (FR-1) and inputs for the build args. Note: Buildooor ignores
430
- // caller-supplied execution units — the real units are stamped into the
431
- // redeemers post-build by _buildScriptTx.
416
+ requestedOutputs = outputs.length;
417
+ // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
418
+ // units, the real ones are stamped post-build by _buildScriptTx.
432
419
  const mints = hasMint
433
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
420
+ ? this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, mintScript, i) }), resolvedMintRedeemer, resolveCtx)
434
421
  : undefined;
435
422
  const scriptInput = {
436
423
  utxo: scriptLedgerUtxo,
@@ -442,8 +429,7 @@ class BuildooorTxBuilder {
442
429
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
443
430
  // and fee computation stay consistent (a mismatch would force re-evaluation).
444
431
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
445
- // Single set of build args — both internal passes and the Ogmios evaluation share
446
- // validity bounds so redeemer ExUnits and fee stay consistent.
432
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
447
433
  const buildParams = {
448
434
  inputs, outputs, changeAddress,
449
435
  mints,
@@ -462,8 +448,293 @@ class BuildooorTxBuilder {
462
448
  });
463
449
  }
464
450
  catch (err) {
465
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
451
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
452
+ }
453
+ }
454
+ /**
455
+ * Several script inputs in one transaction, each with its own redeemer (inline validator or a
456
+ * reference-script UTxO), the outputs exactly in the given order and change after them.
457
+ */
458
+ async buildUnsignedPlutusTransaction(req, ctx) {
459
+ let coinSelectionContext;
460
+ let requestedOutputs;
461
+ try {
462
+ this._ensureCurrentProtocolParameters(ctx);
463
+ const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
464
+ const utxoByKey = new Map(ctx.utxos.map(u => [keyOf(u), u]));
465
+ const refUtxoByKey = new Map((ctx.referenceInputUtxos ?? []).map(u => [keyOf(u), u]));
466
+ const scriptKeys = new Set(req.scriptInputs.map(keyOf));
467
+ // Scripts the reference inputs already carry: the ledger rejects the same script again as a
468
+ // witness (ExtraneousScriptWitnesses), so an inline validator with such a hash uses the reference.
469
+ const referencedByHash = new Map();
470
+ for (const u of ctx.referenceInputUtxos ?? []) {
471
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(u);
472
+ const hash = ledgerUtxo.resolved.refScript?.hash.toString();
473
+ if (hash && !referencedByHash.has(hash))
474
+ referencedByHash.set(hash, ledgerUtxo);
475
+ }
476
+ // Script inputs: each UTxO with its script (inline, or the ledger UTxO carrying it)
477
+ const scriptEntries = req.scriptInputs.map((si, i) => {
478
+ const utxo = utxoByKey.get(keyOf(si));
479
+ if (!utxo)
480
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}] ${keyOf(si)} not found on-chain or already spent`);
481
+ if (si.validatorScript) {
482
+ const script = this._parsePlutusV3Script(si.validatorScript, `scriptInputs[${i}].validatorScript`);
483
+ const scriptHash = script.hash.toString();
484
+ const referenced = referencedByHash.get(scriptHash);
485
+ return referenced ? { si, utxo, refLedgerUtxo: referenced, scriptHash } : { si, utxo, script };
486
+ }
487
+ const refKey = keyOf(si.referenceScript);
488
+ const refUtxo = refUtxoByKey.get(refKey);
489
+ if (!refUtxo)
490
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} not found on-chain or already spent`);
491
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
492
+ if (!refLedgerUtxo.resolved.refScript) {
493
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
494
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
495
+ }
496
+ return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
497
+ });
498
+ // Withdrawals: the staking script inline, by reference, or the one a reference input carries
499
+ const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
500
+ w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
501
+ ...this._resolveScriptWitness({ script: w.stakingScript, referenceScript: w.referenceScript }, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
502
+ }));
503
+ // Certificates: the credential from the stake address; a script runs under the Certifying purpose
504
+ const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
505
+ const certEntries = (req.certificates ?? []).map((c, i) => {
506
+ const at = `certificates[${i}]`;
507
+ const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
508
+ const credentialHash = stake.credentials.toString().toLowerCase();
509
+ const witness = this._resolveScriptWitness({ script: c.stakingScript, referenceScript: c.referenceScript }, at, referencedByHash, refUtxoByKey);
510
+ const scripted = Boolean(witness.script || witness.refLedgerUtxo);
511
+ const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
512
+ if (stake.type === 'script') {
513
+ if (scripted && witnessHash !== credentialHash) {
514
+ throw new errors_1.TransactionValidationError(`${at} staking script hash ${witnessHash} is not the credential of ${c.stakeAddress} (${credentialHash})`);
515
+ }
516
+ if (!scripted && c.type === 'deregisterStake') {
517
+ throw new errors_1.TransactionValidationError(`${at} deregisters the script credential ${c.stakeAddress}; its staking script and redeemer are needed`);
518
+ }
519
+ }
520
+ else if (scripted) {
521
+ throw new errors_1.TransactionValidationError(`${at} ${c.stakeAddress} is a key credential; it takes no staking script`);
522
+ }
523
+ const stakeCredential = stake.type === 'script' ? cardano_ledger_ts_1.Credential.script(stake.credentials) : cardano_ledger_ts_1.Credential.keyHash(stake.credentials);
524
+ const deposit = c.deposit ? BigInt(c.deposit) : stakeDeposit;
525
+ // Without a script the witness-free legacy registration; the deposit forms need the witness
526
+ const cert = c.type === 'registerStake'
527
+ ? (scripted ? new cardano_ledger_ts_1.CertRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeRegistration({ stakeCredential }))
528
+ : (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
529
+ return { c, cert, deposit, ...witness };
530
+ });
531
+ // Mints: each policy inline, by reference, or the one a reference input carries
532
+ const mintEntries = (req.mintActions ?? []).map((m, i) => {
533
+ const at = `mintActions[${i}]`;
534
+ const witness = this._resolveScriptWitness({ script: m.mintingPolicyScript, referenceScript: m.referenceScript }, at, referencedByHash, refUtxoByKey, 'mintingPolicyScript');
535
+ const policyId = (witness.script?.hash ?? witness.refLedgerUtxo.resolved.refScript.hash).toString().toLowerCase();
536
+ if (!m.assetUnit.toLowerCase().startsWith(policyId)) {
537
+ throw new errors_1.TransactionValidationError(`${at}.assetUnit ${m.assetUnit} is not under the policy ${policyId} of its script`);
538
+ }
539
+ return { m, policyId, ...witness };
540
+ });
541
+ // one policy runs from one place: once any action of it uses a reference script, all do
542
+ const mintRefByPolicy = new Map();
543
+ for (const e of mintEntries)
544
+ if (e.refLedgerUtxo && !mintRefByPolicy.has(e.policyId))
545
+ mintRefByPolicy.set(e.policyId, e.refLedgerUtxo);
546
+ for (const e of mintEntries) {
547
+ const ref = mintRefByPolicy.get(e.policyId);
548
+ if (ref) {
549
+ e.refLedgerUtxo = ref;
550
+ e.script = undefined;
551
+ }
552
+ }
553
+ const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
554
+ const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
555
+ const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
556
+ if (scriptKeyClash)
557
+ throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
558
+ 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);
559
+ this._checkForeignForcedInputs(forced, req);
560
+ const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
561
+ // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
562
+ // withdrawals (keepRelevant adds its own lovelace margin for fee and change).
563
+ const need = new Map();
564
+ const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
565
+ for (const o of req.outputs) {
566
+ add('lovelace', BigInt(o.lovelaceAmount));
567
+ for (const a of o.assets ?? [])
568
+ add(a.unit, BigInt(a.quantity));
569
+ }
570
+ for (const u of [...scriptEntries.map(e => e.utxo), ...forced]) {
571
+ for (const a of u.amount)
572
+ add(a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit, -BigInt(a.quantity));
573
+ }
574
+ for (const m of req.mintActions ?? [])
575
+ add(m.assetUnit, -BigInt(m.quantity));
576
+ for (const { w } of withdrawalEntries)
577
+ add('lovelace', -BigInt(w.lovelace));
578
+ // a registration locks the deposit, a deregistration refunds it
579
+ for (const { c, deposit } of certEntries)
580
+ add('lovelace', c.type === 'registerStake' ? deposit : -deposit);
581
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
582
+ for (const [unit, qty] of need) {
583
+ if (qty <= 0n)
584
+ continue;
585
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, unit === 'lovelace'
586
+ ? cardano_ledger_ts_1.Value.lovelaces(qty)
587
+ : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
588
+ }
589
+ // Collateral only when a Plutus script runs; Buildooor writes given collaterals into any body.
590
+ const runsScript = scriptEntries.length > 0 || mintEntries.length > 0 ||
591
+ [...withdrawalEntries, ...certEntries].some(e => e.script || e.refLedgerUtxo);
592
+ const { collateralUtxos, fundingUtxos, collateralReturn } = runsScript
593
+ ? this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress)
594
+ : { collateralUtxos: [], fundingUtxos: rest, collateralReturn: undefined };
595
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
596
+ const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
597
+ const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
598
+ // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
599
+ 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 })));
600
+ const callerRefUtxos = (ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u)));
601
+ const readonlyRefInputs = this._mapReferenceInputs(callerRefUtxos);
602
+ const sortedReferenceInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
603
+ ...callerRefUtxos.map(u => ({ txHash: u.txHash.toLowerCase(), outputIndex: u.outputIndex })),
604
+ ...[...refScriptKeys].map(k => { const [txHash, idx] = k.split('#'); return { txHash, outputIndex: Number(idx) }; }),
605
+ ]);
606
+ // Placeholders resolve against the final input, reference-input and withdrawal order
607
+ const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
608
+ const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
609
+ const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
610
+ const witnessDatums = [];
611
+ const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }, i) => {
612
+ 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));
613
+ let datum = "inline";
614
+ if (si.datumCbor) {
615
+ const bytes = Buffer.from(si.datumCbor, 'hex');
616
+ this._checkWitnessDatum(utxo, bytes, `scriptInputs[${i}].datumCbor`, '');
617
+ witnessDatums.push(bytes);
618
+ datum = (0, plutus_data_1.dataFromCbor)(bytes);
619
+ }
620
+ else if (si.datum !== undefined) {
621
+ datum = (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx));
622
+ this._checkWitnessDatum(utxo, (0, plutus_data_1.dataToCbor)(datum), `scriptInputs[${i}].datumJson`, '; pass datumCbor with the bytes the UTxO was locked with');
623
+ }
624
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
625
+ return script
626
+ ? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
627
+ : { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
628
+ });
629
+ const outputs = [];
630
+ const callerDatums = this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
631
+ ...o,
632
+ inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
633
+ })));
634
+ requestedOutputs = outputs.length;
635
+ const mints = mintEntries.length > 0
636
+ ? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
637
+ : undefined;
638
+ // Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
639
+ const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
640
+ const withdrawal = { rewardAccount, amount: BigInt(w.lovelace) };
641
+ if (!script && !refLedgerUtxo)
642
+ return { withdrawal };
643
+ 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));
644
+ return { withdrawal, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
645
+ });
646
+ // Certificates in the given order; a scripted one carries its redeemer under the Cert purpose
647
+ const certificates = certEntries.map(({ c, cert, script, refLedgerUtxo }) => {
648
+ if (!script && !refLedgerUtxo)
649
+ return { cert };
650
+ 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));
651
+ return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
652
+ });
653
+ const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
654
+ const buildParams = {
655
+ inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
656
+ outputs, changeAddress, mints,
657
+ collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
658
+ invalidBefore, invalidAfter,
659
+ ...(collateralReturn && { collateralReturn }),
660
+ ...(readonlyRefInputs.length > 0 && { readonlyRefInputs }),
661
+ ...(withdrawals.length > 0 && { withdrawals }),
662
+ ...(certificates.length > 0 && { certificates })
663
+ };
664
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction, callerDatums, witnessDatums);
665
+ const details = this._extractTxDetails(tx);
666
+ const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
667
+ if (details.sizeBytes > maxTxSize) {
668
+ const inline = scriptEntries.filter(e => e.script).length;
669
+ throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
670
+ (inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
671
+ }
672
+ // the first script that runs: a spend, else a mint policy, else a withdrawal or certificate script
673
+ const scriptHashes = [
674
+ ...scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash),
675
+ ...mintEntries.map(e => e.policyId),
676
+ ...[...withdrawalEntries, ...certEntries].flatMap(e => {
677
+ const hash = e.script?.hash ?? e.refLedgerUtxo?.resolved.refScript?.hash;
678
+ return hash ? [hash.toString()] : [];
679
+ }),
680
+ ];
681
+ logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
682
+ return this._buildResult(req, ctx, details, {
683
+ scriptHash: scriptHashes[0],
684
+ forcedInputsUsed: forcedInputs.length,
685
+ referenceInputsUsed: readonlyRefInputs.length + refScriptKeys.size
686
+ });
687
+ }
688
+ catch (err) {
689
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
690
+ }
691
+ }
692
+ /**
693
+ * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
694
+ * Returns the inline datums given as CBOR, keyed by output index.
695
+ */
696
+ _appendPlutusOutputs(outputs, list) {
697
+ const callerDatums = new Map();
698
+ for (let i = 0; i < list.length; i++) {
699
+ const o = list[i];
700
+ const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
701
+ const refScript = this._parseReferenceScript(o.referenceScript);
702
+ const callerDatum = o.inlineDatumCbor ? Buffer.from(o.inlineDatumCbor, 'hex') : undefined;
703
+ const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : callerDatum ? (0, plutus_data_1.dataFromCbor)(callerDatum) : undefined;
704
+ const txOut = datum
705
+ ? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
706
+ : this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
707
+ const minLovelaces = this._minOutputLovelace(txOut, callerDatum);
708
+ if (BigInt(o.lovelaceAmount) < minLovelaces) {
709
+ throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
710
+ }
711
+ if (callerDatum)
712
+ callerDatums.set(outputs.length, callerDatum);
713
+ outputs.push(txOut);
466
714
  }
715
+ return callerDatums;
716
+ }
717
+ /**
718
+ * Min-ADA of an output, counting the caller's datum bytes where they are longer than
719
+ * Buildooor's encoding. `forAnyAmount` sizes the coin field for the largest amount, so the
720
+ * result stays valid once written into the output.
721
+ */
722
+ _minOutputLovelace(txOut, callerDatum, forAnyAmount = false) {
723
+ const base = forAnyAmount
724
+ ? this.txBuilder.minimizeLovelaces(txOut).value.lovelaces
725
+ : this.txBuilder.getMinimumOutputLovelaces(txOut);
726
+ const growth = callerDatum ? Math.max(0, (0, caller_datums_1.callerDatumGrowth)(callerDatum)) : 0;
727
+ return base + BigInt(growth) * BigInt(this.txBuilder.protocolParamters.utxoCostPerByte);
728
+ }
729
+ /** Build, then write the caller's datum bytes; when they are longer, a second build raises the fee. */
730
+ async _buildWithCallerDatums(args, datums) {
731
+ const tx = await this.txBuilder.build(args);
732
+ const growth = (0, caller_datums_1.callerDatumsGrowth)(datums);
733
+ if (growth === 0)
734
+ return (0, caller_datums_1.writeCallerDatums)(tx, datums);
735
+ // Fee floor: the extra bytes plus a pad for change-size wobble
736
+ const fee = BigInt(tx.body.fee.toString()) + BigInt(growth + 10) * this._txFeePerByte();
737
+ return (0, caller_datums_1.writeCallerDatums)(await this.txBuilder.build({ ...args, fee }), datums);
467
738
  }
468
739
  //---------------------------------------------------------------------------
469
740
  // Shared Helper Methods
@@ -484,6 +755,12 @@ class BuildooorTxBuilder {
484
755
  address: o.address?.toString?.() ?? "",
485
756
  lovelace: o.value?.lovelaces?.toString?.() ?? "0"
486
757
  })),
758
+ redeemers: (tx.witnesses.redeemers ?? []).map((r) => ({
759
+ tag: (0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag),
760
+ index: r.index,
761
+ mem: r.execUnits.mem.toString(),
762
+ steps: r.execUnits.cpu.toString(),
763
+ })),
487
764
  };
488
765
  }
489
766
  /** Build the standard TxBuildResult object */
@@ -507,31 +784,17 @@ class BuildooorTxBuilder {
507
784
  feeLovelace: txDetails.feeLovelace,
508
785
  inputs,
509
786
  outputs: txDetails.outputs,
787
+ ...(txDetails.redeemers.length > 0 ? { redeemers: txDetails.redeemers } : {}),
510
788
  ...extra,
511
789
  warnings: [],
512
790
  };
513
791
  }
514
792
  /**
515
- * Build a script-bearing transaction whose redeemers carry *real* execution units and
516
- * whose fee covers them.
517
- *
518
- * Background (verified against the vendored Buildooor source): `initTxBuild` constructs
519
- * every redeemer with a dummy budget — caller-supplied execution units in the build args
520
- * are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
521
- * the budget the local CEK run consumed, even when the script failed (partial budget).
522
- * So the declared units are whatever the *local* evaluation produced, and any cushion
523
- * passed into the args silently evaporates. This method makes the declared units real:
524
- *
525
- * 1. First pass: build once; redeemers now carry the local CEK budgets.
526
- * 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
527
- * budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
528
- * 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
529
- * without an Ogmios result aborts — see makeScriptBuildOpts).
530
- * 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
531
- * from its own local budgets, so the floor adds the price + encoding-size delta).
532
- * 5. Stamp the target units into the redeemers and recompute scriptDataHash.
793
+ * Build a script-bearing transaction with real execution units: Buildooor stamps local CEK
794
+ * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
795
+ * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
533
796
  */
534
- async _buildScriptTx(buildParams, evaluator) {
797
+ async _buildScriptTx(buildParams, evaluator, callerDatums = new Map(), witnessDatums = []) {
535
798
  const pass1Failures = [];
536
799
  const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
537
800
  if (!tx1) {
@@ -539,12 +802,10 @@ class BuildooorTxBuilder {
539
802
  }
540
803
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
541
804
  if (rdmrs1.length === 0) {
542
- // Defensive — callers always attach a script. Nothing to evaluate or stamp,
543
- // and Buildooor's calcMinFee already budgets the vkey witnesses to come.
544
- return tx1;
805
+ // Defensive: callers always attach a script; nothing to evaluate or stamp.
806
+ return callerDatums.size === 0 ? tx1 : this._buildWithCallerDatums(buildParams, callerDatums);
545
807
  }
546
- // The first-pass CBOR is exactly what a dedicated "evaluation build" would produce
547
- // (identical args ⇒ identical tx, since passed ExUnits are ignored anyway).
808
+ // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
548
809
  const evaluatedUnits = evaluator
549
810
  ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
550
811
  : undefined;
@@ -552,26 +813,23 @@ class BuildooorTxBuilder {
552
813
  logger.debug('No evaluator available — falling back to buffered local execution units');
553
814
  }
554
815
  const targets1 = this._resolveTargetExUnits(rdmrs1, evaluatedUnits, pass1Failures);
555
- // Fee floor: Buildooor's fee covers its local budgets AND the vkey witnesses to
556
- // come (calcMinFee budgets 104 bytes per estimated signer); add only the price
557
- // delta of the stamped units, their (slightly longer) CBOR encoding, and a small
558
- // pad for change-output size wobble between the two passes.
816
+ // Fee floor: Buildooor's fee already covers local budgets and future vkey witnesses; add the
817
+ // price delta of the stamped units, their longer CBOR encoding, and a pad for change-size wobble.
559
818
  const feeFloor = BigInt(tx1.body.fee.toString())
560
819
  + this._exUnitsPriceDelta(rdmrs1, targets1)
561
820
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
821
+ + BigInt((0, caller_datums_1.callerDatumsGrowth)(callerDatums) + (0, caller_datums_1.witnessDatumsGrowth)(witnessDatums)) * this._txFeePerByte()
562
822
  + 10n * this._txFeePerByte();
563
823
  const pass2Failures = [];
564
824
  const tx2 = await this.txBuilder.build({ ...buildParams, fee: feeFloor }, makeScriptBuildOpts(pass2Failures));
565
825
  const rdmrs2 = tx2.witnesses.redeemers ?? [];
566
826
  const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
567
- return this._stampExecUnits(tx2, targets2);
827
+ const tx = (0, caller_datums_1.writeCallerDatums)(this._stampExecUnits(tx2, targets2), callerDatums);
828
+ return (0, caller_datums_1.writeWitnessDatums)(tx, witnessDatums, this._languageViews(tx));
568
829
  }
569
830
  /**
570
- * Evaluate a transaction via Ogmios and return cushioned budgets keyed per redeemer
571
- * (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
572
- * failure, empty result) so callers fall back to buffered local units. A
573
- * TransactionValidationError or ScriptValidationError from the evaluator is
574
- * authoritative (the script really failed on the ledger) and is rethrown.
831
+ * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
832
+ * evaluation is unusable (transient failure, empty result). Validation errors are rethrown.
575
833
  */
576
834
  async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
577
835
  try {
@@ -585,7 +843,7 @@ class BuildooorTxBuilder {
585
843
  let purpose;
586
844
  let index;
587
845
  if (typeof v === 'string') {
588
- // Legacy "purpose:index" form
846
+ // "purpose:index" string form
589
847
  const [p, i] = v.split(':');
590
848
  purpose = p;
591
849
  index = Number(i);
@@ -605,11 +863,8 @@ class BuildooorTxBuilder {
605
863
  }
606
864
  catch (evalError) {
607
865
  if (evalError instanceof errors_1.TransactionValidationError || evalError instanceof errors_1.ScriptValidationError) {
608
- // Authoritative: Ogmios executed the script and the ledger rejected it. This is
609
- // either a TransactionValidationError or, after normalizeBackendError, a
610
- // ScriptValidationError (PlutusFailure / CekError / budget overspend). Falling
611
- // back to local buffered units here would hand back a transaction the node has
612
- // already rejected — so propagate the failure instead.
866
+ // Authoritative: the ledger executed and rejected the script; falling back to local
867
+ // units would hand back a transaction the node has already rejected.
613
868
  throw evalError;
614
869
  }
615
870
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
@@ -618,9 +873,8 @@ class BuildooorTxBuilder {
618
873
  }
619
874
  }
620
875
  /**
621
- * Combined cushion: relative multiplier catches proportional drift on large
622
- * validators, absolute floor catches sub-percent drift on small ones (observed
623
- * when metadata affects the real tx body vs the evaluator's ScriptContext).
876
+ * Cushion: relative multiplier for proportional drift on large validators, absolute floor
877
+ * for sub-percent drift on small ones.
624
878
  */
625
879
  _applyExUnitBuffer(mem, cpu) {
626
880
  return {
@@ -629,12 +883,9 @@ class BuildooorTxBuilder {
629
883
  };
630
884
  }
631
885
  /**
632
- * Decide the execution units each redeemer must declare.
633
- * - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
634
- * - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
635
- * - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
636
- * - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
637
- * collateral of whoever signs and submits the returned CBOR.
886
+ * Execution units each redeemer must declare: max(local, Ogmios) when both exist, buffered
887
+ * local without Ogmios, Ogmios alone after a local failure; a local failure without Ogmios
888
+ * aborts because unreliable units would forfeit the signer's collateral.
638
889
  */
639
890
  _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
640
891
  return rdmrs.map(r => {
@@ -692,15 +943,9 @@ class BuildooorTxBuilder {
692
943
  return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
693
944
  }
694
945
  /**
695
- * Replace the redeemers' execution units and recompute scriptDataHash.
696
- *
697
- * Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
698
- * 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
699
- * builder's named-key cost models, which clamp the chain array to the parameter
700
- * count the library release knows — wrong whenever the on-chain cost model has
701
- * grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
702
- * _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
703
- * is recomputed here even when the target units already match.
946
+ * Replace the redeemers' execution units and recompute scriptDataHash with the raw chain
947
+ * cost-model arrays (TxBuilder.overrideTxRedeemers hashes with clamped named-key models,
948
+ * which mismatches once the on-chain cost model grows). Recomputed even when units match.
704
949
  */
705
950
  _stampExecUnits(tx, targets) {
706
951
  const rdmrs = tx.witnesses.redeemers ?? [];
@@ -712,8 +957,7 @@ class BuildooorTxBuilder {
712
957
  execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
713
958
  }));
714
959
  const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
715
- const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
716
- const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
960
+ const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, this._languageViews(tx)) });
717
961
  const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
718
962
  if (!unchanged) {
719
963
  logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
@@ -721,6 +965,22 @@ class BuildooorTxBuilder {
721
965
  }
722
966
  return finalTx;
723
967
  }
968
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
969
+ _languageViews(tx) {
970
+ return (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
971
+ }
972
+ /**
973
+ * Check a witness datum against the datum hash its script UTxO is locked with: the ledger
974
+ * finds the datum by the hash of its bytes. Inline-datum UTxOs need no witness datum.
975
+ */
976
+ _checkWitnessDatum(utxo, datum, field, hint) {
977
+ if (!utxo.datumHash || utxo.inlineDatum)
978
+ return;
979
+ const hash = (0, caller_datums_1.datumHashOf)(datum);
980
+ if (hash !== utxo.datumHash.toLowerCase()) {
981
+ throw new errors_1.TransactionValidationError(`${field} hashes to ${hash}, but ${utxo.txHash}#${utxo.outputIndex} is locked with datum hash ${utxo.datumHash}${hint}`);
982
+ }
983
+ }
724
984
  /**
725
985
  * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
726
986
  * (which flags the languages of *executed* scripts). This builder only attaches
@@ -738,12 +998,9 @@ class BuildooorTxBuilder {
738
998
  return opts;
739
999
  }
740
1000
  /**
741
- * Cost models for language-view hashing. The named-key objects the TxBuilder was
742
- * constructed with clamp the chain array to the parameter count this costmodels-ts
743
- * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
744
- * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
745
- * array form through unclamped, so substitute the raw chain arrays where we have
746
- * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
1001
+ * Cost models for language-view hashing: named-key objects clamp the chain array to the
1002
+ * parameter count this library release knows, but the ledger hashes every entry served,
1003
+ * so raw chain arrays (passed through unclamped) are substituted where available.
747
1004
  */
748
1005
  _languageViewCostModels() {
749
1006
  const models = this.txBuilder.protocolParamters.costModels;
@@ -752,40 +1009,145 @@ class BuildooorTxBuilder {
752
1009
  return { ...models, ...this.rawCostModelArrays };
753
1010
  }
754
1011
  /**
755
- * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
756
- * coin selection / collateral). Refs in forceInputs that are not present in utxos are
757
- * silently ignored — the resolver upstream has already validated existence.
1012
+ * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
1013
+ * refs absent from utxos are ignored (existence is validated upstream).
758
1014
  */
759
- _partitionForcedInputs(utxos, forceInputs) {
760
- if (!forceInputs || forceInputs.length === 0)
1015
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs) {
1016
+ const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
1017
+ const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
1018
+ const protectedKeys = new Set((protectInputs ?? []).map(key));
1019
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(hasRefScript)) {
761
1020
  return { forced: [], rest: utxos };
762
- const forcedKeys = new Set(forceInputs.map(r => `${r.txHash}#${r.outputIndex}`));
1021
+ }
1022
+ const forcedKeys = new Set((forceInputs ?? []).map(key));
1023
+ // a UTxO cannot be spent and referenced in one transaction
1024
+ const clash = [...forcedKeys].find(k => referenced.has(k));
1025
+ if (clash)
1026
+ throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input — a UTxO cannot be spent and referenced in one transaction`);
1027
+ const protectedClash = [...forcedKeys].find(k => protectedKeys.has(k));
1028
+ if (protectedClash)
1029
+ throw new errors_1.TransactionValidationError(`forceInputs ${protectedClash} is also in protectInputs`);
763
1030
  const forced = [];
764
1031
  const rest = [];
765
1032
  for (const u of utxos) {
766
- if (forcedKeys.has(`${u.txHash}#${u.outputIndex}`))
1033
+ if (forcedKeys.has(key(u)))
767
1034
  forced.push(u);
768
- else
1035
+ // reference inputs, protected UTxOs and UTxOs carrying a reference script stay out of coin
1036
+ // selection and collateral; a deployed script is spent only when forced
1037
+ else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !hasRefScript(u))
769
1038
  rest.push(u);
770
1039
  }
771
1040
  return { forced, rest };
772
1041
  }
773
1042
  /**
774
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
775
- * Returns empty array when no reference inputs are provided.
1043
+ * Script of a withdrawal, certificate or mint: inline (swapped for a reference input that already
1044
+ * carries the same hash), by reference, or none (key witness).
1045
+ */
1046
+ _resolveScriptWitness(w, at, referencedByHash, refUtxoByKey, scriptField = 'stakingScript') {
1047
+ if (w.script) {
1048
+ const script = this._parsePlutusV3Script(w.script, `${at}.${scriptField}`);
1049
+ const referenced = referencedByHash.get(script.hash.toString());
1050
+ return referenced ? { refLedgerUtxo: referenced } : { script };
1051
+ }
1052
+ if (!w.referenceScript)
1053
+ return {};
1054
+ const refKey = `${w.referenceScript.txHash.toLowerCase()}#${w.referenceScript.outputIndex}`;
1055
+ const refUtxo = refUtxoByKey.get(refKey);
1056
+ if (!refUtxo)
1057
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} not found on-chain or already spent`);
1058
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
1059
+ if (!refLedgerUtxo.resolved.refScript) {
1060
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
1061
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
1062
+ }
1063
+ return { refLedgerUtxo };
1064
+ }
1065
+ /**
1066
+ * Withdrawal credential hashes in ledger order, which `__WDRL_IDX__` resolves against. Buildooor
1067
+ * numbers withdrawal redeemers by hash alone, so a scripted withdrawal whose position differs
1068
+ * between the two orders would get the wrong redeemer; such a build is refused.
1069
+ */
1070
+ _ledgerWithdrawalOrder(entries) {
1071
+ const withHash = entries.map(e => ({
1072
+ credentialHash: e.rewardAccount.credentials.toString().toLowerCase(),
1073
+ isScript: e.rewardAccount.type === 'script',
1074
+ scripted: Boolean(e.script || e.refLedgerUtxo),
1075
+ }));
1076
+ const ledger = (0, plutus_placeholders_1.sortWithdrawalsLikeLedger)(withHash).map(e => e.credentialHash);
1077
+ const buildooor = withHash.map(e => e.credentialHash).sort((a, b) => Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')));
1078
+ const misplaced = withHash.find(e => e.scripted && ledger.indexOf(e.credentialHash) !== buildooor.indexOf(e.credentialHash));
1079
+ if (misplaced) {
1080
+ throw new errors_1.TransactionValidationError(`withdrawals: the scripted withdrawal of credential ${misplaced.credentialHash} cannot be indexed correctly, ` +
1081
+ 'because a key-credential withdrawal sorts before it by hash; move that key withdrawal into a separate transaction');
1082
+ }
1083
+ return ledger;
1084
+ }
1085
+ /**
1086
+ * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
1087
+ * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
1088
+ * Script addresses are refused; those UTxOs are script inputs.
776
1089
  */
1090
+ _checkForeignForcedInputs(forced, req) {
1091
+ const sender = req.senderAddress.toLowerCase();
1092
+ const foreign = forced.filter(u => u.address.toLowerCase() !== sender);
1093
+ if (foreign.length === 0)
1094
+ return;
1095
+ const signers = new Set((req.requiredSigners ?? []).map(s => s.toLowerCase()));
1096
+ const keyOf = (u) => `${u.txHash}#${u.outputIndex}`;
1097
+ const byAddress = new Map();
1098
+ for (const u of foreign)
1099
+ byAddress.set(u.address, [...(byAddress.get(u.address) ?? []), u]);
1100
+ for (const [address, utxos] of byAddress) {
1101
+ const creds = cardano_ledger_ts_1.Address.fromString(address).paymentCreds;
1102
+ const refs = utxos.map(keyOf).join(', ');
1103
+ if (creds.type !== cardano_ledger_ts_1.CredentialType.KeyHash) {
1104
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} are at the script address ${address}; spend script UTxOs via scriptInputs`);
1105
+ }
1106
+ const keyHash = creds.hash.toString().toLowerCase();
1107
+ if (!signers.has(keyHash)) {
1108
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} belong to ${address}; its payment key hash ${keyHash} must be in requiredSigners (the owner co-signs)`);
1109
+ }
1110
+ }
1111
+ const brought = new Map();
1112
+ for (const u of foreign) {
1113
+ for (const a of u.amount) {
1114
+ const unit = a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit;
1115
+ brought.set(unit, (brought.get(unit) ?? 0n) + BigInt(a.quantity));
1116
+ }
1117
+ }
1118
+ const spent = new Map();
1119
+ for (const o of req.outputs) {
1120
+ spent.set('lovelace', (spent.get('lovelace') ?? 0n) + BigInt(o.lovelaceAmount));
1121
+ for (const a of o.assets ?? [])
1122
+ spent.set(a.unit, (spent.get(a.unit) ?? 0n) + BigInt(a.quantity));
1123
+ }
1124
+ for (const [unit, qty] of brought) {
1125
+ const out = spent.get(unit) ?? 0n;
1126
+ if (qty > out) {
1127
+ throw new errors_1.TransactionValidationError(`forceInputs of other addresses bring ${qty} ${unit} but the outputs spend only ${out}; ` +
1128
+ `the difference would go to the sender's change, return it to its owner in outputs`);
1129
+ }
1130
+ }
1131
+ }
1132
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
1133
+ _referencedKeys(ctx, ...refs) {
1134
+ const keys = new Set();
1135
+ for (const u of ctx.referenceInputUtxos ?? [])
1136
+ keys.add(`${u.txHash.toLowerCase()}#${u.outputIndex}`);
1137
+ for (const list of refs)
1138
+ for (const r of list ?? [])
1139
+ keys.add(`${r.txHash.toLowerCase()}#${r.outputIndex}`);
1140
+ return keys;
1141
+ }
1142
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
777
1143
  _mapReferenceInputs(referenceInputUtxos) {
778
1144
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
779
1145
  return [];
780
1146
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
781
1147
  }
782
1148
  /**
783
- * Funding requirement contributed by extra outputs on a mint build:
784
- * the summed lovelace of all entries plus, per asset unit, the demand the
785
- * transaction's own positive mints do NOT cover. Minted quantities are
786
- * aggregated per unit and subtracted from the aggregated output demand;
787
- * only a positive remainder is requested from the wallet (a fully covered
788
- * unit is not requested at all — it does not exist before this tx).
1149
+ * Funding contributed by extra outputs on a mint build: their summed lovelace plus, per asset
1150
+ * unit, the demand the transaction's own positive mints do not cover.
789
1151
  */
790
1152
  _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
791
1153
  const mintedByUnit = new Map();
@@ -814,8 +1176,7 @@ class BuildooorTxBuilder {
814
1176
  return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
815
1177
  }
816
1178
  /**
817
- * The script an individual mint action executes under: its own
818
- * per-action policy when set (multi-policy mint FR), else the request's
1179
+ * Script a mint action executes under: its per-action policy when set, else the request's
819
1180
  * top-level policy script.
820
1181
  */
821
1182
  _mintActionScript(action, defaultScript, index) {
@@ -824,26 +1185,22 @@ class BuildooorTxBuilder {
824
1185
  return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
825
1186
  }
826
1187
  /**
827
- * Build the Buildooor mint-entry array shared by the mint-only flow and the
828
- * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
829
- * they are stamped into the redeemers post-build by _buildScriptTx).
830
- *
831
- * Multi-policy mint FR: each action may carry its own policy script and
832
- * redeemer; absent fields fall back to the request-level ones. The ledger
833
- * carries ONE redeemer per policy, so actions resolving to the same policy
834
- * must agree on their redeemer, checked here.
1188
+ * Buildooor mint entries shared by all mint flows. `scriptFor` gives each action's policy, inline
1189
+ * or as a reference-script UTxO. Each action may carry its own redeemer (falling back to the
1190
+ * request-level one); the ledger holds ONE redeemer per policy, so actions on the same policy must agree.
835
1191
  */
836
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
1192
+ _buildMintEntries(mintActions, scriptFor, resolvedMintRedeemer, resolveCtx) {
837
1193
  const redeemerByPolicy = new Map();
838
1194
  return mintActions.map((action, index) => {
839
- const script = this._mintActionScript(action, mintScript, index);
1195
+ const source = scriptFor(action, index);
1196
+ const policyHash = 'inline' in source ? source.inline.hash : source.ref.resolved.refScript.hash;
840
1197
  const actionRedeemer = action.redeemerJson !== undefined
841
1198
  ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
842
1199
  : resolvedMintRedeemer;
843
1200
  const redeemerData = actionRedeemer !== undefined
844
1201
  ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
845
1202
  : new plutus_data_1.DataI(action.redeemer ?? 0);
846
- const policyId = script.hash.toString();
1203
+ const policyId = policyHash.toString();
847
1204
  // Canonical comparison over the encoded PlutusData: JSON key order must
848
1205
  // not matter, and a JSON {int:0} equals the DataI(0) fallback.
849
1206
  const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
@@ -855,55 +1212,65 @@ class BuildooorTxBuilder {
855
1212
  redeemerByPolicy.set(policyId, redeemerFingerprint);
856
1213
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
857
1214
  return {
858
- value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
859
- script: {
860
- inline: script,
861
- redeemer: redeemerData
862
- }
1215
+ value: cardano_ledger_ts_1.Value.singleAsset(policyHash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
1216
+ script: { ...source, redeemer: redeemerData }
863
1217
  };
864
1218
  });
865
1219
  }
866
1220
  /**
867
- * Consumer-facing context for insufficient-funds rejections after the
868
- * collateral partition: the builder's own "not enough …" message counts only
869
- * the funding pool, and without this the reservation is invisible ("but the
870
- * address HAS enough ADA").
1221
+ * Context for insufficient-funds rejections after the collateral partition: the builder's
1222
+ * message counts only the funding pool, so the reservation would otherwise be invisible.
871
1223
  */
872
- _collateralPartitionContext(collateralUtxos, fundingUtxos) {
873
- const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1224
+ _collateralPartitionContext(collateralUtxos, fundingUtxos, forced = []) {
874
1225
  const fundingLovelace = fundingUtxos.reduce((s, u) => s + (0, tx_build_helper_1.getLovelace)(u), 0n);
875
- return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral; ` +
876
- `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
1226
+ if (collateralUtxos.length === 0) {
1227
+ return `no script runs, so no collateral; ${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
1228
+ }
1229
+ const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1230
+ const collateralKeys = new Set(collateralUtxos.map(u => `${u.utxoRef.id.toString()}#${u.utxoRef.index}`));
1231
+ const isCollateral = (u) => collateralKeys.has(`${u.txHash}#${u.outputIndex}`);
1232
+ const alsoFunding = fundingUtxos.some(isCollateral);
1233
+ const alsoForced = forced.some(isCollateral);
1234
+ return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral` +
1235
+ `${alsoFunding ? ' and also offered as funding' : alsoForced ? ' and also spent as a forced input' : ''}; ` +
1236
+ `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
877
1237
  }
878
1238
  /**
879
- * Pick a collateral UTxO and return remaining funding UTxOs.
880
- * Throws if no ADA-only UTxO is available.
881
- *
882
- * Selection: the SMALLEST ADA-only UTxO that still covers the static
883
- * COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
884
- * The previous "first ADA-only" pick failed both ways: a dust UTxO below
885
- * collateralPercentage × fee is rejected at submit, and a large UTxO is
886
- * fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
887
- * for ADA-only collateral). Everything above the floor is therefore handed
888
- * back via an explicit collateralReturn when the excess satisfies min-ADA.
1239
+ * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
1240
+ * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
1241
+ * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
1242
+ * When the rest cannot pay `requiredLovelace` plus fee and change, the collateral UTxO is
1243
+ * funding too. The ledger allows one UTxO as input and as collateral.
1244
+ * When no UTxO in `utxos` covers the floor, a forced input of the sender that does is the collateral.
889
1245
  */
890
- _setupCollateral(utxos) {
891
- const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
892
- if (adaOnly.length === 0) {
893
- throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
894
- }
895
- const sorted = [...adaOnly].sort((a, b) => {
1246
+ _setupCollateral(utxos, requiredLovelace, forced = [], senderAddress = '') {
1247
+ const byLovelace = (a, b) => {
896
1248
  const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
897
1249
  return diff < 0n ? -1 : diff > 0n ? 1 : 0;
898
- });
1250
+ };
1251
+ const coversFloor = (u) => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE;
1252
+ // ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
1253
+ const sorted = utxos.filter(tx_build_helper_1.isCollateralCandidate).sort(byLovelace);
1254
+ const sender = senderAddress.toLowerCase();
1255
+ const forcedChoice = sorted.some(coversFloor)
1256
+ ? undefined
1257
+ : forced.filter(u => u.address.toLowerCase() === sender && (0, tx_build_helper_1.isCollateralCandidate)(u) && coversFloor(u)).sort(byLovelace)[0];
1258
+ if (sorted.length === 0 && !forcedChoice) {
1259
+ throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral; create one with SetCollateral.');
1260
+ }
899
1261
  // smallest sufficient; if none reaches the floor, the largest available is the best bet
900
- const chosen = sorted.find(u => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE) ?? sorted[sorted.length - 1];
1262
+ const chosen = forcedChoice ?? sorted.find(coversFloor) ?? sorted[sorted.length - 1];
901
1263
  if ((0, tx_build_helper_1.getLovelace)(chosen) < const_1.COLLATERAL_LOVELACE) {
902
1264
  logger.warn(`Largest ADA-only UTxO (${(0, tx_build_helper_1.getLovelace)(chosen)} lovelace) is below the ${const_1.COLLATERAL_LOVELACE} lovelace ` +
903
1265
  `collateral floor — the node will reject the transaction if collateralPercentage × fee exceeds it`);
904
1266
  }
905
1267
  const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(chosen)];
906
- const fundingUtxos = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1268
+ const rest = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1269
+ const restLovelace = rest.reduce((sum, u) => sum + (0, tx_build_helper_1.getLovelace)(u), 0n);
1270
+ // a forced input is already spent, so it is never offered to coin selection as well
1271
+ const fundingUtxos = forcedChoice || restLovelace >= requiredLovelace + const_1.FEE_BUFFER_LOVELACE + BigInt(const_1.MIN_CHANGE_LOVELACE)
1272
+ ? rest
1273
+ : [...rest, chosen];
907
1274
  // Cap the at-risk amount at the floor: return the excess to the owner.
908
1275
  let collateralReturn;
909
1276
  const excess = (0, tx_build_helper_1.getLovelace)(chosen) - const_1.COLLATERAL_LOVELACE;
@@ -913,8 +1280,7 @@ class BuildooorTxBuilder {
913
1280
  if (excess >= minAda) {
914
1281
  collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
915
1282
  }
916
- // excess below min-ADA: no return output possible — whole UTxO stays at risk,
917
- // but by selection it is the smallest sufficient one.
1283
+ // excess below min-ADA: no return output possible, the whole UTxO stays at risk
918
1284
  }
919
1285
  return { collateralUtxos, fundingUtxos, collateralReturn };
920
1286
  }
@@ -945,12 +1311,9 @@ class BuildooorTxBuilder {
945
1311
  return new cardano_ledger_ts_1.TxOut(params);
946
1312
  }
947
1313
  /**
948
- * Parse a consumer-provided, CBOR-wrapped Plutus script and reject UPLC 1.0.0
949
- * code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
950
- * would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
951
- * wrong policy IDs and unspendable script addresses with no error anywhere
952
- * down the line. The UPLC version is the first three flat-encoded naturals
953
- * of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
1314
+ * Parse a CBOR-wrapped Plutus script and reject UPLC 1.0.0 code (V1/V2): Script.fromCbor
1315
+ * defaults to V3 and would hash with the 0x03 prefix, giving a silently wrong script hash.
1316
+ * The UPLC version is the first three flat naturals of the unwrapped script: [1,0,0] vs [1,1,0].
954
1317
  */
955
1318
  _parsePlutusV3Script(hex, field) {
956
1319
  let script;
@@ -972,23 +1335,21 @@ class BuildooorTxBuilder {
972
1335
  _parseReferenceScript(hex) {
973
1336
  if (!hex)
974
1337
  return undefined;
975
- return this._parsePlutusV3Script(hex, 'referenceScript');
1338
+ return ledgerScript(this._parsePlutusV3Script(hex, 'referenceScript'));
976
1339
  }
977
1340
  /**
978
- * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
979
- * UTxO.scriptRef is overloaded across backends: Blockfrost/Ogmios set it to a 28-byte
980
- * hash (56 hex chars), Koios sets it to the full CBOR script bytes. Only full bytes
981
- * are usable here — hash-only entries are preserved only on-chain, not in local eval.
1341
+ * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
1342
+ * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
982
1343
  */
983
1344
  _buildInputRefScript(utxo) {
984
- if (!utxo.scriptRef)
985
- return undefined;
986
- if (utxo.scriptRef.length <= 56) {
987
- logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
1345
+ const cbor = utxo.scriptRefCbor ?? (utxo.scriptRef && utxo.scriptRef.length > 56 ? utxo.scriptRef : undefined);
1346
+ if (!cbor) {
1347
+ if (utxo.scriptRef)
1348
+ logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
988
1349
  return undefined;
989
1350
  }
990
1351
  try {
991
- const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
1352
+ const script = ledgerScript(cardano_ledger_ts_1.Script.fromCbor(Buffer.from(cbor, 'hex')));
992
1353
  // chain data, not consumer input — warn instead of rejecting
993
1354
  const b = script.bytes;
994
1355
  if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
@@ -1003,14 +1364,12 @@ class BuildooorTxBuilder {
1003
1364
  }
1004
1365
  }
1005
1366
  /**
1006
- * Compute the post-sort input order so __INPUT_IDX__ placeholders (FR-3) resolve to the
1007
- * same indices Buildooor will assign during build(). Order: script-input first by convention,
1008
- * then forced + funding sorted lexicographically on (txHash, outputIndex).
1009
- * Buildooor sorts ALL inputs together; we mirror that exact behaviour via sortInputsLikeBuildooor.
1367
+ * Post-sort input order so __INPUT_IDX__ placeholders resolve to the indices Buildooor assigns
1368
+ * in build(): all inputs (script, forced, funding) sorted lexicographically on (txHash, outputIndex).
1010
1369
  */
1011
- _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
1370
+ _computeSortedInputs(scriptUtxoRefs, forcedUtxos, fundingRefs) {
1012
1371
  const all = [
1013
- { txHash: scriptUtxoRef.txHash, outputIndex: scriptUtxoRef.outputIndex },
1372
+ ...scriptUtxoRefs.map(r => ({ txHash: r.txHash, outputIndex: r.outputIndex })),
1014
1373
  ...forcedUtxos.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
1015
1374
  ...fundingRefs
1016
1375
  ];
@@ -1023,10 +1382,7 @@ class BuildooorTxBuilder {
1023
1382
  outputIndex: i.utxo.utxoRef.index
1024
1383
  }));
1025
1384
  }
1026
- /**
1027
- * Resolve __INPUT_IDX__ placeholders (FR-3) inside each extraOutput.inlineDatum.
1028
- * Returns a new array with resolved datums; non-datum fields pass through unchanged.
1029
- */
1385
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
1030
1386
  _resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
1031
1387
  if (!extraOutputs || extraOutputs.length === 0)
1032
1388
  return extraOutputs;
@@ -1038,9 +1394,8 @@ class BuildooorTxBuilder {
1038
1394
  }));
1039
1395
  }
1040
1396
  /**
1041
- * Append parsed extraOutputs (FR-2) to the outputs array, enforcing min-ADA per entry.
1042
- * Throws TransactionValidationError with the required min-ADA in the message so consumers
1043
- * can adjust without having to inspect Buildooor internals.
1397
+ * Append parsed extra outputs, enforcing min-ADA per entry; the rejection names the
1398
+ * required min-ADA so consumers can adjust without inspecting Buildooor internals.
1044
1399
  */
1045
1400
  _appendExtraOutputs(outputs, extraOutputs) {
1046
1401
  if (!extraOutputs || extraOutputs.length === 0)
@@ -1061,10 +1416,8 @@ class BuildooorTxBuilder {
1061
1416
  // UTxO Mapping & Configuration Helpers
1062
1417
  //---------------------------------------------------------------------------
1063
1418
  /**
1064
- * Resolve the transaction's validity window (slots) from the request.
1065
- * Falls back to `now - 2 min` / `now + 1 h` when the request omits bounds.
1066
- * Script-validated builds must call this; plain transfers pass their own
1067
- * explicit bounds through (no defaulting) so replay behavior is opt-in.
1419
+ * Validity window (slots) from the request. Script builds default to `now - 2 min` / `now + 1 h`;
1420
+ * plain transfers pass explicit bounds through without defaulting.
1068
1421
  */
1069
1422
  _resolveValiditySlots(req, mode) {
1070
1423
  const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
@@ -1088,14 +1441,9 @@ class BuildooorTxBuilder {
1088
1441
  };
1089
1442
  }
1090
1443
  /**
1091
- * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape.
1092
- *
1093
- * Every field is null-guarded: a missing/null source value keeps the library
1094
- * default instead of degrading to 0 (`Number(null) === 0` previously set
1095
- * utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
1096
- * execution-unit prices are mapped because they feed the scriptDataHash
1097
- * (language views) and the fee/ExUnits math — stale defaults there cause
1098
- * PPViewHashesDontMatch or fee underestimation on-chain.
1444
+ * Map LedgerProtocolParameter to Buildooor's ProtocolParameters. Every field is null-guarded so a
1445
+ * missing value keeps the library default instead of degrading to 0 (e.g. utxoCostPerByte = 0
1446
+ * disables min-ADA); cost models and ExUnit prices feed scriptDataHash and the fee math.
1099
1447
  */
1100
1448
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
1101
1449
  const pp = protocolParameters;
@@ -1143,15 +1491,9 @@ class BuildooorTxBuilder {
1143
1491
  return mapped;
1144
1492
  }
1145
1493
  /**
1146
- * Parse the cost-models JSON blob (backend-normalized number arrays, keys
1147
- * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
1148
- * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
1149
- * usable is found, so the caller can keep defaults and warn.
1150
- *
1151
- * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
1152
- * for the versions mapped here — the named-key conversion drops every entry past
1153
- * the parameter count this costmodels-ts release knows, and the scriptDataHash
1154
- * must cover all of them (see _languageViewCostModels).
1494
+ * Parse the cost-models JSON (keys 'PlutusVN', 'plutus:vN' or 'PlutusScriptVN') into Buildooor's
1495
+ * CostModels; undefined when nothing usable is found. Also (re)sets this.rawCostModelArrays with
1496
+ * the unclamped chain arrays, which the scriptDataHash must cover (see _languageViewCostModels).
1155
1497
  */
1156
1498
  _mapCostModels(costModelsJson) {
1157
1499
  this.rawCostModelArrays = {};
@@ -1206,9 +1548,7 @@ class BuildooorTxBuilder {
1206
1548
  this.rawCostModelArrays = rawArrays;
1207
1549
  return result;
1208
1550
  }
1209
- /**
1210
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
1211
- */
1551
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
1212
1552
  _mapOdatanoUtxoToLedgerUtxo(utxos) {
1213
1553
  (0, tx_build_helper_1.assertAdaOnly)(utxos);
1214
1554
  return new cardano_ledger_ts_1.UTxO({
@@ -1221,15 +1561,11 @@ class BuildooorTxBuilder {
1221
1561
  })
1222
1562
  });
1223
1563
  }
1224
- /**
1225
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
1226
- */
1564
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
1227
1565
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
1228
1566
  const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
1229
- // Inline datum wins; otherwise carry the datum HASH into the resolved TxOut —
1230
- // Buildooor only includes a provided datum preimage in the witness set when the
1231
- // spent output is marked with its Hash32 (pushWitDatum). Dropping the hash here
1232
- // silently discards the preimage → MissingRequiredDatums on submit.
1567
+ // Inline datum wins; otherwise carry the datum HASH: Buildooor only puts a provided datum
1568
+ // preimage into the witness set when the spent output is marked with its Hash32.
1233
1569
  const datumValue = utxo.inlineDatum
1234
1570
  ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1235
1571
  : utxo.datumHash
@@ -1245,9 +1581,7 @@ class BuildooorTxBuilder {
1245
1581
  })
1246
1582
  });
1247
1583
  }
1248
- /**
1249
- * Map ODATANO metadata JSON to Ledger TxMetadata
1250
- */
1584
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
1251
1585
  _mapOdatanoMetadataToLedgerMetadata(metadataJson) {
1252
1586
  if (!metadataJson) {
1253
1587
  return new TxMetadata_1.TxMetadata({});
@@ -1262,20 +1596,9 @@ class BuildooorTxBuilder {
1262
1596
  return new TxMetadata_1.TxMetadata(metadata);
1263
1597
  }
1264
1598
  /**
1265
- * Recursively convert JSON value to TxMetadatum.
1266
- *
1267
- * Ledger rules enforced here (instead of a node-side rejection or a raw 500):
1268
- * - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
1269
- * - text and byte values are limited to 64 BYTES per metadatum — longer values
1270
- * are chunked into a list of ≤64-byte pieces (the established convention,
1271
- * e.g. CIP-25 long strings)
1272
- * - strings prefixed with "0x" (even hex length) become byte metadata
1273
- * - map keys are not auto-chunked (readers match on the literal key) — over-long
1274
- * keys are rejected with a clear 400
1275
- *
1276
- * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
1277
- * "1155.result" or "721.files[0].src") — named in every rejection
1278
- * so the consumer can locate the offending value.
1599
+ * Recursively convert a JSON value to TxMetadatum, enforcing ledger rules: integers only, text/bytes
1600
+ * over 64 BYTES chunked into a list, "0x..." strings become bytes, over-long map keys rejected.
1601
+ * @param path label-rooted position of `value` (e.g. "721.files[0].src"), named in every rejection
1279
1602
  */
1280
1603
  _jsonToTxMetadatum(value, path) {
1281
1604
  if (typeof value === 'number' || typeof value === 'bigint') {