@odatano/core 2.0.0-rc.2 → 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 (132) 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/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. 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,22 +199,22 @@ 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)
210
+ // Total mint value for the output (positive quantities only); each action mints under its own policy script.
250
211
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
251
- for (const mintAction of req.mintActions) {
212
+ for (const [index, mintAction] of req.mintActions.entries()) {
252
213
  const quantity = BigInt(mintAction.quantity);
253
214
  if (quantity > 0n) {
215
+ const actionScript = this._mintActionScript(mintAction, script, index);
254
216
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
255
- mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), quantity));
217
+ mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), quantity));
256
218
  }
257
219
  }
258
220
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
@@ -264,12 +226,17 @@ class BuildooorTxBuilder {
264
226
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
265
227
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
266
228
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
267
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
268
- const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
229
+ // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
230
+ // demand the mint itself does not cover.
231
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
232
+ if (req.extraOutputs && req.extraOutputs.length > 0) {
233
+ const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
234
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
235
+ }
269
236
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
270
237
  const inputs = [...forcedInputs, ...selectedFunding];
271
238
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
272
- // FR-3: resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum after final input order is known.
239
+ // Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
273
240
  const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
274
241
  ...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
275
242
  ...this._extractFundingRefs(selectedFunding)
@@ -281,27 +248,31 @@ class BuildooorTxBuilder {
281
248
  const resolvedInlineDatum = req.inlineDatum
282
249
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
283
250
  : undefined;
284
- // Build output — recipient gets the minted assets + min ADA
251
+ const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
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.
285
254
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
286
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
255
+ if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
256
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
257
+ }
287
258
  const refScript = this._parseReferenceScript(req.referenceScript);
288
259
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
289
- // Mint entries for the build args (uses pre-resolved redeemer). Note: Buildooor
290
- // ignores caller-supplied execution units — the real units are stamped into the
291
- // redeemers post-build by _buildScriptTx.
292
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
260
+ // Append extra outputs, each independently min-ADA checked.
261
+ this._appendExtraOutputs(outputs, resolvedExtraOutputs);
262
+ // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
263
+ // stamped post-build by _buildScriptTx.
264
+ const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
293
265
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
294
266
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
295
267
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
296
268
  // and fee computation stay consistent (a mismatch would force re-evaluation).
297
269
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
298
- // CIP-20 / label-674 etc. auxiliary metadata. Must be identical across eval + final
299
- // passes since auxiliary_data affects both tx size (→ fee) and script data hash (indirectly via tx hash).
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.
300
272
  const mintMetadata = req.metadataJson
301
273
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
302
274
  : undefined;
303
- // Single set of build args — both internal passes and the Ogmios evaluation share
304
- // validity bounds and metadata so redeemer ExUnits and fee stay consistent.
275
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
305
276
  const buildParams = {
306
277
  inputs, outputs, changeAddress, mints,
307
278
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
@@ -324,14 +295,11 @@ class BuildooorTxBuilder {
324
295
  try {
325
296
  this._ensureCurrentProtocolParameters(ctx);
326
297
  const { plutusScriptExecution } = req;
327
- // Parse the validator script
328
298
  const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
329
299
  if (!plutusScriptExecution.datum) {
330
- // When no explicit datum is provided, the UTxO must have an inline datum.
331
- // If neither exists, the Plutus validator will fail with a cryptic error.
300
+ // Without an explicit datum the script UTxO must carry an inline datum.
332
301
  logger.debug('No datumJson provided — expecting inline datum on script UTxO');
333
302
  }
334
- // Find the specific script UTxO in the provided context UTxOs
335
303
  const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
336
304
  const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
337
305
  if (!scriptOdatanoUtxo) {
@@ -350,9 +318,8 @@ class BuildooorTxBuilder {
350
318
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
351
319
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
352
320
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
353
- // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
354
- // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
355
- // already provides will net out, so over-requesting is harmless — keepRelevant prefers smaller sets.
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.
356
323
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
357
324
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
358
325
  if (req.extraOutputs && req.extraOutputs.length > 0) {
@@ -362,8 +329,8 @@ class BuildooorTxBuilder {
362
329
  }
363
330
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
364
331
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
365
- // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
366
- // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
332
+ // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
333
+ // in redeemer / datum / output datums BEFORE PlutusData encoding.
367
334
  const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
368
335
  const resolveCtx = { sortedInputs };
369
336
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
@@ -378,7 +345,7 @@ class BuildooorTxBuilder {
378
345
  const resolvedMintRedeemer = req.mintRedeemer
379
346
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
380
347
  : undefined;
381
- // 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.
382
349
  const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
383
350
  let mintScript;
384
351
  let mintScriptHash;
@@ -394,24 +361,23 @@ class BuildooorTxBuilder {
394
361
  }
395
362
  // If mints are present and no extraOutputs handle the minted assets, attach positive mints to the primary output.
396
363
  if (hasMint && (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0)) {
397
- for (const action of req.mintActions) {
364
+ for (const [index, action] of req.mintActions.entries()) {
398
365
  const qty = BigInt(action.quantity);
399
366
  if (qty > 0n) {
367
+ const actionScript = this._mintActionScript(action, mintScript, index);
400
368
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
401
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), qty));
369
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), qty));
402
370
  }
403
371
  }
404
372
  }
405
373
  const primaryRefScript = this._parseReferenceScript(req.referenceScript);
406
374
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedPrimaryInlineDatum, primaryRefScript)];
407
- // Append extra outputs (FR-2). Each is independently min-ADA checked so consumers
408
- // get a clear, field-attributed error before Buildooor's coin selection runs.
375
+ // Append extra outputs, each independently min-ADA checked.
409
376
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
410
- // Mint entries (FR-1) and inputs for the build args. Note: Buildooor ignores
411
- // caller-supplied execution units — the real units are stamped into the
412
- // redeemers post-build by _buildScriptTx.
377
+ // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
378
+ // units, the real ones are stamped post-build by _buildScriptTx.
413
379
  const mints = hasMint
414
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
380
+ ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
415
381
  : undefined;
416
382
  const scriptInput = {
417
383
  utxo: scriptLedgerUtxo,
@@ -423,8 +389,7 @@ class BuildooorTxBuilder {
423
389
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
424
390
  // and fee computation stay consistent (a mismatch would force re-evaluation).
425
391
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
426
- // Single set of build args — both internal passes and the Ogmios evaluation share
427
- // validity bounds so redeemer ExUnits and fee stay consistent.
392
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
428
393
  const buildParams = {
429
394
  inputs, outputs, changeAddress,
430
395
  mints,
@@ -493,24 +458,9 @@ class BuildooorTxBuilder {
493
458
  };
494
459
  }
495
460
  /**
496
- * Build a script-bearing transaction whose redeemers carry *real* execution units and
497
- * whose fee covers them.
498
- *
499
- * Background (verified against the vendored Buildooor source): `initTxBuild` constructs
500
- * every redeemer with a dummy budget — caller-supplied execution units in the build args
501
- * are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
502
- * the budget the local CEK run consumed, even when the script failed (partial budget).
503
- * So the declared units are whatever the *local* evaluation produced, and any cushion
504
- * passed into the args silently evaporates. This method makes the declared units real:
505
- *
506
- * 1. First pass: build once; redeemers now carry the local CEK budgets.
507
- * 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
508
- * budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
509
- * 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
510
- * without an Ogmios result aborts — see makeScriptBuildOpts).
511
- * 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
512
- * from its own local budgets, so the floor adds the price + encoding-size delta).
513
- * 5. Stamp the target units into the redeemers and recompute scriptDataHash.
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.
514
464
  */
515
465
  async _buildScriptTx(buildParams, evaluator) {
516
466
  const pass1Failures = [];
@@ -520,12 +470,10 @@ class BuildooorTxBuilder {
520
470
  }
521
471
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
522
472
  if (rdmrs1.length === 0) {
523
- // Defensive — callers always attach a script. Nothing to evaluate or stamp,
524
- // and Buildooor's calcMinFee already budgets the vkey witnesses to come.
473
+ // Defensive: callers always attach a script; nothing to evaluate or stamp.
525
474
  return tx1;
526
475
  }
527
- // The first-pass CBOR is exactly what a dedicated "evaluation build" would produce
528
- // (identical args ⇒ identical tx, since passed ExUnits are ignored anyway).
476
+ // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
529
477
  const evaluatedUnits = evaluator
530
478
  ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
531
479
  : undefined;
@@ -533,10 +481,8 @@ class BuildooorTxBuilder {
533
481
  logger.debug('No evaluator available — falling back to buffered local execution units');
534
482
  }
535
483
  const targets1 = this._resolveTargetExUnits(rdmrs1, evaluatedUnits, pass1Failures);
536
- // Fee floor: Buildooor's fee covers its local budgets AND the vkey witnesses to
537
- // come (calcMinFee budgets 104 bytes per estimated signer); add only the price
538
- // delta of the stamped units, their (slightly longer) CBOR encoding, and a small
539
- // pad for change-output size wobble between the two passes.
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.
540
486
  const feeFloor = BigInt(tx1.body.fee.toString())
541
487
  + this._exUnitsPriceDelta(rdmrs1, targets1)
542
488
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
@@ -548,11 +494,8 @@ class BuildooorTxBuilder {
548
494
  return this._stampExecUnits(tx2, targets2);
549
495
  }
550
496
  /**
551
- * Evaluate a transaction via Ogmios and return cushioned budgets keyed per redeemer
552
- * (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
553
- * failure, empty result) so callers fall back to buffered local units. A
554
- * TransactionValidationError or ScriptValidationError from the evaluator is
555
- * authoritative (the script really failed on the ledger) and is rethrown.
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.
556
499
  */
557
500
  async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
558
501
  try {
@@ -566,7 +509,7 @@ class BuildooorTxBuilder {
566
509
  let purpose;
567
510
  let index;
568
511
  if (typeof v === 'string') {
569
- // Legacy "purpose:index" form
512
+ // "purpose:index" string form
570
513
  const [p, i] = v.split(':');
571
514
  purpose = p;
572
515
  index = Number(i);
@@ -586,11 +529,8 @@ class BuildooorTxBuilder {
586
529
  }
587
530
  catch (evalError) {
588
531
  if (evalError instanceof errors_1.TransactionValidationError || evalError instanceof errors_1.ScriptValidationError) {
589
- // Authoritative: Ogmios executed the script and the ledger rejected it. This is
590
- // either a TransactionValidationError or, after normalizeBackendError, a
591
- // ScriptValidationError (PlutusFailure / CekError / budget overspend). Falling
592
- // back to local buffered units here would hand back a transaction the node has
593
- // already rejected — so propagate the failure instead.
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.
594
534
  throw evalError;
595
535
  }
596
536
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
@@ -599,9 +539,8 @@ class BuildooorTxBuilder {
599
539
  }
600
540
  }
601
541
  /**
602
- * Combined cushion: relative multiplier catches proportional drift on large
603
- * validators, absolute floor catches sub-percent drift on small ones (observed
604
- * when metadata affects the real tx body vs the evaluator's ScriptContext).
542
+ * Cushion: relative multiplier for proportional drift on large validators, absolute floor
543
+ * for sub-percent drift on small ones.
605
544
  */
606
545
  _applyExUnitBuffer(mem, cpu) {
607
546
  return {
@@ -610,12 +549,9 @@ class BuildooorTxBuilder {
610
549
  };
611
550
  }
612
551
  /**
613
- * Decide the execution units each redeemer must declare.
614
- * - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
615
- * - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
616
- * - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
617
- * - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
618
- * collateral of whoever signs and submits the returned CBOR.
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.
619
555
  */
620
556
  _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
621
557
  return rdmrs.map(r => {
@@ -673,15 +609,9 @@ class BuildooorTxBuilder {
673
609
  return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
674
610
  }
675
611
  /**
676
- * Replace the redeemers' execution units and recompute scriptDataHash.
677
- *
678
- * Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
679
- * 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
680
- * builder's named-key cost models, which clamp the chain array to the parameter
681
- * count the library release knows — wrong whenever the on-chain cost model has
682
- * grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
683
- * _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
684
- * is recomputed here even when the target units already match.
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.
685
615
  */
686
616
  _stampExecUnits(tx, targets) {
687
617
  const rdmrs = tx.witnesses.redeemers ?? [];
@@ -719,12 +649,9 @@ class BuildooorTxBuilder {
719
649
  return opts;
720
650
  }
721
651
  /**
722
- * Cost models for language-view hashing. The named-key objects the TxBuilder was
723
- * constructed with clamp the chain array to the parameter count this costmodels-ts
724
- * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
725
- * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
726
- * array form through unclamped, so substitute the raw chain arrays where we have
727
- * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
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.
728
655
  */
729
656
  _languageViewCostModels() {
730
657
  const models = this.txBuilder.protocolParamters.costModels;
@@ -733,9 +660,8 @@ class BuildooorTxBuilder {
733
660
  return { ...models, ...this.rawCostModelArrays };
734
661
  }
735
662
  /**
736
- * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
737
- * coin selection / collateral). Refs in forceInputs that are not present in utxos are
738
- * silently ignored — the resolver upstream has already validated existence.
663
+ * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
664
+ * refs absent from utxos are ignored (existence is validated upstream).
739
665
  */
740
666
  _partitionForcedInputs(utxos, forceInputs) {
741
667
  if (!forceInputs || forceInputs.length === 0)
@@ -751,39 +677,89 @@ class BuildooorTxBuilder {
751
677
  }
752
678
  return { forced, rest };
753
679
  }
754
- /**
755
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
756
- * Returns empty array when no reference inputs are provided.
757
- */
680
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
758
681
  _mapReferenceInputs(referenceInputUtxos) {
759
682
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
760
683
  return [];
761
684
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
762
685
  }
763
686
  /**
764
- * Build the Buildooor mint-entry array shared by the mint-only flow and the
765
- * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
766
- * they are stamped into the redeemers post-build by _buildScriptTx).
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.
767
689
  */
768
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
769
- return mintActions.map(action => {
690
+ _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
691
+ const mintedByUnit = new Map();
692
+ for (const action of mintActions) {
693
+ const quantity = BigInt(action.quantity);
694
+ if (quantity > 0n) {
695
+ const unit = action.assetUnit.toLowerCase();
696
+ mintedByUnit.set(unit, (mintedByUnit.get(unit) ?? 0n) + quantity);
697
+ }
698
+ }
699
+ const demandByUnit = new Map();
700
+ let lovelace = 0n;
701
+ for (const extra of extraOutputs) {
702
+ lovelace += BigInt(extra.lovelaceAmount);
703
+ for (const asset of extra.assets ?? []) {
704
+ const unit = asset.unit.toLowerCase();
705
+ demandByUnit.set(unit, (demandByUnit.get(unit) ?? 0n) + BigInt(asset.quantity));
706
+ }
707
+ }
708
+ const assets = [];
709
+ for (const [unit, demand] of demandByUnit) {
710
+ const uncovered = demand - (mintedByUnit.get(unit) ?? 0n);
711
+ if (uncovered > 0n)
712
+ assets.push({ unit, quantity: uncovered.toString() });
713
+ }
714
+ return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
715
+ }
716
+ /**
717
+ * Script a mint action executes under: its per-action policy when set, else the request's
718
+ * top-level policy script.
719
+ */
720
+ _mintActionScript(action, defaultScript, index) {
721
+ if (!action.mintingPolicyScript)
722
+ return defaultScript;
723
+ return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
724
+ }
725
+ /**
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.
729
+ */
730
+ _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
731
+ const redeemerByPolicy = new Map();
732
+ return mintActions.map((action, index) => {
733
+ const script = this._mintActionScript(action, mintScript, index);
734
+ const actionRedeemer = action.redeemerJson !== undefined
735
+ ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
736
+ : resolvedMintRedeemer;
737
+ const redeemerData = actionRedeemer !== undefined
738
+ ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
739
+ : new plutus_data_1.DataI(action.redeemer ?? 0);
740
+ const policyId = script.hash.toString();
741
+ // Canonical comparison over the encoded PlutusData: JSON key order must
742
+ // not matter, and a JSON {int:0} equals the DataI(0) fallback.
743
+ const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
744
+ const seen = redeemerByPolicy.get(policyId);
745
+ if (seen !== undefined && seen !== redeemerFingerprint) {
746
+ throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
747
+ 'split them into separate transactions or align the redeemers');
748
+ }
749
+ redeemerByPolicy.set(policyId, redeemerFingerprint);
770
750
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
771
751
  return {
772
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
752
+ value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
773
753
  script: {
774
- inline: mintScript,
775
- redeemer: resolvedMintRedeemer
776
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
777
- : new plutus_data_1.DataI(action.redeemer ?? 0)
754
+ inline: script,
755
+ redeemer: redeemerData
778
756
  }
779
757
  };
780
758
  });
781
759
  }
782
760
  /**
783
- * Consumer-facing context for insufficient-funds rejections after the
784
- * collateral partition: the builder's own "not enough …" message counts only
785
- * the funding pool, and without this the reservation is invisible ("but the
786
- * address HAS enough ADA").
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.
787
763
  */
788
764
  _collateralPartitionContext(collateralUtxos, fundingUtxos) {
789
765
  const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
@@ -792,16 +768,9 @@ class BuildooorTxBuilder {
792
768
  `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
793
769
  }
794
770
  /**
795
- * Pick a collateral UTxO and return remaining funding UTxOs.
796
- * Throws if no ADA-only UTxO is available.
797
- *
798
- * Selection: the SMALLEST ADA-only UTxO that still covers the static
799
- * COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
800
- * The previous "first ADA-only" pick failed both ways: a dust UTxO below
801
- * collateralPercentage × fee is rejected at submit, and a large UTxO is
802
- * fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
803
- * for ADA-only collateral). Everything above the floor is therefore handed
804
- * back via an explicit collateralReturn when the excess satisfies min-ADA.
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.
805
774
  */
806
775
  _setupCollateral(utxos) {
807
776
  const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
@@ -829,8 +798,7 @@ class BuildooorTxBuilder {
829
798
  if (excess >= minAda) {
830
799
  collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
831
800
  }
832
- // excess below min-ADA: no return output possible — whole UTxO stays at risk,
833
- // but by selection it is the smallest sufficient one.
801
+ // excess below min-ADA: no return output possible, the whole UTxO stays at risk
834
802
  }
835
803
  return { collateralUtxos, fundingUtxos, collateralReturn };
836
804
  }
@@ -861,12 +829,9 @@ class BuildooorTxBuilder {
861
829
  return new cardano_ledger_ts_1.TxOut(params);
862
830
  }
863
831
  /**
864
- * Parse a consumer-provided, CBOR-wrapped Plutus script and reject UPLC 1.0.0
865
- * code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
866
- * would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
867
- * wrong policy IDs and unspendable script addresses with no error anywhere
868
- * down the line. The UPLC version is the first three flat-encoded naturals
869
- * of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
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].
870
835
  */
871
836
  _parsePlutusV3Script(hex, field) {
872
837
  let script;
@@ -891,10 +856,8 @@ class BuildooorTxBuilder {
891
856
  return this._parsePlutusV3Script(hex, 'referenceScript');
892
857
  }
893
858
  /**
894
- * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
895
- * UTxO.scriptRef is overloaded across backends: Blockfrost/Ogmios set it to a 28-byte
896
- * hash (56 hex chars), Koios sets it to the full CBOR script bytes. Only full bytes
897
- * are usable here — hash-only entries are preserved only on-chain, not in local eval.
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.
898
861
  */
899
862
  _buildInputRefScript(utxo) {
900
863
  if (!utxo.scriptRef)
@@ -919,10 +882,8 @@ class BuildooorTxBuilder {
919
882
  }
920
883
  }
921
884
  /**
922
- * Compute the post-sort input order so __INPUT_IDX__ placeholders (FR-3) resolve to the
923
- * same indices Buildooor will assign during build(). Order: script-input first by convention,
924
- * then forced + funding sorted lexicographically on (txHash, outputIndex).
925
- * Buildooor sorts ALL inputs together; we mirror that exact behaviour via sortInputsLikeBuildooor.
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).
926
887
  */
927
888
  _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
928
889
  const all = [
@@ -939,10 +900,7 @@ class BuildooorTxBuilder {
939
900
  outputIndex: i.utxo.utxoRef.index
940
901
  }));
941
902
  }
942
- /**
943
- * Resolve __INPUT_IDX__ placeholders (FR-3) inside each extraOutput.inlineDatum.
944
- * Returns a new array with resolved datums; non-datum fields pass through unchanged.
945
- */
903
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
946
904
  _resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
947
905
  if (!extraOutputs || extraOutputs.length === 0)
948
906
  return extraOutputs;
@@ -954,9 +912,8 @@ class BuildooorTxBuilder {
954
912
  }));
955
913
  }
956
914
  /**
957
- * Append parsed extraOutputs (FR-2) to the outputs array, enforcing min-ADA per entry.
958
- * Throws TransactionValidationError with the required min-ADA in the message so consumers
959
- * can adjust without having to inspect Buildooor internals.
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.
960
917
  */
961
918
  _appendExtraOutputs(outputs, extraOutputs) {
962
919
  if (!extraOutputs || extraOutputs.length === 0)
@@ -977,10 +934,8 @@ class BuildooorTxBuilder {
977
934
  // UTxO Mapping & Configuration Helpers
978
935
  //---------------------------------------------------------------------------
979
936
  /**
980
- * Resolve the transaction's validity window (slots) from the request.
981
- * Falls back to `now - 2 min` / `now + 1 h` when the request omits bounds.
982
- * Script-validated builds must call this; plain transfers pass their own
983
- * explicit bounds through (no defaulting) so replay behavior is opt-in.
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.
984
939
  */
985
940
  _resolveValiditySlots(req, mode) {
986
941
  const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
@@ -1004,14 +959,9 @@ class BuildooorTxBuilder {
1004
959
  };
1005
960
  }
1006
961
  /**
1007
- * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape.
1008
- *
1009
- * Every field is null-guarded: a missing/null source value keeps the library
1010
- * default instead of degrading to 0 (`Number(null) === 0` previously set
1011
- * utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
1012
- * execution-unit prices are mapped because they feed the scriptDataHash
1013
- * (language views) and the fee/ExUnits math — stale defaults there cause
1014
- * PPViewHashesDontMatch or fee underestimation on-chain.
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.
1015
965
  */
1016
966
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
1017
967
  const pp = protocolParameters;
@@ -1059,15 +1009,9 @@ class BuildooorTxBuilder {
1059
1009
  return mapped;
1060
1010
  }
1061
1011
  /**
1062
- * Parse the cost-models JSON blob (backend-normalized number arrays, keys
1063
- * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
1064
- * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
1065
- * usable is found, so the caller can keep defaults and warn.
1066
- *
1067
- * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
1068
- * for the versions mapped here — the named-key conversion drops every entry past
1069
- * the parameter count this costmodels-ts release knows, and the scriptDataHash
1070
- * must cover all of them (see _languageViewCostModels).
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).
1071
1015
  */
1072
1016
  _mapCostModels(costModelsJson) {
1073
1017
  this.rawCostModelArrays = {};
@@ -1122,9 +1066,7 @@ class BuildooorTxBuilder {
1122
1066
  this.rawCostModelArrays = rawArrays;
1123
1067
  return result;
1124
1068
  }
1125
- /**
1126
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
1127
- */
1069
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
1128
1070
  _mapOdatanoUtxoToLedgerUtxo(utxos) {
1129
1071
  (0, tx_build_helper_1.assertAdaOnly)(utxos);
1130
1072
  return new cardano_ledger_ts_1.UTxO({
@@ -1137,15 +1079,11 @@ class BuildooorTxBuilder {
1137
1079
  })
1138
1080
  });
1139
1081
  }
1140
- /**
1141
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
1142
- */
1082
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
1143
1083
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
1144
1084
  const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
1145
- // Inline datum wins; otherwise carry the datum HASH into the resolved TxOut —
1146
- // Buildooor only includes a provided datum preimage in the witness set when the
1147
- // spent output is marked with its Hash32 (pushWitDatum). Dropping the hash here
1148
- // silently discards the preimage → MissingRequiredDatums on submit.
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.
1149
1087
  const datumValue = utxo.inlineDatum
1150
1088
  ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1151
1089
  : utxo.datumHash
@@ -1161,9 +1099,7 @@ class BuildooorTxBuilder {
1161
1099
  })
1162
1100
  });
1163
1101
  }
1164
- /**
1165
- * Map ODATANO metadata JSON to Ledger TxMetadata
1166
- */
1102
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
1167
1103
  _mapOdatanoMetadataToLedgerMetadata(metadataJson) {
1168
1104
  if (!metadataJson) {
1169
1105
  return new TxMetadata_1.TxMetadata({});
@@ -1178,20 +1114,9 @@ class BuildooorTxBuilder {
1178
1114
  return new TxMetadata_1.TxMetadata(metadata);
1179
1115
  }
1180
1116
  /**
1181
- * Recursively convert JSON value to TxMetadatum.
1182
- *
1183
- * Ledger rules enforced here (instead of a node-side rejection or a raw 500):
1184
- * - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
1185
- * - text and byte values are limited to 64 BYTES per metadatum — longer values
1186
- * are chunked into a list of ≤64-byte pieces (the established convention,
1187
- * e.g. CIP-25 long strings)
1188
- * - strings prefixed with "0x" (even hex length) become byte metadata
1189
- * - map keys are not auto-chunked (readers match on the literal key) — over-long
1190
- * keys are rejected with a clear 400
1191
- *
1192
- * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
1193
- * "1155.result" or "721.files[0].src") — named in every rejection
1194
- * so the consumer can locate the offending value.
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
1195
1120
  */
1196
1121
  _jsonToTxMetadatum(value, path) {
1197
1122
  if (typeof value === 'number' || typeof value === 'bigint') {