@odatano/core 1.8.0 → 1.9.1

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 (202) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +66 -42
  2. package/@cds-models/CardanoODataService/index.d.ts.map +1 -1
  3. package/@cds-models/CardanoODataService/index.js.map +1 -1
  4. package/@cds-models/CardanoODataService/index.ts +11 -7
  5. package/@cds-models/CardanoSignService/index.d.ts +49 -0
  6. package/@cds-models/CardanoSignService/index.d.ts.map +1 -1
  7. package/@cds-models/CardanoSignService/index.js.map +1 -1
  8. package/@cds-models/CardanoSignService/index.ts +41 -0
  9. package/@cds-models/odatano/cardano/index.d.ts +70 -46
  10. package/@cds-models/odatano/cardano/index.d.ts.map +1 -1
  11. package/@cds-models/odatano/cardano/index.js +2 -2
  12. package/@cds-models/odatano/cardano/index.js.map +1 -1
  13. package/@cds-models/odatano/cardano/index.ts +13 -13
  14. package/db/schema.cds +18 -18
  15. package/db/types.cds +3 -3
  16. package/package.json +16 -2
  17. package/src/index.d.ts +29 -0
  18. package/src/index.js +1 -0
  19. package/src/plugin.d.ts +2 -0
  20. package/src/plugin.js +6 -0
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +155 -0
  22. package/srv/blockchain/backends/blockfrost-backend.js +19 -8
  23. package/srv/blockchain/backends/cardano-backend.d.ts +182 -0
  24. package/srv/blockchain/backends/koios-backend.d.ts +171 -0
  25. package/srv/blockchain/backends/koios-backend.js +69 -27
  26. package/srv/blockchain/backends/ogmios-backend.d.ts +188 -0
  27. package/srv/blockchain/backends/ogmios-backend.js +175 -108
  28. package/srv/blockchain/cardano-client.d.ts +279 -0
  29. package/srv/blockchain/cardano-client.js +134 -33
  30. package/srv/blockchain/cardano-indexer.d.ts +330 -0
  31. package/srv/blockchain/cardano-indexer.js +51 -8
  32. package/srv/blockchain/cardano-tx-builder.d.ts +113 -0
  33. package/srv/blockchain/cardano-tx-builder.js +61 -54
  34. package/srv/blockchain/circuit-breaker.d.ts +37 -0
  35. package/srv/blockchain/circuit-breaker.js +11 -2
  36. package/srv/blockchain/request-coalescer.d.ts +23 -0
  37. package/srv/blockchain/signing/cose-verifier.d.ts +34 -0
  38. package/srv/blockchain/signing/cose-verifier.js +128 -0
  39. package/srv/blockchain/signing/external-signer.d.ts +146 -0
  40. package/srv/blockchain/signing/external-signer.js +23 -0
  41. package/srv/blockchain/signing/hsm-signer.d.ts +74 -0
  42. package/srv/blockchain/signing/hsm-signer.js +20 -5
  43. package/srv/blockchain/signing/signature-verifier.d.ts +56 -0
  44. package/srv/blockchain/signing/signature-verifier.js +11 -2
  45. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +236 -0
  46. package/srv/blockchain/transaction-building/buildooor-tx.js +626 -187
  47. package/srv/blockchain/transaction-building/cardano-tx.d.ts +47 -0
  48. package/srv/cardano-service.cds +23 -3
  49. package/srv/cardano-service.d.ts +2 -0
  50. package/srv/cardano-service.js +25 -5
  51. package/srv/cardano-sign-service.cds +25 -0
  52. package/srv/cardano-sign-service.d.ts +2 -0
  53. package/srv/cardano-sign-service.js +243 -131
  54. package/srv/cardano-tx-service.d.ts +12 -0
  55. package/srv/cardano-tx-service.js +152 -110
  56. package/srv/cbor/index.d.ts +2 -0
  57. package/srv/cbor/parse.d.ts +64 -0
  58. package/srv/server.d.ts +90 -0
  59. package/srv/server.js +34 -9
  60. package/srv/utils/backend-request-handler.d.ts +20 -0
  61. package/srv/utils/const.d.ts +183 -0
  62. package/srv/utils/const.js +13 -6
  63. package/srv/utils/error-codes.d.ts +79 -0
  64. package/srv/utils/errors.d.ts +259 -0
  65. package/srv/utils/errors.js +22 -7
  66. package/srv/utils/mappers.d.ts +260 -0
  67. package/srv/utils/mappers.js +52 -17
  68. package/srv/utils/network-context.d.ts +6 -0
  69. package/srv/utils/network-context.js +27 -0
  70. package/srv/utils/plutus-placeholders.d.ts +35 -0
  71. package/srv/utils/plutus-placeholders.js +5 -15
  72. package/srv/utils/signing-helper.d.ts +23 -0
  73. package/srv/utils/signing-helper.js +5 -2
  74. package/srv/utils/tx-build-helper.d.ts +76 -0
  75. package/srv/utils/tx-build-helper.js +10 -37
  76. package/srv/utils/types.d.ts +653 -0
  77. package/srv/utils/validators.d.ts +145 -0
  78. package/srv/utils/validators.js +41 -19
  79. package/@cds-models/CardanoWatcherAdminService/index.js +0 -109
  80. package/@cds-models/CardanoWatcherAdminService/index.js.map +0 -1
  81. package/@cds-models/CardanoWatcherAdminService/index.ts +0 -263
  82. package/@cds-models/cds/outbox/index.js.map +0 -1
  83. package/@cds-models/cds/xt/MTXServices/index.js +0 -8
  84. package/@cds-models/cds/xt/MTXServices/index.js.map +0 -1
  85. package/@cds-models/cds/xt/MTXServices/index.ts +0 -4
  86. package/@cds-models/odatano/reeve/index.js +0 -77
  87. package/@cds-models/odatano/reeve/index.js.map +0 -1
  88. package/@cds-models/odatano/reeve/index.ts +0 -57
  89. package/@cds-models/odatano/transactions/index.js +0 -55
  90. package/@cds-models/odatano/transactions/index.js.map +0 -1
  91. package/@cds-models/odatano/transactions/index.ts +0 -18
  92. package/@cds-models/odatano/watch/index.js +0 -114
  93. package/@cds-models/odatano/watch/index.js.map +0 -1
  94. package/@cds-models/odatano/watch/index.ts +0 -110
  95. package/config/preview/cardano-node/alonzo-genesis.json +0 -196
  96. package/config/preview/cardano-node/byron-genesis.json +0 -117
  97. package/config/preview/cardano-node/config.json +0 -117
  98. package/config/preview/cardano-node/conway-genesis.json +0 -297
  99. package/config/preview/cardano-node/peer-snapshot.json +0 -890
  100. package/config/preview/cardano-node/shelley-genesis.json +0 -68
  101. package/config/preview/cardano-node/topology.json +0 -24
  102. package/output/sora/iter0_base.json +0 -32
  103. package/output/sora/iter0_base.mp4 +0 -0
  104. package/output/sora/logo_ref_1280x720.png +0 -0
  105. package/output/sora/odatano_full_logo_sky_ref_1280x720.png +0 -0
  106. package/output/sora/odatano_full_logo_transparent.png +0 -0
  107. package/output/sora/odatano_full_logo_transparent_dark.png +0 -0
  108. package/output/sora/odatano_full_logo_v4_8s.json +0 -32
  109. package/output/sora/odatano_full_logo_v4_8s.mp4 +0 -0
  110. package/output/sora/odatano_full_logo_v5_create.json +0 -15
  111. package/output/sora/odatano_full_logo_v5_fixes.json +0 -15
  112. package/output/sora/odatano_full_logo_v5_fixes.mp4 +0 -0
  113. package/output/sora/odatano_logo_v1.json +0 -32
  114. package/output/sora/odatano_logo_v1.mp4 +0 -0
  115. package/output/sora/odatano_o_only_clean.png +0 -0
  116. package/output/sora/odatano_o_sky_ref_1280x720.png +0 -0
  117. package/output/sora/odatano_o_sky_v2_8s.json +0 -32
  118. package/output/sora/odatano_o_sky_v2_8s.mp4 +0 -0
  119. package/output/sora/odatano_o_sky_v3_create.json +0 -15
  120. package/output/sora/odatano_o_sky_v3_splash_text.json +0 -15
  121. package/output/sora/odatano_o_sky_v3_splash_text.mp4 +0 -0
  122. package/output/sora/odatano_v6_composite_exact_logo.mp4 +0 -0
  123. package/output/sora/odatano_v6_composite_exact_logo_clean.mp4 +0 -0
  124. package/output/sora/odatano_v6_composite_exact_logo_final.mp4 +0 -0
  125. package/output/sora/odatano_v6_endframe.jpg +0 -0
  126. package/output/sora/odatano_v6_endframe_clean.jpg +0 -0
  127. package/output/sora/odatano_v6_endframe_final.jpg +0 -0
  128. package/output/sora/odatano_v7_1_earlylogo_fadeoldtext.mp4 +0 -0
  129. package/output/sora/odatano_v7_1_end.jpg +0 -0
  130. package/output/sora/odatano_v7_1_transition.jpg +0 -0
  131. package/output/sora/odatano_v7_2_original2d_keep_sky.mp4 +0 -0
  132. package/output/sora/odatano_v7_endframe_nobg.jpg +0 -0
  133. package/output/sora/odatano_v7_endframe_nobg_cleanend.jpg +0 -0
  134. package/output/sora/odatano_v7_spin_splash_logo_nobg.mp4 +0 -0
  135. package/output/sora/odatano_v7_spin_splash_logo_nobg_cleanend.mp4 +0 -0
  136. package/prod.mtaext +0 -17
  137. package/prod.mtaext.example +0 -27
  138. package/review.md +0 -42
  139. package/src/index.d.ts.map +0 -1
  140. package/src/index.js.map +0 -1
  141. package/src/plugin.d.ts.map +0 -1
  142. package/src/plugin.js.map +0 -1
  143. package/srv/blockchain/backends/blockfrost-backend.d.ts.map +0 -1
  144. package/srv/blockchain/backends/blockfrost-backend.js.map +0 -1
  145. package/srv/blockchain/backends/cardano-backend.d.ts.map +0 -1
  146. package/srv/blockchain/backends/cardano-backend.js.map +0 -1
  147. package/srv/blockchain/backends/koios-backend.d.ts.map +0 -1
  148. package/srv/blockchain/backends/koios-backend.js.map +0 -1
  149. package/srv/blockchain/backends/ogmios-backend.d.ts.map +0 -1
  150. package/srv/blockchain/backends/ogmios-backend.js.map +0 -1
  151. package/srv/blockchain/cardano-client.d.ts.map +0 -1
  152. package/srv/blockchain/cardano-client.js.map +0 -1
  153. package/srv/blockchain/cardano-indexer.d.ts.map +0 -1
  154. package/srv/blockchain/cardano-indexer.js.map +0 -1
  155. package/srv/blockchain/cardano-tx-builder.d.ts.map +0 -1
  156. package/srv/blockchain/cardano-tx-builder.js.map +0 -1
  157. package/srv/blockchain/circuit-breaker.d.ts.map +0 -1
  158. package/srv/blockchain/circuit-breaker.js.map +0 -1
  159. package/srv/blockchain/request-coalescer.d.ts.map +0 -1
  160. package/srv/blockchain/request-coalescer.js.map +0 -1
  161. package/srv/blockchain/signing/external-signer.d.ts.map +0 -1
  162. package/srv/blockchain/signing/external-signer.js.map +0 -1
  163. package/srv/blockchain/signing/hsm-signer.d.ts.map +0 -1
  164. package/srv/blockchain/signing/hsm-signer.js.map +0 -1
  165. package/srv/blockchain/signing/signature-verifier.d.ts.map +0 -1
  166. package/srv/blockchain/signing/signature-verifier.js.map +0 -1
  167. package/srv/blockchain/transaction-building/buildooor-tx.d.ts.map +0 -1
  168. package/srv/blockchain/transaction-building/buildooor-tx.js.map +0 -1
  169. package/srv/blockchain/transaction-building/cardano-tx.d.ts.map +0 -1
  170. package/srv/blockchain/transaction-building/cardano-tx.js.map +0 -1
  171. package/srv/cardano-service.d.ts.map +0 -1
  172. package/srv/cardano-service.js.map +0 -1
  173. package/srv/cardano-sign-service.d.ts.map +0 -1
  174. package/srv/cardano-sign-service.js.map +0 -1
  175. package/srv/cardano-tx-service.d.ts.map +0 -1
  176. package/srv/cardano-tx-service.js.map +0 -1
  177. package/srv/cbor/index.d.ts.map +0 -1
  178. package/srv/cbor/index.js.map +0 -1
  179. package/srv/cbor/parse.d.ts.map +0 -1
  180. package/srv/cbor/parse.js.map +0 -1
  181. package/srv/server.d.ts.map +0 -1
  182. package/srv/server.js.map +0 -1
  183. package/srv/utils/backend-request-handler.d.ts.map +0 -1
  184. package/srv/utils/backend-request-handler.js.map +0 -1
  185. package/srv/utils/const.d.ts.map +0 -1
  186. package/srv/utils/const.js.map +0 -1
  187. package/srv/utils/error-codes.d.ts.map +0 -1
  188. package/srv/utils/error-codes.js.map +0 -1
  189. package/srv/utils/errors.d.ts.map +0 -1
  190. package/srv/utils/errors.js.map +0 -1
  191. package/srv/utils/mappers.d.ts.map +0 -1
  192. package/srv/utils/mappers.js.map +0 -1
  193. package/srv/utils/plutus-placeholders.d.ts.map +0 -1
  194. package/srv/utils/plutus-placeholders.js.map +0 -1
  195. package/srv/utils/signing-helper.d.ts.map +0 -1
  196. package/srv/utils/signing-helper.js.map +0 -1
  197. package/srv/utils/tx-build-helper.d.ts.map +0 -1
  198. package/srv/utils/tx-build-helper.js.map +0 -1
  199. package/srv/utils/types.d.ts.map +0 -1
  200. package/srv/utils/types.js.map +0 -1
  201. package/srv/utils/validators.d.ts.map +0 -1
  202. package/srv/utils/validators.js.map +0 -1
@@ -11,6 +11,10 @@ const errors_1 = require("../../utils/errors");
11
11
  const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
12
12
  const cds_1 = __importDefault(require("@sap/cds"));
13
13
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
14
+ // Metadata classes are imported from the DIST paths ON PURPOSE: buildooor's
15
+ // AuxiliaryData/TxMetadata do internal `instanceof` checks against these exact
16
+ // dist-class identities, which differ from the package-root re-exports. Mixing
17
+ // root + dist identities breaks those checks at runtime. (See cbor-parse.test.)
14
18
  const TxMetadata_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadata");
15
19
  const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadatum");
16
20
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
@@ -19,23 +23,110 @@ const logger = cds_1.default.log('BuildooorTxBuilder');
19
23
  /**
20
24
  * Build options for script-bearing transactions.
21
25
  *
22
- * Buildooor evaluates every Plutus script locally during `build()`. Without an
23
- * `onScriptInvalid` handler, a script that fails that local evaluation makes `build()`
24
- * throw and aborts the whole build. The build endpoints only ever produce an *unsigned*
25
- * transaction — on-chain validation at submit time is authoritative — so a local
26
- * evaluation failure should not block returning the CBOR + fee estimate. This restores
27
- * the pre-Buildooor (CSL) contract, where the builder never executed scripts at all.
26
+ * Buildooor evaluates every Plutus script locally during `build()` and unconditionally
27
+ * stamps each redeemer with the budget its local CEK run consumed (`onEvaluationResult`
28
+ * in TxBuilder) — execution units passed in the build args are never read. Without an
29
+ * `onScriptInvalid` handler a local evaluation failure aborts the build; *with* one the
30
+ * redeemer is left carrying the partial budget consumed up to the error, which would
31
+ * fail phase-2 on-chain and forfeit the collateral if signed and submitted.
28
32
  *
29
- * Validators that pass local evaluation never trigger this callback, so real script
30
- * failures surfaced by Ogmios (`ctx.evaluateTransaction`) are still reported upstream.
33
+ * We therefore only record local failures here; `_buildScriptTx` decides afterwards:
34
+ * an authoritative Ogmios evaluation overrides the local result (so local false
35
+ * negatives — e.g. cost-model drift — don't block the build), while a failure without
36
+ * Ogmios aborts with a clear error instead of returning an unsubmittable transaction.
31
37
  */
32
- const SCRIPT_BUILD_OPTS = {
33
- onScriptInvalid: (rdmr, logs) => {
34
- logger.warn(`Plutus script failed local evaluation (redeemer index ${rdmr.index.toString()}); ` +
35
- `returning unsigned tx anyway — on-chain validation is authoritative. ` +
36
- `Logs: [${logs.join(', ')}]`);
37
- }
38
+ function makeScriptBuildOpts(failures) {
39
+ return {
40
+ onScriptInvalid: (rdmr, logs) => {
41
+ failures.push({ tag: rdmr.tag, index: rdmr.index, logs: logs.slice() });
42
+ logger.warn(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(rdmr.tag)}:${rdmr.index}); ` +
43
+ `deferring to Ogmios evaluation if available. Logs: [${logs.join(', ')}]`);
44
+ }
45
+ };
46
+ }
47
+ const redeemerKey = (tag, index) => `${tag}:${index}`;
48
+ /** Ogmios RedeemerPointer purpose → ledger TxRedeemerTag (Ogmios v6 wire names). */
49
+ const PURPOSE_TO_TAG = {
50
+ spend: cardano_ledger_ts_1.TxRedeemerTag.Spend,
51
+ mint: cardano_ledger_ts_1.TxRedeemerTag.Mint,
52
+ publish: cardano_ledger_ts_1.TxRedeemerTag.Cert,
53
+ certificate: cardano_ledger_ts_1.TxRedeemerTag.Cert,
54
+ withdraw: cardano_ledger_ts_1.TxRedeemerTag.Withdraw,
55
+ withdrawal: cardano_ledger_ts_1.TxRedeemerTag.Withdraw
38
56
  };
57
+ /** CBOR-encoded length in bytes of an unsigned integer head + payload. */
58
+ function cborUIntLength(n) {
59
+ if (n < 24n)
60
+ return 1n;
61
+ if (n < 256n)
62
+ return 2n;
63
+ if (n < 65536n)
64
+ return 3n;
65
+ if (n < 4294967296n)
66
+ return 5n;
67
+ return 9n;
68
+ }
69
+ function ceilDiv(a, b) {
70
+ return (a + b - 1n) / b;
71
+ }
72
+ function maxBig(a, b) {
73
+ return a > b ? a : b;
74
+ }
75
+ /**
76
+ * Parse a ledger protocol-parameter value (number or decimal string) into a
77
+ * non-negative safe integer. Returns undefined for null/undefined/empty/invalid
78
+ * input so callers can fall back to library defaults instead of silently
79
+ * coercing to 0 (which e.g. disables min-ADA when applied to utxoCostPerByte).
80
+ */
81
+ function toUInt(value) {
82
+ if (value === null || value === undefined || value === '')
83
+ return undefined;
84
+ const n = Number(value);
85
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
86
+ }
87
+ /** Parse a strictly positive finite number (e.g. exUnit prices); undefined when absent/invalid. */
88
+ function toPositiveNumber(value) {
89
+ if (value === null || value === undefined || value === '')
90
+ return undefined;
91
+ const n = Number(value);
92
+ return Number.isFinite(n) && n > 0 ? n : undefined;
93
+ }
94
+ /**
95
+ * Stable identity of a protocol-parameter set. Params only change at epoch
96
+ * boundaries, so network#epoch is sufficient; fall back to full JSON when
97
+ * either field is missing.
98
+ */
99
+ function protocolParamsFingerprint(p) {
100
+ if (p.network && p.epoch !== undefined && p.epoch !== null)
101
+ return `${p.network}#${p.epoch}`;
102
+ return JSON.stringify(p);
103
+ }
104
+ /** Ledger limit for a single text/bytes metadatum (bytes, not characters). */
105
+ const METADATA_BYTE_LIMIT = 64;
106
+ /**
107
+ * Split a string into pieces of at most maxBytes UTF-8 bytes each, never
108
+ * splitting inside a code point (which would produce invalid UTF-8 on-chain).
109
+ */
110
+ function chunkUtf8(str, maxBytes) {
111
+ const chunks = [];
112
+ let current = '';
113
+ let currentBytes = 0;
114
+ for (const ch of str) {
115
+ const chBytes = Buffer.byteLength(ch, 'utf8');
116
+ if (currentBytes + chBytes > maxBytes) {
117
+ chunks.push(current);
118
+ current = ch;
119
+ currentBytes = chBytes;
120
+ }
121
+ else {
122
+ current += ch;
123
+ currentBytes += chBytes;
124
+ }
125
+ }
126
+ if (current.length > 0 || chunks.length === 0)
127
+ chunks.push(current);
128
+ return chunks;
129
+ }
39
130
  /**
40
131
  * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
41
132
  */
@@ -43,6 +134,8 @@ class BuildooorTxBuilder {
43
134
  name = 'BuildooorTxBuilder';
44
135
  txBuilder;
45
136
  cardanoClient;
137
+ genesisInfos;
138
+ paramsFingerprint;
46
139
  /**
47
140
  * Initialize the builder
48
141
  * @param client - The CardanoClient instance
@@ -51,19 +144,56 @@ class BuildooorTxBuilder {
51
144
  async init(client, protocolParams) {
52
145
  this.cardanoClient = client;
53
146
  const params = protocolParams ?? await client.getProtocolParameters();
54
- const txbParameters = this._mapLedgerParametersToBuildooorParams(params);
55
147
  const genesisInfos = const_1.GENESIS_INFOS_BY_NETWORK[client.network];
56
148
  if (!genesisInfos) {
57
149
  throw new errors_1.ConfigError(`BuildooorTxBuilder: no genesis presets for network "${client.network}"`);
58
150
  }
59
- this.txBuilder = new buildooor_1.TxBuilder(txbParameters, genesisInfos);
151
+ this.genesisInfos = genesisInfos;
152
+ this._applyProtocolParameters(params, protocolParamsFingerprint(params));
60
153
  logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
61
154
  }
62
155
  /**
63
- * Build unsigned transfer transaction (ADA-only or with native assets)
156
+ * Rebuild the TxBuilder when the per-request protocol parameters differ from
157
+ * the ones the current TxBuilder was constructed with. Buildooor's TxBuilder
158
+ * has no setter for protocol params, but its constructor is cheap, so we
159
+ * rebuild on change (effectively once per epoch) instead of staying frozen
160
+ * at init-time parameters for the process lifetime.
64
161
  */
65
- async buildUnsignedTransfer(req, ctx) {
162
+ _ensureCurrentProtocolParameters(ctx) {
163
+ const params = ctx.protocolParameters;
164
+ if (!params)
165
+ return;
166
+ const fingerprint = protocolParamsFingerprint(params);
167
+ if (fingerprint === this.paramsFingerprint)
168
+ return;
169
+ this._applyProtocolParameters(params, fingerprint);
170
+ logger.info(`Refreshed protocol parameters (${fingerprint})`);
171
+ }
172
+ _applyProtocolParameters(params, fingerprint) {
173
+ this.txBuilder = new buildooor_1.TxBuilder(this._mapLedgerParametersToBuildooorParams(params), this.genesisInfos);
174
+ this.paramsFingerprint = fingerprint;
175
+ }
176
+ /**
177
+ * Build unsigned transfer transaction (ADA-only or with native assets).
178
+ */
179
+ buildUnsignedTransfer(req, ctx) {
180
+ return this._buildSimpleTransfer(req, ctx, 'transfer');
181
+ }
182
+ /**
183
+ * Build unsigned transfer transaction with attached metadata.
184
+ */
185
+ buildUnsignedTransactionWithMetadata(req, ctx) {
186
+ return this._buildSimpleTransfer(req, ctx, 'metadata transfer');
187
+ }
188
+ /**
189
+ * Shared non-script transfer build. The two public entry points only differ in
190
+ * the optional pieces of the request they carry (assets/outputDatum on the
191
+ * plain-transfer path, metadataJson on the metadata path) — all handled here
192
+ * conditionally on the field being present, so behaviour matches both.
193
+ */
194
+ async _buildSimpleTransfer(req, ctx, label) {
66
195
  try {
196
+ this._ensureCurrentProtocolParameters(ctx);
67
197
  if (!ctx.utxos || ctx.utxos.length === 0) {
68
198
  throw new errors_1.InsufficientFundsError('lovelace', BigInt(req.lovelaceAmount || 0), 0n);
69
199
  }
@@ -84,34 +214,12 @@ class BuildooorTxBuilder {
84
214
  // Coin selection on candidates only; forced inputs are prepended unconditionally
85
215
  const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
86
216
  const inputs = [...forcedInputs, ...selected];
87
- logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for transfer`);
88
- const validity = this._resolveValiditySlots(req, 'passthrough');
89
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...validity });
90
- logger.debug(`Built unsigned transaction successfully.`);
91
- return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
92
- }
93
- catch (err) {
94
- (0, tx_build_helper_1.mapBuilderError)(err);
95
- }
96
- }
97
- async buildUnsignedTransactionWithMetadata(req, ctx) {
98
- try {
99
- const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
100
- const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
101
- const amount = BigInt(String(req.lovelaceAmount));
102
- const metadata = this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson);
103
- const outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
104
- const refScript = this._parseReferenceScript(req.referenceScript);
105
- const outputs = [this._buildTxOut(recipientAddress, outputValue, undefined, refScript)];
106
- // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
107
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
108
- const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
109
- const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
110
- const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
111
- const inputs = [...forcedInputs, ...selected];
112
- logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for metadata transfer`);
217
+ logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for ${label}`);
218
+ const metadata = req.metadataJson !== undefined && req.metadataJson !== null
219
+ ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
220
+ : undefined;
113
221
  const validity = this._resolveValiditySlots(req, 'passthrough');
114
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, metadata, ...validity });
222
+ const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity });
115
223
  logger.debug(`Built unsigned transaction successfully.`);
116
224
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
117
225
  }
@@ -121,11 +229,11 @@ class BuildooorTxBuilder {
121
229
  }
122
230
  async buildUnsignedMintTransaction(req, ctx) {
123
231
  try {
232
+ this._ensureCurrentProtocolParameters(ctx);
124
233
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
125
234
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
126
235
  // Parse the minting policy script once
127
- const scriptBytes = Buffer.from(req.mintingPolicyScript, 'hex');
128
- const script = cardano_ledger_ts_1.Script.fromCbor(scriptBytes);
236
+ const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
129
237
  // Calculate total mint value for output (only positive quantities - mints, not burns)
130
238
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
131
239
  for (const mintAction of req.mintActions) {
@@ -140,7 +248,7 @@ class BuildooorTxBuilder {
140
248
  const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
141
249
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
142
250
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
143
- const { collateralUtxos, fundingUtxos } = this._setupCollateral(rest);
251
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
144
252
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
145
253
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
146
254
  // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
@@ -165,24 +273,10 @@ class BuildooorTxBuilder {
165
273
  outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
166
274
  const refScript = this._parseReferenceScript(req.referenceScript);
167
275
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
168
- // Helper to build mints array with specified execution units (uses pre-resolved redeemer)
169
- const buildMints = (exUnits) => {
170
- const mints = [];
171
- for (const mintAction of req.mintActions) {
172
- const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
173
- mints.push({
174
- value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(mintAction.quantity)),
175
- script: {
176
- inline: script,
177
- redeemer: resolvedMintRedeemer
178
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
179
- : new plutus_data_1.DataI(mintAction.redeemer ?? 0),
180
- executionUnits: exUnits
181
- }
182
- });
183
- }
184
- return mints;
185
- };
276
+ // Mint entries for the build args (uses pre-resolved redeemer). Note: Buildooor
277
+ // ignores caller-supplied execution units — the real units are stamped into the
278
+ // redeemers post-build by _buildScriptTx.
279
+ const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
186
280
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
187
281
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
188
282
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
@@ -193,26 +287,17 @@ class BuildooorTxBuilder {
193
287
  const mintMetadata = req.metadataJson
194
288
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
195
289
  : undefined;
196
- // Evaluate execution units
197
- const finalExUnits = await this._evaluateExUnits(async () => {
198
- const evalTx = await this.txBuilder.build({
199
- inputs, outputs, changeAddress, mints: buildMints(const_1.HIGH_EXECUTION_UNITS),
200
- collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
201
- invalidBefore, invalidAfter,
202
- ...(mintMetadata && { metadata: mintMetadata }),
203
- ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
204
- }, SCRIPT_BUILD_OPTS);
205
- return (0, uint8array_utils_1.toHex)(evalTx.toCbor());
206
- }, ctx.evaluateTransaction);
207
- // Build with final execution units + witness buffer
208
- const mints = buildMints(finalExUnits);
209
- const tx = await this._buildWithWitnessBuffer({
290
+ // Single set of build args — both internal passes and the Ogmios evaluation share
291
+ // validity bounds and metadata so redeemer ExUnits and fee stay consistent.
292
+ const buildParams = {
210
293
  inputs, outputs, changeAddress, mints,
211
294
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
212
295
  invalidBefore, invalidAfter,
296
+ ...(collateralReturn && { collateralReturn }),
213
297
  ...(mintMetadata && { metadata: mintMetadata }),
214
298
  ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
215
- });
299
+ };
300
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
216
301
  logger.debug(`Built unsigned minting transaction successfully with fee: ${tx.body.fee.toString()}`);
217
302
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
218
303
  }
@@ -222,10 +307,10 @@ class BuildooorTxBuilder {
222
307
  }
223
308
  async buildUnsignedPlutusSpendTransaction(req, ctx) {
224
309
  try {
310
+ this._ensureCurrentProtocolParameters(ctx);
225
311
  const { plutusScriptExecution } = req;
226
312
  // Parse the validator script
227
- const scriptBytes = Buffer.from(plutusScriptExecution.validatorScript, 'hex');
228
- const script = cardano_ledger_ts_1.Script.fromCbor(scriptBytes);
313
+ const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
229
314
  if (!plutusScriptExecution.datum) {
230
315
  // When no explicit datum is provided, the UTxO must have an inline datum.
231
316
  // If neither exists, the Plutus validator will fail with a cryptic error.
@@ -247,7 +332,7 @@ class BuildooorTxBuilder {
247
332
  const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
248
333
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
249
334
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
250
- const { collateralUtxos, fundingUtxos } = this._setupCollateral(rest);
335
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
251
336
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
252
337
  // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
253
338
  // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
@@ -282,7 +367,7 @@ class BuildooorTxBuilder {
282
367
  let mintScript;
283
368
  let mintScriptHash;
284
369
  if (hasMint) {
285
- mintScript = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(req.mintingPolicyScript, 'hex'));
370
+ mintScript = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
286
371
  mintScriptHash = mintScript.hash.toString();
287
372
  }
288
373
  // Build outputs — include multi-assets from script UTxO in continuing output
@@ -306,59 +391,33 @@ class BuildooorTxBuilder {
306
391
  // Append extra outputs (FR-2). Each is independently min-ADA checked so consumers
307
392
  // get a clear, field-attributed error before Buildooor's coin selection runs.
308
393
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
309
- // Helper to build mints array (FR-1) with specified execution units
310
- const buildMints = hasMint
311
- ? (exUnits) => req.mintActions.map(action => {
312
- const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
313
- return {
314
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
315
- script: {
316
- inline: mintScript,
317
- redeemer: resolvedMintRedeemer
318
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
319
- : new plutus_data_1.DataI(action.redeemer ?? 0),
320
- executionUnits: exUnits
321
- }
322
- };
323
- })
394
+ // Mint entries (FR-1) and inputs for the build args. Note: Buildooor ignores
395
+ // caller-supplied execution units — the real units are stamped into the
396
+ // redeemers post-build by _buildScriptTx.
397
+ const mints = hasMint
398
+ ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
324
399
  : undefined;
325
- // Helper to build inputs with specified execution units
326
- const buildInputs = (exUnits) => {
327
- const scriptInput = {
328
- utxo: scriptLedgerUtxo,
329
- inputScript: { script, datum, redeemer: redeemerData, executionUnits: exUnits }
330
- };
331
- return [scriptInput, ...forcedInputs, ...selectedFundingInputs];
400
+ const scriptInput = {
401
+ utxo: scriptLedgerUtxo,
402
+ inputScript: { script, datum, redeemer: redeemerData }
332
403
  };
404
+ const inputs = [scriptInput, ...forcedInputs, ...selectedFundingInputs];
333
405
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
334
406
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
335
407
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
336
408
  // and fee computation stay consistent (a mismatch would force re-evaluation).
337
409
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
338
- // Evaluate execution units
339
- const finalExUnits = await this._evaluateExUnits(async () => {
340
- const evalTx = await this.txBuilder.build({
341
- inputs: buildInputs(const_1.HIGH_EXECUTION_UNITS), outputs, changeAddress,
342
- mints: buildMints?.(const_1.HIGH_EXECUTION_UNITS),
343
- collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
344
- invalidBefore, invalidAfter,
345
- ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
346
- }, SCRIPT_BUILD_OPTS);
347
- if (!evalTx) {
348
- throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null — check inputs, datum, and collateral configuration');
349
- }
350
- return (0, uint8array_utils_1.toHex)(evalTx.toCbor());
351
- }, ctx.evaluateTransaction);
352
- // Build with final execution units + witness buffer
353
- const inputs = buildInputs(finalExUnits);
354
- const mints = buildMints?.(finalExUnits);
355
- const tx = await this._buildWithWitnessBuffer({
410
+ // Single set of build args — both internal passes and the Ogmios evaluation share
411
+ // validity bounds so redeemer ExUnits and fee stay consistent.
412
+ const buildParams = {
356
413
  inputs, outputs, changeAddress,
357
414
  mints,
358
415
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
359
416
  invalidBefore, invalidAfter,
417
+ ...(collateralReturn && { collateralReturn }),
360
418
  ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
361
- });
419
+ };
420
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
362
421
  logger.debug(`Built unsigned Plutus spending transaction successfully with fee: ${tx.body.fee.toString()}`);
363
422
  return this._buildResult(req, ctx, this._extractTxDetails(tx), {
364
423
  scriptHash: script.hash.toString(),
@@ -418,45 +477,227 @@ class BuildooorTxBuilder {
418
477
  };
419
478
  }
420
479
  /**
421
- * Evaluate execution units via callback. Caller provides an async function
422
- * that builds the evaluation tx and returns its CBOR hex.
480
+ * Build a script-bearing transaction whose redeemers carry *real* execution units and
481
+ * whose fee covers them.
482
+ *
483
+ * Background (verified against the vendored Buildooor source): `initTxBuild` constructs
484
+ * every redeemer with a dummy budget — caller-supplied execution units in the build args
485
+ * are never read — and `onEvaluationResult` unconditionally stamps each redeemer with
486
+ * the budget the local CEK run consumed, even when the script failed (partial budget).
487
+ * So the declared units are whatever the *local* evaluation produced, and any cushion
488
+ * passed into the args silently evaporates. This method makes the declared units real:
489
+ *
490
+ * 1. First pass: build once; redeemers now carry the local CEK budgets.
491
+ * 2. Evaluate that CBOR via Ogmios (when configured) for authoritative per-redeemer
492
+ * budgets, cushioned by EXECUTION_UNIT_BUFFER / ABS_*_BUFFER.
493
+ * 3. Resolve target units per redeemer (Ogmios beats buffered-local; a local failure
494
+ * without an Ogmios result aborts — see makeScriptBuildOpts).
495
+ * 4. Second pass with a fee floor covering the target units (Buildooor prices the fee
496
+ * from its own local budgets, so the floor adds the price + encoding-size delta).
497
+ * 5. Stamp the target units into the redeemers and recompute scriptDataHash.
423
498
  */
424
- async _evaluateExUnits(buildEvalTx, evaluator) {
499
+ async _buildScriptTx(buildParams, evaluator) {
500
+ const pass1Failures = [];
501
+ const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
502
+ if (!tx1) {
503
+ throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null — check inputs, datum, and collateral configuration');
504
+ }
505
+ const rdmrs1 = tx1.witnesses.redeemers ?? [];
506
+ if (rdmrs1.length === 0) {
507
+ // Defensive — callers always attach a script. Nothing to evaluate or stamp,
508
+ // and Buildooor's calcMinFee already budgets the vkey witnesses to come.
509
+ return tx1;
510
+ }
511
+ // The first-pass CBOR is exactly what a dedicated "evaluation build" would produce
512
+ // (identical args ⇒ identical tx, since passed ExUnits are ignored anyway).
513
+ const evaluatedUnits = evaluator
514
+ ? await this._evaluateExUnitsByRedeemer((0, uint8array_utils_1.toHex)(tx1.toCbor()), evaluator)
515
+ : undefined;
425
516
  if (!evaluator) {
426
- logger.debug('No evaluator available, using default execution units');
427
- return const_1.DEFAULT_EXECUTION_UNITS;
517
+ logger.debug('No evaluator available — falling back to buffered local execution units');
428
518
  }
429
- logger.debug('Building evaluation pass with high execution units');
430
- const evalTxCbor = await buildEvalTx();
519
+ const targets1 = this._resolveTargetExUnits(rdmrs1, evaluatedUnits, pass1Failures);
520
+ // Fee floor: Buildooor's fee covers its local budgets AND the vkey witnesses to
521
+ // come (calcMinFee budgets 104 bytes per estimated signer); add only the price
522
+ // delta of the stamped units, their (slightly longer) CBOR encoding, and a small
523
+ // pad for change-output size wobble between the two passes.
524
+ const feeFloor = BigInt(tx1.body.fee.toString())
525
+ + this._exUnitsPriceDelta(rdmrs1, targets1)
526
+ + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
527
+ + 10n * this._txFeePerByte();
528
+ const pass2Failures = [];
529
+ const tx2 = await this.txBuilder.build({ ...buildParams, fee: feeFloor }, makeScriptBuildOpts(pass2Failures));
530
+ const rdmrs2 = tx2.witnesses.redeemers ?? [];
531
+ const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
532
+ return this._stampExecUnits(tx2, targets2);
533
+ }
534
+ /**
535
+ * Evaluate a transaction via Ogmios and return cushioned budgets keyed per redeemer
536
+ * (`tag:index`). Returns undefined when the evaluation is unusable (transient backend
537
+ * failure, empty result) so callers fall back to buffered local units. A
538
+ * TransactionValidationError or ScriptValidationError from the evaluator is
539
+ * authoritative (the script really failed on the ledger) and is rethrown.
540
+ */
541
+ async _evaluateExUnitsByRedeemer(evalTxCbor, evaluator) {
431
542
  try {
432
543
  const evalResults = await evaluator(evalTxCbor);
433
544
  logger.debug(`Evaluation results: ${JSON.stringify(evalResults)}`);
434
- if (evalResults && evalResults.length > 0) {
435
- const budget = evalResults[0].budget;
436
- // Combined cushion: relative multiplier catches proportional drift on large
437
- // validators, absolute floor catches sub-percent drift on small ones (observed
438
- // when metadata affects the real tx body vs the evaluator's ScriptContext).
439
- const result = {
440
- mem: Math.ceil(budget.memory * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER,
441
- cpu: Math.ceil(budget.cpu * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER
442
- };
443
- logger.info(`Using evaluated execution units: mem=${result.mem}, cpu=${result.cpu}`);
444
- return result;
545
+ if (!evalResults || evalResults.length === 0)
546
+ return undefined;
547
+ const byRedeemer = new Map();
548
+ for (const result of evalResults) {
549
+ const v = result.validator;
550
+ let purpose;
551
+ let index;
552
+ if (typeof v === 'string') {
553
+ // Legacy "purpose:index" form
554
+ const [p, i] = v.split(':');
555
+ purpose = p;
556
+ index = Number(i);
557
+ }
558
+ else {
559
+ purpose = v.purpose;
560
+ index = Number(v.index);
561
+ }
562
+ const tag = PURPOSE_TO_TAG[purpose];
563
+ if (tag === undefined || !Number.isInteger(index)) {
564
+ logger.warn(`Skipping evaluation result with unrecognized validator pointer: ${JSON.stringify(v)}`);
565
+ continue;
566
+ }
567
+ byRedeemer.set(redeemerKey(tag, index), this._applyExUnitBuffer(result.budget.memory, result.budget.cpu));
445
568
  }
569
+ return byRedeemer.size > 0 ? byRedeemer : undefined;
446
570
  }
447
571
  catch (evalError) {
572
+ if (evalError instanceof errors_1.TransactionValidationError || evalError instanceof errors_1.ScriptValidationError) {
573
+ // Authoritative: Ogmios executed the script and the ledger rejected it. This is
574
+ // either a TransactionValidationError or, after normalizeBackendError, a
575
+ // ScriptValidationError (PlutusFailure / CekError / budget overspend). Falling
576
+ // back to local buffered units here would hand back a transaction the node has
577
+ // already rejected — so propagate the failure instead.
578
+ throw evalError;
579
+ }
448
580
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
449
- logger.warn(`Evaluation failed, using default units: ${msg}`);
581
+ logger.warn(`Evaluation failed (transient), falling back to local execution units: ${msg}`);
582
+ return undefined;
583
+ }
584
+ }
585
+ /**
586
+ * Combined cushion: relative multiplier catches proportional drift on large
587
+ * validators, absolute floor catches sub-percent drift on small ones (observed
588
+ * when metadata affects the real tx body vs the evaluator's ScriptContext).
589
+ */
590
+ _applyExUnitBuffer(mem, cpu) {
591
+ return {
592
+ mem: BigInt(Math.ceil(Number(mem) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER),
593
+ cpu: BigInt(Math.ceil(Number(cpu) * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER)
594
+ };
595
+ }
596
+ /**
597
+ * Decide the execution units each redeemer must declare.
598
+ * - Local run succeeded + Ogmios result → max of both (local is a real lower bound).
599
+ * - Local run succeeded, no Ogmios → buffered local (cushions local↔ledger drift).
600
+ * - Local run failed + Ogmios result → Ogmios (the local partial budget is meaningless).
601
+ * - Local run failed, no Ogmios → abort: declaring unreliable units would forfeit the
602
+ * collateral of whoever signs and submits the returned CBOR.
603
+ */
604
+ _resolveTargetExUnits(rdmrs, evaluatedUnits, failures) {
605
+ return rdmrs.map(r => {
606
+ const local = { mem: BigInt(r.execUnits.mem), cpu: BigInt(r.execUnits.cpu) };
607
+ const evaluated = evaluatedUnits?.get(redeemerKey(r.tag, r.index));
608
+ const failure = failures.find(f => f.tag === r.tag && f.index === r.index);
609
+ if (failure) {
610
+ if (!evaluated) {
611
+ throw new errors_1.TransactionValidationError(`Plutus script failed local evaluation (redeemer ${(0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag)}:${r.index}) ` +
612
+ `and no Ogmios evaluation is available to certify its execution units. Refusing to return a ` +
613
+ `transaction with unreliable execution units — signing and submitting it would forfeit the collateral. ` +
614
+ `Configure an Ogmios backend for authoritative script evaluation, or fix the script/datum/redeemer. ` +
615
+ `Script logs: [${failure.logs.join(', ')}]`);
616
+ }
617
+ return evaluated;
618
+ }
619
+ return evaluated
620
+ ? { mem: maxBig(local.mem, evaluated.mem), cpu: maxBig(local.cpu, evaluated.cpu) }
621
+ : this._applyExUnitBuffer(local.mem, local.cpu);
622
+ });
623
+ }
624
+ /** Fee delta of the target vs local units, priced like Buildooor's own fee loop. */
625
+ _exUnitsPriceDelta(rdmrs, targets) {
626
+ let deltaMem = 0n;
627
+ let deltaCpu = 0n;
628
+ rdmrs.forEach((r, i) => {
629
+ const dMem = targets[i].mem - BigInt(r.execUnits.mem);
630
+ const dCpu = targets[i].cpu - BigInt(r.execUnits.cpu);
631
+ if (dMem > 0n)
632
+ deltaMem += dMem;
633
+ if (dCpu > 0n)
634
+ deltaCpu += dCpu;
635
+ });
636
+ if (deltaMem === 0n && deltaCpu === 0n)
637
+ return 0n;
638
+ const prices = this.txBuilder.protocolParamters.executionUnitPrices;
639
+ if (Array.isArray(prices)) {
640
+ const [memRational, cpuRational] = prices;
641
+ return ceilDiv(deltaMem * memRational.num, memRational.den)
642
+ + ceilDiv(deltaCpu * cpuRational.num, cpuRational.den);
450
643
  }
451
- return const_1.DEFAULT_EXECUTION_UNITS;
644
+ // Plain { priceMemory, priceSteps } number form (pre-normalization shape)
645
+ const obj = prices;
646
+ return BigInt(Math.ceil(Number(deltaMem) * obj.priceMemory) + Math.ceil(Number(deltaCpu) * obj.priceSteps));
647
+ }
648
+ /** CBOR size growth (bytes) from stamping larger budgets into the redeemers. */
649
+ _exUnitsSizeDelta(rdmrs, targets) {
650
+ return rdmrs.reduce((sum, r, i) => {
651
+ const dMem = cborUIntLength(targets[i].mem) - cborUIntLength(BigInt(r.execUnits.mem));
652
+ const dCpu = cborUIntLength(targets[i].cpu) - cborUIntLength(BigInt(r.execUnits.cpu));
653
+ return sum + (dMem > 0n ? dMem : 0n) + (dCpu > 0n ? dCpu : 0n);
654
+ }, 0n);
452
655
  }
453
- /** Two-pass build: first build to calculate fee, then rebuild with witness buffer */
454
- async _buildWithWitnessBuffer(buildParams) {
455
- const txFirstPass = await this.txBuilder.build(buildParams, SCRIPT_BUILD_OPTS);
456
- const calculatedFee = BigInt(txFirstPass.body.fee.toString());
457
- const adjustedMinFee = calculatedFee + BigInt(const_1.WITNESS_BUFFER_BYTES);
458
- logger.debug(`First pass fee: ${calculatedFee}, rebuilding with witness buffer: ${adjustedMinFee}`);
459
- return this.txBuilder.build({ ...buildParams, fee: adjustedMinFee }, SCRIPT_BUILD_OPTS);
656
+ _txFeePerByte() {
657
+ return BigInt(this.txBuilder.protocolParamters.txFeePerByte);
658
+ }
659
+ /**
660
+ * Replace the redeemers' execution units and recompute scriptDataHash.
661
+ *
662
+ * Not implemented via TxBuilder.overrideTxRedeemers: that method computes the script
663
+ * data hash from the OLD witness set (library bug), which would yield a phase-1
664
+ * rejection (PPViewHashesDontMatch). We rebuild the witness set first and hash it with
665
+ * the same exported getScriptDataHash + language views the build itself uses.
666
+ */
667
+ _stampExecUnits(tx, targets) {
668
+ const rdmrs = tx.witnesses.redeemers ?? [];
669
+ const unchanged = rdmrs.every((r, i) => BigInt(r.execUnits.mem) === targets[i].mem && BigInt(r.execUnits.cpu) === targets[i].cpu);
670
+ if (unchanged)
671
+ return tx;
672
+ const stamped = rdmrs.map((r, i) => new cardano_ledger_ts_1.TxRedeemer({
673
+ tag: r.tag,
674
+ index: r.index,
675
+ data: r.data,
676
+ execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
677
+ }));
678
+ const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
679
+ const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this.txBuilder.protocolParamters.costModels, this._usedLanguageViewOpts(tx));
680
+ const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
681
+ const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
682
+ logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
683
+ stamped.map(s => `${(0, cardano_ledger_ts_1.txRedeemerTagToString)(s.tag)}:${s.index} mem=${s.execUnits.mem} cpu=${s.execUnits.cpu}`).join('; '));
684
+ return finalTx;
685
+ }
686
+ /**
687
+ * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
688
+ * (which flags the languages of *executed* scripts). This builder only attaches
689
+ * scripts inline, so the witness set carries every executed script.
690
+ */
691
+ _usedLanguageViewOpts(tx) {
692
+ const w = tx.witnesses;
693
+ const opts = {
694
+ mustHaveV1: (w.plutusV1Scripts?.length ?? 0) > 0,
695
+ mustHaveV2: (w.plutusV2Scripts?.length ?? 0) > 0,
696
+ mustHaveV3: (w.plutusV3Scripts?.length ?? 0) > 0
697
+ };
698
+ if (!opts.mustHaveV1 && !opts.mustHaveV2 && !opts.mustHaveV3)
699
+ opts.mustHaveV3 = true;
700
+ return opts;
460
701
  }
461
702
  /**
462
703
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
@@ -487,17 +728,66 @@ class BuildooorTxBuilder {
487
728
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
488
729
  }
489
730
  /**
490
- * Find an ADA-only UTxO for collateral, map it, and return remaining funding UTxOs.
731
+ * Build the Buildooor mint-entry array shared by the mint-only flow and the
732
+ * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
733
+ * they are stamped into the redeemers post-build by _buildScriptTx).
734
+ */
735
+ _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
736
+ return mintActions.map(action => {
737
+ const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
738
+ return {
739
+ value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
740
+ script: {
741
+ inline: mintScript,
742
+ redeemer: resolvedMintRedeemer
743
+ ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
744
+ : new plutus_data_1.DataI(action.redeemer ?? 0)
745
+ }
746
+ };
747
+ });
748
+ }
749
+ /**
750
+ * Pick a collateral UTxO and return remaining funding UTxOs.
491
751
  * Throws if no ADA-only UTxO is available.
752
+ *
753
+ * Selection: the SMALLEST ADA-only UTxO that still covers the static
754
+ * COLLATERAL_LOVELACE floor (5 ADA ≳ collateralPercentage × any realistic fee).
755
+ * The previous "first ADA-only" pick failed both ways: a dust UTxO below
756
+ * collateralPercentage × fee is rejected at submit, and a large UTxO is
757
+ * fully forfeited on phase-2 failure (Buildooor sets no collateralReturn
758
+ * for ADA-only collateral). Everything above the floor is therefore handed
759
+ * back via an explicit collateralReturn when the excess satisfies min-ADA.
492
760
  */
493
761
  _setupCollateral(utxos) {
494
- const adaOnlyUtxo = utxos.find(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
495
- if (!adaOnlyUtxo) {
762
+ const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
763
+ if (adaOnly.length === 0) {
496
764
  throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
497
765
  }
498
- const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(adaOnlyUtxo)];
499
- const fundingUtxos = utxos.filter(u => !(u.txHash === adaOnlyUtxo.txHash && u.outputIndex === adaOnlyUtxo.outputIndex));
500
- return { collateralUtxos, fundingUtxos };
766
+ const sorted = [...adaOnly].sort((a, b) => {
767
+ const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
768
+ return diff < 0n ? -1 : diff > 0n ? 1 : 0;
769
+ });
770
+ // smallest sufficient; if none reaches the floor, the largest available is the best bet
771
+ const chosen = sorted.find(u => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE) ?? sorted[sorted.length - 1];
772
+ if ((0, tx_build_helper_1.getLovelace)(chosen) < const_1.COLLATERAL_LOVELACE) {
773
+ logger.warn(`Largest ADA-only UTxO (${(0, tx_build_helper_1.getLovelace)(chosen)} lovelace) is below the ${const_1.COLLATERAL_LOVELACE} lovelace ` +
774
+ `collateral floor — the node will reject the transaction if collateralPercentage × fee exceeds it`);
775
+ }
776
+ const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(chosen)];
777
+ const fundingUtxos = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
778
+ // Cap the at-risk amount at the floor: return the excess to the owner.
779
+ let collateralReturn;
780
+ const excess = (0, tx_build_helper_1.getLovelace)(chosen) - const_1.COLLATERAL_LOVELACE;
781
+ if (excess > 0n) {
782
+ const address = cardano_ledger_ts_1.Address.fromString(chosen.address);
783
+ const minAda = this.txBuilder.getMinimumOutputLovelaces(new cardano_ledger_ts_1.TxOut({ address, value: cardano_ledger_ts_1.Value.lovelaces(excess) }));
784
+ if (excess >= minAda) {
785
+ collateralReturn = { address, value: cardano_ledger_ts_1.Value.lovelaces(excess) };
786
+ }
787
+ // excess below min-ADA: no return output possible — whole UTxO stays at risk,
788
+ // but by selection it is the smallest sufficient one.
789
+ }
790
+ return { collateralUtxos, fundingUtxos, collateralReturn };
501
791
  }
502
792
  /** Build a Ledger Value from lovelace + optional multi-asset array */
503
793
  _buildLedgerValue(lovelace, assets) {
@@ -525,17 +815,35 @@ class BuildooorTxBuilder {
525
815
  }
526
816
  return new cardano_ledger_ts_1.TxOut(params);
527
817
  }
528
- /** Parse a Plutus V3 CBOR hex into a Buildooor Script for refScript attachment. */
529
- _parseReferenceScript(hex) {
530
- if (!hex)
531
- return undefined;
818
+ /**
819
+ * Parse a consumer-provided, CBOR-wrapped Plutus script and reject UPLC 1.0.0
820
+ * code (PlutusV1/V2). `Script.fromCbor` defaults to PlutusV3, so V1/V2 bytes
821
+ * would be hashed with the 0x03 prefix — a silently wrong script hash, i.e.
822
+ * wrong policy IDs and unspendable script addresses with no error anywhere
823
+ * down the line. The UPLC version is the first three flat-encoded naturals
824
+ * of the unwrapped script: [1,0,0] (V1/V2) vs [1,1,0] (V3).
825
+ */
826
+ _parsePlutusV3Script(hex, field) {
827
+ let script;
532
828
  try {
533
- return cardano_ledger_ts_1.Script.fromCbor(Buffer.from(hex, 'hex'));
829
+ script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(hex, 'hex'));
534
830
  }
535
831
  catch (err) {
536
832
  const msg = err instanceof Error ? err.message : String(err);
537
- throw new errors_1.TransactionValidationError(`Invalid referenceScript CBOR: ${msg}`);
833
+ throw new errors_1.TransactionValidationError(`Invalid ${field} CBOR: ${msg}`);
834
+ }
835
+ const b = script.bytes;
836
+ if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
837
+ throw new errors_1.TransactionValidationError(`${field} contains UPLC 1.0.0 code (PlutusV1/V2) — ODATANO builds Plutus V3 transactions only. ` +
838
+ `Hashing it as V3 would yield a different script hash (wrong policy ID / unspendable address).`);
538
839
  }
840
+ return script;
841
+ }
842
+ /** Parse a Plutus V3 CBOR hex into a Buildooor Script for refScript attachment. */
843
+ _parseReferenceScript(hex) {
844
+ if (!hex)
845
+ return undefined;
846
+ return this._parsePlutusV3Script(hex, 'referenceScript');
539
847
  }
540
848
  /**
541
849
  * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
@@ -551,7 +859,13 @@ class BuildooorTxBuilder {
551
859
  return undefined;
552
860
  }
553
861
  try {
554
- return cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
862
+ const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
863
+ // chain data, not consumer input — warn instead of rejecting
864
+ const b = script.bytes;
865
+ if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
866
+ logger.warn(`Input refScript on ${utxo.txHash}#${utxo.outputIndex} is UPLC 1.0.0 (PlutusV1/V2) — treated as V3, local eval may misbehave`);
867
+ }
868
+ return script;
555
869
  }
556
870
  catch (err) {
557
871
  const msg = err instanceof Error ? err.message : String(err);
@@ -645,19 +959,111 @@ class BuildooorTxBuilder {
645
959
  };
646
960
  }
647
961
  /**
648
- * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape
962
+ * Map ODATANO LedgerProtocolParameter to Buildooor's ProtocolParameters shape.
963
+ *
964
+ * Every field is null-guarded: a missing/null source value keeps the library
965
+ * default instead of degrading to 0 (`Number(null) === 0` previously set
966
+ * utxoCostPerByte = 0, disabling min-ADA checks entirely). Cost models and
967
+ * execution-unit prices are mapped because they feed the scriptDataHash
968
+ * (language views) and the fee/ExUnits math — stale defaults there cause
969
+ * PPViewHashesDontMatch or fee underestimation on-chain.
649
970
  */
650
971
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
651
- return {
652
- ...cardano_ledger_ts_1.defaultProtocolParameters,
653
- txFeePerByte: Number(protocolParameters.minFeeA),
654
- txFeeFixed: Number(protocolParameters.minFeeB),
655
- utxoCostPerByte: Number(protocolParameters.coinsPerUtxoSize),
656
- poolDeposit: Number(protocolParameters.poolDeposit),
657
- keyDeposit: Number(protocolParameters.keyDeposit),
658
- maxTxSize: Number(protocolParameters.maxTxSize),
659
- maxValueSize: Number(protocolParameters.maxValSize),
972
+ const pp = protocolParameters;
973
+ const d = cardano_ledger_ts_1.defaultProtocolParameters;
974
+ const mapped = {
975
+ ...d,
976
+ txFeePerByte: toUInt(pp.minFeeA) ?? d.txFeePerByte,
977
+ txFeeFixed: toUInt(pp.minFeeB) ?? d.txFeeFixed,
978
+ utxoCostPerByte: toUInt(pp.coinsPerUtxoSize) ?? d.utxoCostPerByte,
979
+ maxTxSize: toUInt(pp.maxTxSize) ?? d.maxTxSize,
980
+ maxValueSize: toUInt(pp.maxValSize) ?? d.maxValueSize,
981
+ maxBlockBodySize: toUInt(pp.maxBlockSize) ?? d.maxBlockBodySize,
982
+ maxBlockHeaderSize: toUInt(pp.maxBlockHeaderSize) ?? d.maxBlockHeaderSize,
983
+ stakeAddressDeposit: toUInt(pp.keyDeposit) ?? d.stakeAddressDeposit,
984
+ stakePoolDeposit: toUInt(pp.poolDeposit) ?? d.stakePoolDeposit,
985
+ minPoolCost: toUInt(pp.minPoolCost) ?? d.minPoolCost,
986
+ poolRetireMaxEpoch: toUInt(pp.eMax) ?? d.poolRetireMaxEpoch,
987
+ stakePoolTargetNum: toUInt(pp.nOpt) ?? d.stakePoolTargetNum,
988
+ collateralPercentage: toUInt(pp.collateralPercent) ?? d.collateralPercentage,
989
+ maxCollateralInputs: toUInt(pp.maxCollateralInputs) ?? d.maxCollateralInputs,
990
+ };
991
+ const maxTxExMem = toUInt(pp.maxTxExMem);
992
+ const maxTxExSteps = toUInt(pp.maxTxExSteps);
993
+ if (maxTxExMem !== undefined && maxTxExSteps !== undefined) {
994
+ mapped.maxTxExecutionUnits = { memory: maxTxExMem, steps: maxTxExSteps };
995
+ }
996
+ const maxBlockExMem = toUInt(pp.maxBlockExMem);
997
+ const maxBlockExSteps = toUInt(pp.maxBlockExSteps);
998
+ if (maxBlockExMem !== undefined && maxBlockExSteps !== undefined) {
999
+ mapped.maxBlockExecutionUnits = { memory: maxBlockExMem, steps: maxBlockExSteps };
1000
+ }
1001
+ const priceMemory = toPositiveNumber(pp.priceMem);
1002
+ const priceSteps = toPositiveNumber(pp.priceStep);
1003
+ if (priceMemory !== undefined && priceSteps !== undefined) {
1004
+ mapped.executionUnitPrices = { priceMemory, priceSteps };
1005
+ }
1006
+ const costModels = this._mapCostModels(pp.costModels);
1007
+ if (costModels) {
1008
+ mapped.costModels = costModels;
1009
+ }
1010
+ else {
1011
+ logger.warn('Protocol parameters carry no usable cost models — keeping library defaults. ' +
1012
+ 'scriptDataHash of script transactions may not match the ledger (PPViewHashesDontMatch risk).');
1013
+ }
1014
+ return mapped;
1015
+ }
1016
+ /**
1017
+ * Parse the cost-models JSON blob (backend-normalized number arrays, keys
1018
+ * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
1019
+ * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
1020
+ * usable is found, so the caller can keep defaults and warn.
1021
+ */
1022
+ _mapCostModels(costModelsJson) {
1023
+ if (!costModelsJson)
1024
+ return undefined;
1025
+ let raw;
1026
+ try {
1027
+ raw = JSON.parse(costModelsJson);
1028
+ }
1029
+ catch {
1030
+ logger.warn('Failed to parse protocol-parameter cost models JSON');
1031
+ return undefined;
1032
+ }
1033
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
1034
+ return undefined;
1035
+ const KEY_MAP = {
1036
+ PlutusV1: 'PlutusScriptV1', 'plutus:v1': 'PlutusScriptV1', PlutusScriptV1: 'PlutusScriptV1',
1037
+ PlutusV2: 'PlutusScriptV2', 'plutus:v2': 'PlutusScriptV2', PlutusScriptV2: 'PlutusScriptV2',
1038
+ PlutusV3: 'PlutusScriptV3', 'plutus:v3': 'PlutusScriptV3', PlutusScriptV3: 'PlutusScriptV3',
660
1039
  };
1040
+ // Buildooor's CEK Machine rejects array-form cost models — convert to named-key objects.
1041
+ const result = {};
1042
+ for (const [key, value] of Object.entries(raw)) {
1043
+ const target = KEY_MAP[key];
1044
+ if (!target || !Array.isArray(value))
1045
+ continue;
1046
+ const arr = value.map(Number);
1047
+ try {
1048
+ if (target === 'PlutusScriptV1')
1049
+ result[target] = (0, buildooor_1.toCostModelV1)(arr);
1050
+ else if (target === 'PlutusScriptV2')
1051
+ result[target] = (0, buildooor_1.toCostModelV2)(arr);
1052
+ else
1053
+ result[target] = (0, buildooor_1.toCostModelV3)(arr);
1054
+ }
1055
+ catch {
1056
+ logger.warn(`Cost-model array for ${key} has unexpected length (${value.length}) — skipping`);
1057
+ }
1058
+ }
1059
+ if (Object.keys(result).length === 0)
1060
+ return undefined;
1061
+ if (!(0, buildooor_1.isCostModels)(result)) {
1062
+ // Buildooor would silently substitute default cost models — surface it instead.
1063
+ logger.warn('Mapped cost models failed Buildooor validation — keeping library defaults');
1064
+ return undefined;
1065
+ }
1066
+ return result;
661
1067
  }
662
1068
  /**
663
1069
  * Map ODATANO UTxO to Ledger UTxO (ADA-only)
@@ -679,7 +1085,15 @@ class BuildooorTxBuilder {
679
1085
  */
680
1086
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
681
1087
  const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
682
- const datumValue = utxo.inlineDatum ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum) : undefined;
1088
+ // Inline datum wins; otherwise carry the datum HASH into the resolved TxOut —
1089
+ // Buildooor only includes a provided datum preimage in the witness set when the
1090
+ // spent output is marked with its Hash32 (pushWitDatum). Dropping the hash here
1091
+ // silently discards the preimage → MissingRequiredDatums on submit.
1092
+ const datumValue = utxo.inlineDatum
1093
+ ? (0, plutus_data_1.dataFromCbor)(utxo.inlineDatum)
1094
+ : utxo.datumHash
1095
+ ? new cardano_ledger_ts_1.Hash32(utxo.datumHash)
1096
+ : undefined;
683
1097
  return new cardano_ledger_ts_1.UTxO({
684
1098
  utxoRef: new cardano_ledger_ts_1.TxOutRef({ id: utxo.txHash, index: utxo.outputIndex }),
685
1099
  resolved: new cardano_ledger_ts_1.TxOut({
@@ -699,25 +1113,47 @@ class BuildooorTxBuilder {
699
1113
  }
700
1114
  const metadata = {};
701
1115
  for (const [label, value] of Object.entries(metadataJson)) {
702
- const numericLabel = parseInt(label, 10);
703
- const txMetadatum = this._jsonToTxMetadatum(value);
704
- logger.debug(`Created TxMetadatum for label ${numericLabel}: ${txMetadatum.constructor.name}`);
705
- metadata[numericLabel] = txMetadatum;
1116
+ if (!/^\d+$/.test(label)) {
1117
+ throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}" — labels must be non-negative integers`);
1118
+ }
1119
+ metadata[Number(label)] = this._jsonToTxMetadatum(value);
706
1120
  }
707
- logger.debug(`Creating TxMetadata with ${Object.keys(metadata).length} labels`);
708
- const txMetadata = new TxMetadata_1.TxMetadata(metadata);
709
- logger.debug(`TxMetadata created: ${txMetadata.constructor.name}, instanceof check: ${txMetadata instanceof TxMetadata_1.TxMetadata}`);
710
- return txMetadata;
1121
+ return new TxMetadata_1.TxMetadata(metadata);
711
1122
  }
712
1123
  /**
713
- * Recursively convert JSON value to TxMetadatum
1124
+ * Recursively convert JSON value to TxMetadatum.
1125
+ *
1126
+ * Ledger rules enforced here (instead of a node-side rejection or a raw 500):
1127
+ * - numbers must be integers (BigInt(1.5) would throw a bare RangeError)
1128
+ * - text and byte values are limited to 64 BYTES per metadatum — longer values
1129
+ * are chunked into a list of ≤64-byte pieces (the established convention,
1130
+ * e.g. CIP-25 long strings)
1131
+ * - strings prefixed with "0x" (even hex length) become byte metadata
1132
+ * - map keys are not auto-chunked (readers match on the literal key) — over-long
1133
+ * keys are rejected with a clear 400
714
1134
  */
715
1135
  _jsonToTxMetadatum(value) {
716
1136
  if (typeof value === 'number' || typeof value === 'bigint') {
1137
+ if (typeof value === 'number' && !Number.isInteger(value)) {
1138
+ throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value}) — encode decimals as strings`);
1139
+ }
717
1140
  return new TxMetadatum_1.TxMetadatumInt(BigInt(value));
718
1141
  }
719
1142
  if (typeof value === 'string') {
720
- return new TxMetadatum_1.TxMetadatumText(value);
1143
+ if (/^0x([0-9a-fA-F]{2})+$/.test(value)) {
1144
+ const bytes = Buffer.from(value.slice(2), 'hex');
1145
+ if (bytes.length <= METADATA_BYTE_LIMIT)
1146
+ return new TxMetadatum_1.TxMetadatumBytes(bytes);
1147
+ const chunks = [];
1148
+ for (let i = 0; i < bytes.length; i += METADATA_BYTE_LIMIT) {
1149
+ chunks.push(new TxMetadatum_1.TxMetadatumBytes(bytes.subarray(i, i + METADATA_BYTE_LIMIT)));
1150
+ }
1151
+ return new TxMetadatum_1.TxMetadatumList(chunks);
1152
+ }
1153
+ const chunks = chunkUtf8(value, METADATA_BYTE_LIMIT);
1154
+ if (chunks.length === 1)
1155
+ return new TxMetadatum_1.TxMetadatumText(value);
1156
+ return new TxMetadatum_1.TxMetadatumList(chunks.map(c => new TxMetadatum_1.TxMetadatumText(c)));
721
1157
  }
722
1158
  if (Array.isArray(value)) {
723
1159
  return new TxMetadatum_1.TxMetadatumList(value.map(v => this._jsonToTxMetadatum(v)));
@@ -725,6 +1161,9 @@ class BuildooorTxBuilder {
725
1161
  if (typeof value === 'object' && value !== null) {
726
1162
  const map = [];
727
1163
  for (const [k, v] of Object.entries(value)) {
1164
+ if (Buffer.byteLength(k, 'utf8') > METADATA_BYTE_LIMIT) {
1165
+ throw new errors_1.TransactionValidationError(`Metadata map key exceeds ${METADATA_BYTE_LIMIT} bytes (UTF-8): "${k.slice(0, 32)}…"`);
1166
+ }
728
1167
  map.push({
729
1168
  k: new TxMetadatum_1.TxMetadatumText(k),
730
1169
  v: this._jsonToTxMetadatum(v)