@odatano/core 2.0.0-rc.24 → 2.0.0-rc.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
  2. package/@cds-models/CardanoIndexerService/index.js +4 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +27 -2
  4. package/@cds-models/CardanoODataService/index.js +3 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +23 -1
  6. package/@cds-models/CardanoSignService/index.js +3 -0
  7. package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
  8. package/@cds-models/CardanoTransactionService/index.js +4 -0
  9. package/@cds-models/index.d.ts +18 -0
  10. package/@cds-models/index.js +3 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +49 -2
  12. package/@cds-models/odatano/cardano/index.js +6 -0
  13. package/README.md +195 -195
  14. package/db/schema.cds +74 -3
  15. package/db/types.cds +27 -0
  16. package/package.json +182 -182
  17. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  18. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  19. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  20. package/srv/blockchain/backends/koios-backend.js +61 -14
  21. package/srv/blockchain/backends/odatano-backend.d.ts +5 -0
  22. package/srv/blockchain/backends/odatano-backend.js +12 -0
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  24. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  25. package/srv/blockchain/cardano-client.d.ts +11 -5
  26. package/srv/blockchain/cardano-client.js +51 -16
  27. package/srv/blockchain/cardano-indexer.d.ts +43 -15
  28. package/srv/blockchain/cardano-indexer.js +177 -68
  29. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  30. package/srv/blockchain/cardano-tx-builder.js +57 -2
  31. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  32. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  33. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  34. package/srv/blockchain/crawler/crawler.js +12 -7
  35. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  36. package/srv/blockchain/crawler/sync-state.js +15 -2
  37. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  38. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  39. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  40. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  41. package/srv/blockchain/ledger-state.d.ts +16 -1
  42. package/srv/blockchain/ledger-state.js +38 -18
  43. package/srv/blockchain/pending-spends.d.ts +28 -0
  44. package/srv/blockchain/pending-spends.js +89 -0
  45. package/srv/blockchain/stored-chain.d.ts +5 -2
  46. package/srv/blockchain/stored-chain.js +31 -5
  47. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  48. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  49. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  50. package/srv/blockchain/transaction-rows.d.ts +1 -1
  51. package/srv/blockchain/transaction-rows.js +2 -1
  52. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  53. package/srv/cardano-backend-service.js +35 -8
  54. package/srv/cardano-indexer-service.cds +201 -176
  55. package/srv/cardano-indexer-service.js +104 -10
  56. package/srv/cardano-service.cds +5 -0
  57. package/srv/cardano-service.js +3 -1
  58. package/srv/cardano-tx-service.cds +39 -0
  59. package/srv/cardano-tx-service.js +88 -14
  60. package/srv/server.js +4 -1
  61. package/srv/utils/agent-grants.js +1 -0
  62. package/srv/utils/const.d.ts +5 -0
  63. package/srv/utils/const.js +6 -1
  64. package/srv/utils/error-codes.d.ts +2 -0
  65. package/srv/utils/error-codes.js +2 -0
  66. package/srv/utils/errors.d.ts +7 -0
  67. package/srv/utils/errors.js +11 -1
  68. package/srv/utils/mappers.d.ts +24 -2
  69. package/srv/utils/mappers.js +49 -0
  70. package/srv/utils/pg-inline-json.d.ts +8 -0
  71. package/srv/utils/pg-inline-json.js +63 -0
  72. package/srv/utils/tx-build-helper.d.ts +2 -0
  73. package/srv/utils/tx-build-helper.js +12 -0
  74. package/srv/utils/tx-request-parsers.d.ts +46 -5
  75. package/srv/utils/tx-request-parsers.js +227 -16
  76. package/srv/utils/types.d.ts +59 -0
  77. package/srv/utils/validators.d.ts +5 -1
  78. package/srv/utils/validators.js +19 -9
@@ -106,6 +106,19 @@ function chunkUtf8(str, maxBytes) {
106
106
  chunks.push(current);
107
107
  return chunks;
108
108
  }
109
+ /**
110
+ * The same script without the CBOR it was parsed from. Script.fromCbor keeps the input bytes (the
111
+ * compiler's bare bytestring) and toCbor() returns them, while an output's script_ref must hold the
112
+ * ledger form [language, bytes]; the hash is the same either way.
113
+ */
114
+ function ledgerScript(script) {
115
+ return new cardano_ledger_ts_1.Script(script.type, script.bytes);
116
+ }
117
+ // Hash32 inherits Hash.clone(), which returns a plain Hash; TxOut rejects that as datum when
118
+ // Buildooor clones outputs, so a datum-hash output could never be built. Hash28 has its own clone.
119
+ if (!Object.prototype.hasOwnProperty.call(cardano_ledger_ts_1.Hash32.prototype, 'clone')) {
120
+ cardano_ledger_ts_1.Hash32.prototype.clone = function () { return new cardano_ledger_ts_1.Hash32(this.toString()); };
121
+ }
109
122
  /** CardanoTxBuilder implementation on top of Buildooor. */
110
123
  class BuildooorTxBuilder {
111
124
  name = 'BuildooorTxBuilder';
@@ -179,7 +192,7 @@ class BuildooorTxBuilder {
179
192
  const refScript = this._parseReferenceScript(req.referenceScript);
180
193
  const outputs = [this._buildTxOut(recipientAddress, outputValue, req.outputDatum, refScript)];
181
194
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
182
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
195
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs));
183
196
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
184
197
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
185
198
  // Coin selection on candidates only; forced inputs are prepended unconditionally
@@ -219,7 +232,7 @@ class BuildooorTxBuilder {
219
232
  }
220
233
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
221
234
  // collateral and coin selection operate on the remainder only.
222
- const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
235
+ const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs));
223
236
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
224
237
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
225
238
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
@@ -312,7 +325,7 @@ class BuildooorTxBuilder {
312
325
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
313
326
  // Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
314
327
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
315
- const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
328
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs));
316
329
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
317
330
  // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
318
331
  const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
@@ -331,7 +344,7 @@ class BuildooorTxBuilder {
331
344
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
332
345
  // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
333
346
  // in redeemer / datum / output datums BEFORE PlutusData encoding.
334
- const sortedInputs = this._computeSortedInputs(scriptUtxoRef, forced, this._extractFundingRefs(selectedFundingInputs));
347
+ const sortedInputs = this._computeSortedInputs([scriptUtxoRef], forced, this._extractFundingRefs(selectedFundingInputs));
335
348
  const resolveCtx = { sortedInputs };
336
349
  const resolvedRedeemer = (0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.redeemer, resolveCtx);
337
350
  const redeemerData = (0, tx_build_helper_1.jsonToPlutusData)(resolvedRedeemer);
@@ -411,6 +424,149 @@ class BuildooorTxBuilder {
411
424
  (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
412
425
  }
413
426
  }
427
+ /**
428
+ * Several script inputs in one transaction, each with its own redeemer (inline validator or a
429
+ * reference-script UTxO), the outputs exactly in the given order and change after them.
430
+ */
431
+ async buildUnsignedPlutusTransaction(req, ctx) {
432
+ let coinSelectionContext;
433
+ try {
434
+ this._ensureCurrentProtocolParameters(ctx);
435
+ const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
436
+ const utxoByKey = new Map(ctx.utxos.map(u => [keyOf(u), u]));
437
+ const refUtxoByKey = new Map((ctx.referenceInputUtxos ?? []).map(u => [keyOf(u), u]));
438
+ const scriptKeys = new Set(req.scriptInputs.map(keyOf));
439
+ // Scripts the reference inputs already carry: the ledger rejects the same script again as a
440
+ // witness (ExtraneousScriptWitnesses), so an inline validator with such a hash uses the reference.
441
+ const referencedByHash = new Map();
442
+ for (const u of ctx.referenceInputUtxos ?? []) {
443
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(u);
444
+ const hash = ledgerUtxo.resolved.refScript?.hash.toString();
445
+ if (hash && !referencedByHash.has(hash))
446
+ referencedByHash.set(hash, ledgerUtxo);
447
+ }
448
+ // Script inputs: each UTxO with its script (inline, or the ledger UTxO carrying it)
449
+ const scriptEntries = req.scriptInputs.map((si, i) => {
450
+ const utxo = utxoByKey.get(keyOf(si));
451
+ if (!utxo)
452
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}] ${keyOf(si)} not found on-chain or already spent`);
453
+ if (si.validatorScript) {
454
+ const script = this._parsePlutusV3Script(si.validatorScript, `scriptInputs[${i}].validatorScript`);
455
+ const scriptHash = script.hash.toString();
456
+ const referenced = referencedByHash.get(scriptHash);
457
+ return referenced ? { si, utxo, refLedgerUtxo: referenced, scriptHash } : { si, utxo, script };
458
+ }
459
+ const refKey = keyOf(si.referenceScript);
460
+ const refUtxo = refUtxoByKey.get(refKey);
461
+ if (!refUtxo)
462
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} not found on-chain or already spent`);
463
+ const refLedgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(refUtxo);
464
+ if (!refLedgerUtxo.resolved.refScript) {
465
+ throw new errors_1.TransactionValidationError(`scriptInputs[${i}].referenceScript ${refKey} carries no reference script, or its bytes are not available ` +
466
+ `from the configured backends (Ogmios or Koios deliver them, Blockfrost only the hash)`);
467
+ }
468
+ return { si, utxo, refLedgerUtxo, scriptHash: refLedgerUtxo.resolved.refScript.hash.toString() };
469
+ });
470
+ const senderUtxos = ctx.utxos.filter(u => !scriptKeys.has(keyOf(u)));
471
+ const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
472
+ const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))));
473
+ const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
474
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
475
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
476
+ const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
477
+ // Funding covers only what the outputs need beyond the script inputs, forced inputs and mints
478
+ // (keepRelevant adds its own lovelace margin for fee and change).
479
+ const need = new Map();
480
+ const add = (unit, qty) => need.set(unit, (need.get(unit) ?? 0n) + qty);
481
+ for (const o of req.outputs) {
482
+ add('lovelace', BigInt(o.lovelaceAmount));
483
+ for (const a of o.assets ?? [])
484
+ add(a.unit, BigInt(a.quantity));
485
+ }
486
+ for (const u of [...scriptEntries.map(e => e.utxo), ...forced]) {
487
+ for (const a of u.amount)
488
+ add(a.unit.toLowerCase() === 'lovelace' ? 'lovelace' : a.unit, -BigInt(a.quantity));
489
+ }
490
+ for (const m of req.mintActions ?? [])
491
+ add(m.assetUnit, -BigInt(m.quantity));
492
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(0n);
493
+ for (const [unit, qty] of need) {
494
+ if (qty <= 0n)
495
+ continue;
496
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, unit === 'lovelace'
497
+ ? cardano_ledger_ts_1.Value.lovelaces(qty)
498
+ : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
499
+ }
500
+ const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
501
+ // Placeholders resolve against the final input order, over all script inputs at once
502
+ const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
503
+ const resolveCtx = { sortedInputs };
504
+ const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }) => {
505
+ 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));
506
+ const datum = si.datumCbor ? (0, plutus_data_1.dataFromCbor)(si.datumCbor)
507
+ : si.datum !== undefined ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx)) : "inline";
508
+ const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
509
+ return script
510
+ ? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
511
+ : { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
512
+ });
513
+ const outputs = [];
514
+ this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
515
+ ...o,
516
+ inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
517
+ })));
518
+ const mints = req.mintActions && req.mintActions.length > 0
519
+ ? this._buildMintEntries(req.mintActions, this._parsePlutusV3Script(req.mintActions[0].mintingPolicyScript, 'mintActions[0].mintingPolicyScript'), undefined, resolveCtx)
520
+ : undefined;
521
+ // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
522
+ const refScriptKeys = new Set(scriptEntries.filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
523
+ const readonlyRefInputs = this._mapReferenceInputs((ctx.referenceInputUtxos ?? []).filter(u => !refScriptKeys.has(keyOf(u)) && (req.referenceInputs ?? []).some(r => keyOf(r) === keyOf(u))));
524
+ const { invalidBefore, invalidAfter } = this._resolveValiditySlots(req, 'script');
525
+ const buildParams = {
526
+ inputs: [...scriptInputs, ...forcedInputs, ...selectedFundingInputs],
527
+ outputs, changeAddress, mints,
528
+ collaterals: collateralUtxos, requiredSigners: req.requiredSigners,
529
+ invalidBefore, invalidAfter,
530
+ ...(collateralReturn && { collateralReturn }),
531
+ ...(readonlyRefInputs.length > 0 && { readonlyRefInputs })
532
+ };
533
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
534
+ const details = this._extractTxDetails(tx);
535
+ const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
536
+ if (details.sizeBytes > maxTxSize) {
537
+ const inline = scriptEntries.filter(e => e.script).length;
538
+ throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
539
+ (inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
540
+ }
541
+ const scriptHashes = scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash);
542
+ logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
543
+ return this._buildResult(req, ctx, details, {
544
+ scriptHash: scriptHashes[0],
545
+ forcedInputsUsed: forcedInputs.length,
546
+ referenceInputsUsed: readonlyRefInputs.length + refScriptKeys.size
547
+ });
548
+ }
549
+ catch (err) {
550
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
551
+ }
552
+ }
553
+ /** Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each. */
554
+ _appendPlutusOutputs(outputs, list) {
555
+ for (let i = 0; i < list.length; i++) {
556
+ const o = list[i];
557
+ const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
558
+ const refScript = this._parseReferenceScript(o.referenceScript);
559
+ const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : o.inlineDatumCbor ? (0, plutus_data_1.dataFromCbor)(o.inlineDatumCbor) : undefined;
560
+ const txOut = datum
561
+ ? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
562
+ : this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
563
+ const minLovelaces = this.txBuilder.getMinimumOutputLovelaces(txOut);
564
+ if (BigInt(o.lovelaceAmount) < minLovelaces) {
565
+ throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
566
+ }
567
+ outputs.push(txOut);
568
+ }
569
+ }
414
570
  //---------------------------------------------------------------------------
415
571
  // Shared Helper Methods
416
572
  //---------------------------------------------------------------------------
@@ -430,6 +586,12 @@ class BuildooorTxBuilder {
430
586
  address: o.address?.toString?.() ?? "",
431
587
  lovelace: o.value?.lovelaces?.toString?.() ?? "0"
432
588
  })),
589
+ redeemers: (tx.witnesses.redeemers ?? []).map((r) => ({
590
+ tag: (0, cardano_ledger_ts_1.txRedeemerTagToString)(r.tag),
591
+ index: r.index,
592
+ mem: r.execUnits.mem.toString(),
593
+ steps: r.execUnits.cpu.toString(),
594
+ })),
433
595
  };
434
596
  }
435
597
  /** Build the standard TxBuildResult object */
@@ -453,6 +615,7 @@ class BuildooorTxBuilder {
453
615
  feeLovelace: txDetails.feeLovelace,
454
616
  inputs,
455
617
  outputs: txDetails.outputs,
618
+ ...(txDetails.redeemers.length > 0 ? { redeemers: txDetails.redeemers } : {}),
456
619
  ...extra,
457
620
  warnings: [],
458
621
  };
@@ -663,20 +826,38 @@ class BuildooorTxBuilder {
663
826
  * Split UTxOs into forced inputs (must be consumed) and remaining candidates; forceInputs
664
827
  * refs absent from utxos are ignored (existence is validated upstream).
665
828
  */
666
- _partitionForcedInputs(utxos, forceInputs) {
667
- if (!forceInputs || forceInputs.length === 0)
829
+ _partitionForcedInputs(utxos, forceInputs, referenced = new Set()) {
830
+ const hasRefScript = (u) => Boolean(u.scriptRef || u.scriptRefCbor);
831
+ if ((!forceInputs || forceInputs.length === 0) && referenced.size === 0 && !utxos.some(hasRefScript))
668
832
  return { forced: [], rest: utxos };
669
- const forcedKeys = new Set(forceInputs.map(r => `${r.txHash}#${r.outputIndex}`));
833
+ const key = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
834
+ const forcedKeys = new Set((forceInputs ?? []).map(key));
835
+ // a UTxO cannot be spent and referenced in one transaction
836
+ const clash = [...forcedKeys].find(k => referenced.has(k));
837
+ if (clash)
838
+ throw new errors_1.TransactionValidationError(`forceInputs ${clash} is also a reference input — a UTxO cannot be spent and referenced in one transaction`);
670
839
  const forced = [];
671
840
  const rest = [];
672
841
  for (const u of utxos) {
673
- if (forcedKeys.has(`${u.txHash}#${u.outputIndex}`))
842
+ if (forcedKeys.has(key(u)))
674
843
  forced.push(u);
675
- else
844
+ // reference inputs and UTxOs carrying a reference script stay out of coin selection and
845
+ // collateral; a deployed script is spent only when forced
846
+ else if (!referenced.has(key(u)) && !hasRefScript(u))
676
847
  rest.push(u);
677
848
  }
678
849
  return { forced, rest };
679
850
  }
851
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
852
+ _referencedKeys(ctx, ...refs) {
853
+ const keys = new Set();
854
+ for (const u of ctx.referenceInputUtxos ?? [])
855
+ keys.add(`${u.txHash.toLowerCase()}#${u.outputIndex}`);
856
+ for (const list of refs)
857
+ for (const r of list ?? [])
858
+ keys.add(`${r.txHash.toLowerCase()}#${r.outputIndex}`);
859
+ return keys;
860
+ }
680
861
  /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
681
862
  _mapReferenceInputs(referenceInputUtxos) {
682
863
  if (!referenceInputUtxos || referenceInputUtxos.length === 0)
@@ -773,9 +954,10 @@ class BuildooorTxBuilder {
773
954
  * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
774
955
  */
775
956
  _setupCollateral(utxos) {
776
- const adaOnly = utxos.filter(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
957
+ // ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
958
+ const adaOnly = utxos.filter(tx_build_helper_1.isCollateralCandidate);
777
959
  if (adaOnly.length === 0) {
778
- throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral.');
960
+ throw new errors_1.TransactionValidationError('No ADA-only UTxO available for collateral. Plutus scripts require ADA-only collateral; create one with SetCollateral.');
779
961
  }
780
962
  const sorted = [...adaOnly].sort((a, b) => {
781
963
  const diff = (0, tx_build_helper_1.getLovelace)(a) - (0, tx_build_helper_1.getLovelace)(b);
@@ -853,21 +1035,21 @@ class BuildooorTxBuilder {
853
1035
  _parseReferenceScript(hex) {
854
1036
  if (!hex)
855
1037
  return undefined;
856
- return this._parsePlutusV3Script(hex, 'referenceScript');
1038
+ return ledgerScript(this._parsePlutusV3Script(hex, 'referenceScript'));
857
1039
  }
858
1040
  /**
859
- * Map an input UTxO's scriptRef to a Script. Blockfrost/Ogmios set scriptRef to the 28-byte
860
- * hash (56 hex chars), Koios to the full CBOR bytes; only full bytes are usable locally.
1041
+ * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
1042
+ * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
861
1043
  */
862
1044
  _buildInputRefScript(utxo) {
863
- if (!utxo.scriptRef)
864
- return undefined;
865
- if (utxo.scriptRef.length <= 56) {
866
- logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
1045
+ const cbor = utxo.scriptRefCbor ?? (utxo.scriptRef && utxo.scriptRef.length > 56 ? utxo.scriptRef : undefined);
1046
+ if (!cbor) {
1047
+ if (utxo.scriptRef)
1048
+ logger.debug(`UTxO ${utxo.txHash}#${utxo.outputIndex} carries scriptRef hash only — local Plutus eval will not see the script`);
867
1049
  return undefined;
868
1050
  }
869
1051
  try {
870
- const script = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(utxo.scriptRef, 'hex'));
1052
+ const script = ledgerScript(cardano_ledger_ts_1.Script.fromCbor(Buffer.from(cbor, 'hex')));
871
1053
  // chain data, not consumer input — warn instead of rejecting
872
1054
  const b = script.bytes;
873
1055
  if (b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0) {
@@ -885,9 +1067,9 @@ class BuildooorTxBuilder {
885
1067
  * Post-sort input order so __INPUT_IDX__ placeholders resolve to the indices Buildooor assigns
886
1068
  * in build(): all inputs (script, forced, funding) sorted lexicographically on (txHash, outputIndex).
887
1069
  */
888
- _computeSortedInputs(scriptUtxoRef, forcedUtxos, fundingRefs) {
1070
+ _computeSortedInputs(scriptUtxoRefs, forcedUtxos, fundingRefs) {
889
1071
  const all = [
890
- { txHash: scriptUtxoRef.txHash, outputIndex: scriptUtxoRef.outputIndex },
1072
+ ...scriptUtxoRefs.map(r => ({ txHash: r.txHash, outputIndex: r.outputIndex })),
891
1073
  ...forcedUtxos.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })),
892
1074
  ...fundingRefs
893
1075
  ];
@@ -1,4 +1,4 @@
1
- import { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
1
+ import { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildPlutusRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
2
2
  import { CardanoClient } from "../cardano-client";
3
3
  /** Interface for the Cardano transaction builder (Buildooor). */
4
4
  export interface CardanoTxBuilder {
@@ -17,5 +17,6 @@ export interface CardanoTxBuilder {
17
17
  buildUnsignedMintTransaction(req: TxBuildMintRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
18
18
  /** Build an unsigned Plutus spending transaction (consume a UTxO at a script address). */
19
19
  buildUnsignedPlutusSpendTransaction(req: TxBuildPlutusSpendRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
20
+ buildUnsignedPlutusTransaction(req: TxBuildPlutusRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
20
21
  }
21
22
  //# sourceMappingURL=cardano-tx.d.ts.map
@@ -7,6 +7,6 @@ export interface TxKey {
7
7
  export declare const seqKey: (txSeq: number | string) => string;
8
8
  /** Hash and txSeq of the given transactions that are indexed. */
9
9
  export declare function readTxKeys(tx: CapTransaction, hashes: string[]): Promise<TxKey[]>;
10
- /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
10
+ /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal and redeemer rows. */
11
11
  export declare function deleteTransactionRows(tx: CapTransaction, keys: TxKey[]): Promise<void>;
12
12
  //# sourceMappingURL=transaction-rows.d.ts.map
@@ -22,7 +22,7 @@ async function readTxKeys(tx, hashes) {
22
22
  }
23
23
  return keys;
24
24
  }
25
- /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
25
+ /** Delete transactions with their input/output, asset, metadata, certificate, withdrawal and redeemer rows. */
26
26
  async function deleteTransactionRows(tx, keys) {
27
27
  for (const keyChunk of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
28
28
  const hashes = keyChunk.map(k => k.hash);
@@ -36,6 +36,7 @@ async function deleteTransactionRows(tx, keys) {
36
36
  await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: hashes } }));
37
37
  await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: hashes } }));
38
38
  await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: hashes } }));
39
+ await tx.run(DELETE.from(cardano_1.TransactionRedeemers).where({ tx_hash: { in: hashes } }));
39
40
  await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: hashes } }));
40
41
  }
41
42
  }
@@ -24,7 +24,7 @@ function parseJsonField(raw, field) {
24
24
  return undefined;
25
25
  if (typeof value !== 'string')
26
26
  fail(`${field} must be a JSON string`);
27
- const result = (0, validators_1.validateJsonWithLimits)(value, field);
27
+ const result = validators_1.PLUTUS_JSON_FIELDS.has(field) ? (0, validators_1.validatePlutusJson)(value, field) : (0, validators_1.validateJsonWithLimits)(value, field);
28
28
  if (!result.valid)
29
29
  fail(result.error);
30
30
  return result.parsed;
@@ -61,17 +61,34 @@ module.exports = (srv) => {
61
61
  // --- blocks and transactions -------------------------------------------------------------------
62
62
  op('GetTransaction', async ({ hash }, db) => {
63
63
  const stored = (await (0, stored_chain_1.readTransactionsByHash)(db, [String(hash)])).get(String(hash));
64
- if (stored)
64
+ if (stored && !(0, stored_chain_1.lacksOutpoints)(stored))
65
65
  return stored;
66
+ if (stored) {
67
+ // An old row without input outpoints: the backend's copy when one can serve it
68
+ if (!client().hasBackendFor('getTransaction'))
69
+ return stored;
70
+ return client().getTransaction(String(hash)).catch(() => stored);
71
+ }
66
72
  await indexer().refuseOutsideCrawl(db, 'getTransaction', `Transaction ${hash}`);
67
73
  return client().getTransaction(String(hash));
68
74
  }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
69
75
  op('GetTransactionsBatch', async ({ hashes }, db) => {
70
76
  const wanted = hashes;
71
77
  const found = await (0, stored_chain_1.readTransactionsByHash)(db, wanted);
72
- const missing = wanted.filter(h => !found.has(h));
73
- if (missing.length && client().hasBackendFor('getTransactionsBatch')) {
74
- for (const [h, t] of await client().getTransactionsBatch(missing))
78
+ const absent = wanted.filter(h => !found.has(h));
79
+ // old rows without input outpoints: the backend's copy replaces them when it has one
80
+ const stale = wanted.filter(h => found.has(h) && (0, stored_chain_1.lacksOutpoints)(found.get(h)));
81
+ if ((absent.length || stale.length) && client().hasBackendFor('getTransactionsBatch')) {
82
+ let fetched;
83
+ try {
84
+ fetched = await client().getTransactionsBatch([...absent, ...stale]);
85
+ }
86
+ catch (err) {
87
+ if (absent.length)
88
+ throw err;
89
+ fetched = new Map();
90
+ }
91
+ for (const [h, t] of fetched)
75
92
  found.set(h, t);
76
93
  }
77
94
  return found;
@@ -112,16 +129,26 @@ module.exports = (srv) => {
112
129
  if (!anchor && afterHeight != null) {
113
130
  const canonical = await (0, stored_chain_1.readBlockByHeight)(db, Number(afterHeight));
114
131
  if (canonical) {
115
- throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${afterHeight} is no longer canonical (canonical block: ${canonical.hash})`, 'odatano');
132
+ throw new errors_1.ChainPointMismatchError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${afterHeight} is no longer canonical (canonical block: ${canonical.hash})`, 'odatano');
116
133
  }
117
134
  }
118
135
  const paging = client().getPaginatingBackend();
119
- if (paging)
120
- return paging.getNextBlocks(String(afterHash), n, afterHeight == null ? undefined : Number(afterHeight));
136
+ if (paging) {
137
+ try {
138
+ return await paging.getNextBlocks(String(afterHash), n, afterHeight == null ? undefined : Number(afterHeight));
139
+ }
140
+ catch (err) {
141
+ // the provider's reorg marker, as 409 so it survives production error masking
142
+ const message = err instanceof Error ? err.message : '';
143
+ if (message.startsWith('CHAIN_POINT_MISMATCH:'))
144
+ throw new errors_1.ChainPointMismatchError(message, 'odatano');
145
+ throw err;
146
+ }
147
+ }
121
148
  // Nothing indexed past the cursor yet: the caller is at this instance's tip.
122
149
  if (anchor)
123
150
  return [];
124
- throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
151
+ throw new errors_1.ChainPointMismatchError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
125
152
  }, need(validators_1.isBlockHash, 'afterHash', 'block hash'));
126
153
  op('GetBlockTransactions', async ({ blockHash }, db) => {
127
154
  const stored = await (0, stored_chain_1.readBlockTransactions)(db, String(blockHash));