@odatano/core 1.9.3 → 1.9.5

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.
@@ -9,6 +9,8 @@ const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
9
9
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
12
+ // Vendored coin selection (buildooor PR #12 fix) — NOT this.txBuilder.keepRelevant; see keep-relevant.ts
13
+ const keep_relevant_1 = require("./keep-relevant");
12
14
  const cds_1 = __importDefault(require("@sap/cds"));
13
15
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
14
16
  // Metadata classes are imported from the DIST paths ON PURPOSE: buildooor's
@@ -136,6 +138,13 @@ class BuildooorTxBuilder {
136
138
  cardanoClient;
137
139
  genesisInfos;
138
140
  paramsFingerprint;
141
+ /**
142
+ * Chain cost-model arrays kept verbatim for language-view hashing. Maintained by
143
+ * _mapCostModels (in lockstep with the named-key models the TxBuilder is built
144
+ * with); consumed by _languageViewCostModels. Empty when the current parameters
145
+ * carry no usable cost models (library defaults in effect).
146
+ */
147
+ rawCostModelArrays = {};
139
148
  /**
140
149
  * Initialize the builder
141
150
  * @param client - The CardanoClient instance
@@ -212,7 +221,7 @@ class BuildooorTxBuilder {
212
221
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
213
222
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
214
223
  // Coin selection on candidates only; forced inputs are prepended unconditionally
215
- const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
224
+ const selected = (0, keep_relevant_1.keepRelevant)(outputValue, candidateInputs);
216
225
  const inputs = [...forcedInputs, ...selected];
217
226
  logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for ${label}`);
218
227
  const metadata = req.metadataJson !== undefined && req.metadataJson !== null
@@ -228,6 +237,9 @@ class BuildooorTxBuilder {
228
237
  }
229
238
  }
230
239
  async buildUnsignedMintTransaction(req, ctx) {
240
+ // Set once the collateral partition is known — an insufficient-funds rejection
241
+ // after that point is usually CAUSED by it, and the builder's message can't know.
242
+ let coinSelectionContext;
231
243
  try {
232
244
  this._ensureCurrentProtocolParameters(ctx);
233
245
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
@@ -249,11 +261,12 @@ class BuildooorTxBuilder {
249
261
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
250
262
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
251
263
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
264
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
252
265
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
253
266
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
254
267
  // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
255
268
  const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
256
- const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
269
+ const selectedFunding = (0, keep_relevant_1.keepRelevant)(requiredFundingValue, allFundingInputs);
257
270
  const inputs = [...forcedInputs, ...selectedFunding];
258
271
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
259
272
  // FR-3: resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum after final input order is known.
@@ -302,10 +315,12 @@ class BuildooorTxBuilder {
302
315
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
303
316
  }
304
317
  catch (err) {
305
- (0, tx_build_helper_1.mapBuilderError)(err);
318
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
306
319
  }
307
320
  }
308
321
  async buildUnsignedPlutusSpendTransaction(req, ctx) {
322
+ // See buildUnsignedMintTransaction — same collateral-partition context for rejections.
323
+ let coinSelectionContext;
309
324
  try {
310
325
  this._ensureCurrentProtocolParameters(ctx);
311
326
  const { plutusScriptExecution } = req;
@@ -333,6 +348,7 @@ class BuildooorTxBuilder {
333
348
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
334
349
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
335
350
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
351
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
336
352
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
337
353
  // Coin selection: funding UTxOs only need to cover fee + min change (script UTxO covers the output).
338
354
  // Extra outputs (FR-2) add their lovelace + assets to the requirement; assets that the script UTxO
@@ -344,7 +360,7 @@ class BuildooorTxBuilder {
344
360
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
345
361
  }
346
362
  }
347
- const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
363
+ const selectedFundingInputs = (0, keep_relevant_1.keepRelevant)(requiredFundingValue, allFundingInputs);
348
364
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
349
365
  // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
350
366
  // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
@@ -427,7 +443,7 @@ class BuildooorTxBuilder {
427
443
  });
428
444
  }
429
445
  catch (err) {
430
- (0, tx_build_helper_1.mapBuilderError)(err);
446
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
431
447
  }
432
448
  }
433
449
  //---------------------------------------------------------------------------
@@ -662,25 +678,31 @@ class BuildooorTxBuilder {
662
678
  * Not implemented via TxBuilder.overrideTxRedeemers: that method computes the script
663
679
  * data hash from the OLD witness set (library bug), which would yield a phase-1
664
680
  * rejection (PPViewHashesDontMatch). We rebuild the witness set first and hash it with
665
- * the same exported getScriptDataHash + language views the build itself uses.
681
+ * the same exported getScriptDataHash the build itself uses.
682
+ *
683
+ * The hash is recomputed even when the target units already match: Buildooor's
684
+ * internal hash comes from the named-key cost models, which clamp the chain array
685
+ * to the parameter count the library release knows — wrong on networks whose cost
686
+ * model has grown past that (ScriptIntegrityHashMismatch at submit). This recompute
687
+ * with _languageViewCostModels (raw chain arrays) is where the hash becomes correct.
666
688
  */
667
689
  _stampExecUnits(tx, targets) {
668
690
  const rdmrs = tx.witnesses.redeemers ?? [];
669
691
  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({
692
+ const stamped = unchanged ? [...rdmrs] : rdmrs.map((r, i) => new cardano_ledger_ts_1.TxRedeemer({
673
693
  tag: r.tag,
674
694
  index: r.index,
675
695
  data: r.data,
676
696
  execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
677
697
  }));
678
698
  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));
699
+ const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
680
700
  const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
681
701
  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('; '));
702
+ if (!unchanged) {
703
+ logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
704
+ stamped.map(s => `${(0, cardano_ledger_ts_1.txRedeemerTagToString)(s.tag)}:${s.index} mem=${s.execUnits.mem} cpu=${s.execUnits.cpu}`).join('; '));
705
+ }
684
706
  return finalTx;
685
707
  }
686
708
  /**
@@ -699,6 +721,20 @@ class BuildooorTxBuilder {
699
721
  opts.mustHaveV3 = true;
700
722
  return opts;
701
723
  }
724
+ /**
725
+ * Cost models for language-view hashing. The named-key objects the TxBuilder was
726
+ * constructed with clamp the chain array to the parameter count this costmodels-ts
727
+ * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
728
+ * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
729
+ * array form through unclamped, so substitute the raw chain arrays where we have
730
+ * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
731
+ */
732
+ _languageViewCostModels() {
733
+ const models = this.txBuilder.protocolParamters.costModels;
734
+ if (Object.keys(this.rawCostModelArrays).length === 0)
735
+ return models;
736
+ return { ...models, ...this.rawCostModelArrays };
737
+ }
702
738
  /**
703
739
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
704
740
  * coin selection / collateral). Refs in forceInputs that are not present in utxos are
@@ -746,6 +782,18 @@ class BuildooorTxBuilder {
746
782
  };
747
783
  });
748
784
  }
785
+ /**
786
+ * Consumer-facing context for insufficient-funds rejections after the
787
+ * collateral partition: the builder's own "not enough …" message counts only
788
+ * the funding pool, and without this the reservation is invisible ("but the
789
+ * address HAS enough ADA").
790
+ */
791
+ _collateralPartitionContext(collateralUtxos, fundingUtxos) {
792
+ const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
793
+ const fundingLovelace = fundingUtxos.reduce((s, u) => s + (0, tx_build_helper_1.getLovelace)(u), 0n);
794
+ return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral; ` +
795
+ `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
796
+ }
749
797
  /**
750
798
  * Pick a collateral UTxO and return remaining funding UTxOs.
751
799
  * Throws if no ADA-only UTxO is available.
@@ -1018,8 +1066,14 @@ class BuildooorTxBuilder {
1018
1066
  * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
1019
1067
  * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
1020
1068
  * usable is found, so the caller can keep defaults and warn.
1069
+ *
1070
+ * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
1071
+ * for the versions mapped here — the named-key conversion drops every entry past
1072
+ * the parameter count this costmodels-ts release knows, and the scriptDataHash
1073
+ * must cover all of them (see _languageViewCostModels).
1021
1074
  */
1022
1075
  _mapCostModels(costModelsJson) {
1076
+ this.rawCostModelArrays = {};
1023
1077
  if (!costModelsJson)
1024
1078
  return undefined;
1025
1079
  let raw;
@@ -1039,6 +1093,7 @@ class BuildooorTxBuilder {
1039
1093
  };
1040
1094
  // Buildooor's CEK Machine rejects array-form cost models — convert to named-key objects.
1041
1095
  const result = {};
1096
+ const rawArrays = {};
1042
1097
  for (const [key, value] of Object.entries(raw)) {
1043
1098
  const target = KEY_MAP[key];
1044
1099
  if (!target || !Array.isArray(value))
@@ -1051,6 +1106,10 @@ class BuildooorTxBuilder {
1051
1106
  result[target] = (0, buildooor_1.toCostModelV2)(arr);
1052
1107
  else
1053
1108
  result[target] = (0, buildooor_1.toCostModelV3)(arr);
1109
+ // Non-finite entries would break the language-view CBOR; without a raw array
1110
+ // the hash falls back to the clamped named-key form for this version.
1111
+ if (arr.every(Number.isFinite))
1112
+ rawArrays[target] = arr;
1054
1113
  }
1055
1114
  catch {
1056
1115
  logger.warn(`Cost-model array for ${key} has unexpected length (${value.length}) — skipping`);
@@ -1063,6 +1122,7 @@ class BuildooorTxBuilder {
1063
1122
  logger.warn('Mapped cost models failed Buildooor validation — keeping library defaults');
1064
1123
  return undefined;
1065
1124
  }
1125
+ this.rawCostModelArrays = rawArrays;
1066
1126
  return result;
1067
1127
  }
1068
1128
  /**
@@ -1116,7 +1176,7 @@ class BuildooorTxBuilder {
1116
1176
  if (!/^\d+$/.test(label)) {
1117
1177
  throw new errors_1.TransactionValidationError(`Invalid metadata label "${label}" — labels must be non-negative integers`);
1118
1178
  }
1119
- metadata[Number(label)] = this._jsonToTxMetadatum(value);
1179
+ metadata[Number(label)] = this._jsonToTxMetadatum(value, label);
1120
1180
  }
1121
1181
  return new TxMetadata_1.TxMetadata(metadata);
1122
1182
  }
@@ -1131,11 +1191,15 @@ class BuildooorTxBuilder {
1131
1191
  * - strings prefixed with "0x" (even hex length) become byte metadata
1132
1192
  * - map keys are not auto-chunked (readers match on the literal key) — over-long
1133
1193
  * keys are rejected with a clear 400
1194
+ *
1195
+ * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
1196
+ * "1155.result" or "721.files[0].src") — named in every rejection
1197
+ * so the consumer can locate the offending value.
1134
1198
  */
1135
- _jsonToTxMetadatum(value) {
1199
+ _jsonToTxMetadatum(value, path) {
1136
1200
  if (typeof value === 'number' || typeof value === 'bigint') {
1137
1201
  if (typeof value === 'number' && !Number.isInteger(value)) {
1138
- throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value}) — encode decimals as strings`);
1202
+ throw new errors_1.TransactionValidationError(`Metadata numbers must be integers (got ${value} at ${path}) — encode decimals as strings`);
1139
1203
  }
1140
1204
  return new TxMetadatum_1.TxMetadatumInt(BigInt(value));
1141
1205
  }
@@ -1156,22 +1220,23 @@ class BuildooorTxBuilder {
1156
1220
  return new TxMetadatum_1.TxMetadatumList(chunks.map(c => new TxMetadatum_1.TxMetadatumText(c)));
1157
1221
  }
1158
1222
  if (Array.isArray(value)) {
1159
- return new TxMetadatum_1.TxMetadatumList(value.map(v => this._jsonToTxMetadatum(v)));
1223
+ return new TxMetadatum_1.TxMetadatumList(value.map((v, i) => this._jsonToTxMetadatum(v, `${path}[${i}]`)));
1160
1224
  }
1161
1225
  if (typeof value === 'object' && value !== null) {
1162
1226
  const map = [];
1163
1227
  for (const [k, v] of Object.entries(value)) {
1164
1228
  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)}…"`);
1229
+ throw new errors_1.TransactionValidationError(`Metadata map key exceeds ${METADATA_BYTE_LIMIT} bytes (UTF-8) at ${path}: "${k.slice(0, 32)}…"`);
1166
1230
  }
1167
1231
  map.push({
1168
1232
  k: new TxMetadatum_1.TxMetadatumText(k),
1169
- v: this._jsonToTxMetadatum(v)
1233
+ v: this._jsonToTxMetadatum(v, `${path}.${k}`)
1170
1234
  });
1171
1235
  }
1172
1236
  return new TxMetadatum_1.TxMetadatumMap(map);
1173
1237
  }
1174
- throw new errors_1.TransactionValidationError(`Unsupported metadata value type: ${typeof value}`);
1238
+ throw new errors_1.TransactionValidationError(`Unsupported metadata value type: ${value === null ? 'null' : typeof value} at ${path}` +
1239
+ (typeof value === 'boolean' ? ' — on-chain metadata has no boolean; encode as string or 0/1' : ''));
1175
1240
  }
1176
1241
  }
1177
1242
  exports.BuildooorTxBuilder = BuildooorTxBuilder;
@@ -0,0 +1,29 @@
1
+ import { type CanBeUInteger, type ITxBuildInput } from "@harmoniclabs/buildooor";
2
+ import { Value, type ValueUnits } from "@harmoniclabs/cardano-ledger-ts";
3
+ /**
4
+ * Coin selection ("keep relevant" strategy) — vendored fix for
5
+ * @harmoniclabs/buildooor 0.2.6 (HarmonicLabs/buildooor PR #12).
6
+ *
7
+ * The shipped `TxBuilder.keepRelevant` has several defects: the asset-relevance
8
+ * filter matches lovelace too (whenever lovelace is requested, EVERY input counts
9
+ * as a multi-asset match and the whole UTxO set is selected), the dedup between
10
+ * the asset and lovelace selection phases compares only the tx id — not id#index,
11
+ * so sibling outputs of one transaction collapse and inputs get selected twice —
12
+ * the lovelace sort goes through parseInt/number (breaks above 2^53), and
13
+ * `enoughValueHasBeenSelected` has an operator-precedence bug that makes asset
14
+ * sums meaningless.
15
+ *
16
+ * Vendored here (instead of patch-package) so the fix actually reaches consumers
17
+ * of the published package: `patches/` never ships in the tarball, and running
18
+ * patch-package from a dependency's postinstall is unreliable under npm hoisting.
19
+ * Drop this module and call `txBuilder.keepRelevant` again once a buildooor
20
+ * release contains the upstream PR.
21
+ *
22
+ * Semantics: select the inputs holding any requested non-lovelace asset, then add
23
+ * smallest-first lovelace-relevant inputs until the requested lovelace (plus a
24
+ * safety minimum for fee/change) is covered. Selection may still undershoot when
25
+ * the pool itself is insufficient — Buildooor's build() surfaces that as its own
26
+ * insufficient-funds error, exactly like the upstream implementation.
27
+ */
28
+ export declare function keepRelevant(requestedOutputSet: Value | ValueUnits | Record<string, CanBeUInteger>, initialUTxOSet: ITxBuildInput[], minimumLovelaceRequired?: CanBeUInteger): ITxBuildInput[];
29
+ //# sourceMappingURL=keep-relevant.d.ts.map
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keepRelevant = keepRelevant;
4
+ const buildooor_1 = require("@harmoniclabs/buildooor");
5
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
+ /**
7
+ * Coin selection ("keep relevant" strategy) — vendored fix for
8
+ * @harmoniclabs/buildooor 0.2.6 (HarmonicLabs/buildooor PR #12).
9
+ *
10
+ * The shipped `TxBuilder.keepRelevant` has several defects: the asset-relevance
11
+ * filter matches lovelace too (whenever lovelace is requested, EVERY input counts
12
+ * as a multi-asset match and the whole UTxO set is selected), the dedup between
13
+ * the asset and lovelace selection phases compares only the tx id — not id#index,
14
+ * so sibling outputs of one transaction collapse and inputs get selected twice —
15
+ * the lovelace sort goes through parseInt/number (breaks above 2^53), and
16
+ * `enoughValueHasBeenSelected` has an operator-precedence bug that makes asset
17
+ * sums meaningless.
18
+ *
19
+ * Vendored here (instead of patch-package) so the fix actually reaches consumers
20
+ * of the published package: `patches/` never ships in the tarball, and running
21
+ * patch-package from a dependency's postinstall is unreliable under npm hoisting.
22
+ * Drop this module and call `txBuilder.keepRelevant` again once a buildooor
23
+ * release contains the upstream PR.
24
+ *
25
+ * Semantics: select the inputs holding any requested non-lovelace asset, then add
26
+ * smallest-first lovelace-relevant inputs until the requested lovelace (plus a
27
+ * safety minimum for fee/change) is covered. Selection may still undershoot when
28
+ * the pool itself is insufficient — Buildooor's build() surfaces that as its own
29
+ * insufficient-funds error, exactly like the upstream implementation.
30
+ */
31
+ function keepRelevant(requestedOutputSet, initialUTxOSet, minimumLovelaceRequired = 5_000_000) {
32
+ const requested = normalizeRequestedOutputSet(requestedOutputSet);
33
+ const requestedLovelace = (requested["lovelace"] ?? 0n) + (0, buildooor_1.forceBigUInt)(minimumLovelaceRequired);
34
+ const requestedAssetUnits = Object.keys(requested).filter(unit => unit !== "lovelace");
35
+ const multiAssetIns = initialUTxOSet.filter(input => new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
36
+ .filter(asset => asset.unit !== "lovelace")
37
+ .some(asset => requestedAssetUnits.includes(asset.unit)));
38
+ const totLovelaces = getTotLovelaces(multiAssetIns);
39
+ const lovelaceIns = totLovelaces < requestedLovelace
40
+ ? remainingLovelace(requestedLovelace - totLovelaces,
41
+ // filter out inputs already picked by the multi-asset selection
42
+ initialUTxOSet.filter(initialUtxo => {
43
+ const refStr = utxoRefStr(initialUtxo);
44
+ return !multiAssetIns.some(selected => utxoRefStr(selected) === refStr);
45
+ }))
46
+ : [];
47
+ return lovelaceIns.concat(multiAssetIns).map(buildooor_1.normalizeITxBuildInput);
48
+ }
49
+ /**
50
+ * Tolerates `Value` instances from a duplicated `cardano-ledger-ts` in
51
+ * node_modules, where `instanceof` fails across the two copies.
52
+ */
53
+ function isValueLike(x) {
54
+ return x instanceof cardano_ledger_ts_1.Value ||
55
+ (!Array.isArray(x) && typeof x?.toUnits === "function");
56
+ }
57
+ /**
58
+ * `keepRelevant` historically accepted two shapes besides `Value`: the
59
+ * `ValueUnits` array returned by `Value.toUnits()` and a Mesh-style
60
+ * `{ [unit]: quantity }` record. Normalize all of them to a record with
61
+ * `bigint` quantities so the algorithm only deals with one shape.
62
+ */
63
+ function normalizeRequestedOutputSet(requested) {
64
+ const units = isValueLike(requested)
65
+ ? requested.toUnits()
66
+ : requested;
67
+ const result = {};
68
+ if (Array.isArray(units)) {
69
+ for (const { unit, quantity } of units) {
70
+ result[unit] = (result[unit] ?? 0n) + BigInt(quantity);
71
+ }
72
+ return result;
73
+ }
74
+ for (const unit of Object.keys(units)) {
75
+ result[unit] = BigInt(units[unit]);
76
+ }
77
+ return result;
78
+ }
79
+ /** Full utxo ref (id#index) — the id alone collapses sibling outputs of one tx. */
80
+ function utxoRefStr(input) {
81
+ const ref = input.utxo.utxoRef;
82
+ return `${ref.id.toString()}#${ref.index.toString()}`;
83
+ }
84
+ function getTotLovelaces(inputs) {
85
+ return inputs.reduce((sum, input) => sum + new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.lovelaces, 0n);
86
+ }
87
+ function remainingLovelace(quantity, initialUTxOSet) {
88
+ // smallest-first, compared as bigint (a number sort breaks above 2^53 lovelace)
89
+ const sortedUTxOs = initialUTxOSet.slice().sort((a, b) => {
90
+ const aLovelaces = new cardano_ledger_ts_1.UTxO(a.utxo).resolved.value.lovelaces;
91
+ const bLovelaces = new cardano_ledger_ts_1.UTxO(b.utxo).resolved.value.lovelaces;
92
+ return aLovelaces < bLovelaces ? -1 : aLovelaces > bLovelaces ? 1 : 0;
93
+ });
94
+ return selectValue(sortedUTxOs, { lovelace: quantity });
95
+ }
96
+ function enoughValueHasBeenSelected(selection, assets) {
97
+ return Object.keys(assets).every(unit => selection.reduce((selectedQuantity, input) => {
98
+ const utxoQuantity = new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
99
+ .reduce((quantity, a) => quantity + (unit === a.unit ? BigInt(a.quantity) : 0n), 0n);
100
+ return selectedQuantity + utxoQuantity;
101
+ }, 0n) >= assets[unit]);
102
+ }
103
+ function selectValue(inputUTxO, outputSet, selection = []) {
104
+ if (inputUTxO.length === 0 || enoughValueHasBeenSelected(selection, outputSet)) {
105
+ return selection;
106
+ }
107
+ if (canValueBeSelected(inputUTxO[0], outputSet)) {
108
+ return selectValue(inputUTxO.slice(1), outputSet, selection.concat(inputUTxO[0]));
109
+ }
110
+ return selectValue(inputUTxO.slice(1), outputSet, selection);
111
+ }
112
+ function canValueBeSelected(input, assets) {
113
+ return Object.keys(assets).some(unit => new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
114
+ .some(asset => asset.unit === unit));
115
+ }
116
+ //# sourceMappingURL=keep-relevant.js.map
@@ -208,7 +208,7 @@ service CardanoODataService @(impl: './cardano-service') {
208
208
  action GetMetadataByTxHash(
209
209
  @title: 'Transaction Hash'
210
210
  @description: 'The unique identifier of the transaction'
211
- tx_hash: Blake2b256) returns many TransactionMetadata;
211
+ txHash: Blake2b256) returns many TransactionMetadata;
212
212
 
213
213
  @title : 'Get Addresses by Bech32 Address'
214
214
  @description: 'Retrieve address information using the Bech32 Address'
@@ -249,17 +249,18 @@ module.exports = (srv) => {
249
249
  srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, (db, h) => indexer().indexTransactionMetadata(db, h), { errorMessage: 'Invalid transaction hash format' }));
250
250
  /**
251
251
  * Action: GetMetadataByTxHash - returns multiple metadata rows (uses SELECT.from, not SELECT.one).
252
+ * Takes camelCase `txHash` like every other action (renamed from `tx_hash` in 1.9.4).
252
253
  */
253
254
  srv.on('GetMetadataByTxHash', async (req) => {
254
- const { tx_hash } = req.data;
255
- if (!tx_hash)
256
- (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'tx_hash');
257
- if (!(0, validators_1.isTxHash)(tx_hash))
258
- (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'tx_hash');
255
+ const { txHash } = req.data;
256
+ if (!txHash)
257
+ (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'txHash');
258
+ if (!(0, validators_1.isTxHash)(txHash))
259
+ (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'txHash');
259
260
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
260
- const existing = await db.run(SELECT.from(TransactionMetadata).where({ tx_hash }));
261
+ const existing = await db.run(SELECT.from(TransactionMetadata).where({ tx_hash: txHash }));
261
262
  if (!existing || existing.length === 0) {
262
- return await indexer().indexTransactionMetadata(db, tx_hash);
263
+ return await indexer().indexTransactionMetadata(db, txHash);
263
264
  }
264
265
  return existing;
265
266
  });
@@ -14,6 +14,7 @@ const external_signer_1 = require("./blockchain/signing/external-signer");
14
14
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
15
15
  const cose_verifier_1 = require("./blockchain/signing/cose-verifier");
16
16
  const signing_helper_1 = require("./utils/signing-helper");
17
+ const tx_build_helper_1 = require("./utils/tx-build-helper");
17
18
  const { SELECT, UPDATE } = cds_1.default.ql;
18
19
  const logger = cds_1.default.log('CardanoSignService');
19
20
  /**
@@ -106,6 +107,14 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
106
107
  const submission = await (0, server_1.getCardanoIndexer)().indexVerifiedTransactionSubmission(db, params);
107
108
  if (afterFinalize)
108
109
  await afterFinalize(db);
110
+ // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
111
+ // must never roll back the durable submission record.
112
+ try {
113
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
114
+ }
115
+ catch (invalidateErr) {
116
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
117
+ }
109
118
  return submission;
110
119
  });
111
120
  try {
@@ -14,7 +14,7 @@ const mappers_1 = require("./utils/mappers");
14
14
  const server_1 = require("./server");
15
15
  const const_1 = require("./utils/const");
16
16
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
17
- const { SELECT, UPDATE, DELETE: DELETE_FROM } = cds_1.default.ql;
17
+ const { SELECT, UPDATE } = cds_1.default.ql;
18
18
  const logger = cds_1.default.log('CardanoTxService');
19
19
  /**
20
20
  * Parse and validate a JSON array of UTxO refs ({txHash, outputIndex}) — the shared
@@ -175,7 +175,6 @@ function parseExtraOutputs(extraOutputsJson) {
175
175
  module.exports = (srv) => {
176
176
  logger.debug('Module loaded - registering handlers');
177
177
  const { TransactionBuilds, TransactionSubmissions, AddressTransactionBuilds } = require('#cds-models/CardanoTransactionService');
178
- const { Addresses, AddressUTxOs, AddressAssets } = require('#cds-models/CardanoODataService');
179
178
  /**
180
179
  * Build a simple ADA-only transaction
181
180
  * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, changeAddress)
@@ -466,13 +465,13 @@ module.exports = (srv) => {
466
465
  delete cleanData.referenceScriptHex;
467
466
  // Apply script parameters if provided (for parameterized validators)
468
467
  let finalMintingPolicyScript = mintingPolicyScript;
468
+ let effectivePolicyId;
469
469
  if (scriptParams && scriptParams.length > 0) {
470
- let appliedPolicyId;
471
470
  try {
472
471
  finalMintingPolicyScript = (0, tx_build_helper_1.applyScriptParameters)(mintingPolicyScript, scriptParams);
473
472
  // BUG 7 fix: expand assetName-only entries to full assetUnit using the applied script's policyId.
474
473
  const appliedScript = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalMintingPolicyScript, 'hex'));
475
- appliedPolicyId = appliedScript.hash.toString();
474
+ effectivePolicyId = appliedScript.hash.toString();
476
475
  }
477
476
  catch (err) {
478
477
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -480,14 +479,34 @@ module.exports = (srv) => {
480
479
  }
481
480
  for (const action of parsedMintActions) {
482
481
  if (action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
483
- action.assetUnit = appliedPolicyId + action.assetUnit;
482
+ action.assetUnit = effectivePolicyId + action.assetUnit;
484
483
  }
485
484
  }
486
485
  // lockOnScript: route output to the enterprise script address derived from applied script hash
487
486
  if (lockOnScript) {
488
- const scriptAddr = (0, mappers_1.scriptHashToEnterpriseAddress)(appliedPolicyId, (0, server_1.getCardanoClient)().network);
487
+ const scriptAddr = (0, mappers_1.scriptHashToEnterpriseAddress)(effectivePolicyId, (0, server_1.getCardanoClient)().network);
489
488
  cleanData.recipientAddress = scriptAddr;
490
- logger.debug({ scriptAddress: scriptAddr, scriptHash: appliedPolicyId }, 'lockOnScript: routing output to script address');
489
+ logger.debug({ scriptAddress: scriptAddr, scriptHash: effectivePolicyId }, 'lockOnScript: routing output to script address');
490
+ }
491
+ }
492
+ else {
493
+ try {
494
+ effectivePolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(mintingPolicyScript, 'hex')).hash.toString();
495
+ }
496
+ catch {
497
+ // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
498
+ }
499
+ }
500
+ // BUG 9 fix: the builder mints every action under the policy script's hash and
501
+ // parseAssetUnit silently discards the unit's first 56 hex chars. A bare asset name
502
+ // of 29-32 bytes is length-indistinguishable from a full unit, so a mismatched
503
+ // prefix would mint a truncated name. At this point every action holds a full
504
+ // unit (bare names were expanded above), so all of them must carry the policyId.
505
+ if (effectivePolicyId) {
506
+ const policyId = effectivePolicyId;
507
+ const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
508
+ if (mismatch) {
509
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`, 'mintActionsJson');
491
510
  }
492
511
  }
493
512
  const buildResult = await (0, server_1.getCardanoIndexer)().indexMintBuildResult(db, {
@@ -504,10 +523,13 @@ module.exports = (srv) => {
504
523
  if (buildResult.scriptHash) {
505
524
  const policyId = buildResult.scriptHash;
506
525
  const updates = {};
507
- // CIP-14 asset fingerprint for the first minted asset
526
+ // CIP-14 asset fingerprint for the first minted asset. The unit is always a
527
+ // full policyId+assetName here: bare names were expanded before the build and
528
+ // the BUG 9 prefix check rejected everything else (a 56-hex unit is an empty
529
+ // asset name, not a bare 28-byte name).
508
530
  if (parsedMintActions.length > 0) {
509
531
  const firstAssetUnit = parsedMintActions[0].assetUnit;
510
- const assetNameHex = firstAssetUnit.length >= const_1.MIN_FULL_ASSET_UNIT_LENGTH ? firstAssetUnit.slice(const_1.POLICY_ID_HEX_LENGTH) : firstAssetUnit;
532
+ const assetNameHex = firstAssetUnit.slice(const_1.POLICY_ID_HEX_LENGTH);
511
533
  buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex);
512
534
  updates.fingerprint = buildResult.fingerprint;
513
535
  }
@@ -671,6 +693,26 @@ module.exports = (srv) => {
671
693
  }
672
694
  }
673
695
  }
696
+ // BUG 9 fix: same policyId-prefix check as BuildMintTransaction — the builder
697
+ // mints every action under the mint script's hash and parseAssetUnit silently
698
+ // discards the unit's first 56 hex chars, so a mismatched prefix would mint a
699
+ // truncated asset name.
700
+ if (finalMintingPolicyScript) {
701
+ let mintPolicyId;
702
+ try {
703
+ mintPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalMintingPolicyScript, 'hex')).hash.toString();
704
+ }
705
+ catch {
706
+ // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
707
+ }
708
+ if (mintPolicyId) {
709
+ const policyId = mintPolicyId;
710
+ const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
711
+ if (mismatch) {
712
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`, 'mintActionsJson');
713
+ }
714
+ }
715
+ }
674
716
  }
675
717
  const cleanData = {
676
718
  ...req.data,
@@ -832,13 +874,15 @@ module.exports = (srv) => {
832
874
  logger.info({ txHash }, 'Transaction submitted to blockchain');
833
875
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
834
876
  submissionRecord.status = 'submitted';
835
- // Invalidate sender address cache so next read fetches fresh data
836
- const addrBuild = await db.run(SELECT.one.from(AddressTransactionBuilds).where({ txBuild_id: buildId }));
837
- if (addrBuild?.address_address) {
838
- await db.run(DELETE_FROM.from(Addresses).where({ address: addrBuild.address_address }));
839
- await db.run(DELETE_FROM.from(AddressUTxOs).where({ address_address: addrBuild.address_address }));
840
- await db.run(DELETE_FROM.from(AddressAssets).where({ address_address: addrBuild.address_address }));
841
- logger.debug(`Invalidated cache for sender address ${addrBuild.address_address.substring(0, 20)}...`);
877
+ // Invalidate stale UTxO cache: spent input refs + output addresses from
878
+ // the signed CBOR, plus the build's sender address. Best-effort — a
879
+ // failure here must not fail the already-successful submit.
880
+ try {
881
+ const addrBuild = await db.run(SELECT.one.from(AddressTransactionBuilds).where({ txBuild_id: buildId }));
882
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor), addrBuild?.address_address ? [addrBuild.address_address] : []);
883
+ }
884
+ catch (invalidateErr) {
885
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
842
886
  }
843
887
  }
844
888
  catch (err) {
@@ -883,6 +927,13 @@ module.exports = (srv) => {
883
927
  logger.info({ txHash }, 'External transaction submitted');
884
928
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
885
929
  submissionRecord.status = 'submitted';
930
+ // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort
931
+ try {
932
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor));
933
+ }
934
+ catch (invalidateErr) {
935
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
936
+ }
886
937
  }
887
938
  catch (err) {
888
939
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -88,11 +88,14 @@ export declare class InsufficientFundsError extends BackendError {
88
88
  readonly available: bigint;
89
89
  /** Constructor
90
90
  * @param assetUnit the asset unit that is insufficient (e.g., "lovelace" or "policyId.assetName")
91
- * @param required the required amount
92
- * @param available the available amount
91
+ * @param required the required amount (0n when unknown)
92
+ * @param available the available amount (0n when unknown)
93
93
  * @param originalError original error object
94
+ * @param detail human-readable cause shown INSTEAD of the amounts — use when
95
+ * the amounts are unknown; "required 0, available 0" reads as
96
+ * nonsense from the consumer's perspective
94
97
  */
95
- constructor(assetUnit: string, required: bigint, available: bigint, originalError?: unknown);
98
+ constructor(assetUnit: string, required: bigint, available: bigint, originalError?: unknown, detail?: string);
96
99
  }
97
100
  /**
98
101
  * MixedAssetsError - UTxO contains mixed assets when pure ADA is required (400)