@odatano/core 2.0.0-rc.27 → 2.0.0-rc.29

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.27",
3
+ "version": "2.0.0-rc.29",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -75,7 +75,7 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
75
75
  init(): Promise<boolean>;
76
76
  /**
77
77
  * Retry (500 → 1000 → 2000 ms) when Koios transiently returns [] for a valid query.
78
- * Element type is `any` on purpose: only non-emptiness is checked; rows are narrowed at use sites.
78
+ * Only non-emptiness is checked here; rows keep the caller's element type.
79
79
  */
80
80
  private fetchWithRetryOnEmpty;
81
81
  /**
@@ -114,10 +114,9 @@ class KoiosBackend {
114
114
  }
115
115
  /**
116
116
  * Retry (500 → 1000 → 2000 ms) when Koios transiently returns [] for a valid query.
117
- * Element type is `any` on purpose: only non-emptiness is checked; rows are narrowed at use sites.
117
+ * Only non-emptiness is checked here; rows keep the caller's element type.
118
118
  */
119
- async fetchWithRetryOnEmpty(fn, // eslint-disable-line @typescript-eslint/no-explicit-any
120
- label) {
119
+ async fetchWithRetryOnEmpty(fn, label) {
121
120
  const maxRetries = 3;
122
121
  const baseDelayMs = 500;
123
122
  const result = await fn();
@@ -445,8 +444,8 @@ class KoiosBackend {
445
444
  _mapKoiosPool(poolData, fallbackId) {
446
445
  return {
447
446
  poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
448
- vrfKeyHash: poolData.vrf_key_hash,
449
- blocksMinted: poolData.block_count,
447
+ vrfKeyHash: poolData.vrf_key_hash || '',
448
+ blocksMinted: poolData.block_count || 0,
450
449
  // Koios pool_info has no blocks-in-current-epoch figure. null = not available;
451
450
  // a 0 would be indistinguishable from a real zero downstream.
452
451
  blocksEpoch: null,
@@ -461,7 +460,7 @@ class KoiosBackend {
461
460
  pledge: poolData.pledge || '0',
462
461
  margin: poolData.margin || 0,
463
462
  fixedCost: poolData.fixed_cost || '0',
464
- rewardAccount: poolData.reward_addr,
463
+ rewardAccount: poolData.reward_addr || '',
465
464
  };
466
465
  }
467
466
  /**
@@ -911,6 +910,9 @@ class KoiosBackend {
911
910
  const info = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [afterHash] }), `getNextBlocks/height(${afterHash})`);
912
911
  if (!info.length)
913
912
  throw new errors_1.NotFoundError('Block', this.name);
913
+ if (info[0].block_height == null) {
914
+ throw new errors_1.ProviderUnavailableError(`Block ${afterHash} has no height on Koios and cannot anchor pagination`, this.name);
915
+ }
914
916
  anchorHeight = info[0].block_height;
915
917
  }
916
918
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`), `getNextBlocks(${afterHash})`);
@@ -8,6 +8,7 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const axios_1 = __importDefault(require("axios"));
9
9
  const client_1 = require("@cardano-ogmios/client");
10
10
  const errors_1 = require("../../utils/errors");
11
+ const error_codes_1 = require("../../utils/error-codes");
11
12
  const logger = cds_1.default.log('OdatanoBackend');
12
13
  /** Public ODATANO API per network (ACCESS gateway); mainnet has no default and needs `odatanoUrl`. */
13
14
  exports.ODATANO_API_URLS = {
@@ -154,8 +155,11 @@ class OdatanoBackend {
154
155
  const retryAfter = Number(ax.response?.headers?.['retry-after']);
155
156
  return new errors_1.RateLimitError(message, this.name, Number.isFinite(retryAfter) ? retryAfter : undefined);
156
157
  }
157
- if (status === 400)
158
- return new errors_1.TransactionValidationError(message);
158
+ if (status === 400) {
159
+ return message.includes(error_codes_1.ERROR_CODES.SCRIPT_VALIDATION_FAILURE)
160
+ ? new errors_1.ScriptValidationError(message)
161
+ : new errors_1.TransactionValidationError(message);
162
+ }
159
163
  if (status === 401 || status === 402 || status === 403) {
160
164
  logger.error(`${operation}: the remote ODATANO refused the key (${status}): ${message}`);
161
165
  }
@@ -740,8 +740,23 @@ class OgmiosBackend {
740
740
  async evaluateTransaction(unsignedTxCbor) {
741
741
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
742
742
  await this.ensureConnected();
743
- const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
744
- return results;
743
+ try {
744
+ const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
745
+ return results;
746
+ }
747
+ catch (err) {
748
+ // JSON-RPC 3000-3099 except 3003: the transaction cannot be evaluated as given, a 400 with its reason.
749
+ // 3003 means the node is still syncing, so it stays retryable.
750
+ const known = (0, errors_1.normalizeBackendError)(err, this.name);
751
+ if (known.statusCode >= 400 && known.statusCode < 500)
752
+ throw known;
753
+ const e = err;
754
+ if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 3100 && e.code !== 3003) {
755
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
756
+ throw new errors_1.TransactionValidationError(`transaction cannot be evaluated (${e.code}): ${String(e.message ?? '')}${detail}`, err);
757
+ }
758
+ throw err;
759
+ }
745
760
  }, this.name);
746
761
  }
747
762
  /**
@@ -361,7 +361,7 @@ export declare class CardanoIndexer {
361
361
  buildId?: string | null;
362
362
  }): Promise<TransactionSubmission>;
363
363
  /** Update a submission's status (two-phase submit: pending → submitted or failed). */
364
- updateSubmissionStatus(tx: CapTransaction, submissionId: string, status: string, errorMessage?: string): Promise<void>;
364
+ updateSubmissionStatus(tx: CapTransaction, submissionId: string, status: TransactionSubmission['status'], errorMessage?: string): Promise<void>;
365
365
  /** Persist a new signing request and link it to the build's sender address. */
366
366
  persistSigningRequest(tx: CapTransaction, params: {
367
367
  buildId: string;
@@ -190,6 +190,7 @@ class CardanoTransactionBuilder {
190
190
  ...req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])),
191
191
  ...(req.withdrawals ?? []).flatMap(w => (w.referenceScript ? [w.referenceScript] : [])),
192
192
  ...(req.certificates ?? []).flatMap(c => (c.referenceScript ? [c.referenceScript] : [])),
193
+ ...(req.mintActions ?? []).flatMap(m => (m.referenceScript ? [m.referenceScript] : [])),
193
194
  ], [], 'referenceScript');
194
195
  const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
195
196
  const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
@@ -16,7 +16,6 @@ const logger = cds_1.default.log('SubmissionFinalizer');
16
16
  // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
17
17
  // getters are only needed at runtime.
18
18
  function server() {
19
- // eslint-disable-next-line @typescript-eslint/no-var-requires
20
19
  return require('../../server');
21
20
  }
22
21
  /**
@@ -97,10 +97,16 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
97
97
  */
98
98
  private _partitionForcedInputs;
99
99
  /**
100
- * Staking script of a withdrawal or certificate: inline (swapped for a reference input that already
100
+ * Script of a withdrawal, certificate or mint: inline (swapped for a reference input that already
101
101
  * carries the same hash), by reference, or none (key witness).
102
102
  */
103
- private _resolveStakingScript;
103
+ private _resolveScriptWitness;
104
+ /**
105
+ * Withdrawal credential hashes in ledger order, which `__WDRL_IDX__` resolves against. Buildooor
106
+ * numbers withdrawal redeemers by hash alone, so a scripted withdrawal whose position differs
107
+ * between the two orders would get the wrong redeemer; such a build is refused.
108
+ */
109
+ private _ledgerWithdrawalOrder;
104
110
  /**
105
111
  * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
106
112
  * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
@@ -122,9 +128,9 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
122
128
  */
123
129
  private _mintActionScript;
124
130
  /**
125
- * Buildooor mint entries shared by the mint-only and combined spend+mint flows. Each action may
126
- * carry its own policy script and redeemer (falling back to the request-level ones); the ledger
127
- * holds ONE redeemer per policy, so actions on the same policy must agree, checked here.
131
+ * Buildooor mint entries shared by all mint flows. `scriptFor` gives each action's policy, inline
132
+ * or as a reference-script UTxO. Each action may carry its own redeemer (falling back to the
133
+ * request-level one); the ledger holds ONE redeemer per policy, so actions on the same policy must agree.
128
134
  */
129
135
  private _buildMintEntries;
130
136
  /**
@@ -274,7 +274,7 @@ class BuildooorTxBuilder {
274
274
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
275
275
  // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
276
276
  // stamped post-build by _buildScriptTx.
277
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
277
+ const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
278
278
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
279
279
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
280
280
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
@@ -390,7 +390,7 @@ class BuildooorTxBuilder {
390
390
  // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
391
391
  // units, the real ones are stamped post-build by _buildScriptTx.
392
392
  const mints = hasMint
393
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
393
+ ? this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, mintScript, i) }), resolvedMintRedeemer, resolveCtx)
394
394
  : undefined;
395
395
  const scriptInput = {
396
396
  utxo: scriptLedgerUtxo,
@@ -470,7 +470,7 @@ class BuildooorTxBuilder {
470
470
  // Withdrawals: the staking script inline, by reference, or the one a reference input carries
471
471
  const withdrawalEntries = (req.withdrawals ?? []).map((w, i) => ({
472
472
  w, rewardAccount: cardano_ledger_ts_1.StakeAddress.fromString(w.rewardAddress),
473
- ...this._resolveStakingScript(w, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
473
+ ...this._resolveScriptWitness({ script: w.stakingScript, referenceScript: w.referenceScript }, `withdrawals[${i}]`, referencedByHash, refUtxoByKey),
474
474
  }));
475
475
  // Certificates: the credential from the stake address; a script runs under the Certifying purpose
476
476
  const stakeDeposit = BigInt(String(this.txBuilder.protocolParamters.stakeAddressDeposit ?? cardano_ledger_ts_1.defaultProtocolParameters.stakeAddressDeposit));
@@ -478,7 +478,7 @@ class BuildooorTxBuilder {
478
478
  const at = `certificates[${i}]`;
479
479
  const stake = cardano_ledger_ts_1.StakeAddress.fromString(c.stakeAddress);
480
480
  const credentialHash = stake.credentials.toString().toLowerCase();
481
- const witness = this._resolveStakingScript(c, at, referencedByHash, refUtxoByKey);
481
+ const witness = this._resolveScriptWitness({ script: c.stakingScript, referenceScript: c.referenceScript }, at, referencedByHash, refUtxoByKey);
482
482
  const scripted = Boolean(witness.script || witness.refLedgerUtxo);
483
483
  const witnessHash = (witness.script?.hash ?? witness.refLedgerUtxo?.resolved.refScript?.hash)?.toString().toLowerCase();
484
484
  if (stake.type === 'script') {
@@ -500,6 +500,28 @@ class BuildooorTxBuilder {
500
500
  : (c.deposit ? new cardano_ledger_ts_1.CertUnRegistrationDeposit({ stakeCredential, deposit }) : new cardano_ledger_ts_1.CertStakeDeRegistration({ stakeCredential }));
501
501
  return { c, cert, deposit, ...witness };
502
502
  });
503
+ // Mints: each policy inline, by reference, or the one a reference input carries
504
+ const mintEntries = (req.mintActions ?? []).map((m, i) => {
505
+ const at = `mintActions[${i}]`;
506
+ const witness = this._resolveScriptWitness({ script: m.mintingPolicyScript, referenceScript: m.referenceScript }, at, referencedByHash, refUtxoByKey, 'mintingPolicyScript');
507
+ const policyId = (witness.script?.hash ?? witness.refLedgerUtxo.resolved.refScript.hash).toString().toLowerCase();
508
+ if (!m.assetUnit.toLowerCase().startsWith(policyId)) {
509
+ throw new errors_1.TransactionValidationError(`${at}.assetUnit ${m.assetUnit} is not under the policy ${policyId} of its script`);
510
+ }
511
+ return { m, policyId, ...witness };
512
+ });
513
+ // one policy runs from one place: once any action of it uses a reference script, all do
514
+ const mintRefByPolicy = new Map();
515
+ for (const e of mintEntries)
516
+ if (e.refLedgerUtxo && !mintRefByPolicy.has(e.policyId))
517
+ mintRefByPolicy.set(e.policyId, e.refLedgerUtxo);
518
+ for (const e of mintEntries) {
519
+ const ref = mintRefByPolicy.get(e.policyId);
520
+ if (ref) {
521
+ e.refLedgerUtxo = ref;
522
+ e.script = undefined;
523
+ }
524
+ }
503
525
  const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
504
526
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
505
527
  const scriptKeyClash = (req.protectInputs ?? []).map(keyOf).find(k => scriptKeys.has(k));
@@ -540,9 +562,18 @@ class BuildooorTxBuilder {
540
562
  : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
541
563
  }
542
564
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
543
- // Placeholders resolve against the final input order, over all script inputs at once
565
+ // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
566
+ const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries, ...mintEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
567
+ const callerRefUtxos = (ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u)));
568
+ const readonlyRefInputs = this._mapReferenceInputs(callerRefUtxos);
569
+ const sortedReferenceInputs = (0, plutus_placeholders_1.sortInputsLikeBuildooor)([
570
+ ...callerRefUtxos.map(u => ({ txHash: u.txHash.toLowerCase(), outputIndex: u.outputIndex })),
571
+ ...[...refScriptKeys].map(k => { const [txHash, idx] = k.split('#'); return { txHash, outputIndex: Number(idx) }; }),
572
+ ]);
573
+ // Placeholders resolve against the final input, reference-input and withdrawal order
544
574
  const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
545
- const resolveCtx = { sortedInputs };
575
+ const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
576
+ const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
546
577
  const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }) => {
547
578
  const redeemer = si.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(si.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.redeemer, resolveCtx));
548
579
  const datum = si.datumCbor ? (0, plutus_data_1.dataFromCbor)(si.datumCbor)
@@ -557,8 +588,8 @@ class BuildooorTxBuilder {
557
588
  ...o,
558
589
  inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
559
590
  })));
560
- const mints = req.mintActions && req.mintActions.length > 0
561
- ? this._buildMintEntries(req.mintActions, this._parsePlutusV3Script(req.mintActions[0].mintingPolicyScript, 'mintActions[0].mintingPolicyScript'), undefined, resolveCtx)
591
+ const mints = mintEntries.length > 0
592
+ ? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
562
593
  : undefined;
563
594
  // Withdrawals: Buildooor sorts them by reward account and runs each script under the Reward purpose
564
595
  const withdrawals = withdrawalEntries.map(({ w, script, refLedgerUtxo, rewardAccount }) => {
@@ -575,9 +606,6 @@ class BuildooorTxBuilder {
575
606
  const redeemer = c.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(c.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(c.redeemer ?? null, resolveCtx));
576
607
  return { cert, script: script ? { inline: script, redeemer } : { ref: refLedgerUtxo, redeemer } };
577
608
  });
578
- // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
579
- const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
580
- const readonlyRefInputs = this._mapReferenceInputs((ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u))));
581
609
  const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
582
610
  const buildParams = {
583
611
  inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
@@ -913,12 +941,12 @@ class BuildooorTxBuilder {
913
941
  return { forced, rest };
914
942
  }
915
943
  /**
916
- * Staking script of a withdrawal or certificate: inline (swapped for a reference input that already
944
+ * Script of a withdrawal, certificate or mint: inline (swapped for a reference input that already
917
945
  * carries the same hash), by reference, or none (key witness).
918
946
  */
919
- _resolveStakingScript(w, at, referencedByHash, refUtxoByKey) {
920
- if (w.stakingScript) {
921
- const script = this._parsePlutusV3Script(w.stakingScript, `${at}.stakingScript`);
947
+ _resolveScriptWitness(w, at, referencedByHash, refUtxoByKey, scriptField = 'stakingScript') {
948
+ if (w.script) {
949
+ const script = this._parsePlutusV3Script(w.script, `${at}.${scriptField}`);
922
950
  const referenced = referencedByHash.get(script.hash.toString());
923
951
  return referenced ? { refLedgerUtxo: referenced } : { script };
924
952
  }
@@ -935,6 +963,26 @@ class BuildooorTxBuilder {
935
963
  }
936
964
  return { refLedgerUtxo };
937
965
  }
966
+ /**
967
+ * Withdrawal credential hashes in ledger order, which `__WDRL_IDX__` resolves against. Buildooor
968
+ * numbers withdrawal redeemers by hash alone, so a scripted withdrawal whose position differs
969
+ * between the two orders would get the wrong redeemer; such a build is refused.
970
+ */
971
+ _ledgerWithdrawalOrder(entries) {
972
+ const withHash = entries.map(e => ({
973
+ credentialHash: e.rewardAccount.credentials.toString().toLowerCase(),
974
+ isScript: e.rewardAccount.type === 'script',
975
+ scripted: Boolean(e.script || e.refLedgerUtxo),
976
+ }));
977
+ const ledger = (0, plutus_placeholders_1.sortWithdrawalsLikeLedger)(withHash).map(e => e.credentialHash);
978
+ const buildooor = withHash.map(e => e.credentialHash).sort((a, b) => Buffer.compare(Buffer.from(a, 'hex'), Buffer.from(b, 'hex')));
979
+ const misplaced = withHash.find(e => e.scripted && ledger.indexOf(e.credentialHash) !== buildooor.indexOf(e.credentialHash));
980
+ if (misplaced) {
981
+ throw new errors_1.TransactionValidationError(`withdrawals: the scripted withdrawal of credential ${misplaced.credentialHash} cannot be indexed correctly, ` +
982
+ 'because a key-credential withdrawal sorts before it by hash; move that key withdrawal into a separate transaction');
983
+ }
984
+ return ledger;
985
+ }
938
986
  /**
939
987
  * Forced inputs of other key addresses: the owner's payment key hash must be a required signer,
940
988
  * and every unit they bring must be spent by the outputs, so none of it lands in the sender's change.
@@ -1038,21 +1086,22 @@ class BuildooorTxBuilder {
1038
1086
  return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
1039
1087
  }
1040
1088
  /**
1041
- * Buildooor mint entries shared by the mint-only and combined spend+mint flows. Each action may
1042
- * carry its own policy script and redeemer (falling back to the request-level ones); the ledger
1043
- * holds ONE redeemer per policy, so actions on the same policy must agree, checked here.
1089
+ * Buildooor mint entries shared by all mint flows. `scriptFor` gives each action's policy, inline
1090
+ * or as a reference-script UTxO. Each action may carry its own redeemer (falling back to the
1091
+ * request-level one); the ledger holds ONE redeemer per policy, so actions on the same policy must agree.
1044
1092
  */
1045
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
1093
+ _buildMintEntries(mintActions, scriptFor, resolvedMintRedeemer, resolveCtx) {
1046
1094
  const redeemerByPolicy = new Map();
1047
1095
  return mintActions.map((action, index) => {
1048
- const script = this._mintActionScript(action, mintScript, index);
1096
+ const source = scriptFor(action, index);
1097
+ const policyHash = 'inline' in source ? source.inline.hash : source.ref.resolved.refScript.hash;
1049
1098
  const actionRedeemer = action.redeemerJson !== undefined
1050
1099
  ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
1051
1100
  : resolvedMintRedeemer;
1052
1101
  const redeemerData = actionRedeemer !== undefined
1053
1102
  ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
1054
1103
  : new plutus_data_1.DataI(action.redeemer ?? 0);
1055
- const policyId = script.hash.toString();
1104
+ const policyId = policyHash.toString();
1056
1105
  // Canonical comparison over the encoded PlutusData: JSON key order must
1057
1106
  // not matter, and a JSON {int:0} equals the DataI(0) fallback.
1058
1107
  const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
@@ -1064,11 +1113,8 @@ class BuildooorTxBuilder {
1064
1113
  redeemerByPolicy.set(policyId, redeemerFingerprint);
1065
1114
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
1066
1115
  return {
1067
- value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
1068
- script: {
1069
- inline: script,
1070
- redeemer: redeemerData
1071
- }
1116
+ value: cardano_ledger_ts_1.Value.singleAsset(policyHash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
1117
+ script: { ...source, redeemer: redeemerData }
1072
1118
  };
1073
1119
  });
1074
1120
  }
@@ -9,6 +9,17 @@ const validators_1 = require("./utils/validators");
9
9
  const errors_1 = require("./utils/errors");
10
10
  const backend_request_handler_1 = require("./utils/backend-request-handler");
11
11
  const cbor_1 = require("./cbor");
12
+ /** Newest temporal slice per key; child tables keep one row per validFrom. */
13
+ function latestSlices(rows, keyOf) {
14
+ const seen = new Map();
15
+ for (const row of rows) {
16
+ const key = keyOf(row);
17
+ const prev = seen.get(key);
18
+ if (!prev || (row.validFrom ?? '') > (prev.validFrom ?? ''))
19
+ seen.set(key, row);
20
+ }
21
+ return Array.from(seen.values());
22
+ }
12
23
  const { SELECT } = cds_1.default.ql;
13
24
  const logger = cds_1.default.log(`CardanoService`);
14
25
  /** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
@@ -194,14 +205,7 @@ module.exports = (srv) => {
194
205
  if (!existing)
195
206
  await indexer().indexAddress(db, address);
196
207
  const assets = await db.run(SELECT.from(AddressAssets).where({ address_address: address }));
197
- // Keep the latest temporal slice per unit
198
- const seen = new Map();
199
- for (const asset of assets) {
200
- if (!seen.has(asset.unit) || asset.validFrom > seen.get(asset.unit).validFrom) {
201
- seen.set(asset.unit, asset);
202
- }
203
- }
204
- return Array.from(seen.values());
208
+ return latestSlices(assets, (asset) => asset.unit ?? '');
205
209
  });
206
210
  });
207
211
  // GetUTxOsByAddress — indexes the parent address if needed, then queries child UTxOs.
@@ -232,15 +236,7 @@ module.exports = (srv) => {
232
236
  const fresh = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
233
237
  return fresh;
234
238
  }
235
- // Keep the latest temporal slice per hash#index
236
- const seen = new Map();
237
- for (const utxo of existing) {
238
- const key = `${utxo.hash}#${utxo.index}`;
239
- if (!seen.has(key) || utxo.validFrom > seen.get(key).validFrom) {
240
- seen.set(key, utxo);
241
- }
242
- }
243
- return Array.from(seen.values());
239
+ return latestSlices(existing, (utxo) => `${utxo.hash}#${utxo.index}`);
244
240
  });
245
241
  });
246
242
  // GetUTxOsByCredential — always-fresh credential-keyed UTxO query (dApp state reads need current