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

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.
@@ -413,11 +413,11 @@ export class UTxOAssets extends Array<UTxOAsset> {
413
413
 
414
414
  export declare const BuildSimpleAdaTransaction: {
415
415
  // positional
416
- (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, assetsJson: string | null, forceInputsJson: string | null, protectInputsJson: string | null, validatorScript: string | null, scriptParamsJson: string | null, lockOnScript: boolean | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
416
+ (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, outputDatumCbor: string | null, ensureMinAda: boolean | null, assetsJson: string | null, forceInputsJson: string | null, protectInputsJson: string | null, validatorScript: string | null, scriptParamsJson: string | null, lockOnScript: boolean | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
417
417
  // named
418
- ({senderAddress, recipientAddress, lovelaceAmount, changeAddress, outputDatumJson, assetsJson, forceInputsJson, protectInputsJson, validatorScript, scriptParamsJson, lockOnScript, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
418
+ ({senderAddress, recipientAddress, lovelaceAmount, changeAddress, outputDatumJson, outputDatumCbor, ensureMinAda, assetsJson, forceInputsJson, protectInputsJson, validatorScript, scriptParamsJson, lockOnScript, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, outputDatumCbor?: string | null, ensureMinAda?: boolean | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
419
419
  // metadata (do not use)
420
- __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
420
+ __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, outputDatumCbor?: string | null, ensureMinAda?: boolean | null, assetsJson?: string | null, forceInputsJson?: string | null, protectInputsJson?: string | null, validatorScript?: string | null, scriptParamsJson?: string | null, lockOnScript?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
421
421
  kind: 'action'
422
422
  }
423
423
 
@@ -433,11 +433,11 @@ export declare const BuildTransactionWithMetadata: {
433
433
 
434
434
  export declare const BuildMultiAssetTransaction: {
435
435
  // positional
436
- (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, assetsJson: string | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
436
+ (senderAddress: _.Bech32 | null, recipientAddress: _.Bech32 | null, lovelaceAmount: _.Lovelace | null, assetsJson: string | null, changeAddress: _.Bech32 | null, outputDatumJson: string | null, outputDatumCbor: string | null, ensureMinAda: boolean | null, referenceScriptHex: string | null, validityStartMs: string | null, validityEndMs: string | null): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
437
437
  // named
438
- ({senderAddress, recipientAddress, lovelaceAmount, assetsJson, changeAddress, outputDatumJson, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, assetsJson?: string | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
438
+ ({senderAddress, recipientAddress, lovelaceAmount, assetsJson, changeAddress, outputDatumJson, outputDatumCbor, ensureMinAda, referenceScriptHex, validityStartMs, validityEndMs}: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, assetsJson?: string | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, outputDatumCbor?: string | null, ensureMinAda?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}): globalThis.Promise<TransactionBuild | null> | TransactionBuild | null
439
439
  // metadata (do not use)
440
- __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, assetsJson?: string | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
440
+ __parameters: {senderAddress?: _.Bech32 | null, recipientAddress?: _.Bech32 | null, lovelaceAmount?: _.Lovelace | null, assetsJson?: string | null, changeAddress?: _.Bech32 | null, outputDatumJson?: string | null, outputDatumCbor?: string | null, ensureMinAda?: boolean | null, referenceScriptHex?: string | null, validityStartMs?: string | null, validityEndMs?: string | null}, __returns: globalThis.Promise<TransactionBuild | null> | TransactionBuild | null, __self: never
441
441
  kind: 'action'
442
442
  }
443
443
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.29",
3
+ "version": "2.0.0-rc.30",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
package/src/index.d.ts CHANGED
@@ -13,6 +13,7 @@ export type { AgentGrantsConfig } from '../srv/utils/agent-grants-config';
13
13
  export type { HsmConfig, HsmSignResult } from '../srv/utils/types';
14
14
  export { parseTransaction } from '../srv/cbor';
15
15
  export type { ParsedTransaction, ParsedInput, ParsedOutput, ParsedAsset, ParsedWitnesses, } from '../srv/cbor';
16
+ export { applyScriptParameters, plutusScriptHash } from '../srv/utils/tx-build-helper';
16
17
  /**
17
18
  * Initialize the plugin: config from cds.env.requires["odatano-core"] or env vars,
18
19
  * then all blockchain components plus the optional crawler and wallet worker.
package/src/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.parseTransaction = exports.loadAgentGrantsConfig = exports.registerTransportLane = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
39
+ exports.plutusScriptHash = exports.applyScriptParameters = exports.parseTransaction = exports.loadAgentGrantsConfig = exports.registerTransportLane = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
40
40
  exports.initialize = initialize;
41
41
  exports.shutdown = shutdown;
42
42
  exports.getStatus = getStatus;
@@ -86,6 +86,10 @@ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get:
86
86
  // Re-export pure CBOR utilities (no CAP round-trip needed)
87
87
  var cbor_1 = require("../srv/cbor");
88
88
  Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return cbor_1.parseTransaction; } });
89
+ // Pure script helpers (no initialize() needed)
90
+ var tx_build_helper_1 = require("../srv/utils/tx-build-helper");
91
+ Object.defineProperty(exports, "applyScriptParameters", { enumerable: true, get: function () { return tx_build_helper_1.applyScriptParameters; } });
92
+ Object.defineProperty(exports, "plutusScriptHash", { enumerable: true, get: function () { return tx_build_helper_1.plutusScriptHash; } });
89
93
  /**
90
94
  * Initialize the plugin: config from cds.env.requires["odatano-core"] or env vars,
91
95
  * then all blockchain components plus the optional crawler and wallet worker.
@@ -40,8 +40,19 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
40
40
  * reference-script UTxO), the outputs exactly in the given order and change after them.
41
41
  */
42
42
  buildUnsignedPlutusTransaction(req: TxBuildPlutusRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
43
- /** Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each. */
43
+ /**
44
+ * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
45
+ * Returns the inline datums given as CBOR, keyed by output index.
46
+ */
44
47
  private _appendPlutusOutputs;
48
+ /**
49
+ * Min-ADA of an output, counting the caller's datum bytes where they are longer than
50
+ * Buildooor's encoding. `forAnyAmount` sizes the coin field for the largest amount, so the
51
+ * result stays valid once written into the output.
52
+ */
53
+ private _minOutputLovelace;
54
+ /** Build, then write the caller's datum bytes; when they are longer, a second build raises the fee. */
55
+ private _buildWithCallerDatums;
45
56
  /** Extract CBOR, hash, fee, size, inputs and outputs from a built Buildooor Tx */
46
57
  private _extractTxDetails;
47
58
  /** Build the standard TxBuildResult object */
@@ -16,6 +16,7 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
16
16
  const TxMetadata_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadata");
17
17
  const TxMetadatum_1 = require("@harmoniclabs/cardano-ledger-ts/dist/tx/metadata/TxMetadatum");
18
18
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
19
+ const caller_datums_1 = require("./caller-datums");
19
20
  const const_1 = require("../../utils/const");
20
21
  const logger = cds_1.default.log('BuildooorTxBuilder');
21
22
  /**
@@ -185,12 +186,27 @@ class BuildooorTxBuilder {
185
186
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
186
187
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
187
188
  const amount = BigInt(String(req.lovelaceAmount));
188
- let outputValue = cardano_ledger_ts_1.Value.lovelaces(amount);
189
- if (req.assets && req.assets.length > 0) {
190
- outputValue = this._buildLedgerValue(amount, req.assets);
189
+ if (req.outputDatum !== undefined && req.outputDatumCbor !== undefined) {
190
+ throw new errors_1.TransactionValidationError('outputDatum and outputDatumCbor exclude each other; pass one');
191
191
  }
192
+ const callerDatum = req.outputDatumCbor !== undefined ? Buffer.from(req.outputDatumCbor, 'hex') : undefined;
192
193
  const refScript = this._parseReferenceScript(req.referenceScript);
193
- const outputs = [this._buildTxOut(recipientAddress, outputValue, req.outputDatum, refScript)];
194
+ const recipientOut = (lovelace) => {
195
+ const value = this._buildLedgerValue(lovelace, req.assets);
196
+ return callerDatum
197
+ ? new cardano_ledger_ts_1.TxOut({ address: recipientAddress, value, datum: (0, plutus_data_1.dataFromCbor)(callerDatum), ...(refScript && { refScript }) })
198
+ : this._buildTxOut(recipientAddress, value, req.outputDatum, refScript);
199
+ };
200
+ let recipient = recipientOut(amount);
201
+ const minLovelace = this._minOutputLovelace(recipient, callerDatum);
202
+ if (amount < minLovelace) {
203
+ if (!req.ensureMinAda) {
204
+ throw new errors_1.TransactionValidationError(`recipient output needs at least ${minLovelace.toString()} lovelace (has ${amount.toString()}); raise lovelaceAmount or set ensureMinAda`);
205
+ }
206
+ recipient = recipientOut(this._minOutputLovelace(recipient, callerDatum, true));
207
+ }
208
+ const outputValue = recipient.value;
209
+ const outputs = [recipient];
194
210
  // Partition: forced UTxOs become fixed inputs; rest is the coin-selection pool
195
211
  const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
196
212
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
@@ -203,7 +219,8 @@ class BuildooorTxBuilder {
203
219
  ? this._mapOdatanoMetadataToLedgerMetadata(req.metadataJson)
204
220
  : undefined;
205
221
  const validity = this._resolveValiditySlots(req, 'passthrough');
206
- const tx = await this.txBuilder.build({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity });
222
+ const callerDatums = new Map(callerDatum ? [[0, callerDatum]] : []);
223
+ const tx = await this._buildWithCallerDatums({ inputs, outputs, changeAddress, ...(metadata && { metadata }), ...validity }, callerDatums);
207
224
  logger.debug(`Built unsigned transaction successfully.`);
208
225
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
209
226
  }
@@ -584,7 +601,7 @@ class BuildooorTxBuilder {
584
601
  : { utxo: ledgerUtxo, referenceScript: { refUtxo: refLedgerUtxo, datum, redeemer } };
585
602
  });
586
603
  const outputs = [];
587
- this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
604
+ const callerDatums = this._appendPlutusOutputs(outputs, req.outputs.map(o => ({
588
605
  ...o,
589
606
  inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
590
607
  })));
@@ -617,7 +634,7 @@ class BuildooorTxBuilder {
617
634
  ...(withdrawals.length > 0 && { withdrawals }),
618
635
  ...(certificates.length > 0 && { certificates })
619
636
  };
620
- const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction);
637
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction, callerDatums);
621
638
  const details = this._extractTxDetails(tx);
622
639
  const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
623
640
  if (details.sizeBytes > maxTxSize) {
@@ -637,22 +654,52 @@ class BuildooorTxBuilder {
637
654
  (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
638
655
  }
639
656
  }
640
- /** Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each. */
657
+ /**
658
+ * Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each.
659
+ * Returns the inline datums given as CBOR, keyed by output index.
660
+ */
641
661
  _appendPlutusOutputs(outputs, list) {
662
+ const callerDatums = new Map();
642
663
  for (let i = 0; i < list.length; i++) {
643
664
  const o = list[i];
644
665
  const value = this._buildLedgerValue(BigInt(o.lovelaceAmount), o.assets);
645
666
  const refScript = this._parseReferenceScript(o.referenceScript);
646
- const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : o.inlineDatumCbor ? (0, plutus_data_1.dataFromCbor)(o.inlineDatumCbor) : undefined;
667
+ const callerDatum = o.inlineDatumCbor ? Buffer.from(o.inlineDatumCbor, 'hex') : undefined;
668
+ const datum = o.datumHash ? new cardano_ledger_ts_1.Hash32(o.datumHash) : callerDatum ? (0, plutus_data_1.dataFromCbor)(callerDatum) : undefined;
647
669
  const txOut = datum
648
670
  ? new cardano_ledger_ts_1.TxOut({ address: cardano_ledger_ts_1.Address.fromString(o.address), value, datum, ...(refScript && { refScript }) })
649
671
  : this._buildTxOut(cardano_ledger_ts_1.Address.fromString(o.address), value, o.inlineDatum, refScript);
650
- const minLovelaces = this.txBuilder.getMinimumOutputLovelaces(txOut);
672
+ const minLovelaces = this._minOutputLovelace(txOut, callerDatum);
651
673
  if (BigInt(o.lovelaceAmount) < minLovelaces) {
652
674
  throw new errors_1.TransactionValidationError(`outputs[${i}] needs at least ${minLovelaces.toString()} lovelace (has ${o.lovelaceAmount}); raise its lovelaceAmount`);
653
675
  }
676
+ if (callerDatum)
677
+ callerDatums.set(outputs.length, callerDatum);
654
678
  outputs.push(txOut);
655
679
  }
680
+ return callerDatums;
681
+ }
682
+ /**
683
+ * Min-ADA of an output, counting the caller's datum bytes where they are longer than
684
+ * Buildooor's encoding. `forAnyAmount` sizes the coin field for the largest amount, so the
685
+ * result stays valid once written into the output.
686
+ */
687
+ _minOutputLovelace(txOut, callerDatum, forAnyAmount = false) {
688
+ const base = forAnyAmount
689
+ ? this.txBuilder.minimizeLovelaces(txOut).value.lovelaces
690
+ : this.txBuilder.getMinimumOutputLovelaces(txOut);
691
+ const growth = callerDatum ? Math.max(0, (0, caller_datums_1.callerDatumGrowth)(callerDatum)) : 0;
692
+ return base + BigInt(growth) * BigInt(this.txBuilder.protocolParamters.utxoCostPerByte);
693
+ }
694
+ /** Build, then write the caller's datum bytes; when they are longer, a second build raises the fee. */
695
+ async _buildWithCallerDatums(args, datums) {
696
+ const tx = await this.txBuilder.build(args);
697
+ const growth = (0, caller_datums_1.callerDatumsGrowth)(datums);
698
+ if (growth === 0)
699
+ return (0, caller_datums_1.writeCallerDatums)(tx, datums);
700
+ // Fee floor: the extra bytes plus a pad for change-size wobble
701
+ const fee = BigInt(tx.body.fee.toString()) + BigInt(growth + 10) * this._txFeePerByte();
702
+ return (0, caller_datums_1.writeCallerDatums)(await this.txBuilder.build({ ...args, fee }), datums);
656
703
  }
657
704
  //---------------------------------------------------------------------------
658
705
  // Shared Helper Methods
@@ -712,7 +759,7 @@ class BuildooorTxBuilder {
712
759
  * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
713
760
  * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
714
761
  */
715
- async _buildScriptTx(buildParams, evaluator) {
762
+ async _buildScriptTx(buildParams, evaluator, callerDatums = new Map()) {
716
763
  const pass1Failures = [];
717
764
  const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
718
765
  if (!tx1) {
@@ -721,7 +768,7 @@ class BuildooorTxBuilder {
721
768
  const rdmrs1 = tx1.witnesses.redeemers ?? [];
722
769
  if (rdmrs1.length === 0) {
723
770
  // Defensive: callers always attach a script; nothing to evaluate or stamp.
724
- return tx1;
771
+ return callerDatums.size === 0 ? tx1 : this._buildWithCallerDatums(buildParams, callerDatums);
725
772
  }
726
773
  // The first-pass CBOR equals a dedicated evaluation build (passed ExUnits are ignored anyway).
727
774
  const evaluatedUnits = evaluator
@@ -736,12 +783,13 @@ class BuildooorTxBuilder {
736
783
  const feeFloor = BigInt(tx1.body.fee.toString())
737
784
  + this._exUnitsPriceDelta(rdmrs1, targets1)
738
785
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
786
+ + BigInt((0, caller_datums_1.callerDatumsGrowth)(callerDatums)) * this._txFeePerByte()
739
787
  + 10n * this._txFeePerByte();
740
788
  const pass2Failures = [];
741
789
  const tx2 = await this.txBuilder.build({ ...buildParams, fee: feeFloor }, makeScriptBuildOpts(pass2Failures));
742
790
  const rdmrs2 = tx2.witnesses.redeemers ?? [];
743
791
  const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
744
- return this._stampExecUnits(tx2, targets2);
792
+ return (0, caller_datums_1.writeCallerDatums)(this._stampExecUnits(tx2, targets2), callerDatums);
745
793
  }
746
794
  /**
747
795
  * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
@@ -0,0 +1,17 @@
1
+ import { Tx } from "@harmoniclabs/cardano-ledger-ts";
2
+ /**
3
+ * Inline datums given as CBOR, keyed by output index. Buildooor writes every datum in its
4
+ * own encoding, so definite lists and maps change bytes and hash. These helpers put the
5
+ * caller's bytes back into the built transaction.
6
+ */
7
+ export type CallerDatums = Map<number, Uint8Array>;
8
+ /** Bytes one output gains when its datum is written as given; negative when it shrinks. */
9
+ export declare function callerDatumGrowth(datum: Uint8Array): number;
10
+ /** Bytes the whole transaction gains from the caller's datums, never below zero. */
11
+ export declare function callerDatumsGrowth(datums: CallerDatums): number;
12
+ /**
13
+ * Replace Buildooor's datum encoding in the listed outputs with the caller's bytes.
14
+ * Only the datum bytes change. Containers in CBOR count items, not bytes, so the rest stays valid.
15
+ */
16
+ export declare function writeCallerDatums(tx: Tx, datums: CallerDatums): Tx;
17
+ //# sourceMappingURL=caller-datums.d.ts.map
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.callerDatumGrowth = callerDatumGrowth;
4
+ exports.callerDatumsGrowth = callerDatumsGrowth;
5
+ exports.writeCallerDatums = writeCallerDatums;
6
+ const cbor_1 = require("@harmoniclabs/cbor");
7
+ const plutus_data_1 = require("@harmoniclabs/plutus-data");
8
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
9
+ const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
10
+ /** Output map entry `2 => [1, #6.24(datum)]` that holds an inline datum. */
11
+ function inlineDatumEntry(datum) {
12
+ return Buffer.concat([Buffer.from([0x02, 0x82, 0x01]), Buffer.from(cbor_1.Cbor.encode(new cbor_1.CborTag(24, new cbor_1.CborBytes(datum))))]);
13
+ }
14
+ /** Bytes one output gains when its datum is written as given; negative when it shrinks. */
15
+ function callerDatumGrowth(datum) {
16
+ return inlineDatumEntry(datum).length - inlineDatumEntry((0, plutus_data_1.dataToCbor)((0, plutus_data_1.dataFromCbor)(datum))).length;
17
+ }
18
+ /** Bytes the whole transaction gains from the caller's datums, never below zero. */
19
+ function callerDatumsGrowth(datums) {
20
+ let growth = 0;
21
+ for (const datum of datums.values())
22
+ growth += callerDatumGrowth(datum);
23
+ return Math.max(0, growth);
24
+ }
25
+ /**
26
+ * Replace Buildooor's datum encoding in the listed outputs with the caller's bytes.
27
+ * Only the datum bytes change. Containers in CBOR count items, not bytes, so the rest stays valid.
28
+ */
29
+ function writeCallerDatums(tx, datums) {
30
+ if (datums.size === 0)
31
+ return tx;
32
+ let bytes = Buffer.from(tx.toCbor());
33
+ const outputs = cardano_ledger_ts_1.Tx.fromCbor((0, uint8array_utils_1.toHex)(bytes)).body.outputs;
34
+ // Last output first, so the offsets of earlier outputs stay valid
35
+ for (const index of [...datums.keys()].sort((a, b) => b - a)) {
36
+ const out = outputs[index];
37
+ const ref = out?.cborRef;
38
+ if (!out || !ref || out.datum === undefined || out.datum instanceof cardano_ledger_ts_1.Hash32) {
39
+ throw new Error(`output ${index} of the built transaction carries no inline datum`);
40
+ }
41
+ const built = inlineDatumEntry((0, plutus_data_1.dataToCbor)(out.datum));
42
+ const at = bytes.subarray(ref.start, ref.end).indexOf(built);
43
+ if (at < 0)
44
+ throw new Error(`inline datum of output ${index} not found in the built transaction`);
45
+ const start = ref.start + at;
46
+ bytes = Buffer.concat([bytes.subarray(0, start), inlineDatumEntry(datums.get(index)), bytes.subarray(start + built.length)]);
47
+ }
48
+ return cardano_ledger_ts_1.Tx.fromCbor((0, uint8array_utils_1.toHex)(bytes));
49
+ }
50
+ //# sourceMappingURL=caller-datums.js.map
@@ -103,6 +103,12 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
103
103
  @title: 'Output Datum JSON'
104
104
  @description: 'Optional inline datum to attach to the recipient output (JSON, cardano-cli DetailedSchema format). Required when sending to a script address.'
105
105
  outputDatumJson: String,
106
+ @title: 'Output Datum CBOR'
107
+ @description: 'Optional inline datum for the recipient output as PlutusData CBOR hex, written byte for byte. Use instead of outputDatumJson when the datum bytes must match exactly.'
108
+ outputDatumCbor: String,
109
+ @title: 'Ensure Min-ADA'
110
+ @description: 'Optional. When true, a lovelaceAmount below the recipient output min-ADA is raised to it; otherwise such a request is rejected with the required amount.'
111
+ ensureMinAda: Boolean,
106
112
  @title: 'Assets JSON'
107
113
  @description: 'Optional JSON array of native assets to include in the output ([{"unit":"policyId+assetName","quantity":"amount"}]). Use when locking tokens at a script address.'
108
114
  assetsJson: String,
@@ -171,6 +177,12 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
171
177
  @title: 'Output Datum JSON'
172
178
  @description: 'Optional inline datum to attach to the recipient output (JSON, DetailedSchema). Required when sending to a script address.'
173
179
  outputDatumJson: String,
180
+ @title: 'Output Datum CBOR'
181
+ @description: 'Optional inline datum for the recipient output as PlutusData CBOR hex, written byte for byte. Use instead of outputDatumJson when the datum bytes must match exactly.'
182
+ outputDatumCbor: String,
183
+ @title: 'Ensure Min-ADA'
184
+ @description: 'Optional. When true, a lovelaceAmount below the recipient output min-ADA is raised to it; otherwise such a request is rejected with the required amount.'
185
+ ensureMinAda: Boolean,
174
186
  @title: 'Reference Script Hex'
175
187
  @description: 'Optional Plutus V3 validator CBOR hex to attach as referenceScript on the primary recipient output (CIP-33 reference script deploy). Significantly increases the output min-ADA — lovelaceAmount must cover the inflated requirement.'
176
188
  referenceScriptHex: String,
@@ -47,6 +47,15 @@ module.exports = (srv) => {
47
47
  cleanData.outputDatum = jsonResult.parsed;
48
48
  delete cleanData.outputDatumJson;
49
49
  }
50
+ delete cleanData.outputDatumCbor;
51
+ if (req.data.outputDatumCbor != null) {
52
+ if (outputDatumJson)
53
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', 'outputDatumJson and outputDatumCbor exclude each other; pass one', 'outputDatumCbor');
54
+ const cbor = (0, tx_request_parsers_1.parsePlutusCbor)(req.data.outputDatumCbor, 'outputDatumCbor');
55
+ if (cbor.error)
56
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', cbor.error, 'outputDatumCbor');
57
+ cleanData.outputDatumCbor = cbor.hex;
58
+ }
50
59
  // Native assets to lock at a script address
51
60
  const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
52
61
  if (assetsResult.error)
@@ -147,6 +156,15 @@ module.exports = (srv) => {
147
156
  cleanData.outputDatum = jsonResult.parsed;
148
157
  delete cleanData.outputDatumJson;
149
158
  }
159
+ delete cleanData.outputDatumCbor;
160
+ if (req.data.outputDatumCbor != null) {
161
+ if (outputDatumJson)
162
+ return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'outputDatumJson and outputDatumCbor exclude each other; pass one', 'outputDatumCbor');
163
+ const cbor = (0, tx_request_parsers_1.parsePlutusCbor)(req.data.outputDatumCbor, 'outputDatumCbor');
164
+ if (cbor.error)
165
+ return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', cbor.error, 'outputDatumCbor');
166
+ cleanData.outputDatumCbor = cbor.hex;
167
+ }
150
168
  if (referenceScriptHex) {
151
169
  cleanData.referenceScript = referenceScriptHex;
152
170
  }
package/srv/cbor/parse.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseTransaction = parseTransaction;
4
4
  const buildooor_1 = require("@harmoniclabs/buildooor");
5
+ const cbor_1 = require("@harmoniclabs/cbor");
5
6
  const errors_1 = require("../utils/errors");
6
7
  const error_codes_1 = require("../utils/error-codes");
7
8
  /**
@@ -66,7 +67,7 @@ function mapOutput(out) {
66
67
  }
67
68
  else {
68
69
  // anything not a Hash32 is an inline `Data` (PlutusData) payload
69
- inlineDatumHex = Buffer.from((0, buildooor_1.dataToCbor)(out.datum)).toString('hex');
70
+ inlineDatumHex = Buffer.from(inlineDatumBytes(out) ?? (0, buildooor_1.dataToCbor)(out.datum)).toString('hex');
70
71
  }
71
72
  }
72
73
  const referenceScriptHex = out.refScript
@@ -81,6 +82,17 @@ function mapOutput(out) {
81
82
  referenceScriptHex,
82
83
  };
83
84
  }
85
+ /** Inline datum bytes as they stand in the transaction; decoding and re-encoding may change them. */
86
+ function inlineDatumBytes(out) {
87
+ if (!out.cborRef)
88
+ return undefined;
89
+ const parsed = cbor_1.Cbor.parse(out.toCborBytes());
90
+ if (!(parsed instanceof cbor_1.CborMap))
91
+ return undefined;
92
+ const option = parsed.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === 2n)?.v;
93
+ const tagged = option instanceof cbor_1.CborArray ? option.array[1] : undefined;
94
+ return tagged instanceof cbor_1.CborTag && tagged.data instanceof cbor_1.CborBytes ? tagged.data.bytes : undefined;
95
+ }
84
96
  function mapMint(mint) {
85
97
  if (!mint)
86
98
  return [];
@@ -58,4 +58,10 @@ export declare function encodeScriptParam(param: JSONValue): UPLCConst;
58
58
  * @returns CBOR hex of the applied script
59
59
  */
60
60
  export declare function applyScriptParameters(scriptHex: string, params: JSONValue[]): string;
61
+ /**
62
+ * Script hash of a Plutus script, CBOR-wrapped once or twice as cardano-cli writes it:
63
+ * blake2b-224 over the language byte and the once-wrapped CBOR. The version cannot be read
64
+ * from the script, so the caller names it.
65
+ */
66
+ export declare function plutusScriptHash(scriptHex: string, version: 'plutusV2' | 'plutusV3'): string;
61
67
  //# sourceMappingURL=tx-build-helper.d.ts.map
@@ -11,6 +11,7 @@ exports.jsonToPlutusData = jsonToPlutusData;
11
11
  exports.inlineDatumToHex = inlineDatumToHex;
12
12
  exports.encodeScriptParam = encodeScriptParam;
13
13
  exports.applyScriptParameters = applyScriptParameters;
14
+ exports.plutusScriptHash = plutusScriptHash;
14
15
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
15
16
  const crypto_1 = require("@harmoniclabs/crypto");
16
17
  const errors_1 = require("./errors");
@@ -307,4 +308,27 @@ function applyScriptParameters(scriptHex, params) {
307
308
  const cborEncoded = cbor_1.Cbor.encode(new cbor_1.CborBytes(appliedFlatBytes));
308
309
  return (0, uint8array_utils_1.toHex)(cborEncoded);
309
310
  }
311
+ /**
312
+ * Script hash of a Plutus script, CBOR-wrapped once or twice as cardano-cli writes it:
313
+ * blake2b-224 over the language byte and the once-wrapped CBOR. The version cannot be read
314
+ * from the script, so the caller names it.
315
+ */
316
+ function plutusScriptHash(scriptHex, version) {
317
+ if (version !== 'plutusV2' && version !== 'plutusV3') {
318
+ throw new errors_1.TransactionValidationError(`version must be plutusV2 or plutusV3, got ${String(version)}`);
319
+ }
320
+ let script;
321
+ try {
322
+ script = new cardano_ledger_ts_1.Script(version === 'plutusV2' ? cardano_ledger_ts_1.ScriptType.PlutusV2 : cardano_ledger_ts_1.ScriptType.PlutusV3, (0, uint8array_utils_1.fromHex)(scriptHex));
323
+ }
324
+ catch (err) {
325
+ throw new errors_1.TransactionValidationError(`scriptHex is not a CBOR-wrapped Plutus script: ${err instanceof Error ? err.message : String(err)}`);
326
+ }
327
+ // Plutus V2 runs UPLC 1.0.0 only; the first three flat bytes hold the UPLC version
328
+ const b = script.bytes;
329
+ if (version === 'plutusV2' && !(b.length >= 3 && b[0] === 1 && b[1] === 0 && b[2] === 0)) {
330
+ throw new errors_1.TransactionValidationError('scriptHex is not UPLC 1.0.0 code, so it cannot be a Plutus V2 script');
331
+ }
332
+ return script.hash.toString();
333
+ }
310
334
  //# sourceMappingURL=tx-build-helper.js.map
@@ -1,4 +1,13 @@
1
1
  import type { JSONValue, MintAction } from './types';
2
+ /**
3
+ * Shared parsers for the Build*-action JSON payload fields (transaction service and wallet worker).
4
+ * Result contract: `{ parsed }` on success (undefined for absent/empty input) or `{ error }` with a client message.
5
+ */
6
+ /** PlutusData as CBOR hex, checked to decode; `field` names it in the error. */
7
+ export declare function parsePlutusCbor(value: unknown, field: string): {
8
+ hex?: string;
9
+ error?: string;
10
+ };
2
11
  export declare function parseUtxoRefArray(json: string | undefined, fieldName: 'forceInputsJson' | 'referenceInputsJson' | 'protectInputsJson'): {
3
12
  parsed?: Array<{
4
13
  txHash: string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MAX_CERTIFICATES = exports.MAX_WITHDRAWALS = exports.MAX_SCRIPT_INPUTS = exports.MAX_EXTRA_OUTPUTS = void 0;
4
+ exports.parsePlutusCbor = parsePlutusCbor;
4
5
  exports.parseUtxoRefArray = parseUtxoRefArray;
5
6
  exports.parseRequiredSigners = parseRequiredSigners;
6
7
  exports.parseAssetsArray = parseAssetsArray;
@@ -365,6 +365,10 @@ export type TxBuildRequest = {
365
365
  plutusScriptExecution?: PlutusScriptExecution;
366
366
  /** Inline datum to attach to the recipient output (optional) - for locking at script addresses */
367
367
  outputDatum?: JSONValue;
368
+ /** PlutusData CBOR hex; optional; inline datum on the recipient output, written byte for byte. Excludes outputDatum. */
369
+ outputDatumCbor?: string;
370
+ /** Raise lovelaceAmount to the recipient output's min-ADA instead of rejecting the request. */
371
+ ensureMinAda?: boolean;
368
372
  /** Required signers - Ed25519 key hashes (hex, 28 bytes each) */
369
373
  requiredSigners?: string[];
370
374
  /** Script parameters (PlutusData JSON array) applied to the script before building */