@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -4,45 +4,39 @@ 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");
9
+ const crypto_1 = require("@harmoniclabs/crypto");
11
10
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
12
11
  const errors_1 = require("../../utils/errors");
13
12
  const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
14
13
  const cds_1 = __importDefault(require("@sap/cds"));
15
14
  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.)
15
+ // Metadata classes come from the dist paths on purpose. Buildooor's `instanceof` checks
16
+ // match these exact classes, not the package-root re-exports.
20
17
  const TxMetadata_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadata");
21
18
  const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadatum");
22
19
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
23
20
  const const_1 = require("../../utils/const");
21
+ const reference_script_1 = require("../../utils/reference-script");
24
22
  const logger = cds_1.default.log('BuildooorTxBuilder');
25
23
  /**
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.
24
+ * Records local script failures instead of aborting, so `_buildScriptTx` can let Ogmios decide.
39
25
  */
40
26
  function makeScriptBuildOpts(failures) {
27
+ // The machine's message comes with the result, which Buildooor reports before onScriptInvalid.
28
+ const machineErrors = new Map();
41
29
  return {
30
+ onScriptResult: (rdmr, result) => {
31
+ const msg = result?.msg;
32
+ if (typeof msg === 'string' && msg)
33
+ machineErrors.set(redeemerKey(rdmr.tag, rdmr.index), msg);
34
+ },
42
35
  onScriptInvalid: (rdmr, logs) => {
43
- failures.push({ tag: rdmr.tag, index: rdmr.index, logs: logs.slice() });
36
+ const error = machineErrors.get(redeemerKey(rdmr.tag, rdmr.index)) ?? null;
37
+ failures.push({ tag: rdmr.tag, index: rdmr.index, logs: logs.slice(), error });
44
38
  logger.warn(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(rdmr.tag)}:${rdmr.index}); ` +
45
- `deferring to Ogmios evaluation if available. Logs: [${logs.join(', ')}]`);
39
+ `deferring to Ogmios evaluation if available. Machine error: ${error ?? 'none reported'}. Logs: [${logs.join(', ')}]`);
46
40
  }
47
41
  };
48
42
  }
@@ -74,41 +68,29 @@ function ceilDiv(a, b) {
74
68
  function maxBig(a, b) {
75
69
  return a > b ? a : b;
76
70
  }
77
- /**
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).
82
- */
71
+ /** Non-negative safe integer, or undefined so callers keep library defaults instead of 0. */
83
72
  function toUInt(value) {
84
73
  if (value === null || value === undefined || value === '')
85
74
  return undefined;
86
75
  const n = Number(value);
87
76
  return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
88
77
  }
89
- /** Parse a strictly positive finite number (e.g. exUnit prices); undefined when absent/invalid. */
78
+ /** Strictly positive finite number, else undefined. */
90
79
  function toPositiveNumber(value) {
91
80
  if (value === null || value === undefined || value === '')
92
81
  return undefined;
93
82
  const n = Number(value);
94
83
  return Number.isFinite(n) && n > 0 ? n : undefined;
95
84
  }
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
- */
85
+ /** Stable identity of a protocol-parameter set: network#epoch (params change per epoch), else full JSON. */
101
86
  function protocolParamsFingerprint(p) {
102
87
  if (p.network && p.epoch !== undefined && p.epoch !== null)
103
88
  return `${p.network}#${p.epoch}`;
104
89
  return JSON.stringify(p);
105
90
  }
106
- /** Ledger limit for a single text/bytes metadatum (bytes, not characters). */
91
+ /** Ledger limit for one text or bytes metadatum, counted in bytes. */
107
92
  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
- */
93
+ /** Split a string into pieces of at most maxBytes UTF-8 bytes without splitting a code point. */
112
94
  function chunkUtf8(str, maxBytes) {
113
95
  const chunks = [];
114
96
  let current = '';
@@ -129,27 +111,22 @@ function chunkUtf8(str, maxBytes) {
129
111
  chunks.push(current);
130
112
  return chunks;
131
113
  }
132
- /**
133
- * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
134
- */
114
+ // Script.fromCbor keeps the compiler bytes, but an output's script_ref needs the ledger form.
115
+ // Rebuilding the script gives that form. The hash stays the same.
116
+ function ledgerScript(script) {
117
+ return new cardano_ledger_ts_1.Script(script.type, script.bytes);
118
+ }
119
+ const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
120
+ /** CardanoTxBuilder implementation on top of Buildooor. */
135
121
  class BuildooorTxBuilder {
136
122
  name = 'BuildooorTxBuilder';
137
123
  txBuilder;
138
124
  cardanoClient;
139
125
  genesisInfos;
140
126
  paramsFingerprint;
141
- /**
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).
146
- */
127
+ /** Chain cost-model arrays kept verbatim for language-view hashing. */
147
128
  rawCostModelArrays = {};
148
- /**
149
- * Initialize the builder
150
- * @param client - The CardanoClient instance
151
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
152
- */
129
+ /** Initialize the builder. Protocol parameters are fetched when omitted. */
153
130
  async init(client, protocolParams) {
154
131
  this.cardanoClient = client;
155
132
  const params = protocolParams ?? await client.getProtocolParameters();
@@ -161,13 +138,7 @@ class BuildooorTxBuilder {
161
138
  this._applyProtocolParameters(params, protocolParamsFingerprint(params));
162
139
  logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
163
140
  }
164
- /**
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.
170
- */
141
+ /** TxBuilder has no setter, so it is rebuilt when the protocol parameters change. */
171
142
  _ensureCurrentProtocolParameters(ctx) {
172
143
  const params = ctx.protocolParameters;
173
144
  if (!params)
@@ -182,25 +153,16 @@ class BuildooorTxBuilder {
182
153
  this.txBuilder = new buildooor_1.TxBuilder(this._mapLedgerParametersToBuildooorParams(params), this.genesisInfos);
183
154
  this.paramsFingerprint = fingerprint;
184
155
  }
185
- /**
186
- * Build unsigned transfer transaction (ADA-only or with native assets).
187
- */
156
+ /** Build an unsigned transfer transaction (ADA-only or with native assets). */
188
157
  buildUnsignedTransfer(req, ctx) {
189
- return this._buildSimpleTransfer(req, ctx, 'transfer');
158
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'transfer', include));
190
159
  }
191
- /**
192
- * Build unsigned transfer transaction with attached metadata.
193
- */
160
+ /** Build an unsigned transfer transaction with attached metadata. */
194
161
  buildUnsignedTransactionWithMetadata(req, ctx) {
195
- return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
162
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildSimpleTransfer(req, ctx, 'metadata transfer', include));
196
163
  }
197
- /**
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.
202
- */
203
- async _buildSimpleTransfer(req, ctx, label) {
164
+ /** Shared non-script transfer build. */
165
+ async _buildSimpleTransfer(req, ctx, label, includeRefScriptUtxos) {
204
166
  try {
205
167
  this._ensureCurrentProtocolParameters(ctx);
206
168
  if (!ctx.utxos || ctx.utxos.length === 0) {
@@ -209,15 +171,30 @@ class BuildooorTxBuilder {
209
171
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
210
172
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
211
173
  const amount = BigInt(String(req.lovelaceAmount));
212
- // Build output value (lovelace + optional native assets)
213
- let outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
214
- if (req.assets && req.assets.length > 0) {
215
- outputValue = this._buildLedgerValue(amount, req.assets);
174
+ if (req.outputDatum !== undefined && req.outputDatumCbor !== undefined) {
175
+ throw new errors_1.TransactionValidationError('outputDatum and outputDatumCbor exclude each other; pass one');
216
176
  }
177
+ // a datum given as CBOR keeps its bytes
178
+ const datum = req.outputDatumCbor !== undefined ? (0, plutus_data_1.dataFromCbor)(req.outputDatumCbor) : undefined;
217
179
  const refScript = this._parseReferenceScript(req.referenceScript);
218
- const outputs = [this._buildTxOut(recipientAddress, outputValue, req.outputDatum, refScript)];
180
+ const recipientOut = (lovelace) => {
181
+ const value = this._buildLedgerValue(lovelace, req.assets);
182
+ return datum
183
+ ? new cardano_ledger_ts_1.TxOut({ address: recipientAddress, value, datum, ...(refScript && { refScript }) })
184
+ : this._buildTxOut(recipientAddress, value, req.outputDatum, refScript);
185
+ };
186
+ let recipient = recipientOut(amount);
187
+ const minLovelace = this._minOutputLovelace(recipient);
188
+ if (amount < minLovelace) {
189
+ if (!req.ensureMinAda) {
190
+ throw new errors_1.TransactionValidationError(`recipient output needs at least ${minLovelace.toString()} lovelace (has ${amount.toString()}); raise lovelaceAmount or set ensureMinAda`);
191
+ }
192
+ recipient = recipientOut(this._minOutputLovelace(recipient, true));
193
+ }
194
+ const outputValue = recipient.value;
195
+ const outputs = [recipient];
219
196
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
220
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
197
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
221
198
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
222
199
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
223
200
  // Coin selection on candidates only; forced inputs are prepended unconditionally
@@ -233,21 +210,24 @@ class BuildooorTxBuilder {
233
210
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
234
211
  }
235
212
  catch (err) {
236
- (0, tx_build_helper_1.mapBuilderError)(err);
213
+ // one requested output; Buildooor appends the change after it
214
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, undefined, 1);
237
215
  }
238
216
  }
239
- 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.
217
+ buildUnsignedMintTransaction(req, ctx) {
218
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildMintTransaction(req, ctx, include));
219
+ }
220
+ async _buildMintTransaction(req, ctx, includeRefScriptUtxos) {
221
+ // Set once the collateral partition is known: it explains insufficient-funds rejections
222
+ // that the builder's own message cannot attribute.
242
223
  let coinSelectionContext;
224
+ let requestedOutputs;
243
225
  try {
244
226
  this._ensureCurrentProtocolParameters(ctx);
245
227
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
246
228
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
- // Parse the minting policy script once
248
229
  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).
230
+ // Total mint value for the output (positive quantities only); each action mints under its own policy script.
251
231
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
252
232
  for (const [index, mintAction] of req.mintActions.entries()) {
253
233
  const quantity = BigInt(mintAction.quantity);
@@ -258,27 +238,25 @@ class BuildooorTxBuilder {
258
238
  }
259
239
  }
260
240
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
261
- // collateral and coin selection operate on the remainder only.
262
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
241
+ // coin selection operates on the remainder only.
242
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
263
243
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
264
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
265
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
266
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
267
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
268
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
269
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
270
- // thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
271
- // demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
272
- // from the wallet).
244
+ // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
245
+ // demand the mint itself does not cover.
273
246
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
274
247
  if (req.extraOutputs && req.extraOutputs.length > 0) {
275
248
  const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
276
249
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
277
250
  }
251
+ // Collateral + funding separation from the candidates; a forced input is collateral only as a fallback
252
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress);
253
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
254
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
255
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
278
256
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
279
257
  const inputs = [...forcedInputs, ...selectedFunding];
280
258
  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.
259
+ // Resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum once the final input order is known.
282
260
  const sortedInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
283
261
  ...forced.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
284
262
  ...this._extractFundingRefs(selectedFunding)
@@ -291,10 +269,8 @@ class BuildooorTxBuilder {
291
269
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
292
270
  : undefined;
293
271
  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.
272
+ // Primary output: minted assets + min ADA. With extra outputs declared, those carry
273
+ // the minted assets and the primary output stays ADA(+datum)-only.
298
274
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
299
275
  if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
300
276
  outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
@@ -303,23 +279,20 @@ class BuildooorTxBuilder {
303
279
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
304
280
  // Append extra outputs, each independently min-ADA checked.
305
281
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
306
- // Mint entries for the build args (uses pre-resolved redeemers; per-action
307
- // redeemers resolve their own placeholders). Note: Buildooor ignores
308
- // caller-supplied execution units — the real units are stamped into the
309
- // redeemers post-build by _buildScriptTx.
310
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
282
+ requestedOutputs = outputs.length;
283
+ // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
284
+ // stamped post-build by _buildScriptTx.
285
+ const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
311
286
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
312
287
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
313
- // Resolve validity bounds once — both passes must share them so redeemer ExUnits
314
- // and fee computation stay consistent (a mismatch would force re-evaluation).
288
+ // Both passes must share the validity bounds so redeemer ExUnits and fee stay consistent.
315
289
  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).
290
+ // Auxiliary metadata (CIP-20, label 674, ...) must be identical across eval + final passes:
291
+ // it affects tx size (fee) and the script data hash.
318
292
  const mintMetadata = req.metadataJson
319
293
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
320
294
  : 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.
295
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
323
296
  const buildParams = {
324
297
  inputs, outputs, changeAddress, mints,
325
298
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
@@ -333,23 +306,24 @@ class BuildooorTxBuilder {
333
306
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
334
307
  }
335
308
  catch (err) {
336
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
309
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
337
310
  }
338
311
  }
339
- async buildUnsignedPlutusSpendTransaction(req, ctx) {
340
- // See buildUnsignedMintTransaction — same collateral-partition context for rejections.
312
+ buildUnsignedPlutusSpendTransaction(req, ctx) {
313
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusSpendTransaction(req, ctx, include));
314
+ }
315
+ async _buildPlutusSpendTransaction(req, ctx, includeRefScriptUtxos) {
316
+ // Same collateral-partition context as in _buildMintTransaction.
341
317
  let coinSelectionContext;
318
+ let requestedOutputs;
342
319
  try {
343
320
  this._ensureCurrentProtocolParameters(ctx);
344
321
  const { plutusScriptExecution } = req;
345
- // Parse the validator script
346
322
  const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
347
323
  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.
350
- logger.debug('No datumJson provided — expecting inline datum on script UTxO');
324
+ // Without an explicit datum the script UTxO must carry an inline datum.
325
+ logger.debug('No datumJson provided, expecting inline datum on script UTxO');
351
326
  }
352
- // Find the specific script UTxO in the provided context UTxOs
353
327
  const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
354
328
  const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
355
329
  if (!scriptOdatanoUtxo) {
@@ -360,35 +334,38 @@ class BuildooorTxBuilder {
360
334
  const senderUtxos = ctx.utxos.filter(u => !(u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex));
361
335
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
362
336
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
363
- // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
337
+ // A forced input that matches the script UTxO is silently ignored.
364
338
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
365
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
339
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs, includeRefScriptUtxos);
366
340
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
367
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
368
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
369
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
370
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
371
- // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
372
- // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
373
- // already provides will net out, so over-requesting is harmless — keepRelevant prefers smaller sets.
374
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
341
+ // Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
342
+ // assets the script UTxO already provides net out, so over-requesting is harmless.
375
343
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
376
344
  if (req.extraOutputs && req.extraOutputs.length > 0) {
377
345
  for (const extra of req.extraOutputs) {
378
346
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
379
347
  }
380
348
  }
349
+ // Collateral + funding separation from the candidates; a forced input is collateral only as a fallback.
350
+ // The script UTxO pays its part of the outputs, so the collateral check counts only the rest.
351
+ const fundingGap = requiredFundingValue.lovelaces - (0, tx_build_helper_1.getLovelace)(scriptOdatanoUtxo);
352
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, fundingGap > 0n ? fundingGap : 0n, forced, req.senderAddress);
353
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
354
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
355
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
381
356
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
382
357
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
383
- // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
384
- // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
385
- const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
358
+ // Resolve __INPUT_IDX__ placeholders against Buildooor's input order before PlutusData encoding.
359
+ const sortedInputs = this._computeSortedInputs([scriptUtxoRef], forced, this._extractFundingRefs(selectedFundingInputs));
386
360
  const resolveCtx = { sortedInputs };
387
361
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
388
362
  const redeemerData = (0, tx_build_helper_1.jsonToPlutusData)(resolvedRedeemer);
389
363
  const datum = plutusScriptExecution.datum
390
364
  ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.datum, resolveCtx))
391
365
  : "inline";
366
+ if (datum !== "inline") {
367
+ this._checkWitnessDatum(scriptOdatanoUtxo, (0, plutus_data_1.dataToCbor)(datum), 'datumJson', '; BuildPlutusTransaction takes the datum as datumCbor with the bytes the UTxO was locked with');
368
+ }
392
369
  const resolvedPrimaryInlineDatum = req.inlineDatum
393
370
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
394
371
  : undefined;
@@ -396,7 +373,7 @@ class BuildooorTxBuilder {
396
373
  const resolvedMintRedeemer = req.mintRedeemer
397
374
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.mintRedeemer, resolveCtx)
398
375
  : undefined;
399
- // FR-1: combined spend+mint flow. When mintActions are present, build mints alongside the spend input.
376
+ // Combined spend+mint: with mintActions present, mints are built alongside the spend input.
400
377
  const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
401
378
  let mintScript;
402
379
  let mintScriptHash;
@@ -404,7 +381,7 @@ class BuildooorTxBuilder {
404
381
  mintScript = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
405
382
  mintScriptHash = mintScript.hash.toString();
406
383
  }
407
- // Build outputs — include multi-assets from script UTxO in continuing output
384
+ // The continuing output carries the multi-assets of the script UTxO.
408
385
  const scriptNonAdaAssets = scriptOdatanoUtxo.amount.filter(a => a.unit.toLowerCase() !== 'lovelace' && BigInt(a.quantity) > 0n);
409
386
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
410
387
  if (scriptNonAdaAssets.length > 0) {
@@ -423,14 +400,13 @@ class BuildooorTxBuilder {
423
400
  }
424
401
  const primaryRefScript = this._parseReferenceScript(req.referenceScript);
425
402
  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.
403
+ // Append extra outputs, each independently min-ADA checked.
428
404
  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.
405
+ requestedOutputs = outputs.length;
406
+ // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
407
+ // units, the real ones are stamped post-build by _buildScriptTx.
432
408
  const mints = hasMint
433
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
409
+ ? this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, mintScript, i) }), resolvedMintRedeemer, resolveCtx)
434
410
  : undefined;
435
411
  const scriptInput = {
436
412
  utxo: scriptLedgerUtxo,
@@ -439,11 +415,9 @@ class BuildooorTxBuilder {
439
415
  const inputs = [scriptInput, ...forcedInputs, ...selectedFundingInputs];
440
416
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
441
417
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
442
- // Resolve validity bounds once — both passes must share them so redeemer ExUnits
443
- // and fee computation stay consistent (a mismatch would force re-evaluation).
418
+ // Both passes must share the validity bounds so redeemer ExUnits and fee stay consistent.
444
419
  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.
420
+ // One set of build args shared by both internal passes and the Ogmios evaluation.
447
421
  const buildParams = {
448
422
  inputs, outputs, changeAddress,
449
423
  mints,
@@ -462,9 +436,269 @@ class BuildooorTxBuilder {
462
436
  });
463
437
  }
464
438
  catch (err) {
465
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
439
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
440
+ }
441
+ }
442
+ // Several script inputs, each with its own redeemer and an inline or referenced validator.
443
+ // Outputs keep the given order, change comes after them.
444
+ buildUnsignedPlutusTransaction(req, ctx) {
445
+ return this._withRefScriptFallback(ctx.utxos, (include) => this._buildPlutusTransaction(req, ctx, include));
446
+ }
447
+ async _buildPlutusTransaction(req, ctx, includeRefScriptUtxos) {
448
+ let coinSelectionContext;
449
+ let requestedOutputs;
450
+ try {
451
+ this._ensureCurrentProtocolParameters(ctx);
452
+ const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
453
+ const utxoByKey = new Map(ctx.utxos.map(u => [keyOf(u), u]));
454
+ const refUtxoByKey = new Map((ctx.referenceInputUtxos ?? []).map(u => [keyOf(u), u]));
455
+ const scriptKeys = new Set(req.scriptInputs.map(keyOf));
456
+ // Scripts the reference inputs already carry: the ledger rejects the same script again as a
457
+ // witness (ExtraneousScriptWitnesses), so an inline validator with such a hash uses the reference.
458
+ const referencedByHash = new Map();
459
+ for (const u of ctx.referenceInputUtxos ?? []) {
460
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(u);
461
+ const hash = ledgerUtxo.resolved.refScript?.hash.toString();
462
+ if (hash && !referencedByHash.has(hash))
463
+ referencedByHash.set(hash, ledgerUtxo);
464
+ }
465
+ // Script inputs: each UTxO with its script (inline, or the ledger UTxO carrying it)
466
+ const scriptEntries = req.scriptInputs.map((si, i) => {
467
+ const utxo = utxoByKey.get(keyOf(si));
468
+ if (!utxo)
469
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}] ${keyOf(si)} not found on-chain or already spent`);
470
+ if (si.validatorScript) {
471
+ const script = this._parsePlutusV3Script(si.validatorScript, `scriptInputs[${i}].validatorScript`);
472
+ const scriptHash = script.hash.toString();
473
+ const referenced = referencedByHash.get(scriptHash);
474
+ return referenced ? { si, utxo, refLedgerUtxo: referenced, scriptHash } : { si, utxo, script };
475
+ }
476
+ const refKey = keyOf(si.referenceScript);
477
+ const refUtxo = refUtxoByKey.get(refKey);
478
+ if (!refUtxo)
479
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} not found on-chain or already spent`);
480
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
481
+ if (!refLedgerUtxo.resolved.refScript) {
482
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
483
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
484
+ }
485
+ return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
486
+ });
487
+ // Withdrawals: the staking script inline, by reference, or the one a reference input carries
488
+ const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
489
+ w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
490
+ ...this._resolveScriptWitness({ script: w.stakingScript, referenceScript: w.referenceScript }, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
491
+ }));
492
+ // Certificates: the credential from the stake address; a script runs under the Certifying purpose
493
+ const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
494
+ const certEntries = (req.certificates ?? []).map((c, i) => {
495
+ const at = `certificates[${i}]`;
496
+ const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
497
+ const credentialHash = stake.credentials.toString().toLowerCase();
498
+ const witness = this._resolveScriptWitness({ script: c.stakingScript, referenceScript: c.referenceScript }, at, referencedByHash, refUtxoByKey);
499
+ const scripted = Boolean(witness.script || witness.refLedgerUtxo);
500
+ const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
501
+ if (stake.type === 'script') {
502
+ if (scripted && witnessHash !== credentialHash) {
503
+ throw new errors_1.TransactionValidationError(`${at} staking script hash ${witnessHash} is not the credential of ${c.stakeAddress} (${credentialHash})`);
504
+ }
505
+ if (!scripted && c.type === 'deregisterStake') {
506
+ throw new errors_1.TransactionValidationError(`${at} deregisters the script credential ${c.stakeAddress}; its staking script and redeemer are needed`);
507
+ }
508
+ }
509
+ else if (scripted) {
510
+ throw new errors_1.TransactionValidationError(`${at} ${c.stakeAddress} is a key credential; it takes no staking script`);
511
+ }
512
+ const stakeCredential = stake.type === 'script' ? cardano_ledger_ts_1.Credential.script(stake.credentials) : cardano_ledger_ts_1.Credential.keyHash(stake.credentials);
513
+ const deposit = c.deposit ? BigInt(c.deposit) : stakeDeposit;
514
+ // Without a script the witness-free legacy registration; the deposit forms need the witness
515
+ const cert = c.type === 'registerStake'
516
+ ? (scripted ? new cardano_ledger_ts_1.CertRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeRegistration({ stakeCredential }))
517
+ : (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
518
+ return { c, cert, deposit, ...witness };
519
+ });
520
+ // Mints: each policy inline, by reference, or the one a reference input carries
521
+ const mintEntries = (req.mintActions ?? []).map((m, i) => {
522
+ const at = `mintActions[${i}]`;
523
+ const witness = this._resolveScriptWitness({ script: m.mintingPolicyScript, referenceScript: m.referenceScript }, at, referencedByHash, refUtxoByKey, 'mintingPolicyScript');
524
+ const policyId = (witness.script?.hash ?? witness.refLedgerUtxo.resolved.refScript.hash).toString().toLowerCase();
525
+ if (!m.assetUnit.toLowerCase().startsWith(policyId)) {
526
+ throw new errors_1.TransactionValidationError(`${at}.assetUnit ${m.assetUnit} is not under the policy ${policyId} of its script`);
527
+ }
528
+ return { m, policyId, ...witness };
529
+ });
530
+ // one policy runs from one place: once any action of it uses a reference script, all do
531
+ const mintRefByPolicy = new Map();
532
+ for (const e of mintEntries)
533
+ if (e.refLedgerUtxo && !mintRefByPolicy.has(e.policyId))
534
+ mintRefByPolicy.set(e.policyId, e.refLedgerUtxo);
535
+ for (const e of mintEntries) {
536
+ const ref = mintRefByPolicy.get(e.policyId);
537
+ if (ref) {
538
+ e.refLedgerUtxo = ref;
539
+ e.script = undefined;
540
+ }
541
+ }
542
+ const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
543
+ const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
544
+ const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
545
+ if (scriptKeyClash)
546
+ throw new errors_1.TransactionValidationError(`protectInputs ${scriptKeyClash} is also a script input`);
547
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs, includeRefScriptUtxos);
548
+ this._checkForeignForcedInputs(forced, req);
549
+ const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
550
+ // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
551
+ // withdrawals (keepRelevant adds its own lovelace margin for fee and change).
552
+ const need = new Map();
553
+ const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
554
+ for (const o of req.outputs) {
555
+ add('lovelace', BigInt(o.lovelaceAmount));
556
+ for (const a of o.assets ?? [])
557
+ add(a.unit, BigInt(a.quantity));
558
+ }
559
+ for (const u of [...scriptEntries.map(e => e.utxo), ...forced]) {
560
+ for (const a of u.amount)
561
+ add(a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit, -BigInt(a.quantity));
562
+ }
563
+ for (const m of req.mintActions ?? [])
564
+ add(m.assetUnit, -BigInt(m.quantity));
565
+ for (const { w } of withdrawalEntries)
566
+ add('lovelace', -BigInt(w.lovelace));
567
+ // a registration locks the deposit, a deregistration refunds it
568
+ for (const { c, deposit } of certEntries)
569
+ add('lovelace', c.type === 'registerStake' ? deposit : -deposit);
570
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
571
+ for (const [unit, qty] of need) {
572
+ if (qty <= 0n)
573
+ continue;
574
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, unit === 'lovelace'
575
+ ? cardano_ledger_ts_1.Value.lovelaces(qty)
576
+ : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
577
+ }
578
+ // Collateral only when a Plutus script runs; Buildooor writes given collaterals into any body.
579
+ const runsScript = scriptEntries.length > 0 || mintEntries.length > 0 ||
580
+ [...withdrawalEntries, ...certEntries].some(e => e.script || e.refLedgerUtxo);
581
+ const { collateralUtxos, fundingUtxos, collateralReturn } = runsScript
582
+ ? this._setupCollateral(rest, requiredFundingValue.lovelaces, forced, req.senderAddress)
583
+ : { collateralUtxos: [], fundingUtxos: rest, collateralReturn: undefined };
584
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos, forced);
585
+ const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
586
+ const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
587
+ // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
588
+ const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries, ...mintEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
589
+ const callerRefUtxos = (ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u)));
590
+ const readonlyRefInputs = this._mapReferenceInputs(callerRefUtxos);
591
+ const sortedReferenceInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
592
+ ...callerRefUtxos.map(u => ({ txHash: u.txHash.toLowerCase(), outputIndex: u.outputIndex })),
593
+ ...[...refScriptKeys].map(k => { const [txHash, idx] = k.split('#'); return { txHash, outputIndex: Number(idx) }; }),
594
+ ]);
595
+ // Placeholders resolve against the final input, reference-input and withdrawal order
596
+ const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
597
+ const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
598
+ const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
599
+ const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }, i) => {
600
+ const redeemer = si.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(si.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.redeemer, resolveCtx));
601
+ let datum = "inline";
602
+ if (si.datumCbor) {
603
+ const bytes = Buffer.from(si.datumCbor, 'hex');
604
+ this._checkWitnessDatum(utxo, bytes, `scriptInputs[${i}].datumCbor`, '');
605
+ datum = (0, plutus_data_1.dataFromCbor)(bytes);
606
+ }
607
+ else if (si.datum !== undefined) {
608
+ datum = (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx));
609
+ this._checkWitnessDatum(utxo, (0, plutus_data_1.dataToCbor)(datum), `scriptInputs[${i}].datumJson`, '; pass datumCbor with the bytes the UTxO was locked with');
610
+ }
611
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
612
+ return script
613
+ ? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
614
+ : { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
615
+ });
616
+ const outputs = [];
617
+ this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
618
+ ...o,
619
+ inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
620
+ })));
621
+ requestedOutputs = outputs.length;
622
+ const mints = mintEntries.length > 0
623
+ ? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
624
+ : undefined;
625
+ // Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
626
+ const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
627
+ const withdrawal = { rewardAccount, amount: BigInt(w.lovelace) };
628
+ if (!script && !refLedgerUtxo)
629
+ return { withdrawal };
630
+ const redeemer = w.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(w.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(w.redeemer ?? null, resolveCtx));
631
+ return { withdrawal, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
632
+ });
633
+ // Certificates in the given order; a scripted one carries its redeemer under the Cert purpose
634
+ const certificates = certEntries.map(({ c, cert, script, refLedgerUtxo }) => {
635
+ if (!script && !refLedgerUtxo)
636
+ return { cert };
637
+ const redeemer = c.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(c.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(c.redeemer ?? null, resolveCtx));
638
+ return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
639
+ });
640
+ const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
641
+ const buildParams = {
642
+ inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
643
+ outputs, changeAddress, mints,
644
+ collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
645
+ invalidBefore, invalidAfter,
646
+ ...(collateralReturn && { collateralReturn }),
647
+ ...(readonlyRefInputs.length > 0 && { readonlyRefInputs }),
648
+ ...(withdrawals.length > 0 && { withdrawals }),
649
+ ...(certificates.length > 0 && { certificates })
650
+ };
651
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
652
+ const details = this._extractTxDetails(tx);
653
+ const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
654
+ if (details.sizeBytes > maxTxSize) {
655
+ const inline = scriptEntries.filter(e => e.script).length;
656
+ throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
657
+ (inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
658
+ }
659
+ // the first script that runs: a spend, else a mint policy, else a withdrawal or certificate script
660
+ const scriptHashes = [
661
+ ...scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash),
662
+ ...mintEntries.map(e => e.policyId),
663
+ ...[...withdrawalEntries, ...certEntries].flatMap(e => {
664
+ const hash = e.script?.hash ?? e.refLedgerUtxo?.resolved.refScript?.hash;
665
+ return hash ? [hash.toString()] : [];
666
+ }),
667
+ ];
668
+ logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
669
+ return this._buildResult(req, ctx, details, {
670
+ scriptHash: scriptHashes[0],
671
+ forcedInputsUsed: forcedInputs.length,
672
+ referenceInputsUsed: readonlyRefInputs.length + refScriptKeys.size
673
+ });
674
+ }
675
+ catch (err) {
676
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
466
677
  }
467
678
  }
679
+ /** Appends the outputs in order. A CBOR inline datum keeps its bytes. */
680
+ _appendPlutusOutputs(outputs, list) {
681
+ for (let i = 0; i < list.length; i++) {
682
+ const o = list[i];
683
+ const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
684
+ const refScript = this._parseReferenceScript(o.referenceScript);
685
+ const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : o.inlineDatumCbor ? (0, plutus_data_1.dataFromCbor)(o.inlineDatumCbor) : undefined;
686
+ const txOut = datum
687
+ ? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
688
+ : this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
689
+ const minLovelaces = this._minOutputLovelace(txOut);
690
+ if (BigInt(o.lovelaceAmount) < minLovelaces) {
691
+ throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
692
+ }
693
+ outputs.push(txOut);
694
+ }
695
+ }
696
+ // `forAnyAmount` sizes the coin field for the largest amount, so the result holds for any amount.
697
+ _minOutputLovelace(txOut, forAnyAmount = false) {
698
+ return forAnyAmount
699
+ ? this.txBuilder.minimizeLovelaces(txOut).value.lovelaces
700
+ : this.txBuilder.getMinimumOutputLovelaces(txOut);
701
+ }
468
702
  //---------------------------------------------------------------------------
469
703
  // Shared Helper Methods
470
704
  //---------------------------------------------------------------------------
@@ -484,6 +718,12 @@ class BuildooorTxBuilder {
484
718
  address: o.address?.toString?.() ?? "",
485
719
  lovelace: o.value?.lovelaces?.toString?.() ?? "0"
486
720
  })),
721
+ redeemers: (tx.witnesses.redeemers ?? []).map((r) => ({
722
+ tag: (0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag),
723
+ index: r.index,
724
+ mem: r.execUnits.mem.toString(),
725
+ steps: r.execUnits.cpu.toString(),
726
+ })),
487
727
  };
488
728
  }
489
729
  /** Build the standard TxBuildResult object */
@@ -501,61 +741,41 @@ class BuildooorTxBuilder {
501
741
  unsignedTxCbor: txDetails.unsignedTxCbor,
502
742
  txBodyHash: txDetails.txBodyHash,
503
743
  senderAddress: req.senderAddress,
744
+ changeAddress: req.changeAddress ?? req.senderAddress,
504
745
  network: this.cardanoClient.network,
505
746
  builderEngine: this.name,
506
747
  sizeBytes: txDetails.sizeBytes,
507
748
  feeLovelace: txDetails.feeLovelace,
508
749
  inputs,
509
750
  outputs: txDetails.outputs,
751
+ ...(txDetails.redeemers.length > 0 ? { redeemers: txDetails.redeemers } : {}),
510
752
  ...extra,
511
753
  warnings: [],
512
754
  };
513
755
  }
514
- /**
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.
533
- */
756
+ // Buildooor stamps local CEK budgets and ignores caller units. So build once, evaluate via Ogmios,
757
+ // rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
534
758
  async _buildScriptTx(buildParams, evaluator) {
535
759
  const pass1Failures = [];
536
760
  const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
537
761
  if (!tx1) {
538
- throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null — check inputs, datum, and collateral configuration');
762
+ throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null; check inputs, datum, and collateral configuration');
539
763
  }
540
764
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
541
765
  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.
766
+ // Defensive: callers always attach a script; nothing to evaluate or stamp.
544
767
  return tx1;
545
768
  }
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).
769
+ // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
548
770
  const evaluatedUnits = evaluator
549
771
  ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
550
772
  : undefined;
551
773
  if (!evaluator) {
552
- logger.debug('No evaluator available — falling back to buffered local execution units');
774
+ logger.debug('No evaluator available, falling back to buffered local execution units');
553
775
  }
554
776
  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.
777
+ // Fee floor: Buildooor's fee already covers local budgets and future vkey witnesses; add the
778
+ // price delta of the stamped units, their longer CBOR encoding, and a pad for change-size wobble.
559
779
  const feeFloor = BigInt(tx1.body.fee.toString())
560
780
  + this._exUnitsPriceDelta(rdmrs1, targets1)
561
781
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
@@ -566,13 +786,8 @@ class BuildooorTxBuilder {
566
786
  const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
567
787
  return this._stampExecUnits(tx2, targets2);
568
788
  }
569
- /**
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.
575
- */
789
+ // Cushioned Ogmios budgets keyed `tag:index`. Undefined when the evaluation is unusable.
790
+ // Validation errors are rethrown.
576
791
  async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
577
792
  try {
578
793
  const evalResults = await evaluator(evalTxCbor);
@@ -585,7 +800,7 @@ class BuildooorTxBuilder {
585
800
  let purpose;
586
801
  let index;
587
802
  if (typeof v === 'string') {
588
- // Legacy "purpose:index" form
803
+ // "purpose:index" string form
589
804
  const [p, i] = v.split(':');
590
805
  purpose = p;
591
806
  index = Number(i);
@@ -605,11 +820,8 @@ class BuildooorTxBuilder {
605
820
  }
606
821
  catch (evalError) {
607
822
  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.
823
+ // Authoritative: the ledger executed and rejected the script; falling back to local
824
+ // units would hand back a transaction the node has already rejected.
613
825
  throw evalError;
614
826
  }
615
827
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
@@ -617,25 +829,15 @@ class BuildooorTxBuilder {
617
829
  return undefined;
618
830
  }
619
831
  }
620
- /**
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).
624
- */
832
+ // The multiplier covers drift on large validators, the absolute floor covers small ones.
625
833
  _applyExUnitBuffer(mem, cpu) {
626
834
  return {
627
835
  mem: BigInt(Math.ceil(Number(mem) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER),
628
836
  cpu: BigInt(Math.ceil(Number(cpu) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER)
629
837
  };
630
838
  }
631
- /**
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.
638
- */
839
+ // Per redeemer: max of local and Ogmios, else buffered local, else Ogmios after a local failure.
840
+ // A local failure without Ogmios aborts, since unreliable units would forfeit the collateral.
639
841
  _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
640
842
  return rdmrs.map(r => {
641
843
  const local = { mem: BigInt(r.execUnits.mem), cpu: BigInt(r.execUnits.cpu) };
@@ -645,9 +847,9 @@ class BuildooorTxBuilder {
645
847
  if (!evaluated) {
646
848
  throw new errors_1.TransactionValidationError(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag)}:${r.index}) ` +
647
849
  `and no Ogmios evaluation is available to certify its execution units. Refusing to return a ` +
648
- `transaction with unreliable execution units — signing and submitting it would forfeit the collateral. ` +
850
+ `transaction with unreliable execution units. Signing and submitting it would forfeit the collateral. ` +
649
851
  `Configure an Ogmios backend for authoritative script evaluation, or fix the script/datum/redeemer. ` +
650
- `Script logs: [${failure.logs.join(', ')}]`);
852
+ `Machine error: ${failure.error ?? 'none reported'}. Script logs: [${failure.logs.join(', ')}]`);
651
853
  }
652
854
  return evaluated;
653
855
  }
@@ -691,17 +893,8 @@ class BuildooorTxBuilder {
691
893
  _txFeePerByte() {
692
894
  return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
693
895
  }
694
- /**
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.
704
- */
896
+ // Recomputes scriptDataHash with the raw chain cost-model arrays, even when units match.
897
+ // TxBuilder.overrideTxRedeemers hashes clamped models, which breaks once the chain model grows.
705
898
  _stampExecUnits(tx, targets) {
706
899
  const rdmrs = tx.witnesses.redeemers ?? [];
707
900
  const unchanged = rdmrs.every((r, i) => BigInt(r.execUnits.mem) === targets[i].mem && BigInt(r.execUnits.cpu) === targets[i].cpu);
@@ -712,8 +905,7 @@ class BuildooorTxBuilder {
712
905
  execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
713
906
  }));
714
907
  const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
715
- const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
716
- const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
908
+ const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, this._languageViews(tx)) });
717
909
  const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
718
910
  if (!unchanged) {
719
911
  logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
@@ -721,11 +913,22 @@ class BuildooorTxBuilder {
721
913
  }
722
914
  return finalTx;
723
915
  }
724
- /**
725
- * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
726
- * (which flags the languages of *executed* scripts). This builder only attaches
727
- * scripts inline, so the witness set carries every executed script.
728
- */
916
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
917
+ _languageViews(tx) {
918
+ return (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
919
+ }
920
+ // The ledger finds a witness datum by the hash of its bytes, so it must match the UTxO's datum hash.
921
+ // Inline-datum UTxOs need no witness datum.
922
+ _checkWitnessDatum(utxo, datum, field, hint) {
923
+ if (!utxo.datumHash || utxo.inlineDatum)
924
+ return;
925
+ const hash = (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(datum));
926
+ if (hash !== utxo.datumHash.toLowerCase()) {
927
+ throw new errors_1.TransactionValidationError(`${field} hashes to ${hash}, but ${utxo.txHash}#${utxo.outputIndex} is locked with datum hash ${utxo.datumHash}${hint}`);
928
+ }
929
+ }
930
+ // Mirrors Buildooor's initTxBuild, which flags the languages of executed scripts.
931
+ // Scripts are attached inline here, so the witness set carries every executed script.
729
932
  _usedLanguageViewOpts(tx) {
730
933
  const w = tx.witnesses;
731
934
  const opts = {
@@ -737,56 +940,154 @@ class BuildooorTxBuilder {
737
940
  opts.mustHaveV3 = true;
738
941
  return opts;
739
942
  }
740
- /**
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.)
747
- */
943
+ // Named-key models are clamped to the parameter count the library knows.
944
+ // The ledger hashes every served entry, so the raw chain arrays win where available.
748
945
  _languageViewCostModels() {
749
946
  const models = this.txBuilder.protocolParamters.costModels;
750
947
  if (Object.keys(this.rawCostModelArrays).length === 0)
751
948
  return models;
752
949
  return { ...models, ...this.rawCostModelArrays };
753
950
  }
754
- /**
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.
758
- */
759
- _partitionForcedInputs(utxos, forceInputs) {
760
- if (!forceInputs || forceInputs.length === 0)
951
+ // Builds without the sender's reference-script UTxOs first, since their script bytes raise the fee.
952
+ // When funds are short, builds again with them in the pool.
953
+ async _withRefScriptFallback(utxos, build) {
954
+ try {
955
+ return await build(false);
956
+ }
957
+ catch (err) {
958
+ if (!(err instanceof errors_1.InsufficientFundsError) || !(utxos ?? []).some(hasRefScript))
959
+ throw err;
960
+ logger.info('Funds short without the reference-script UTxOs, building again with them in the coin-selection pool');
961
+ return build(true);
962
+ }
963
+ }
964
+ // Forced inputs must be consumed. Refs absent from utxos are ignored, upstream validates them.
965
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set(), protectInputs, includeRefScriptUtxos = false) {
966
+ const excluded = (u) => !includeRefScriptUtxos && hasRefScript(u);
967
+ const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
968
+ const protectedKeys = new Set((protectInputs ?? []).map(key));
969
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && protectedKeys.size === 0 && !utxos.some(excluded)) {
761
970
  return { forced: [], rest: utxos };
762
- const forcedKeys = new Set(forceInputs.map(r => `${r.txHash}#${r.outputIndex}`));
971
+ }
972
+ const forcedKeys = new Set((forceInputs ?? []).map(key));
973
+ // a UTxO cannot be spent and referenced in one transaction
974
+ const clash = [...forcedKeys].find(k => referenced.has(k));
975
+ if (clash)
976
+ throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input; a UTxO cannot be spent and referenced in one transaction`);
977
+ const protectedClash = [...forcedKeys].find(k => protectedKeys.has(k));
978
+ if (protectedClash)
979
+ throw new errors_1.TransactionValidationError(`forceInputs ${protectedClash} is also in protectInputs`);
763
980
  const forced = [];
764
981
  const rest = [];
765
982
  for (const u of utxos) {
766
- if (forcedKeys.has(`${u.txHash}#${u.outputIndex}`))
983
+ if (forcedKeys.has(key(u)))
767
984
  forced.push(u);
768
- else
985
+ // reference inputs and protected UTxOs stay out of coin selection; UTxOs carrying a reference
986
+ // script too, until the other funds prove short (then their bytes are priced into the fee)
987
+ else if (!referenced.has(key(u)) && !protectedKeys.has(key(u)) && !excluded(u))
769
988
  rest.push(u);
770
989
  }
771
990
  return { forced, rest };
772
991
  }
773
- /**
774
- * Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO format.
775
- * Returns empty array when no reference inputs are provided.
776
- */
992
+ // Script of a withdrawal, certificate or mint. Inline scripts are swapped for a reference input
993
+ // with the same hash. No script means a key witness.
994
+ _resolveScriptWitness(w, at, referencedByHash, refUtxoByKey, scriptField = 'stakingScript') {
995
+ if (w.script) {
996
+ const script = this._parsePlutusV3Script(w.script, `${at}.${scriptField}`);
997
+ const referenced = referencedByHash.get(script.hash.toString());
998
+ return referenced ? { refLedgerUtxo: referenced } : { script };
999
+ }
1000
+ if (!w.referenceScript)
1001
+ return {};
1002
+ const refKey = `${w.referenceScript.txHash.toLowerCase()}#${w.referenceScript.outputIndex}`;
1003
+ const refUtxo = refUtxoByKey.get(refKey);
1004
+ if (!refUtxo)
1005
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} not found on-chain or already spent`);
1006
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
1007
+ if (!refLedgerUtxo.resolved.refScript) {
1008
+ throw new errors_1.TransactionValidationError(`${at}.referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
1009
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
1010
+ }
1011
+ return { refLedgerUtxo };
1012
+ }
1013
+ // Ledger order of withdrawal credential hashes, used by `__WDRL_IDX__`. Buildooor numbers
1014
+ // withdrawal redeemers by hash alone, so a build where the two orders differ is refused.
1015
+ _ledgerWithdrawalOrder(entries) {
1016
+ const withHash = entries.map(e => ({
1017
+ credentialHash: e.rewardAccount.credentials.toString().toLowerCase(),
1018
+ isScript: e.rewardAccount.type === 'script',
1019
+ scripted: Boolean(e.script || e.refLedgerUtxo),
1020
+ }));
1021
+ const ledger = (0, plutus_placeholders_1.sortWithdrawalsLikeLedger)(withHash).map(e => e.credentialHash);
1022
+ const buildooor = withHash.map(e => e.credentialHash).sort((a, b) => Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')));
1023
+ const misplaced = withHash.find(e => e.scripted && ledger.indexOf(e.credentialHash) !== buildooor.indexOf(e.credentialHash));
1024
+ if (misplaced) {
1025
+ throw new errors_1.TransactionValidationError(`withdrawals: the scripted withdrawal of credential ${misplaced.credentialHash} cannot be indexed correctly, ` +
1026
+ 'because a key-credential withdrawal sorts before it by hash; move that key withdrawal into a separate transaction');
1027
+ }
1028
+ return ledger;
1029
+ }
1030
+ // A forced input of another key address needs its owner as required signer, and the outputs
1031
+ // must spend all it brings so nothing lands in the sender's change. Script addresses are refused.
1032
+ _checkForeignForcedInputs(forced, req) {
1033
+ const sender = req.senderAddress.toLowerCase();
1034
+ const foreign = forced.filter(u => u.address.toLowerCase() !== sender);
1035
+ if (foreign.length === 0)
1036
+ return;
1037
+ const signers = new Set((req.requiredSigners ?? []).map(s => s.toLowerCase()));
1038
+ const keyOf = (u) => `${u.txHash}#${u.outputIndex}`;
1039
+ const byAddress = new Map();
1040
+ for (const u of foreign)
1041
+ byAddress.set(u.address, [...(byAddress.get(u.address) ?? []), u]);
1042
+ for (const [address, utxos] of byAddress) {
1043
+ const creds = cardano_ledger_ts_1.Address.fromString(address).paymentCreds;
1044
+ const refs = utxos.map(keyOf).join(', ');
1045
+ if (creds.type !== cardano_ledger_ts_1.CredentialType.KeyHash) {
1046
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} are at the script address ${address}; spend script UTxOs via scriptInputs`);
1047
+ }
1048
+ const keyHash = creds.hash.toString().toLowerCase();
1049
+ if (!signers.has(keyHash)) {
1050
+ throw new errors_1.TransactionValidationError(`forceInputs ${refs} belong to ${address}; its payment key hash ${keyHash} must be in requiredSigners (the owner co-signs)`);
1051
+ }
1052
+ }
1053
+ const brought = new Map();
1054
+ for (const u of foreign) {
1055
+ for (const a of u.amount) {
1056
+ const unit = a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit;
1057
+ brought.set(unit, (brought.get(unit) ?? 0n) + BigInt(a.quantity));
1058
+ }
1059
+ }
1060
+ const spent = new Map();
1061
+ for (const o of req.outputs) {
1062
+ spent.set('lovelace', (spent.get('lovelace') ?? 0n) + BigInt(o.lovelaceAmount));
1063
+ for (const a of o.assets ?? [])
1064
+ spent.set(a.unit, (spent.get(a.unit) ?? 0n) + BigInt(a.quantity));
1065
+ }
1066
+ for (const [unit, qty] of brought) {
1067
+ const out = spent.get(unit) ?? 0n;
1068
+ if (qty > out) {
1069
+ throw new errors_1.TransactionValidationError(`forceInputs of other addresses bring ${qty} ${unit} but the outputs spend only ${out}; ` +
1070
+ `the difference would go to the sender's change, return it to its owner in outputs`);
1071
+ }
1072
+ }
1073
+ }
1074
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
1075
+ _referencedKeys(ctx, ...refs) {
1076
+ const keys = new Set();
1077
+ for (const u of ctx.referenceInputUtxos ?? [])
1078
+ keys.add(`${u.txHash.toLowerCase()}#${u.outputIndex}`);
1079
+ for (const list of refs)
1080
+ for (const r of list ?? [])
1081
+ keys.add(`${r.txHash.toLowerCase()}#${r.outputIndex}`);
1082
+ return keys;
1083
+ }
1084
+ /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
777
1085
  _mapReferenceInputs(referenceInputUtxos) {
778
1086
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
779
1087
  return [];
780
1088
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
781
1089
  }
782
- /**
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).
789
- */
1090
+ // Extra outputs need their lovelace plus any asset amount the mints themselves do not cover.
790
1091
  _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
791
1092
  const mintedByUnit = new Map();
792
1093
  for (const action of mintActions) {
@@ -813,97 +1114,89 @@ class BuildooorTxBuilder {
813
1114
  }
814
1115
  return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
815
1116
  }
816
- /**
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
819
- * top-level policy script.
820
- */
1117
+ /** Per-action policy script when set, else the request's policy script. */
821
1118
  _mintActionScript(action, defaultScript, index) {
822
1119
  if (!action.mintingPolicyScript)
823
1120
  return defaultScript;
824
1121
  return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
825
1122
  }
826
- /**
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.
835
- */
836
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
1123
+ // Mint entries for all mint flows. An action may carry its own redeemer, but the ledger holds
1124
+ // one redeemer per policy, so actions on the same policy must agree.
1125
+ _buildMintEntries(mintActions, scriptFor, resolvedMintRedeemer, resolveCtx) {
837
1126
  const redeemerByPolicy = new Map();
838
1127
  return mintActions.map((action, index) => {
839
- const script = this._mintActionScript(action, mintScript, index);
1128
+ const source = scriptFor(action, index);
1129
+ const policyHash = 'inline' in source ? source.inline.hash : source.ref.resolved.refScript.hash;
840
1130
  const actionRedeemer = action.redeemerJson !== undefined
841
1131
  ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
842
1132
  : resolvedMintRedeemer;
843
1133
  const redeemerData = actionRedeemer !== undefined
844
1134
  ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
845
1135
  : new plutus_data_1.DataI(action.redeemer ?? 0);
846
- const policyId = script.hash.toString();
1136
+ const policyId = policyHash.toString();
847
1137
  // Canonical comparison over the encoded PlutusData: JSON key order must
848
1138
  // not matter, and a JSON {int:0} equals the DataI(0) fallback.
849
1139
  const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
850
1140
  const seen = redeemerByPolicy.get(policyId);
851
1141
  if (seen !== undefined && seen !== redeemerFingerprint) {
852
- throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
1142
+ throw new Error(`mint actions under policy ${policyId} carry different redeemers; the ledger allows one redeemer per policy; ` +
853
1143
  'split them into separate transactions or align the redeemers');
854
1144
  }
855
1145
  redeemerByPolicy.set(policyId, redeemerFingerprint);
856
1146
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
857
1147
  return {
858
- value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
859
- script: {
860
- inline: script,
861
- redeemer: redeemerData
862
- }
1148
+ value: cardano_ledger_ts_1.Value.singleAsset(policyHash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
1149
+ script: { ...source, redeemer: redeemerData }
863
1150
  };
864
1151
  });
865
1152
  }
866
- /**
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").
871
- */
872
- _collateralPartitionContext(collateralUtxos, fundingUtxos) {
873
- const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1153
+ // The builder's insufficient-funds message counts only the funding pool.
1154
+ // This context makes the collateral reservation visible.
1155
+ _collateralPartitionContext(collateralUtxos, fundingUtxos, forced = []) {
874
1156
  const fundingLovelace = fundingUtxos.reduce((s, u) => s + (0, tx_build_helper_1.getLovelace)(u), 0n);
875
- return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral; ` +
876
- `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
1157
+ if (collateralUtxos.length === 0) {
1158
+ return `no script runs, so no collateral; ${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
1159
+ }
1160
+ const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1161
+ const collateralKeys = new Set(collateralUtxos.map(u => `${u.utxoRef.id.toString()}#${u.utxoRef.index}`));
1162
+ const isCollateral = (u) => collateralKeys.has(`${u.txHash}#${u.outputIndex}`);
1163
+ const alsoFunding = fundingUtxos.some(isCollateral);
1164
+ const alsoForced = forced.some(isCollateral);
1165
+ return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral` +
1166
+ `${alsoFunding ? ' and also offered as funding' : alsoForced ? ' and also spent as a forced input' : ''}; ` +
1167
+ `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
877
1168
  }
878
- /**
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.
889
- */
890
- _setupCollateral(utxos) {
891
- const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
892
- if (adaOnly.length === 0) {
893
- throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
894
- }
895
- const sorted = [...adaOnly].sort((a, b) => {
1169
+ // Smallest ADA-only UTxO covering COLLATERAL_LOVELACE, else a forced sender input. Buildooor sets no
1170
+ // collateralReturn for it, so the excess is returned here. When funds are short the collateral
1171
+ // UTxO also funds the transaction, which the ledger allows.
1172
+ _setupCollateral(utxos, requiredLovelace, forced = [], senderAddress = '') {
1173
+ const byLovelace = (a, b) => {
896
1174
  const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
897
1175
  return diff < 0n ? -1 : diff > 0n ? 1 : 0;
898
- });
1176
+ };
1177
+ const coversFloor = (u) => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE;
1178
+ // ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
1179
+ const sorted = utxos.filter(tx_build_helper_1.isCollateralCandidate).sort(byLovelace);
1180
+ const sender = senderAddress.toLowerCase();
1181
+ const forcedChoice = sorted.some(coversFloor)
1182
+ ? undefined
1183
+ : forced.filter(u => u.address.toLowerCase() === sender && (0, tx_build_helper_1.isCollateralCandidate)(u) && coversFloor(u)).sort(byLovelace)[0];
1184
+ if (sorted.length === 0 && !forcedChoice) {
1185
+ throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral; create one with SetCollateral.');
1186
+ }
899
1187
  // smallest sufficient; if none reaches the floor, the largest available is the best bet
900
- const chosen = sorted.find(u => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE) ?? sorted[sorted.length - 1];
1188
+ const chosen = forcedChoice ?? sorted.find(coversFloor) ?? sorted[sorted.length - 1];
901
1189
  if ((0, tx_build_helper_1.getLovelace)(chosen) < const_1.COLLATERAL_LOVELACE) {
902
1190
  logger.warn(`Largest ADA-only UTxO (${(0, tx_build_helper_1.getLovelace)(chosen)} lovelace) is below the ${const_1.COLLATERAL_LOVELACE} lovelace ` +
903
- `collateral floor — the node will reject the transaction if collateralPercentage × fee exceeds it`);
1191
+ `collateral floor; the node will reject the transaction if collateralPercentage × fee exceeds it`);
904
1192
  }
905
1193
  const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(chosen)];
906
- const fundingUtxos = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1194
+ const rest = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1195
+ const restLovelace = rest.reduce((sum, u) => sum + (0, tx_build_helper_1.getLovelace)(u), 0n);
1196
+ // a forced input is already spent, so it is never offered to coin selection as well
1197
+ const fundingUtxos = forcedChoice || restLovelace >= requiredLovelace + const_1.FEE_BUFFER_LOVELACE + BigInt(const_1.MIN_CHANGE_LOVELACE)
1198
+ ? rest
1199
+ : [...rest, chosen];
907
1200
  // Cap the at-risk amount at the floor: return the excess to the owner.
908
1201
  let collateralReturn;
909
1202
  const excess = (0, tx_build_helper_1.getLovelace)(chosen) - const_1.COLLATERAL_LOVELACE;
@@ -913,8 +1206,7 @@ class BuildooorTxBuilder {
913
1206
  if (excess >= minAda) {
914
1207
  collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
915
1208
  }
916
- // excess below min-ADA: no return output possible — whole UTxO stays at risk,
917
- // but by selection it is the smallest sufficient one.
1209
+ // excess below min-ADA: no return output possible, the whole UTxO stays at risk
918
1210
  }
919
1211
  return { collateralUtxos, fundingUtxos, collateralReturn };
920
1212
  }
@@ -944,14 +1236,8 @@ class BuildooorTxBuilder {
944
1236
  }
945
1237
  return new cardano_ledger_ts_1.TxOut(params);
946
1238
  }
947
- /**
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).
954
- */
1239
+ // Rejects UPLC 1.0.0 code. Script.fromCbor assumes V3 and would give a wrong script hash.
1240
+ // The UPLC version is the first three flat naturals of the unwrapped script.
955
1241
  _parsePlutusV3Script(hex, field) {
956
1242
  let script;
957
1243
  try {
@@ -963,7 +1249,7 @@ class BuildooorTxBuilder {
963
1249
  }
964
1250
  const b = script.bytes;
965
1251
  if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
966
- throw new errors_1.TransactionValidationError(`${field} contains UPLC 1.0.0 code (PlutusV1/V2) — ODATANO builds Plutus V3 transactions only. ` +
1252
+ throw new errors_1.TransactionValidationError(`${field} contains UPLC 1.0.0 code (PlutusV1/V2). ODATANO builds Plutus V3 transactions only. ` +
967
1253
  `Hashing it as V3 would yield a different script hash (wrong policy ID / unspendable address).`);
968
1254
  }
969
1255
  return script;
@@ -972,27 +1258,27 @@ class BuildooorTxBuilder {
972
1258
  _parseReferenceScript(hex) {
973
1259
  if (!hex)
974
1260
  return undefined;
975
- return this._parsePlutusV3Script(hex, 'referenceScript');
1261
+ return ledgerScript(this._parsePlutusV3Script(hex, 'referenceScript'));
976
1262
  }
977
- /**
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.
982
- */
1263
+ // Uses `scriptRefCbor`. With hash and size only, a placeholder of that size stands in so the
1264
+ // fee counts its bytes.
983
1265
  _buildInputRefScript(utxo) {
984
- if (!utxo.scriptRef)
985
- return undefined;
986
- if (utxo.scriptRef.length <= 56) {
987
- logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
1266
+ const cbor = utxo.scriptRefCbor ?? undefined;
1267
+ if (!cbor) {
1268
+ if (utxo.scriptRef && utxo.scriptRefSize) {
1269
+ logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash and size only; fee counts ${utxo.scriptRefSize} bytes, local Plutus eval will not see the script`);
1270
+ return (0, reference_script_1.sizePlaceholderScript)(utxo.scriptRefSize);
1271
+ }
1272
+ if (utxo.scriptRef)
1273
+ logger.warn(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only; its reference-script fee cannot be counted, the node may reject the transaction as underpaid`);
988
1274
  return undefined;
989
1275
  }
990
1276
  try {
991
- const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
992
- // chain data, not consumer input — warn instead of rejecting
1277
+ const script = ledgerScript(cardano_ledger_ts_1.Script.fromCbor(Buffer.from(cbor, 'hex')));
1278
+ // Chain data, not consumer input, so warn instead of rejecting.
993
1279
  const b = script.bytes;
994
1280
  if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
995
- logger.warn(`Input refScript on ${utxo.txHash}#${utxo.outputIndex} is UPLC 1.0.0 (PlutusV1/V2) — treated as V3, local eval may misbehave`);
1281
+ logger.warn(`Input refScript on ${utxo.txHash}#${utxo.outputIndex} is UPLC 1.0.0 (PlutusV1/V2), treated as V3, local eval may misbehave`);
996
1282
  }
997
1283
  return script;
998
1284
  }
@@ -1002,15 +1288,10 @@ class BuildooorTxBuilder {
1002
1288
  return undefined;
1003
1289
  }
1004
1290
  }
1005
- /**
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.
1010
- */
1011
- _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
1291
+ // Buildooor sorts all inputs by txHash and outputIndex. __INPUT_IDX__ resolves against that order.
1292
+ _computeSortedInputs(scriptUtxoRefs, forcedUtxos, fundingRefs) {
1012
1293
  const all = [
1013
- { txHash: scriptUtxoRef.txHash, outputIndex: scriptUtxoRef.outputIndex },
1294
+ ...scriptUtxoRefs.map(r => ({ txHash: r.txHash, outputIndex: r.outputIndex })),
1014
1295
  ...forcedUtxos.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
1015
1296
  ...fundingRefs
1016
1297
  ];
@@ -1023,10 +1304,7 @@ class BuildooorTxBuilder {
1023
1304
  outputIndex: i.utxo.utxoRef.index
1024
1305
  }));
1025
1306
  }
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
- */
1307
+ /** Resolve __INPUT_IDX__ placeholders inside each extraOutput.inlineDatum; other fields pass through. */
1030
1308
  _resolveExtraOutputPlaceholders(extraOutputs, resolveCtx) {
1031
1309
  if (!extraOutputs || extraOutputs.length === 0)
1032
1310
  return extraOutputs;
@@ -1037,11 +1315,7 @@ class BuildooorTxBuilder {
1037
1315
  : undefined
1038
1316
  }));
1039
1317
  }
1040
- /**
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.
1044
- */
1318
+ /** Appends extra outputs. A rejection names the required min-ADA. */
1045
1319
  _appendExtraOutputs(outputs, extraOutputs) {
1046
1320
  if (!extraOutputs || extraOutputs.length === 0)
1047
1321
  return;
@@ -1060,26 +1334,27 @@ class BuildooorTxBuilder {
1060
1334
  //---------------------------------------------------------------------------
1061
1335
  // UTxO Mapping & Configuration Helpers
1062
1336
  //---------------------------------------------------------------------------
1063
- /**
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.
1068
- */
1337
+ // Every build expires: without validityEndMs one hour ahead. Script builds also start two minutes
1338
+ // ago; plain transfers set a start only when the caller asks for one. The expiry is what lets a
1339
+ // submit that got no answer be called failed once the tip has passed it.
1069
1340
  _resolveValiditySlots(req, mode) {
1070
1341
  const hasStart = req.validityStartMs !== undefined && req.validityStartMs !== null && req.validityStartMs !== '';
1071
1342
  const hasEnd = req.validityEndMs !== undefined && req.validityEndMs !== null && req.validityEndMs !== '';
1343
+ const nowMs = Date.now();
1344
+ // a start in the future moves the default expiry with it, so the range never inverts
1345
+ const endMs = hasEnd
1346
+ ? Number(req.validityEndMs)
1347
+ : Math.max(nowMs, hasStart ? Number(req.validityStartMs) : nowMs) + const_1.DEFAULT_VALIDITY_END_OFFSET_MS;
1348
+ if (endMs > nowMs + const_1.MAX_VALIDITY_MS) {
1349
+ throw new errors_1.TransactionValidationError(`The transaction would expire more than ${const_1.MAX_VALIDITY_MS / 3_600_000} hours from now; choose an earlier validityEndMs or validityStartMs`);
1350
+ }
1072
1351
  if (mode === 'passthrough') {
1073
- const result = {};
1352
+ const result = { invalidAfter: BigInt(this.txBuilder.posixToSlot(endMs)) };
1074
1353
  if (hasStart)
1075
1354
  result.invalidBefore = BigInt(this.txBuilder.posixToSlot(Number(req.validityStartMs)));
1076
- if (hasEnd)
1077
- result.invalidAfter = BigInt(this.txBuilder.posixToSlot(Number(req.validityEndMs)));
1078
1355
  return result;
1079
1356
  }
1080
- const nowMs = Date.now();
1081
1357
  const startMs = hasStart ? Number(req.validityStartMs) : nowMs - const_1.DEFAULT_VALIDITY_START_OFFSET_MS;
1082
- const endMs = hasEnd ? Number(req.validityEndMs) : nowMs + const_1.DEFAULT_VALIDITY_END_OFFSET_MS;
1083
1358
  const startSlot = this.txBuilder.posixToSlot(startMs);
1084
1359
  const endSlot = this.txBuilder.posixToSlot(endMs);
1085
1360
  return {
@@ -1087,21 +1362,16 @@ class BuildooorTxBuilder {
1087
1362
  invalidAfter: BigInt(endSlot),
1088
1363
  };
1089
1364
  }
1090
- /**
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.
1099
- */
1365
+ // A missing value keeps the library default instead of 0. For example, utxoCostPerByte = 0
1366
+ // would disable min-ADA.
1100
1367
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
1101
1368
  const pp = protocolParameters;
1102
1369
  const d = cardano_ledger_ts_1.defaultProtocolParameters;
1370
+ const major = toUInt(pp.protocolMajorVer);
1103
1371
  const mapped = {
1104
1372
  ...d,
1373
+ // Buildooor prices builtins by protocol version. Without one it takes the latest it knows.
1374
+ protocolVersion: major ? { major, minor: toUInt(pp.protocolMinorVer) ?? 0 } : undefined,
1105
1375
  txFeePerByte: toUInt(pp.minFeeA) ?? d.txFeePerByte,
1106
1376
  txFeeFixed: toUInt(pp.minFeeB) ?? d.txFeeFixed,
1107
1377
  utxoCostPerByte: toUInt(pp.coinsPerUtxoSize) ?? d.utxoCostPerByte,
@@ -1116,6 +1386,9 @@ class BuildooorTxBuilder {
1116
1386
  stakePoolTargetNum: toUInt(pp.nOpt) ?? d.stakePoolTargetNum,
1117
1387
  collateralPercentage: toUInt(pp.collateralPercent) ?? d.collateralPercentage,
1118
1388
  maxCollateralInputs: toUInt(pp.maxCollateralInputs) ?? d.maxCollateralInputs,
1389
+ minfeeRefScriptCostPerByte: pp.minFeeRefScriptCostPerByte != null && Number(pp.minFeeRefScriptCostPerByte) > 0
1390
+ ? Number(pp.minFeeRefScriptCostPerByte)
1391
+ : d.minfeeRefScriptCostPerByte,
1119
1392
  };
1120
1393
  const maxTxExMem = toUInt(pp.maxTxExMem);
1121
1394
  const maxTxExSteps = toUInt(pp.maxTxExSteps);
@@ -1137,22 +1410,13 @@ class BuildooorTxBuilder {
1137
1410
  mapped.costModels = costModels;
1138
1411
  }
1139
1412
  else {
1140
- logger.warn('Protocol parameters carry no usable cost models — keeping library defaults. ' +
1413
+ logger.warn('Protocol parameters carry no usable cost models; keeping library defaults. ' +
1141
1414
  'scriptDataHash of script transactions may not match the ledger (PPViewHashesDontMatch risk).');
1142
1415
  }
1143
1416
  return mapped;
1144
1417
  }
1145
- /**
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).
1155
- */
1418
+ // Accepts the keys 'PlutusVN', 'plutus:vN' and 'PlutusScriptVN'. Also resets rawCostModelArrays,
1419
+ // since the scriptDataHash must cover the unclamped chain arrays.
1156
1420
  _mapCostModels(costModelsJson) {
1157
1421
  this.rawCostModelArrays = {};
1158
1422
  if (!costModelsJson)
@@ -1172,7 +1436,7 @@ class BuildooorTxBuilder {
1172
1436
  PlutusV2: 'PlutusScriptV2', 'plutus:v2': 'PlutusScriptV2', PlutusScriptV2: 'PlutusScriptV2',
1173
1437
  PlutusV3: 'PlutusScriptV3', 'plutus:v3': 'PlutusScriptV3', PlutusScriptV3: 'PlutusScriptV3',
1174
1438
  };
1175
- // Buildooor's CEK Machine rejects array-form cost models — convert to named-key objects.
1439
+ // Buildooor's CEK machine rejects array-form cost models, so convert them to named-key objects.
1176
1440
  const result = {};
1177
1441
  const rawArrays = {};
1178
1442
  for (const [key, value] of Object.entries(raw)) {
@@ -1193,22 +1457,20 @@ class BuildooorTxBuilder {
1193
1457
  rawArrays[target] = arr;
1194
1458
  }
1195
1459
  catch {
1196
- logger.warn(`Cost-model array for ${key} has unexpected length (${value.length}) — skipping`);
1460
+ logger.warn(`Cost-model array for ${key} has unexpected length (${value.length}), skipping`);
1197
1461
  }
1198
1462
  }
1199
1463
  if (Object.keys(result).length === 0)
1200
1464
  return undefined;
1201
1465
  if (!(0, buildooor_1.isCostModels)(result)) {
1202
- // Buildooor would silently substitute default cost models — surface it instead.
1203
- logger.warn('Mapped cost models failed Buildooor validation — keeping library defaults');
1466
+ // Buildooor would silently substitute default cost models, so surface it instead.
1467
+ logger.warn('Mapped cost models failed Buildooor validation, keeping library defaults');
1204
1468
  return undefined;
1205
1469
  }
1206
1470
  this.rawCostModelArrays = rawArrays;
1207
1471
  return result;
1208
1472
  }
1209
- /**
1210
- * Map ODATANO UTxO to Ledger UTxO (ADA-only)
1211
- */
1473
+ /** Map an ADA-only UTxO to a Ledger UTxO. */
1212
1474
  _mapOdatanoUtxoToLedgerUtxo(utxos) {
1213
1475
  (0, tx_build_helper_1.assertAdaOnly)(utxos);
1214
1476
  return new cardano_ledger_ts_1.UTxO({
@@ -1221,15 +1483,11 @@ class BuildooorTxBuilder {
1221
1483
  })
1222
1484
  });
1223
1485
  }
1224
- /**
1225
- * Map ODATANO UTxO to Ledger UTxO (with multi-asset support)
1226
- */
1486
+ /** Map a UTxO (with multi-assets) to a Ledger UTxO. */
1227
1487
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
1228
1488
  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.
1489
+ // Inline datum wins; otherwise carry the datum HASH: Buildooor only puts a provided datum
1490
+ // preimage into the witness set when the spent output is marked with its Hash32.
1233
1491
  const datumValue = utxo.inlineDatum
1234
1492
  ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1235
1493
  : utxo.datumHash
@@ -1245,9 +1503,7 @@ class BuildooorTxBuilder {
1245
1503
  })
1246
1504
  });
1247
1505
  }
1248
- /**
1249
- * Map ODATANO metadata JSON to Ledger TxMetadata
1250
- */
1506
+ /** Map metadata JSON (label -> value) to Ledger TxMetadata. */
1251
1507
  _mapOdatanoMetadataToLedgerMetadata(metadataJson) {
1252
1508
  if (!metadataJson) {
1253
1509
  return new TxMetadata_1.TxMetadata({});
@@ -1255,32 +1511,18 @@ class BuildooorTxBuilder {
1255
1511
  const metadata = {};
1256
1512
  for (const [label, value] of Object.entries(metadataJson)) {
1257
1513
  if (!/^\d+$/.test(label)) {
1258
- throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}" — labels must be non-negative integers`);
1514
+ throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}": labels must be non-negative integers`);
1259
1515
  }
1260
1516
  metadata[Number(label)] = this._jsonToTxMetadatum(value, label);
1261
1517
  }
1262
1518
  return new TxMetadata_1.TxMetadata(metadata);
1263
1519
  }
1264
- /**
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.
1279
- */
1520
+ // Ledger rules: integers only, text over 64 bytes is chunked into a list, "0x" strings become bytes.
1521
+ // `path` is the position of `value`, for example "721.files[0].src", named in every rejection.
1280
1522
  _jsonToTxMetadatum(value, path) {
1281
1523
  if (typeof value === 'number' || typeof value === 'bigint') {
1282
1524
  if (typeof value === 'number' && !Number.isInteger(value)) {
1283
- throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value} at ${path}) — encode decimals as strings`);
1525
+ throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value} at ${path}); encode decimals as strings`);
1284
1526
  }
1285
1527
  return new TxMetadatum_1.TxMetadatumInt(BigInt(value));
1286
1528
  }
@@ -1317,7 +1559,7 @@ class BuildooorTxBuilder {
1317
1559
  return new TxMetadatum_1.TxMetadatumMap(map);
1318
1560
  }
1319
1561
  throw new errors_1.TransactionValidationError(`Unsupported metadata value type: ${value === null ? 'null' : typeof value} at ${path}` +
1320
- (typeof value === 'boolean' ? ' — on-chain metadata has no boolean; encode as string or 0/1' : ''));
1562
+ (typeof value === 'boolean' ? '; on-chain metadata has no boolean, encode as string or 0/1' : ''));
1321
1563
  }
1322
1564
  }
1323
1565
  exports.BuildooorTxBuilder = BuildooorTxBuilder;