@odatano/core 1.9.2 → 1.9.4

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.
@@ -117,6 +117,43 @@ class CardanoClient {
117
117
  });
118
118
  await this.initPromise;
119
119
  }
120
+ /**
121
+ * Transient (retryable) init failures: a backend momentarily unreachable at
122
+ * startup — e.g. Ogmios's /health response cut short while the node processes
123
+ * a freshly-arrived block ("Premature close"), or the socket still coming up
124
+ * (ECONNREFUSED). Config/validation errors are NOT transient.
125
+ */
126
+ static isTransientInitError(err) {
127
+ const e = err;
128
+ const code = e?.code ?? e?.cause?.code ?? '';
129
+ const msg = `${e?.message ?? ''} ${e?.cause?.message ?? ''}`.toLowerCase();
130
+ if (['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_SOCKET'].includes(code))
131
+ return true;
132
+ return /premature close|socket hang up|econnreset|econnrefused|etimedout|timeout|fetch failed|terminated|other side closed/.test(msg);
133
+ }
134
+ /**
135
+ * Init a backend, retrying brief transient failures. Deliberately SMALL: the
136
+ * integration suites bootstrap under a 20s cds.test() hook, so total retry
137
+ * time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
138
+ * ≈ 14s worst case; in practice "Premature close" returns sub-second). With
139
+ * the node at tip these failures are momentary block-processing blips, so a
140
+ * couple of quick retries ride over them; a sustained outage still fails fast.
141
+ */
142
+ async initBackendWithRetry(backend) {
143
+ const maxAttempts = 3;
144
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
145
+ try {
146
+ await backend.init();
147
+ return;
148
+ }
149
+ catch (err) {
150
+ if (attempt >= maxAttempts || !CardanoClient.isTransientInitError(err))
151
+ throw err;
152
+ logger.warn(`Init of ${backend.name} failed (attempt ${attempt}/${maxAttempts}) — transient, retrying in 1s`, err);
153
+ await new Promise(r => setTimeout(r, 1000));
154
+ }
155
+ }
156
+ }
120
157
  /**
121
158
  * Initialize all backends from configuration.
122
159
  * Backends that fail to initialize are KEPT (previously removed permanently)
@@ -131,7 +168,7 @@ class CardanoClient {
131
168
  if (this.liveBackend) {
132
169
  try {
133
170
  logger.debug(`Initializing live backend: ${this.liveBackend.name}`);
134
- await this.liveBackend.init();
171
+ await this.initBackendWithRetry(this.liveBackend);
135
172
  this.uninitializedBackends.delete(this.liveBackend);
136
173
  logger.debug(`Live backend initialized: ${this.liveBackend.name}`);
137
174
  }
@@ -145,7 +182,7 @@ class CardanoClient {
145
182
  for (const backend of this.historicalBackends) {
146
183
  try {
147
184
  logger.debug(`Initializing historical backend: ${backend.name}`);
148
- await backend.init();
185
+ await this.initBackendWithRetry(backend);
149
186
  this.uninitializedBackends.delete(backend);
150
187
  logger.debug(`Historical backend initialized: ${backend.name}`);
151
188
  }
@@ -4,6 +4,7 @@ import type { CardanoTransactionBuilder } from './cardano-tx-builder';
4
4
  import { Transaction as CardanoTransaction, AddressUTxOs, TransactionMetadata, NetworkInformation, Block, Epoch, AssetHistory, Account, Drep, Pool, Asset, Address, LedgerProtocolParameter, AddressTransactions } from '#cds-models/CardanoODataService';
5
5
  import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTransactionService';
6
6
  import { TxBuildRequest, Transaction as ProviderTransaction } from '../utils/types';
7
+ import type { TxCacheTargets } from '../utils/tx-build-helper';
7
8
  /**
8
9
  * CardanoIndexer - Indexer for Cardano blockchain data into OData entities
9
10
  *
@@ -72,6 +73,24 @@ export declare class CardanoIndexer {
72
73
  * @return UTxO entity rows for the address (empty when the address holds none)
73
74
  */
74
75
  indexAddressUtxos(tx: CapTransaction, addr: string): Promise<AddressUTxOs[]>;
76
+ /**
77
+ * Evict cached rows a submitted transaction made stale, so the next read
78
+ * refetches instead of serving spent UTxOs for up to indexTtlMs:
79
+ * - every consumed input ref (spent under WHATEVER address cached it),
80
+ * - all address-level rows of the output addresses (their UTxO set gained
81
+ * the new outputs — sender change included) and of `extraAddresses`
82
+ * (e.g. the build's sender when the CBOR could not be parsed).
83
+ *
84
+ * Only the read cache is touched; submissions/builds stay untouched. Note the
85
+ * next refetch may STILL see pre-submit state on lagging backends
86
+ * (Blockfrost/Koios propagation) — that matches cache-less behaviour and is
87
+ * not recoverable server-side.
88
+ *
89
+ * @param tx CAP transaction
90
+ * @param targets input refs + output addresses from extractTxCacheTargets
91
+ * @param extraAddresses additional bech32 addresses to evict
92
+ */
93
+ invalidateUtxoCacheForTx(tx: CapTransaction, targets: TxCacheTargets, extraAddresses?: string[]): Promise<void>;
75
94
  /**
76
95
  * Index & return address transactions (separate from indexAddress for lazy loading)
77
96
  * @param tx CAP transaction
@@ -9,7 +9,7 @@ const CardanoODataService_1 = require("#cds-models/CardanoODataService");
9
9
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
10
10
  const CardanoSignService_1 = require("#cds-models/CardanoSignService");
11
11
  const mappers_1 = require("../utils/mappers");
12
- const { UPSERT, INSERT, UPDATE, SELECT } = cds_1.default.ql;
12
+ const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
13
13
  const logger = cds_1.default.log('CardanoIndexer');
14
14
  /**
15
15
  * CardanoIndexer - Indexer for Cardano blockchain data into OData entities
@@ -235,6 +235,39 @@ class CardanoIndexer {
235
235
  }
236
236
  return utxoEntities;
237
237
  }
238
+ /**
239
+ * Evict cached rows a submitted transaction made stale, so the next read
240
+ * refetches instead of serving spent UTxOs for up to indexTtlMs:
241
+ * - every consumed input ref (spent under WHATEVER address cached it),
242
+ * - all address-level rows of the output addresses (their UTxO set gained
243
+ * the new outputs — sender change included) and of `extraAddresses`
244
+ * (e.g. the build's sender when the CBOR could not be parsed).
245
+ *
246
+ * Only the read cache is touched; submissions/builds stay untouched. Note the
247
+ * next refetch may STILL see pre-submit state on lagging backends
248
+ * (Blockfrost/Koios propagation) — that matches cache-less behaviour and is
249
+ * not recoverable server-side.
250
+ *
251
+ * @param tx CAP transaction
252
+ * @param targets input refs + output addresses from extractTxCacheTargets
253
+ * @param extraAddresses additional bech32 addresses to evict
254
+ */
255
+ async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
256
+ const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
257
+ for (const address of addresses) {
258
+ await tx.run(DELETE.from(CardanoODataService_1.UTxOAssets).where({ utxo_address_address: address }));
259
+ await tx.run(DELETE.from(CardanoODataService_1.AddressUTxOs).where({ address_address: address }));
260
+ await tx.run(DELETE.from(CardanoODataService_1.AddressAssets).where({ address_address: address }));
261
+ await tx.run(DELETE.from(CardanoODataService_1.Addresses).where({ address }));
262
+ }
263
+ for (const input of targets.inputs) {
264
+ await tx.run(DELETE.from(CardanoODataService_1.UTxOAssets).where({ utxo_hash: input.txHash, utxo_index: input.outputIndex }));
265
+ await tx.run(DELETE.from(CardanoODataService_1.AddressUTxOs).where({ hash: input.txHash, index: input.outputIndex }));
266
+ }
267
+ if (addresses.length || targets.inputs.length) {
268
+ logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
269
+ }
270
+ }
238
271
  /**
239
272
  * Index & return address transactions (separate from indexAddress for lazy loading)
240
273
  * @param tx CAP transaction
@@ -359,7 +359,7 @@ class CardanoTransactionBuilder {
359
359
  const utxos = await this.client.getAddressUtxos(address);
360
360
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
361
361
  if (utxos.length === 0) {
362
- throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), new Error(`Address ${address} has no UTxOs. Verify this is the correct sender address and that it has been funded.`));
362
+ throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
363
363
  }
364
364
  return utxos;
365
365
  }
@@ -10,6 +10,13 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
10
10
  private cardanoClient;
11
11
  private genesisInfos;
12
12
  private paramsFingerprint;
13
+ /**
14
+ * Chain cost-model arrays kept verbatim for language-view hashing. Maintained by
15
+ * _mapCostModels (in lockstep with the named-key models the TxBuilder is built
16
+ * with); consumed by _languageViewCostModels. Empty when the current parameters
17
+ * carry no usable cost models (library defaults in effect).
18
+ */
19
+ private rawCostModelArrays;
13
20
  /**
14
21
  * Initialize the builder
15
22
  * @param client - The CardanoClient instance
@@ -101,7 +108,13 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
101
108
  * Not implemented via TxBuilder.overrideTxRedeemers: that method computes the script
102
109
  * data hash from the OLD witness set (library bug), which would yield a phase-1
103
110
  * rejection (PPViewHashesDontMatch). We rebuild the witness set first and hash it with
104
- * the same exported getScriptDataHash + language views the build itself uses.
111
+ * the same exported getScriptDataHash the build itself uses.
112
+ *
113
+ * The hash is recomputed even when the target units already match: Buildooor's
114
+ * internal hash comes from the named-key cost models, which clamp the chain array
115
+ * to the parameter count the library release knows — wrong on networks whose cost
116
+ * model has grown past that (ScriptIntegrityHashMismatch at submit). This recompute
117
+ * with _languageViewCostModels (raw chain arrays) is where the hash becomes correct.
105
118
  */
106
119
  private _stampExecUnits;
107
120
  /**
@@ -110,6 +123,15 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
110
123
  * scripts inline, so the witness set carries every executed script.
111
124
  */
112
125
  private _usedLanguageViewOpts;
126
+ /**
127
+ * Cost models for language-view hashing. The named-key objects the TxBuilder was
128
+ * constructed with clamp the chain array to the parameter count this costmodels-ts
129
+ * release knows (e.g. 297 for V3 pre-protocol-11), but the ledger hashes EVERY
130
+ * entry the chain serves (350 on protocol-11 networks). toCostModelArrVN passes
131
+ * array form through unclamped, so substitute the raw chain arrays where we have
132
+ * them. (The named-key form stays in the TxBuilder — the CEK machine needs it.)
133
+ */
134
+ private _languageViewCostModels;
113
135
  /**
114
136
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates (free for
115
137
  * coin selection / collateral). Refs in forceInputs that are not present in utxos are
@@ -127,6 +149,13 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
127
149
  * they are stamped into the redeemers post-build by _buildScriptTx).
128
150
  */
129
151
  private _buildMintEntries;
152
+ /**
153
+ * Consumer-facing context for insufficient-funds rejections after the
154
+ * collateral partition: the builder's own "not enough …" message counts only
155
+ * the funding pool, and without this the reservation is invisible ("but the
156
+ * address HAS enough ADA").
157
+ */
158
+ private _collateralPartitionContext;
130
159
  /**
131
160
  * Pick a collateral UTxO and return remaining funding UTxOs.
132
161
  * Throws if no ADA-only UTxO is available.
@@ -205,6 +234,11 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
205
234
  * 'PlutusV1'/'PlutusV2'/'PlutusV3' or Ogmios 'plutus:vN') into Buildooor's
206
235
  * CostModels shape ('PlutusScriptVN' keys). Returns undefined when nothing
207
236
  * usable is found, so the caller can keep defaults and warn.
237
+ *
238
+ * Side effect: (re)sets this.rawCostModelArrays with the unclamped chain arrays
239
+ * for the versions mapped here — the named-key conversion drops every entry past
240
+ * the parameter count this costmodels-ts release knows, and the scriptDataHash
241
+ * must cover all of them (see _languageViewCostModels).
208
242
  */
209
243
  private _mapCostModels;
210
244
  /**
@@ -230,6 +264,10 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
230
264
  * - strings prefixed with "0x" (even hex length) become byte metadata
231
265
  * - map keys are not auto-chunked (readers match on the literal key) — over-long
232
266
  * keys are rejected with a clear 400
267
+ *
268
+ * @param path position of `value` inside the metadata JSON (label-rooted, e.g.
269
+ * "1155.result" or "721.files[0].src") — named in every rejection
270
+ * so the consumer can locate the offending value.
233
271
  */
234
272
  private _jsonToTxMetadatum;
235
273
  }
@@ -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