@odatano/core 1.7.10 → 1.9.0

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/odatano/cardano/index.d.ts +70 -46
  6. package/@cds-models/odatano/cardano/index.d.ts.map +1 -1
  7. package/@cds-models/odatano/cardano/index.js +2 -2
  8. package/@cds-models/odatano/cardano/index.js.map +1 -1
  9. package/@cds-models/odatano/cardano/index.ts +13 -13
  10. package/LICENSE +1 -24
  11. package/README.md +102 -96
  12. package/db/schema.cds +18 -18
  13. package/db/types.cds +3 -3
  14. package/package.json +25 -11
  15. package/src/index.d.ts +29 -0
  16. package/src/index.js +1 -0
  17. package/src/plugin.d.ts +2 -0
  18. package/src/plugin.js +6 -0
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +155 -0
  20. package/srv/blockchain/backends/blockfrost-backend.js +19 -8
  21. package/srv/blockchain/backends/cardano-backend.d.ts +182 -0
  22. package/srv/blockchain/backends/koios-backend.d.ts +171 -0
  23. package/srv/blockchain/backends/koios-backend.js +69 -27
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +188 -0
  25. package/srv/blockchain/backends/ogmios-backend.js +175 -108
  26. package/srv/blockchain/cardano-client.d.ts +279 -0
  27. package/srv/blockchain/cardano-client.js +134 -33
  28. package/srv/blockchain/cardano-indexer.d.ts +330 -0
  29. package/srv/blockchain/cardano-indexer.js +51 -8
  30. package/srv/blockchain/cardano-tx-builder.d.ts +113 -0
  31. package/srv/blockchain/cardano-tx-builder.js +64 -57
  32. package/srv/blockchain/circuit-breaker.d.ts +37 -0
  33. package/srv/blockchain/circuit-breaker.js +11 -2
  34. package/srv/blockchain/request-coalescer.d.ts +23 -0
  35. package/srv/blockchain/signing/external-signer.d.ts +146 -0
  36. package/srv/blockchain/signing/external-signer.js +23 -0
  37. package/srv/blockchain/signing/hsm-signer.d.ts +74 -0
  38. package/srv/blockchain/signing/hsm-signer.js +20 -5
  39. package/srv/blockchain/signing/signature-verifier.d.ts +56 -0
  40. package/srv/blockchain/signing/signature-verifier.js +79 -79
  41. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +236 -0
  42. package/srv/blockchain/transaction-building/buildooor-tx.js +632 -173
  43. package/srv/blockchain/transaction-building/cardano-tx.d.ts +47 -0
  44. package/srv/cardano-service.cds +23 -3
  45. package/srv/cardano-service.d.ts +2 -0
  46. package/srv/cardano-service.js +26 -6
  47. package/srv/cardano-sign-service.cds +5 -0
  48. package/srv/cardano-sign-service.d.ts +2 -0
  49. package/srv/cardano-sign-service.js +221 -134
  50. package/srv/cardano-tx-service.cds +8 -0
  51. package/srv/cardano-tx-service.d.ts +12 -0
  52. package/srv/cardano-tx-service.js +170 -111
  53. package/srv/cbor/index.d.ts +2 -0
  54. package/srv/cbor/parse.d.ts +64 -0
  55. package/srv/server.d.ts +90 -0
  56. package/srv/server.js +52 -41
  57. package/srv/utils/backend-request-handler.d.ts +20 -0
  58. package/srv/utils/const.d.ts +183 -0
  59. package/srv/utils/const.js +13 -6
  60. package/srv/utils/error-codes.d.ts +79 -0
  61. package/srv/utils/errors.d.ts +259 -0
  62. package/srv/utils/errors.js +22 -7
  63. package/srv/utils/mappers.d.ts +260 -0
  64. package/srv/utils/mappers.js +34 -10
  65. package/srv/utils/plutus-placeholders.d.ts +35 -0
  66. package/srv/utils/plutus-placeholders.js +6 -17
  67. package/srv/utils/signing-helper.d.ts +23 -0
  68. package/srv/utils/signing-helper.js +11 -49
  69. package/srv/utils/tx-build-helper.d.ts +76 -0
  70. package/srv/utils/tx-build-helper.js +29 -80
  71. package/srv/utils/types.d.ts +653 -0
  72. package/srv/utils/validators.d.ts +145 -0
  73. package/srv/utils/validators.js +28 -1
  74. package/@cds-models/CardanoWatcherAdminService/index.js +0 -109
  75. package/@cds-models/CardanoWatcherAdminService/index.js.map +0 -1
  76. package/@cds-models/CardanoWatcherAdminService/index.ts +0 -263
  77. package/@cds-models/cds/outbox/index.js.map +0 -1
  78. package/@cds-models/cds/xt/MTXServices/index.js +0 -8
  79. package/@cds-models/cds/xt/MTXServices/index.js.map +0 -1
  80. package/@cds-models/cds/xt/MTXServices/index.ts +0 -4
  81. package/@cds-models/odatano/reeve/index.js +0 -77
  82. package/@cds-models/odatano/reeve/index.js.map +0 -1
  83. package/@cds-models/odatano/reeve/index.ts +0 -57
  84. package/@cds-models/odatano/transactions/index.js +0 -55
  85. package/@cds-models/odatano/transactions/index.js.map +0 -1
  86. package/@cds-models/odatano/transactions/index.ts +0 -18
  87. package/@cds-models/odatano/watch/index.js +0 -114
  88. package/@cds-models/odatano/watch/index.js.map +0 -1
  89. package/@cds-models/odatano/watch/index.ts +0 -110
  90. package/config/preview/cardano-node/alonzo-genesis.json +0 -196
  91. package/config/preview/cardano-node/byron-genesis.json +0 -117
  92. package/config/preview/cardano-node/config.json +0 -118
  93. package/config/preview/cardano-node/conway-genesis.json +0 -297
  94. package/config/preview/cardano-node/shelley-genesis.json +0 -68
  95. package/config/preview/cardano-node/topology.json +0 -19
  96. package/output/sora/iter0_base.json +0 -32
  97. package/output/sora/iter0_base.mp4 +0 -0
  98. package/output/sora/logo_ref_1280x720.png +0 -0
  99. package/output/sora/odatano_full_logo_sky_ref_1280x720.png +0 -0
  100. package/output/sora/odatano_full_logo_transparent.png +0 -0
  101. package/output/sora/odatano_full_logo_transparent_dark.png +0 -0
  102. package/output/sora/odatano_full_logo_v4_8s.json +0 -32
  103. package/output/sora/odatano_full_logo_v4_8s.mp4 +0 -0
  104. package/output/sora/odatano_full_logo_v5_create.json +0 -15
  105. package/output/sora/odatano_full_logo_v5_fixes.json +0 -15
  106. package/output/sora/odatano_full_logo_v5_fixes.mp4 +0 -0
  107. package/output/sora/odatano_logo_v1.json +0 -32
  108. package/output/sora/odatano_logo_v1.mp4 +0 -0
  109. package/output/sora/odatano_o_only_clean.png +0 -0
  110. package/output/sora/odatano_o_sky_ref_1280x720.png +0 -0
  111. package/output/sora/odatano_o_sky_v2_8s.json +0 -32
  112. package/output/sora/odatano_o_sky_v2_8s.mp4 +0 -0
  113. package/output/sora/odatano_o_sky_v3_create.json +0 -15
  114. package/output/sora/odatano_o_sky_v3_splash_text.json +0 -15
  115. package/output/sora/odatano_o_sky_v3_splash_text.mp4 +0 -0
  116. package/output/sora/odatano_v6_composite_exact_logo.mp4 +0 -0
  117. package/output/sora/odatano_v6_composite_exact_logo_clean.mp4 +0 -0
  118. package/output/sora/odatano_v6_composite_exact_logo_final.mp4 +0 -0
  119. package/output/sora/odatano_v6_endframe.jpg +0 -0
  120. package/output/sora/odatano_v6_endframe_clean.jpg +0 -0
  121. package/output/sora/odatano_v6_endframe_final.jpg +0 -0
  122. package/output/sora/odatano_v7_1_earlylogo_fadeoldtext.mp4 +0 -0
  123. package/output/sora/odatano_v7_1_end.jpg +0 -0
  124. package/output/sora/odatano_v7_1_transition.jpg +0 -0
  125. package/output/sora/odatano_v7_2_original2d_keep_sky.mp4 +0 -0
  126. package/output/sora/odatano_v7_endframe_nobg.jpg +0 -0
  127. package/output/sora/odatano_v7_endframe_nobg_cleanend.jpg +0 -0
  128. package/output/sora/odatano_v7_spin_splash_logo_nobg.mp4 +0 -0
  129. package/output/sora/odatano_v7_spin_splash_logo_nobg_cleanend.mp4 +0 -0
  130. package/src/index.d.ts.map +0 -1
  131. package/src/index.js.map +0 -1
  132. package/src/plugin.d.ts.map +0 -1
  133. package/src/plugin.js.map +0 -1
  134. package/srv/blockchain/backends/blockfrost-backend.d.ts.map +0 -1
  135. package/srv/blockchain/backends/blockfrost-backend.js.map +0 -1
  136. package/srv/blockchain/backends/cardano-backend.d.ts.map +0 -1
  137. package/srv/blockchain/backends/cardano-backend.js.map +0 -1
  138. package/srv/blockchain/backends/gerolamo-backend.d.ts.map +0 -1
  139. package/srv/blockchain/backends/gerolamo-backend.js +0 -321
  140. package/srv/blockchain/backends/gerolamo-backend.js.map +0 -1
  141. package/srv/blockchain/backends/koios-backend.d.ts.map +0 -1
  142. package/srv/blockchain/backends/koios-backend.js.map +0 -1
  143. package/srv/blockchain/backends/ogmios-backend.d.ts.map +0 -1
  144. package/srv/blockchain/backends/ogmios-backend.js.map +0 -1
  145. package/srv/blockchain/cardano-client.d.ts.map +0 -1
  146. package/srv/blockchain/cardano-client.js.map +0 -1
  147. package/srv/blockchain/cardano-indexer.d.ts.map +0 -1
  148. package/srv/blockchain/cardano-indexer.js.map +0 -1
  149. package/srv/blockchain/cardano-tx-builder.d.ts.map +0 -1
  150. package/srv/blockchain/cardano-tx-builder.js.map +0 -1
  151. package/srv/blockchain/circuit-breaker.d.ts.map +0 -1
  152. package/srv/blockchain/circuit-breaker.js.map +0 -1
  153. package/srv/blockchain/request-coalescer.d.ts.map +0 -1
  154. package/srv/blockchain/request-coalescer.js.map +0 -1
  155. package/srv/blockchain/signing/external-signer.d.ts.map +0 -1
  156. package/srv/blockchain/signing/external-signer.js.map +0 -1
  157. package/srv/blockchain/signing/hsm-signer.d.ts.map +0 -1
  158. package/srv/blockchain/signing/hsm-signer.js.map +0 -1
  159. package/srv/blockchain/signing/signature-verifier.d.ts.map +0 -1
  160. package/srv/blockchain/signing/signature-verifier.js.map +0 -1
  161. package/srv/blockchain/transaction-building/buildooor-tx.d.ts.map +0 -1
  162. package/srv/blockchain/transaction-building/buildooor-tx.js.map +0 -1
  163. package/srv/blockchain/transaction-building/cardano-tx.d.ts.map +0 -1
  164. package/srv/blockchain/transaction-building/cardano-tx.js.map +0 -1
  165. package/srv/blockchain/transaction-building/csl-tx.d.ts.map +0 -1
  166. package/srv/blockchain/transaction-building/csl-tx.js +0 -922
  167. package/srv/blockchain/transaction-building/csl-tx.js.map +0 -1
  168. package/srv/blockchain/transaction-building/tx-builder-registry.d.ts.map +0 -1
  169. package/srv/blockchain/transaction-building/tx-builder-registry.js +0 -69
  170. package/srv/blockchain/transaction-building/tx-builder-registry.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,11 +11,122 @@ 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");
17
21
  const const_1 = require("../../utils/const");
18
22
  const logger = cds_1.default.log('BuildooorTxBuilder');
23
+ /**
24
+ * Build options for script-bearing transactions.
25
+ *
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.
32
+ *
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.
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
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
+ }
19
130
  /**
20
131
  * BuildooorTxBuilder - Implementation of CardanoTxBuilder using Buildooor library
21
132
  */
@@ -23,6 +134,8 @@ class BuildooorTxBuilder {
23
134
  name = 'BuildooorTxBuilder';
24
135
  txBuilder;
25
136
  cardanoClient;
137
+ genesisInfos;
138
+ paramsFingerprint;
26
139
  /**
27
140
  * Initialize the builder
28
141
  * @param client - The CardanoClient instance
@@ -31,19 +144,56 @@ class BuildooorTxBuilder {
31
144
  async init(client, protocolParams) {
32
145
  this.cardanoClient = client;
33
146
  const params = protocolParams ?? await client.getProtocolParameters();
34
- const txbParameters = this._mapLedgerParametersToBuildooorParams(params);
35
147
  const genesisInfos = const_1.GENESIS_INFOS_BY_NETWORK[client.network];
36
148
  if (!genesisInfos) {
37
149
  throw new errors_1.ConfigError(`BuildooorTxBuilder: no genesis presets for network "${client.network}"`);
38
150
  }
39
- this.txBuilder = new buildooor_1.TxBuilder(txbParameters, genesisInfos);
151
+ this.genesisInfos = genesisInfos;
152
+ this._applyProtocolParameters(params, protocolParamsFingerprint(params));
40
153
  logger.debug(`Initialized with protocol parameters and ${client.network} genesis infos`);
41
154
  }
42
155
  /**
43
- * 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.
161
+ */
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).
44
178
  */
45
- async buildUnsignedTransfer(req, ctx) {
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) {
46
195
  try {
196
+ this._ensureCurrentProtocolParameters(ctx);
47
197
  if (!ctx.utxos || ctx.utxos.length === 0) {
48
198
  throw new errors_1.InsufficientFundsError('lovelace', BigInt(req.lovelaceAmount || 0), 0n);
49
199
  }
@@ -64,34 +214,12 @@ class BuildooorTxBuilder {
64
214
  // Coin selection on candidates only; forced inputs are prepended unconditionally
65
215
  const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
66
216
  const inputs = [...forcedInputs, ...selected];
67
- logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for transfer`);
68
- const validity = this._resolveValiditySlots(req, 'passthrough');
69
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...validity });
70
- logger.debug(`Built unsigned transaction successfully.`);
71
- return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
72
- }
73
- catch (err) {
74
- (0, tx_build_helper_1.mapBuilderError)(err);
75
- }
76
- }
77
- async buildUnsignedTransactionWithMetadata(req, ctx) {
78
- try {
79
- const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
80
- const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
81
- const amount = BigInt(String(req.lovelaceAmount));
82
- const metadata = this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson);
83
- const outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
84
- const refScript = this._parseReferenceScript(req.referenceScript);
85
- const outputs = [this._buildTxOut(recipientAddress, outputValue, undefined, refScript)];
86
- // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
87
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
88
- const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
89
- const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
90
- const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
91
- const inputs = [...forcedInputs, ...selected];
92
- 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;
93
221
  const validity = this._resolveValiditySlots(req, 'passthrough');
94
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, metadata, ...validity });
222
+ const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity });
95
223
  logger.debug(`Built unsigned transaction successfully.`);
96
224
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
97
225
  }
@@ -101,11 +229,11 @@ class BuildooorTxBuilder {
101
229
  }
102
230
  async buildUnsignedMintTransaction(req, ctx) {
103
231
  try {
232
+ this._ensureCurrentProtocolParameters(ctx);
104
233
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
105
234
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
106
235
  // Parse the minting policy script once
107
- const scriptBytes = Buffer.from(req.mintingPolicyScript, 'hex');
108
- const script = cardano_ledger_ts_1.Script.fromCbor(scriptBytes);
236
+ const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
109
237
  // Calculate total mint value for output (only positive quantities - mints, not burns)
110
238
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
111
239
  for (const mintAction of req.mintActions) {
@@ -120,7 +248,7 @@ class BuildooorTxBuilder {
120
248
  const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
121
249
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
122
250
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
123
- const { collateralUtxos, fundingUtxos } = this._setupCollateral(rest);
251
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
124
252
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
125
253
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
126
254
  // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
@@ -145,24 +273,10 @@ class BuildooorTxBuilder {
145
273
  outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
146
274
  const refScript = this._parseReferenceScript(req.referenceScript);
147
275
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
148
- // Helper to build mints array with specified execution units (uses pre-resolved redeemer)
149
- const buildMints = (exUnits) => {
150
- const mints = [];
151
- for (const mintAction of req.mintActions) {
152
- const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
153
- mints.push({
154
- value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(mintAction.quantity)),
155
- script: {
156
- inline: script,
157
- redeemer: resolvedMintRedeemer
158
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
159
- : new plutus_data_1.DataI(mintAction.redeemer ?? 0),
160
- executionUnits: exUnits
161
- }
162
- });
163
- }
164
- return mints;
165
- };
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);
166
280
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
167
281
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
168
282
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
@@ -173,26 +287,17 @@ class BuildooorTxBuilder {
173
287
  const mintMetadata = req.metadataJson
174
288
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
175
289
  : undefined;
176
- // Evaluate execution units
177
- const finalExUnits = await this._evaluateExUnits(async () => {
178
- const evalTx = await this.txBuilder.build({
179
- inputs, outputs, changeAddress, mints: buildMints(const_1.HIGH_EXECUTION_UNITS),
180
- collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
181
- invalidBefore, invalidAfter,
182
- ...(mintMetadata && { metadata: mintMetadata }),
183
- ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
184
- });
185
- return (0, uint8array_utils_1.toHex)(evalTx.toCbor());
186
- }, ctx.evaluateTransaction);
187
- // Build with final execution units + witness buffer
188
- const mints = buildMints(finalExUnits);
189
- 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 = {
190
293
  inputs, outputs, changeAddress, mints,
191
294
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
192
295
  invalidBefore, invalidAfter,
296
+ ...(collateralReturn && { collateralReturn }),
193
297
  ...(mintMetadata && { metadata: mintMetadata }),
194
298
  ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
195
- });
299
+ };
300
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
196
301
  logger.debug(`Built unsigned minting transaction successfully with fee: ${tx.body.fee.toString()}`);
197
302
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
198
303
  }
@@ -202,10 +307,10 @@ class BuildooorTxBuilder {
202
307
  }
203
308
  async buildUnsignedPlutusSpendTransaction(req, ctx) {
204
309
  try {
310
+ this._ensureCurrentProtocolParameters(ctx);
205
311
  const { plutusScriptExecution } = req;
206
312
  // Parse the validator script
207
- const scriptBytes = Buffer.from(plutusScriptExecution.validatorScript, 'hex');
208
- const script = cardano_ledger_ts_1.Script.fromCbor(scriptBytes);
313
+ const script = this._parsePlutusV3Script(plutusScriptExecution.validatorScript, 'plutusScriptExecution.validatorScript');
209
314
  if (!plutusScriptExecution.datum) {
210
315
  // When no explicit datum is provided, the UTxO must have an inline datum.
211
316
  // If neither exists, the Plutus validator will fail with a cryptic error.
@@ -227,7 +332,7 @@ class BuildooorTxBuilder {
227
332
  const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
228
333
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
229
334
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
230
- const { collateralUtxos, fundingUtxos } = this._setupCollateral(rest);
335
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
231
336
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
232
337
  // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
233
338
  // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
@@ -262,7 +367,7 @@ class BuildooorTxBuilder {
262
367
  let mintScript;
263
368
  let mintScriptHash;
264
369
  if (hasMint) {
265
- mintScript = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(req.mintingPolicyScript, 'hex'));
370
+ mintScript = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
266
371
  mintScriptHash = mintScript.hash.toString();
267
372
  }
268
373
  // Build outputs — include multi-assets from script UTxO in continuing output
@@ -286,59 +391,33 @@ class BuildooorTxBuilder {
286
391
  // Append extra outputs (FR-2). Each is independently min-ADA checked so consumers
287
392
  // get a clear, field-attributed error before Buildooor's coin selection runs.
288
393
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
289
- // Helper to build mints array (FR-1) with specified execution units
290
- const buildMints = hasMint
291
- ? (exUnits) => req.mintActions.map(action => {
292
- const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
293
- return {
294
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
295
- script: {
296
- inline: mintScript,
297
- redeemer: resolvedMintRedeemer
298
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
299
- : new plutus_data_1.DataI(action.redeemer ?? 0),
300
- executionUnits: exUnits
301
- }
302
- };
303
- })
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)
304
399
  : undefined;
305
- // Helper to build inputs with specified execution units
306
- const buildInputs = (exUnits) => {
307
- const scriptInput = {
308
- utxo: scriptLedgerUtxo,
309
- inputScript: { script, datum, redeemer: redeemerData, executionUnits: exUnits }
310
- };
311
- return [scriptInput, ...forcedInputs, ...selectedFundingInputs];
400
+ const scriptInput = {
401
+ utxo: scriptLedgerUtxo,
402
+ inputScript: { script, datum, redeemer: redeemerData }
312
403
  };
404
+ const inputs = [scriptInput, ...forcedInputs, ...selectedFundingInputs];
313
405
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
314
406
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
315
407
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
316
408
  // and fee computation stay consistent (a mismatch would force re-evaluation).
317
409
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
318
- // Evaluate execution units
319
- const finalExUnits = await this._evaluateExUnits(async () => {
320
- const evalTx = await this.txBuilder.build({
321
- inputs: buildInputs(const_1.HIGH_EXECUTION_UNITS), outputs, changeAddress,
322
- mints: buildMints?.(const_1.HIGH_EXECUTION_UNITS),
323
- collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
324
- invalidBefore, invalidAfter,
325
- ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
326
- });
327
- if (!evalTx) {
328
- throw new errors_1.TransactionValidationError('Buildooor txBuilder.build() returned null — check inputs, datum, and collateral configuration');
329
- }
330
- return (0, uint8array_utils_1.toHex)(evalTx.toCbor());
331
- }, ctx.evaluateTransaction);
332
- // Build with final execution units + witness buffer
333
- const inputs = buildInputs(finalExUnits);
334
- const mints = buildMints?.(finalExUnits);
335
- 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 = {
336
413
  inputs, outputs, changeAddress,
337
414
  mints,
338
415
  collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
339
416
  invalidBefore, invalidAfter,
417
+ ...(collateralReturn && { collateralReturn }),
340
418
  ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
341
- });
419
+ };
420
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
342
421
  logger.debug(`Built unsigned Plutus spending transaction successfully with fee: ${tx.body.fee.toString()}`);
343
422
  return this._buildResult(req, ctx, this._extractTxDetails(tx), {
344
423
  scriptHash: script.hash.toString(),
@@ -398,45 +477,227 @@ class BuildooorTxBuilder {
398
477
  };
399
478
  }
400
479
  /**
401
- * Evaluate execution units via callback. Caller provides an async function
402
- * 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.
403
498
  */
404
- 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;
405
516
  if (!evaluator) {
406
- logger.debug('No evaluator available, using default execution units');
407
- return const_1.DEFAULT_EXECUTION_UNITS;
517
+ logger.debug('No evaluator available — falling back to buffered local execution units');
408
518
  }
409
- logger.debug('Building evaluation pass with high execution units');
410
- 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) {
411
542
  try {
412
543
  const evalResults = await evaluator(evalTxCbor);
413
544
  logger.debug(`Evaluation results: ${JSON.stringify(evalResults)}`);
414
- if (evalResults && evalResults.length > 0) {
415
- const budget = evalResults[0].budget;
416
- // Combined cushion: relative multiplier catches proportional drift on large
417
- // validators, absolute floor catches sub-percent drift on small ones (observed
418
- // when metadata affects the real tx body vs the evaluator's ScriptContext).
419
- const result = {
420
- mem: Math.ceil(budget.memory * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER,
421
- cpu: Math.ceil(budget.cpu * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER
422
- };
423
- logger.info(`Using evaluated execution units: mem=${result.mem}, cpu=${result.cpu}`);
424
- 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));
425
568
  }
569
+ return byRedeemer.size > 0 ? byRedeemer : undefined;
426
570
  }
427
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
+ }
428
580
  const msg = evalError instanceof Error ? evalError.message : String(evalError);
429
- logger.warn(`Evaluation failed, using default units: ${msg}`);
581
+ logger.warn(`Evaluation failed (transient), falling back to local execution units: ${msg}`);
582
+ return undefined;
430
583
  }
431
- return const_1.DEFAULT_EXECUTION_UNITS;
432
584
  }
433
- /** Two-pass build: first build to calculate fee, then rebuild with witness buffer */
434
- async _buildWithWitnessBuffer(buildParams) {
435
- const txFirstPass = await this.txBuilder.build(buildParams);
436
- const calculatedFee = BigInt(txFirstPass.body.fee.toString());
437
- const adjustedMinFee = calculatedFee + BigInt(const_1.WITNESS_BUFFER_BYTES);
438
- logger.debug(`First pass fee: ${calculatedFee}, rebuilding with witness buffer: ${adjustedMinFee}`);
439
- return this.txBuilder.build({ ...buildParams, fee: adjustedMinFee });
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);
643
+ }
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);
655
+ }
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;
440
701
  }
441
702
  /**
442
703
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
@@ -467,17 +728,66 @@ class BuildooorTxBuilder {
467
728
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
468
729
  }
469
730
  /**
470
- * 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.
471
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.
472
760
  */
473
761
  _setupCollateral(utxos) {
474
- const adaOnlyUtxo = utxos.find(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
475
- if (!adaOnlyUtxo) {
762
+ const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
763
+ if (adaOnly.length === 0) {
476
764
  throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
477
765
  }
478
- const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(adaOnlyUtxo)];
479
- const fundingUtxos = utxos.filter(u => !(u.txHash === adaOnlyUtxo.txHash && u.outputIndex === adaOnlyUtxo.outputIndex));
480
- 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 };
481
791
  }
482
792
  /** Build a Ledger Value from lovelace + optional multi-asset array */
483
793
  _buildLedgerValue(lovelace, assets) {
@@ -505,17 +815,35 @@ class BuildooorTxBuilder {
505
815
  }
506
816
  return new cardano_ledger_ts_1.TxOut(params);
507
817
  }
508
- /** Parse a Plutus V3 CBOR hex into a Buildooor Script for refScript attachment. */
509
- _parseReferenceScript(hex) {
510
- if (!hex)
511
- 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;
512
828
  try {
513
- return cardano_ledger_ts_1.Script.fromCbor(Buffer.from(hex, 'hex'));
829
+ script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(hex, 'hex'));
514
830
  }
515
831
  catch (err) {
516
832
  const msg = err instanceof Error ? err.message : String(err);
517
- 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).`);
518
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');
519
847
  }
520
848
  /**
521
849
  * Map an input UTxO's scriptRef field to a Buildooor Script when possible.
@@ -531,7 +859,13 @@ class BuildooorTxBuilder {
531
859
  return undefined;
532
860
  }
533
861
  try {
534
- 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;
535
869
  }
536
870
  catch (err) {
537
871
  const msg = err instanceof Error ? err.message : String(err);
@@ -625,19 +959,111 @@ class BuildooorTxBuilder {
625
959
  };
626
960
  }
627
961
  /**
628
- * 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.
629
970
  */
630
971
  _mapLedgerParametersToBuildooorParams(protocolParameters) {
631
- return {
632
- ...cardano_ledger_ts_1.defaultProtocolParameters,
633
- txFeePerByte: Number(protocolParameters.minFeeA),
634
- txFeeFixed: Number(protocolParameters.minFeeB),
635
- utxoCostPerByte: Number(protocolParameters.coinsPerUtxoSize),
636
- poolDeposit: Number(protocolParameters.poolDeposit),
637
- keyDeposit: Number(protocolParameters.keyDeposit),
638
- maxTxSize: Number(protocolParameters.maxTxSize),
639
- 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,
640
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',
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;
641
1067
  }
642
1068
  /**
643
1069
  * Map ODATANO UTxO to Ledger UTxO (ADA-only)
@@ -659,7 +1085,15 @@ class BuildooorTxBuilder {
659
1085
  */
660
1086
  _mapMultiAssetUtxoToLedgerUtxo(utxo) {
661
1087
  const value = this._buildLedgerValue((0, tx_build_helper_1.getLovelace)(utxo), utxo.amount);
662
- 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;
663
1097
  return new cardano_ledger_ts_1.UTxO({
664
1098
  utxoRef: new cardano_ledger_ts_1.TxOutRef({ id: utxo.txHash, index: utxo.outputIndex }),
665
1099
  resolved: new cardano_ledger_ts_1.TxOut({
@@ -679,25 +1113,47 @@ class BuildooorTxBuilder {
679
1113
  }
680
1114
  const metadata = {};
681
1115
  for (const [label, value] of Object.entries(metadataJson)) {
682
- const numericLabel = parseInt(label, 10);
683
- const txMetadatum = this._jsonToTxMetadatum(value);
684
- logger.debug(`Created TxMetadatum for label ${numericLabel}: ${txMetadatum.constructor.name}`);
685
- 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);
686
1120
  }
687
- logger.debug(`Creating TxMetadata with ${Object.keys(metadata).length} labels`);
688
- const txMetadata = new TxMetadata_1.TxMetadata(metadata);
689
- logger.debug(`TxMetadata created: ${txMetadata.constructor.name}, instanceof check: ${txMetadata instanceof TxMetadata_1.TxMetadata}`);
690
- return txMetadata;
1121
+ return new TxMetadata_1.TxMetadata(metadata);
691
1122
  }
692
1123
  /**
693
- * 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
694
1134
  */
695
1135
  _jsonToTxMetadatum(value) {
696
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
+ }
697
1140
  return new TxMetadatum_1.TxMetadatumInt(BigInt(value));
698
1141
  }
699
1142
  if (typeof value === 'string') {
700
- 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)));
701
1157
  }
702
1158
  if (Array.isArray(value)) {
703
1159
  return new TxMetadatum_1.TxMetadatumList(value.map(v => this._jsonToTxMetadatum(v)));
@@ -705,6 +1161,9 @@ class BuildooorTxBuilder {
705
1161
  if (typeof value === 'object' && value !== null) {
706
1162
  const map = [];
707
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
+ }
708
1167
  map.push({
709
1168
  k: new TxMetadatum_1.TxMetadatumText(k),
710
1169
  v: this._jsonToTxMetadatum(v)