@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

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 (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -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,17 @@ 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");
23
19
  const const_1 = require("../../utils/const");
24
20
  const logger = cds_1.default.log('BuildooorTxBuilder');
25
21
  /**
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.
22
+ * Build options for script-bearing transactions. Buildooor stamps each redeemer with its
23
+ * local CEK budget and, without `onScriptInvalid`, aborts on a local failure; we only record
24
+ * failures here and let `_buildScriptTx` decide (Ogmios result wins, otherwise abort).
39
25
  */
40
26
  function makeScriptBuildOpts(failures) {
41
27
  return {
@@ -75,10 +61,8 @@ function maxBig(a, b) {
75
61
  return a > b ? a : b;
76
62
  }
77
63
  /**
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).
64
+ * Parse a protocol-parameter value (number or decimal string) into a non-negative safe integer;
65
+ * undefined for null/empty/invalid so callers keep library defaults instead of coercing to 0.
82
66
  */
83
67
  function toUInt(value) {
84
68
  if (value === null || value === undefined || value === '')
@@ -93,11 +77,7 @@ function toPositiveNumber(value) {
93
77
  const n = Number(value);
94
78
  return Number.isFinite(n) && n > 0 ? n : undefined;
95
79
  }
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
- */
80
+ /** Stable identity of a protocol-parameter set: network#epoch (params change per epoch), else full JSON. */
101
81
  function protocolParamsFingerprint(p) {
102
82
  if (p.network && p.epoch !== undefined && p.epoch !== null)
103
83
  return `${p.network}#${p.epoch}`;
@@ -105,10 +85,7 @@ function protocolParamsFingerprint(p) {
105
85
  }
106
86
  /** Ledger limit for a single text/bytes metadatum (bytes, not characters). */
107
87
  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
- */
88
+ /** Split a string into pieces of at most maxBytes UTF-8 bytes without splitting a code point. */
112
89
  function chunkUtf8(str, maxBytes) {
113
90
  const chunks = [];
114
91
  let current = '';
@@ -129,9 +106,7 @@ function chunkUtf8(str, maxBytes) {
129
106
  chunks.push(current);
130
107
  return chunks;
131
108
  }
132
- /**
133
- * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
134
- */
109
+ /** CardanoTxBuilder implementation on top of Buildooor. */
135
110
  class BuildooorTxBuilder {
136
111
  name = 'BuildooorTxBuilder';
137
112
  txBuilder;
@@ -139,16 +114,13 @@ class BuildooorTxBuilder {
139
114
  genesisInfos;
140
115
  paramsFingerprint;
141
116
  /**
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).
117
+ * Chain cost-model arrays kept verbatim for language-view hashing; set by _mapCostModels,
118
+ * empty when the current parameters carry no usable cost models.
146
119
  */
147
120
  rawCostModelArrays = {};
148
121
  /**
149
- * Initialize the builder
150
- * @param client - The CardanoClient instance
151
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
122
+ * Initialize the builder.
123
+ * @param protocolParams - optional; fetched from the backend when omitted
152
124
  */
153
125
  async init(client, protocolParams) {
154
126
  this.cardanoClient = client;
@@ -162,11 +134,8 @@ class BuildooorTxBuilder {
162
134
  logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
163
135
  }
164
136
  /**
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.
137
+ * Rebuild the TxBuilder when the per-request protocol parameters differ from the current
138
+ * ones; the TxBuilder has no setter but its constructor is cheap (effectively once per epoch).
170
139
  */
171
140
  _ensureCurrentProtocolParameters(ctx) {
172
141
  const params = ctx.protocolParameters;
@@ -182,23 +151,17 @@ class BuildooorTxBuilder {
182
151
  this.txBuilder = new buildooor_1.TxBuilder(this._mapLedgerParametersToBuildooorParams(params), this.genesisInfos);
183
152
  this.paramsFingerprint = fingerprint;
184
153
  }
185
- /**
186
- * Build unsigned transfer transaction (ADA-only or with native assets).
187
- */
154
+ /** Build an unsigned transfer transaction (ADA-only or with native assets). */
188
155
  buildUnsignedTransfer(req, ctx) {
189
156
  return this._buildSimpleTransfer(req, ctx, 'transfer');
190
157
  }
191
- /**
192
- * Build unsigned transfer transaction with attached metadata.
193
- */
158
+ /** Build an unsigned transfer transaction with attached metadata. */
194
159
  buildUnsignedTransactionWithMetadata(req, ctx) {
195
160
  return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
196
161
  }
197
162
  /**
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.
163
+ * Shared non-script transfer build; assets, outputDatum and metadataJson are each
164
+ * handled only when present in the request.
202
165
  */
203
166
  async _buildSimpleTransfer(req, ctx, label) {
204
167
  try {
@@ -209,7 +172,6 @@ class BuildooorTxBuilder {
209
172
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
210
173
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
211
174
  const amount = BigInt(String(req.lovelaceAmount));
212
- // Build output value (lovelace + optional native assets)
213
175
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
214
176
  if (req.assets && req.assets.length > 0) {
215
177
  outputValue = this._buildLedgerValue(amount, req.assets);
@@ -237,17 +199,15 @@ class BuildooorTxBuilder {
237
199
  }
238
200
  }
239
201
  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.
202
+ // Set once the collateral partition is known: it explains insufficient-funds rejections
203
+ // that the builder's own message cannot attribute.
242
204
  let coinSelectionContext;
243
205
  try {
244
206
  this._ensureCurrentProtocolParameters(ctx);
245
207
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
246
208
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
- // Parse the minting policy script once
248
209
  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).
210
+ // Total mint value for the output (positive quantities only); each action mints under its own policy script.
251
211
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
252
212
  for (const [index, mintAction] of req.mintActions.entries()) {
253
213
  const quantity = BigInt(mintAction.quantity);
@@ -266,10 +226,8 @@ class BuildooorTxBuilder {
266
226
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
267
227
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
268
228
  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).
229
+ // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
230
+ // demand the mint itself does not cover.
273
231
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
274
232
  if (req.extraOutputs && req.extraOutputs.length > 0) {
275
233
  const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
@@ -278,7 +236,7 @@ class BuildooorTxBuilder {
278
236
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
279
237
  const inputs = [...forcedInputs, ...selectedFunding];
280
238
  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.
239
+ // Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
282
240
  const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
283
241
  ...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
284
242
  ...this._extractFundingRefs(selectedFunding)
@@ -291,10 +249,8 @@ class BuildooorTxBuilder {
291
249
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
292
250
  : undefined;
293
251
  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.
252
+ // Primary output: minted assets + min ADA. With extra outputs declared, those carry
253
+ // the minted assets and the primary output stays ADA(+datum)-only.
298
254
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
299
255
  if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
300
256
  outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
@@ -303,23 +259,20 @@ class BuildooorTxBuilder {
303
259
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
304
260
  // Append extra outputs, each independently min-ADA checked.
305
261
  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.
262
+ // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
263
+ // stamped post-build by _buildScriptTx.
310
264
  const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
311
265
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
312
266
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
313
267
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
314
268
  // and fee computation stay consistent (a mismatch would force re-evaluation).
315
269
  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).
270
+ // Auxiliary metadata (CIP-20, label 674, ...) must be identical across eval + final passes:
271
+ // it affects tx size (fee) and the script data hash.
318
272
  const mintMetadata = req.metadataJson
319
273
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
320
274
  : 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.
275
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
323
276
  const buildParams = {
324
277
  inputs, outputs, changeAddress, mints,
325
278
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
@@ -342,14 +295,11 @@ class BuildooorTxBuilder {
342
295
  try {
343
296
  this._ensureCurrentProtocolParameters(ctx);
344
297
  const { plutusScriptExecution } = req;
345
- // Parse the validator script
346
298
  const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
347
299
  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.
300
+ // Without an explicit datum the script UTxO must carry an inline datum.
350
301
  logger.debug('No datumJson provided — expecting inline datum on script UTxO');
351
302
  }
352
- // Find the specific script UTxO in the provided context UTxOs
353
303
  const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
354
304
  const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
355
305
  if (!scriptOdatanoUtxo) {
@@ -368,9 +318,8 @@ class BuildooorTxBuilder {
368
318
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
369
319
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
370
320
  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.
321
+ // Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
322
+ // assets the script UTxO already provides net out, so over-requesting is harmless.
374
323
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
375
324
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
376
325
  if (req.extraOutputs && req.extraOutputs.length > 0) {
@@ -380,8 +329,8 @@ class BuildooorTxBuilder {
380
329
  }
381
330
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
382
331
  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.
332
+ // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
333
+ // in redeemer / datum / output datums BEFORE PlutusData encoding.
385
334
  const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
386
335
  const resolveCtx = { sortedInputs };
387
336
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
@@ -396,7 +345,7 @@ class BuildooorTxBuilder {
396
345
  const resolvedMintRedeemer = req.mintRedeemer
397
346
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
398
347
  : undefined;
399
- // FR-1: combined spend+mint flow. When mintActions are present, build mints alongside the spend input.
348
+ // Combined spend+mint: with mintActions present, mints are built alongside the spend input.
400
349
  const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
401
350
  let mintScript;
402
351
  let mintScriptHash;
@@ -423,12 +372,10 @@ class BuildooorTxBuilder {
423
372
  }
424
373
  const primaryRefScript = this._parseReferenceScript(req.referenceScript);
425
374
  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.
375
+ // Append extra outputs, each independently min-ADA checked.
428
376
  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.
377
+ // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
378
+ // units, the real ones are stamped post-build by _buildScriptTx.
432
379
  const mints = hasMint
433
380
  ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
434
381
  : undefined;
@@ -442,8 +389,7 @@ class BuildooorTxBuilder {
442
389
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
443
390
  // and fee computation stay consistent (a mismatch would force re-evaluation).
444
391
  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.
392
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
447
393
  const buildParams = {
448
394
  inputs, outputs, changeAddress,
449
395
  mints,
@@ -512,24 +458,9 @@ class BuildooorTxBuilder {
512
458
  };
513
459
  }
514
460
  /**
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.
461
+ * Build a script-bearing transaction with real execution units: Buildooor stamps local CEK
462
+ * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
463
+ * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
533
464
  */
534
465
  async _buildScriptTx(buildParams, evaluator) {
535
466
  const pass1Failures = [];
@@ -539,12 +470,10 @@ class BuildooorTxBuilder {
539
470
  }
540
471
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
541
472
  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.
473
+ // Defensive: callers always attach a script; nothing to evaluate or stamp.
544
474
  return tx1;
545
475
  }
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).
476
+ // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
548
477
  const evaluatedUnits = evaluator
549
478
  ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
550
479
  : undefined;
@@ -552,10 +481,8 @@ class BuildooorTxBuilder {
552
481
  logger.debug('No evaluator available — falling back to buffered local execution units');
553
482
  }
554
483
  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.
484
+ // Fee floor: Buildooor's fee already covers local budgets and future vkey witnesses; add the
485
+ // price delta of the stamped units, their longer CBOR encoding, and a pad for change-size wobble.
559
486
  const feeFloor = BigInt(tx1.body.fee.toString())
560
487
  + this._exUnitsPriceDelta(rdmrs1, targets1)
561
488
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
@@ -567,11 +494,8 @@ class BuildooorTxBuilder {
567
494
  return this._stampExecUnits(tx2, targets2);
568
495
  }
569
496
  /**
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.
497
+ * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
498
+ * evaluation is unusable (transient failure, empty result). Validation errors are rethrown.
575
499
  */
576
500
  async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
577
501
  try {
@@ -585,7 +509,7 @@ class BuildooorTxBuilder {
585
509
  let purpose;
586
510
  let index;
587
511
  if (typeof v === 'string') {
588
- // Legacy "purpose:index" form
512
+ // "purpose:index" string form
589
513
  const [p, i] = v.split(':');
590
514
  purpose = p;
591
515
  index = Number(i);
@@ -605,11 +529,8 @@ class BuildooorTxBuilder {
605
529
  }
606
530
  catch (evalError) {
607
531
  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.
532
+ // Authoritative: the ledger executed and rejected the script; falling back to local
533
+ // units would hand back a transaction the node has already rejected.
613
534
  throw evalError;
614
535
  }
615
536
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
@@ -618,9 +539,8 @@ class BuildooorTxBuilder {
618
539
  }
619
540
  }
620
541
  /**
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).
542
+ * Cushion: relative multiplier for proportional drift on large validators, absolute floor
543
+ * for sub-percent drift on small ones.
624
544
  */
625
545
  _applyExUnitBuffer(mem, cpu) {
626
546
  return {
@@ -629,12 +549,9 @@ class BuildooorTxBuilder {
629
549
  };
630
550
  }
631
551
  /**
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.
552
+ * Execution units each redeemer must declare: max(local, Ogmios) when both exist, buffered
553
+ * local without Ogmios, Ogmios alone after a local failure; a local failure without Ogmios
554
+ * aborts because unreliable units would forfeit the signer's collateral.
638
555
  */
639
556
  _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
640
557
  return rdmrs.map(r => {
@@ -692,15 +609,9 @@ class BuildooorTxBuilder {
692
609
  return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
693
610
  }
694
611
  /**
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.
612
+ * Replace the redeemers' execution units and recompute scriptDataHash with the raw chain
613
+ * cost-model arrays (TxBuilder.overrideTxRedeemers hashes with clamped named-key models,
614
+ * which mismatches once the on-chain cost model grows). Recomputed even when units match.
704
615
  */
705
616
  _stampExecUnits(tx, targets) {
706
617
  const rdmrs = tx.witnesses.redeemers ?? [];
@@ -738,12 +649,9 @@ class BuildooorTxBuilder {
738
649
  return opts;
739
650
  }
740
651
  /**
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.)
652
+ * Cost models for language-view hashing: named-key objects clamp the chain array to the
653
+ * parameter count this library release knows, but the ledger hashes every entry served,
654
+ * so raw chain arrays (passed through unclamped) are substituted where available.
747
655
  */
748
656
  _languageViewCostModels() {
749
657
  const models = this.txBuilder.protocolParamters.costModels;
@@ -752,9 +660,8 @@ class BuildooorTxBuilder {
752
660
  return { ...models, ...this.rawCostModelArrays };
753
661
  }
754
662
  /**
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.
663
+ * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
664
+ * refs absent from utxos are ignored (existence is validated upstream).
758
665
  */
759
666
  _partitionForcedInputs(utxos, forceInputs) {
760
667
  if (!forceInputs || forceInputs.length === 0)
@@ -770,22 +677,15 @@ class BuildooorTxBuilder {
770
677
  }
771
678
  return { forced, rest };
772
679
  }
773
- /**
774
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
775
- * Returns empty array when no reference inputs are provided.
776
- */
680
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
777
681
  _mapReferenceInputs(referenceInputUtxos) {
778
682
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
779
683
  return [];
780
684
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
781
685
  }
782
686
  /**
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).
687
+ * Funding contributed by extra outputs on a mint build: their summed lovelace plus, per asset
688
+ * unit, the demand the transaction's own positive mints do not cover.
789
689
  */
790
690
  _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
791
691
  const mintedByUnit = new Map();
@@ -814,8 +714,7 @@ class BuildooorTxBuilder {
814
714
  return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
815
715
  }
816
716
  /**
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
717
+ * Script a mint action executes under: its per-action policy when set, else the request's
819
718
  * top-level policy script.
820
719
  */
821
720
  _mintActionScript(action, defaultScript, index) {
@@ -824,14 +723,9 @@ class BuildooorTxBuilder {
824
723
  return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
825
724
  }
826
725
  /**
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.
726
+ * Buildooor mint entries shared by the mint-only and combined spend+mint flows. Each action may
727
+ * carry its own policy script and redeemer (falling back to the request-level ones); the ledger
728
+ * holds ONE redeemer per policy, so actions on the same policy must agree, checked here.
835
729
  */
836
730
  _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
837
731
  const redeemerByPolicy = new Map();
@@ -864,10 +758,8 @@ class BuildooorTxBuilder {
864
758
  });
865
759
  }
866
760
  /**
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").
761
+ * Context for insufficient-funds rejections after the collateral partition: the builder's
762
+ * message counts only the funding pool, so the reservation would otherwise be invisible.
871
763
  */
872
764
  _collateralPartitionContext(collateralUtxos, fundingUtxos) {
873
765
  const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
@@ -876,16 +768,9 @@ class BuildooorTxBuilder {
876
768
  `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
877
769
  }
878
770
  /**
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.
771
+ * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
772
+ * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
773
+ * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
889
774
  */
890
775
  _setupCollateral(utxos) {
891
776
  const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
@@ -913,8 +798,7 @@ class BuildooorTxBuilder {
913
798
  if (excess >= minAda) {
914
799
  collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
915
800
  }
916
- // excess below min-ADA: no return output possible — whole UTxO stays at risk,
917
- // but by selection it is the smallest sufficient one.
801
+ // excess below min-ADA: no return output possible, the whole UTxO stays at risk
918
802
  }
919
803
  return { collateralUtxos, fundingUtxos, collateralReturn };
920
804
  }
@@ -945,12 +829,9 @@ class BuildooorTxBuilder {
945
829
  return new cardano_ledger_ts_1.TxOut(params);
946
830
  }
947
831
  /**
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).
832
+ * Parse a CBOR-wrapped Plutus script and reject UPLC 1.0.0 code (V1/V2): Script.fromCbor
833
+ * defaults to V3 and would hash with the 0x03 prefix, giving a silently wrong script hash.
834
+ * The UPLC version is the first three flat naturals of the unwrapped script: [1,0,0] vs [1,1,0].
954
835
  */
955
836
  _parsePlutusV3Script(hex, field) {
956
837
  let script;
@@ -975,10 +856,8 @@ class BuildooorTxBuilder {
975
856
  return this._parsePlutusV3Script(hex, 'referenceScript');
976
857
  }
977
858
  /**
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.
859
+ * Map an input UTxO's scriptRef to a Script. Blockfrost/Ogmios set scriptRef to the 28-byte
860
+ * hash (56 hex chars), Koios to the full CBOR bytes; only full bytes are usable locally.
982
861
  */
983
862
  _buildInputRefScript(utxo) {
984
863
  if (!utxo.scriptRef)
@@ -1003,10 +882,8 @@ class BuildooorTxBuilder {
1003
882
  }
1004
883
  }
1005
884
  /**
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.
885
+ * Post-sort input order so __INPUT_IDX__ placeholders resolve to the indices Buildooor assigns
886
+ * in build(): all inputs (script, forced, funding) sorted lexicographically on (txHash, outputIndex).
1010
887
  */
1011
888
  _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
1012
889
  const all = [
@@ -1023,10 +900,7 @@ class BuildooorTxBuilder {
1023
900
  outputIndex: i.utxo.utxoRef.index
1024
901
  }));
1025
902
  }
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
- */
903
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
1030
904
  _resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
1031
905
  if (!extraOutputs || extraOutputs.length === 0)
1032
906
  return extraOutputs;
@@ -1038,9 +912,8 @@ class BuildooorTxBuilder {
1038
912
  }));
1039
913
  }
1040
914
  /**
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.
915
+ * Append parsed extra outputs, enforcing min-ADA per entry; the rejection names the
916
+ * required min-ADA so consumers can adjust without inspecting Buildooor internals.
1044
917
  */
1045
918
  _appendExtraOutputs(outputs, extraOutputs) {
1046
919
  if (!extraOutputs || extraOutputs.length === 0)
@@ -1061,10 +934,8 @@ class BuildooorTxBuilder {
1061
934
  // UTxO Mapping & Configuration Helpers
1062
935
  //---------------------------------------------------------------------------
1063
936
  /**
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.
937
+ * Validity window (slots) from the request. Script builds default to `now - 2 min` / `now + 1 h`;
938
+ * plain transfers pass explicit bounds through without defaulting.
1068
939
  */
1069
940
  _resolveValiditySlots(req, mode) {
1070
941
  const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
@@ -1088,14 +959,9 @@ class BuildooorTxBuilder {
1088
959
  };
1089
960
  }
1090
961
  /**
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.
962
+ * Map LedgerProtocolParameter to Buildooor's ProtocolParameters. Every field is null-guarded so a
963
+ * missing value keeps the library default instead of degrading to 0 (e.g. utxoCostPerByte = 0
964
+ * disables min-ADA); cost models and ExUnit prices feed scriptDataHash and the fee math.
1099
965
  */
1100
966
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
1101
967
  const pp = protocolParameters;
@@ -1143,15 +1009,9 @@ class BuildooorTxBuilder {
1143
1009
  return mapped;
1144
1010
  }
1145
1011
  /**
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).
1012
+ * Parse the cost-models JSON (keys 'PlutusVN', 'plutus:vN' or 'PlutusScriptVN') into Buildooor's
1013
+ * CostModels; undefined when nothing usable is found. Also (re)sets this.rawCostModelArrays with
1014
+ * the unclamped chain arrays, which the scriptDataHash must cover (see _languageViewCostModels).
1155
1015
  */
1156
1016
  _mapCostModels(costModelsJson) {
1157
1017
  this.rawCostModelArrays = {};
@@ -1206,9 +1066,7 @@ class BuildooorTxBuilder {
1206
1066
  this.rawCostModelArrays = rawArrays;
1207
1067
  return result;
1208
1068
  }
1209
- /**
1210
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
1211
- */
1069
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
1212
1070
  _mapOdatanoUtxoToLedgerUtxo(utxos) {
1213
1071
  (0, tx_build_helper_1.assertAdaOnly)(utxos);
1214
1072
  return new cardano_ledger_ts_1.UTxO({
@@ -1221,15 +1079,11 @@ class BuildooorTxBuilder {
1221
1079
  })
1222
1080
  });
1223
1081
  }
1224
- /**
1225
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
1226
- */
1082
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
1227
1083
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
1228
1084
  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.
1085
+ // Inline datum wins; otherwise carry the datum HASH: Buildooor only puts a provided datum
1086
+ // preimage into the witness set when the spent output is marked with its Hash32.
1233
1087
  const datumValue = utxo.inlineDatum
1234
1088
  ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1235
1089
  : utxo.datumHash
@@ -1245,9 +1099,7 @@ class BuildooorTxBuilder {
1245
1099
  })
1246
1100
  });
1247
1101
  }
1248
- /**
1249
- * Map ODATANO metadata JSON to Ledger TxMetadata
1250
- */
1102
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
1251
1103
  _mapOdatanoMetadataToLedgerMetadata(metadataJson) {
1252
1104
  if (!metadataJson) {
1253
1105
  return new TxMetadata_1.TxMetadata({});
@@ -1262,20 +1114,9 @@ class BuildooorTxBuilder {
1262
1114
  return new TxMetadata_1.TxMetadata(metadata);
1263
1115
  }
1264
1116
  /**
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.
1117
+ * Recursively convert a JSON value to TxMetadatum, enforcing ledger rules: integers only, text/bytes
1118
+ * over 64 BYTES chunked into a list, "0x..." strings become bytes, over-long map keys rejected.
1119
+ * @param path label-rooted position of `value` (e.g. "721.files[0].src"), named in every rejection
1279
1120
  */
1280
1121
  _jsonToTxMetadatum(value, path) {
1281
1122
  if (typeof value === 'number' || typeof value === 'bigint') {