@odatano/core 1.7.9 → 1.8.0
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/LICENSE +1 -24
- package/README.md +102 -96
- package/config/preview/cardano-node/config.json +0 -1
- package/config/preview/cardano-node/peer-snapshot.json +890 -0
- package/config/preview/cardano-node/topology.json +18 -13
- package/package.json +9 -10
- package/prod.mtaext +17 -0
- package/prod.mtaext.example +27 -0
- package/review.md +42 -0
- package/src/index.d.ts.map +1 -1
- package/src/index.js +12 -2
- package/src/index.js.map +1 -1
- package/srv/blockchain/cardano-client.d.ts.map +1 -1
- package/srv/blockchain/cardano-tx-builder.js +3 -3
- package/srv/blockchain/cardano-tx-builder.js.map +1 -1
- package/srv/blockchain/signing/signature-verifier.d.ts.map +1 -1
- package/srv/blockchain/signing/signature-verifier.js +70 -79
- package/srv/blockchain/signing/signature-verifier.js.map +1 -1
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts.map +1 -1
- package/srv/blockchain/transaction-building/buildooor-tx.js +24 -4
- package/srv/blockchain/transaction-building/buildooor-tx.js.map +1 -1
- package/srv/cardano-service.js +1 -1
- package/srv/cardano-service.js.map +1 -1
- package/srv/cardano-sign-service.cds +5 -0
- package/srv/cardano-sign-service.js +2 -3
- package/srv/cardano-sign-service.js.map +1 -1
- package/srv/cardano-tx-service.cds +8 -0
- package/srv/cardano-tx-service.js +19 -2
- package/srv/cardano-tx-service.js.map +1 -1
- package/srv/server.d.ts.map +1 -1
- package/srv/server.js +33 -32
- package/srv/server.js.map +1 -1
- package/srv/utils/plutus-placeholders.d.ts.map +1 -1
- package/srv/utils/plutus-placeholders.js +2 -3
- package/srv/utils/plutus-placeholders.js.map +1 -1
- package/srv/utils/signing-helper.d.ts.map +1 -1
- package/srv/utils/signing-helper.js +6 -47
- package/srv/utils/signing-helper.js.map +1 -1
- package/srv/utils/tx-build-helper.d.ts.map +1 -1
- package/srv/utils/tx-build-helper.js +19 -43
- package/srv/utils/tx-build-helper.js.map +1 -1
- package/srv/blockchain/backends/gerolamo-backend.d.ts.map +0 -1
- package/srv/blockchain/backends/gerolamo-backend.js +0 -321
- package/srv/blockchain/backends/gerolamo-backend.js.map +0 -1
- package/srv/blockchain/transaction-building/csl-tx.d.ts.map +0 -1
- package/srv/blockchain/transaction-building/csl-tx.js +0 -922
- package/srv/blockchain/transaction-building/csl-tx.js.map +0 -1
- package/srv/blockchain/transaction-building/tx-builder-registry.d.ts.map +0 -1
- package/srv/blockchain/transaction-building/tx-builder-registry.js +0 -69
- package/srv/blockchain/transaction-building/tx-builder-registry.js.map +0 -1
|
@@ -1,922 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
-
};
|
|
38
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.CSLTxBuilder = void 0;
|
|
40
|
-
const cds_1 = __importDefault(require("@sap/cds"));
|
|
41
|
-
const CSL = __importStar(require("@emurgo/cardano-serialization-lib-nodejs"));
|
|
42
|
-
const blake2b_1 = __importDefault(require("blake2b"));
|
|
43
|
-
const tx_build_helper_1 = require("../../utils/tx-build-helper");
|
|
44
|
-
const errors_1 = require("../../utils/errors");
|
|
45
|
-
const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
|
|
46
|
-
const const_1 = require("../../utils/const");
|
|
47
|
-
const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
|
|
48
|
-
const logger = cds_1.default.log('CSLTxBuilder');
|
|
49
|
-
/**
|
|
50
|
-
* CSLTxBuilder - Implementation of CardanoTxBuilder using cardano-serialization-lib (CSL)
|
|
51
|
-
*/
|
|
52
|
-
class CSLTxBuilder {
|
|
53
|
-
name = "CslTxBuilder";
|
|
54
|
-
txBuilderConfig;
|
|
55
|
-
protocolParameters; // Store for cost models
|
|
56
|
-
cardanoClient;
|
|
57
|
-
/**
|
|
58
|
-
* Initialize the builder
|
|
59
|
-
* @param cardanoClient - The CardanoClient instance
|
|
60
|
-
* @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
|
|
61
|
-
*/
|
|
62
|
-
async init(cardanoClient, protocolParams) {
|
|
63
|
-
this.protocolParameters = protocolParams ?? await cardanoClient.getProtocolParameters();
|
|
64
|
-
this.txBuilderConfig = this._createTxBuilderConfig(this.protocolParameters);
|
|
65
|
-
this.cardanoClient = cardanoClient;
|
|
66
|
-
logger.info(`Initialized with protocol parameters.`);
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Build unsigned transfer transaction (ADA-only or with native assets)
|
|
70
|
-
*/
|
|
71
|
-
async buildUnsignedTransfer(req, ctx) {
|
|
72
|
-
try {
|
|
73
|
-
if (!ctx.utxos || ctx.utxos.length === 0) {
|
|
74
|
-
throw new errors_1.InsufficientFundsError('lovelace', BigInt(req.lovelaceAmount || 0), 0n);
|
|
75
|
-
}
|
|
76
|
-
const recipientAddress = CSL.Address.from_bech32(req.recipientAddress);
|
|
77
|
-
const changeAddress = CSL.Address.from_bech32(req.changeAddress ?? req.senderAddress);
|
|
78
|
-
const txb = CSL.TransactionBuilder.new(this.txBuilderConfig);
|
|
79
|
-
// Build output value (lovelace + optional native assets)
|
|
80
|
-
const outValue = CSL.Value.new(CSL.BigNum.from_str(String(req.lovelaceAmount)));
|
|
81
|
-
if (req.assets && req.assets.length > 0) {
|
|
82
|
-
outValue.set_multiasset(this._buildCslMultiAsset(req.assets));
|
|
83
|
-
}
|
|
84
|
-
const out = CSL.TransactionOutput.new(recipientAddress, outValue);
|
|
85
|
-
this._attachInlineDatum(out, req.outputDatum);
|
|
86
|
-
this._attachReferenceScript(out, req.referenceScript);
|
|
87
|
-
txb.add_output(out);
|
|
88
|
-
// Partition forced vs candidate UTxOs. Forced inputs are committed first; coin
|
|
89
|
-
// selection then appends additional candidates via add_inputs_from().
|
|
90
|
-
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
91
|
-
if (forced.length > 0) {
|
|
92
|
-
txb.set_inputs(this._buildForcedInputsBuilder(forced));
|
|
93
|
-
}
|
|
94
|
-
const cslUtxos = this._mapMultiAssetUtxosToCslUtxos(rest);
|
|
95
|
-
txb.add_inputs_from(cslUtxos, CSL.CoinSelectionStrategyCIP2.LargestFirstMultiAsset);
|
|
96
|
-
txb.add_change_if_needed(changeAddress);
|
|
97
|
-
const unsignedTx = txb.build_tx();
|
|
98
|
-
const txDetails = this._extractTxDetails(unsignedTx);
|
|
99
|
-
logger.info(`Built unsigned transaction successfully (${forced.length} forced inputs).`);
|
|
100
|
-
return this._buildResult(req, ctx, txDetails, { forcedInputsUsed: forced.length });
|
|
101
|
-
}
|
|
102
|
-
catch (err) {
|
|
103
|
-
(0, tx_build_helper_1.mapBuilderError)(err);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
async buildUnsignedTransactionWithMetadata(req, ctx) {
|
|
107
|
-
try {
|
|
108
|
-
const recipientAddress = CSL.Address.from_bech32(req.recipientAddress);
|
|
109
|
-
const changeAddress = CSL.Address.from_bech32(req.changeAddress ?? req.senderAddress);
|
|
110
|
-
const txb = CSL.TransactionBuilder.new(this.txBuilderConfig);
|
|
111
|
-
const amount = CSL.BigNum.from_str(String(req.lovelaceAmount));
|
|
112
|
-
const outValue = CSL.Value.new(amount);
|
|
113
|
-
const out = CSL.TransactionOutput.new(recipientAddress, outValue);
|
|
114
|
-
this._attachReferenceScript(out, req.referenceScript);
|
|
115
|
-
txb.add_output(out);
|
|
116
|
-
if (req.metadataJson) {
|
|
117
|
-
const metadata = this._mapOdatanoMetadataToCSLMetadata(req.metadataJson);
|
|
118
|
-
txb.set_metadata(metadata);
|
|
119
|
-
}
|
|
120
|
-
// Partition forced vs candidate UTxOs
|
|
121
|
-
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
122
|
-
if (forced.length > 0) {
|
|
123
|
-
txb.set_inputs(this._buildForcedInputsBuilder(forced));
|
|
124
|
-
}
|
|
125
|
-
const cslUtxos = this._mapMultiAssetUtxosToCslUtxos(rest);
|
|
126
|
-
txb.add_inputs_from(cslUtxos, CSL.CoinSelectionStrategyCIP2.LargestFirstMultiAsset);
|
|
127
|
-
txb.add_change_if_needed(changeAddress);
|
|
128
|
-
const unsignedTx = txb.build_tx();
|
|
129
|
-
const txDetails = this._extractTxDetails(unsignedTx);
|
|
130
|
-
logger.info(`Built unsigned transaction with metadata successfully (${forced.length} forced inputs).`);
|
|
131
|
-
return this._buildResult(req, ctx, txDetails, { forcedInputsUsed: forced.length });
|
|
132
|
-
}
|
|
133
|
-
catch (err) {
|
|
134
|
-
(0, tx_build_helper_1.mapBuilderError)(err);
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
// Note: `req.validityStartMs` / `req.validityEndMs` are accepted on the shared
|
|
138
|
-
// TxBuildRequest type but ignored by CSL. CSL PlutusV3 is currently blocked by
|
|
139
|
-
// PPViewHashesDontMatch (see CLAUDE.md); once that is fixed, mirror the Buildooor
|
|
140
|
-
// implementation here via `set_validity_start_interval_bignum` + `set_ttl_bignum`.
|
|
141
|
-
async buildUnsignedMintTransaction(req, ctx) {
|
|
142
|
-
try {
|
|
143
|
-
this._rejectIndexPlaceholders(req);
|
|
144
|
-
this._rejectReferenceInputs(ctx);
|
|
145
|
-
const finalExUnits = await this._evaluateExUnits((exUnits) => this._buildMintTx(req, ctx, exUnits), ctx.evaluateTransaction);
|
|
146
|
-
const unsignedTx = this._buildMintTx(req, ctx, finalExUnits);
|
|
147
|
-
const txDetails = this._extractTxDetails(unsignedTx);
|
|
148
|
-
const { hashHex: scriptHash } = this._computeScriptHash(req.mintingPolicyScript);
|
|
149
|
-
const { forced: forcedUsed } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
150
|
-
logger.info(`Built unsigned minting transaction successfully. Fee: ${txDetails.feeLovelace}`);
|
|
151
|
-
return this._buildResult(req, ctx, txDetails, { scriptHash, forcedInputsUsed: forcedUsed.length });
|
|
152
|
-
}
|
|
153
|
-
catch (error) {
|
|
154
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
155
|
-
logger.error(`BuildUnsignedMintTransaction error: ${msg}`);
|
|
156
|
-
(0, tx_build_helper_1.mapBuilderError)(error);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Helper to build mint transaction with specified execution units
|
|
161
|
-
*/
|
|
162
|
-
_buildMintTx(req, ctx, exUnits) {
|
|
163
|
-
const recipientAddress = CSL.Address.from_bech32(req.recipientAddress);
|
|
164
|
-
const changeAddress = CSL.Address.from_bech32(req.changeAddress ?? req.senderAddress);
|
|
165
|
-
const txb = CSL.TransactionBuilder.new(this.txBuilderConfig);
|
|
166
|
-
// Attach optional CIP-20 / label-674 metadata. Set before mints so both evaluate
|
|
167
|
-
// and final passes see the same auxiliary_data (affects tx size → fee).
|
|
168
|
-
if (req.metadataJson) {
|
|
169
|
-
const metadata = this._mapOdatanoMetadataToCSLMetadata(req.metadataJson);
|
|
170
|
-
txb.set_metadata(metadata);
|
|
171
|
-
}
|
|
172
|
-
const { plutusScript, cslHash: scriptHash } = this._computeScriptHash(req.mintingPolicyScript);
|
|
173
|
-
const scriptSource = CSL.PlutusScriptSource.new(plutusScript);
|
|
174
|
-
// Create MintBuilder and track total minted value for output
|
|
175
|
-
const mintBuilder = CSL.MintBuilder.new();
|
|
176
|
-
let totalMintedValue = CSL.Value.new(CSL.BigNum.from_str('0'));
|
|
177
|
-
for (const mintAction of req.mintActions) {
|
|
178
|
-
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
|
|
179
|
-
const cslAssetName = CSL.AssetName.new(Buffer.from(assetName, 'hex'));
|
|
180
|
-
const qty = String(mintAction.quantity);
|
|
181
|
-
const mintQuantity = qty.startsWith('-')
|
|
182
|
-
? CSL.Int.new_negative(CSL.BigNum.from_str(qty.slice(1)))
|
|
183
|
-
: CSL.Int.new(CSL.BigNum.from_str(qty));
|
|
184
|
-
const redeemerData = req.mintRedeemer
|
|
185
|
-
? this._toPlutusData(req.mintRedeemer)
|
|
186
|
-
: CSL.PlutusData.new_integer(CSL.BigInt.from_str(String(mintAction.redeemer ?? 0)));
|
|
187
|
-
const redeemer = CSL.Redeemer.new(CSL.RedeemerTag.new_mint(), CSL.BigNum.from_str('0'), redeemerData, CSL.ExUnits.new(CSL.BigNum.from_str(exUnits.mem), CSL.BigNum.from_str(exUnits.cpu)));
|
|
188
|
-
const mintWitness = CSL.MintWitness.new_plutus_script(scriptSource, redeemer);
|
|
189
|
-
mintBuilder.add_asset(mintWitness, cslAssetName, mintQuantity);
|
|
190
|
-
if (!String(mintAction.quantity).startsWith('-')) {
|
|
191
|
-
const assetValue = CSL.Value.new(CSL.BigNum.from_str('0'));
|
|
192
|
-
const multiAsset = CSL.MultiAsset.new();
|
|
193
|
-
const assets = CSL.Assets.new();
|
|
194
|
-
assets.insert(cslAssetName, CSL.BigNum.from_str(String(mintAction.quantity)));
|
|
195
|
-
multiAsset.insert(scriptHash, assets);
|
|
196
|
-
assetValue.set_multiasset(multiAsset);
|
|
197
|
-
totalMintedValue = totalMintedValue.checked_add(assetValue);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
txb.set_mint_builder(mintBuilder);
|
|
201
|
-
this._addRequiredSigners(txb, req.requiredSigners);
|
|
202
|
-
// Create output with minted assets + minimum lovelace
|
|
203
|
-
const outputValue = CSL.Value.new(CSL.BigNum.from_str(String(req.lovelaceAmount)));
|
|
204
|
-
const finalOutputValue = outputValue.checked_add(totalMintedValue);
|
|
205
|
-
const recipientOutput = CSL.TransactionOutput.new(recipientAddress, finalOutputValue);
|
|
206
|
-
this._attachInlineDatum(recipientOutput, req.inlineDatum);
|
|
207
|
-
this._attachReferenceScript(recipientOutput, req.referenceScript);
|
|
208
|
-
txb.add_output(recipientOutput);
|
|
209
|
-
// Partition forced vs candidate UTxOs. Forced inputs are always consumed; collateral
|
|
210
|
-
// + coin selection operate on candidates only.
|
|
211
|
-
const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
212
|
-
// Collateral + funding UTxO separation (from candidates only)
|
|
213
|
-
const { fundingUtxos } = this._setupCollateral(txb, rest);
|
|
214
|
-
// Greedy coin selection: only include funding UTxOs until we have enough ADA.
|
|
215
|
-
// We still add inputs explicitly (not via add_inputs_from) because CSL does not
|
|
216
|
-
// properly forward native tokens from selected inputs to the change output
|
|
217
|
-
// during Plutus minting transactions, causing ValueNotConservedUTxO.
|
|
218
|
-
const requiredLovelace = BigInt(req.lovelaceAmount) + const_1.COLLATERAL_LOVELACE; // output + buffer for fee + min change
|
|
219
|
-
// Subtract lovelace already contributed by forced inputs from the coin-selection target
|
|
220
|
-
const forcedLovelace = forced.reduce((sum, u) => sum + BigInt((0, tx_build_helper_1.getLovelace)(u)), 0n);
|
|
221
|
-
const remainingLovelace = requiredLovelace > forcedLovelace ? requiredLovelace - forcedLovelace : 0n;
|
|
222
|
-
const selectedFundingUtxos = remainingLovelace > 0n
|
|
223
|
-
? this._selectMinimalUtxos(fundingUtxos, remainingLovelace)
|
|
224
|
-
: [];
|
|
225
|
-
logger.debug(`Coin selection: ${selectedFundingUtxos.length}/${fundingUtxos.length} candidate UTxOs selected (${forced.length} forced) for CSL mint`);
|
|
226
|
-
// Combined input set: forced + selected funding (forced first for stable ordering)
|
|
227
|
-
const allInputUtxos = [...forced, ...selectedFundingUtxos];
|
|
228
|
-
const fundingInputsBuilder = CSL.TxInputsBuilder.new();
|
|
229
|
-
for (const u of allInputUtxos) {
|
|
230
|
-
const fTxHash = CSL.TransactionHash.from_bytes(Buffer.from(u.txHash, 'hex'));
|
|
231
|
-
const fInput = CSL.TransactionInput.new(fTxHash, u.outputIndex);
|
|
232
|
-
const fAddress = CSL.Address.from_bech32(u.address);
|
|
233
|
-
const fValue = this._buildCslValue((0, tx_build_helper_1.getLovelace)(u), u.amount);
|
|
234
|
-
fundingInputsBuilder.add_regular_input(fAddress, fInput, fValue);
|
|
235
|
-
}
|
|
236
|
-
txb.set_inputs(fundingInputsBuilder);
|
|
237
|
-
// Create explicit change output for native tokens from input UTxOs.
|
|
238
|
-
// CSL's add_change_if_needed does not forward native tokens from inputs
|
|
239
|
-
// to the change output during Plutus minting transactions.
|
|
240
|
-
const fundingNativeAssets = new Map();
|
|
241
|
-
for (const u of allInputUtxos) {
|
|
242
|
-
for (const a of u.amount) {
|
|
243
|
-
if (a.unit.toLowerCase() === 'lovelace')
|
|
244
|
-
continue;
|
|
245
|
-
if (BigInt(a.quantity) <= 0n)
|
|
246
|
-
continue;
|
|
247
|
-
const { policyId: pid, assetName: an } = (0, tx_build_helper_1.parseAssetUnit)(a.unit);
|
|
248
|
-
if (!fundingNativeAssets.has(pid))
|
|
249
|
-
fundingNativeAssets.set(pid, new Map());
|
|
250
|
-
const policy = fundingNativeAssets.get(pid);
|
|
251
|
-
policy.set(an, (policy.get(an) || 0n) + BigInt(a.quantity));
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
// Adjust for burned tokens (negative mint quantities)
|
|
255
|
-
const scriptHashHex = Buffer.from(scriptHash.to_bytes()).toString('hex');
|
|
256
|
-
for (const mintAction of req.mintActions) {
|
|
257
|
-
const qty = BigInt(mintAction.quantity);
|
|
258
|
-
if (qty >= 0n)
|
|
259
|
-
continue;
|
|
260
|
-
const { assetName: burnAssetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
|
|
261
|
-
const burnAmount = -qty;
|
|
262
|
-
const policyAssets = fundingNativeAssets.get(scriptHashHex);
|
|
263
|
-
if (policyAssets) {
|
|
264
|
-
const currentQty = policyAssets.get(burnAssetName) || 0n;
|
|
265
|
-
const newQty = currentQty - burnAmount;
|
|
266
|
-
if (newQty <= 0n) {
|
|
267
|
-
policyAssets.delete(burnAssetName);
|
|
268
|
-
if (policyAssets.size === 0)
|
|
269
|
-
fundingNativeAssets.delete(scriptHashHex);
|
|
270
|
-
}
|
|
271
|
-
else {
|
|
272
|
-
policyAssets.set(burnAssetName, newQty);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
if (fundingNativeAssets.size > 0) {
|
|
277
|
-
const nativeChangeMA = CSL.MultiAsset.new();
|
|
278
|
-
for (const [pid, assets] of fundingNativeAssets) {
|
|
279
|
-
const ph = CSL.ScriptHash.from_bytes(Buffer.from(pid, 'hex'));
|
|
280
|
-
const cslAssets = CSL.Assets.new();
|
|
281
|
-
for (const [an, qty] of assets) {
|
|
282
|
-
cslAssets.insert(CSL.AssetName.new(Buffer.from(an, 'hex')), CSL.BigNum.from_str(qty.toString()));
|
|
283
|
-
}
|
|
284
|
-
nativeChangeMA.insert(ph, cslAssets);
|
|
285
|
-
}
|
|
286
|
-
const nativeChangeValue = CSL.Value.new(CSL.BigNum.from_str(String(const_1.MIN_CHANGE_LOVELACE)));
|
|
287
|
-
nativeChangeValue.set_multiasset(nativeChangeMA);
|
|
288
|
-
txb.add_output(CSL.TransactionOutput.new(changeAddress, nativeChangeValue));
|
|
289
|
-
logger.debug(`Added explicit change output for existing native tokens from funding UTxOs`);
|
|
290
|
-
}
|
|
291
|
-
const costModels = this._createCostModels('v3');
|
|
292
|
-
txb.calc_script_data_hash(costModels);
|
|
293
|
-
txb.add_change_if_needed(changeAddress);
|
|
294
|
-
const tx = txb.build_tx();
|
|
295
|
-
return this._patchScriptDataHash(tx);
|
|
296
|
-
}
|
|
297
|
-
async buildUnsignedPlutusSpendTransaction(req, ctx) {
|
|
298
|
-
try {
|
|
299
|
-
this._rejectIndexPlaceholders(req);
|
|
300
|
-
this._rejectReferenceInputs(ctx);
|
|
301
|
-
const finalExUnits = await this._evaluateExUnits((exUnits) => this._buildPlutusSpendTx(req, ctx, exUnits), ctx.evaluateTransaction);
|
|
302
|
-
const unsignedTx = this._buildPlutusSpendTx(req, ctx, finalExUnits);
|
|
303
|
-
const txDetails = this._extractTxDetails(unsignedTx);
|
|
304
|
-
const { hashHex: scriptHash } = this._computeScriptHash(req.plutusScriptExecution.validatorScript);
|
|
305
|
-
const mintScriptHash = (req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript)
|
|
306
|
-
? this._computeScriptHash(req.mintingPolicyScript).hashHex
|
|
307
|
-
: undefined;
|
|
308
|
-
const scriptUtxoRef = req.plutusScriptExecution.scriptUtxo;
|
|
309
|
-
const { forced } = this._partitionForcedInputs(ctx.utxos, req.forceInputs);
|
|
310
|
-
const forcedUsed = forced.filter(u => !(u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex)).length;
|
|
311
|
-
logger.info(`Built unsigned Plutus spending transaction. Fee: ${txDetails.feeLovelace}`);
|
|
312
|
-
return this._buildResult(req, ctx, txDetails, { scriptHash, mintScriptHash, forcedInputsUsed: forcedUsed });
|
|
313
|
-
}
|
|
314
|
-
catch (error) {
|
|
315
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
316
|
-
logger.error(`buildUnsignedPlutusSpendTransaction error: ${msg}`);
|
|
317
|
-
(0, tx_build_helper_1.mapBuilderError)(error);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
/**
|
|
321
|
-
* Helper to build Plutus spending transaction with specified execution units
|
|
322
|
-
*/
|
|
323
|
-
_buildPlutusSpendTx(req, ctx, exUnits) {
|
|
324
|
-
const { plutusScriptExecution } = req;
|
|
325
|
-
const scriptUtxoRef = plutusScriptExecution.scriptUtxo;
|
|
326
|
-
const recipientAddress = CSL.Address.from_bech32(req.recipientAddress);
|
|
327
|
-
const changeAddress = CSL.Address.from_bech32(req.changeAddress ?? req.senderAddress);
|
|
328
|
-
const txb = CSL.TransactionBuilder.new(this.txBuilderConfig);
|
|
329
|
-
const { plutusScript } = this._computeScriptHash(plutusScriptExecution.validatorScript);
|
|
330
|
-
const scriptSource = CSL.PlutusScriptSource.new(plutusScript);
|
|
331
|
-
// Build redeemer
|
|
332
|
-
const redeemerPlutusData = this._toPlutusData(plutusScriptExecution.redeemer);
|
|
333
|
-
const redeemer = CSL.Redeemer.new(CSL.RedeemerTag.new_spend(), CSL.BigNum.from_str('0'), // index will be corrected by CSL
|
|
334
|
-
redeemerPlutusData, CSL.ExUnits.new(CSL.BigNum.from_str(exUnits.mem), CSL.BigNum.from_str(exUnits.cpu)));
|
|
335
|
-
// Add the script input using TxInputsBuilder
|
|
336
|
-
const scriptInputsBuilder = CSL.TxInputsBuilder.new();
|
|
337
|
-
const scriptTxHash = CSL.TransactionHash.from_bytes(Buffer.from(scriptUtxoRef.txHash, 'hex'));
|
|
338
|
-
const scriptInput = CSL.TransactionInput.new(scriptTxHash, scriptUtxoRef.outputIndex);
|
|
339
|
-
// Find the script UTxO to get its value
|
|
340
|
-
const scriptOdatanoUtxo = ctx.utxos.find(u => u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex);
|
|
341
|
-
if (!scriptOdatanoUtxo) {
|
|
342
|
-
throw new errors_1.TransactionValidationError(`Script UTxO ${scriptUtxoRef.txHash}#${scriptUtxoRef.outputIndex} not found in provided UTxOs`);
|
|
343
|
-
}
|
|
344
|
-
const scriptNonAdaAssets = scriptOdatanoUtxo.amount.filter(a => a.unit.toLowerCase() !== 'lovelace' && BigInt(a.quantity) > 0n);
|
|
345
|
-
const scriptUtxoValue = this._buildCslValue((0, tx_build_helper_1.getLovelace)(scriptOdatanoUtxo), scriptOdatanoUtxo.amount);
|
|
346
|
-
// Build PlutusWitness: datum handling depends on whether UTxO has inline datum
|
|
347
|
-
let plutusWitness;
|
|
348
|
-
if (plutusScriptExecution.datum) {
|
|
349
|
-
const datumSource = CSL.DatumSource.new(this._toPlutusData(plutusScriptExecution.datum));
|
|
350
|
-
plutusWitness = CSL.PlutusWitness.new_with_ref(scriptSource, datumSource, redeemer);
|
|
351
|
-
}
|
|
352
|
-
else {
|
|
353
|
-
plutusWitness = CSL.PlutusWitness.new_with_ref_without_datum(scriptSource, redeemer);
|
|
354
|
-
}
|
|
355
|
-
scriptInputsBuilder.add_plutus_script_input(plutusWitness, scriptInput, scriptUtxoValue);
|
|
356
|
-
this._addRequiredSigners(txb, req.requiredSigners);
|
|
357
|
-
// Separate sender UTxOs (excluding script UTxO)
|
|
358
|
-
const senderUtxos = ctx.utxos.filter(u => !(u.txHash === scriptUtxoRef.txHash && u.outputIndex === scriptUtxoRef.outputIndex));
|
|
359
|
-
// Partition forced inputs (excluding any ref that matches the script UTxO — silently ignored)
|
|
360
|
-
const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
|
|
361
|
-
const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered);
|
|
362
|
-
// Add forced UTxOs to the inputs builder alongside the script input
|
|
363
|
-
for (const u of forced) {
|
|
364
|
-
const fTxHash = CSL.TransactionHash.from_bytes(Buffer.from(u.txHash, 'hex'));
|
|
365
|
-
const fInput = CSL.TransactionInput.new(fTxHash, u.outputIndex);
|
|
366
|
-
const fAddress = CSL.Address.from_bech32(u.address);
|
|
367
|
-
const fValue = this._buildCslValue((0, tx_build_helper_1.getLovelace)(u), u.amount);
|
|
368
|
-
scriptInputsBuilder.add_regular_input(fAddress, fInput, fValue);
|
|
369
|
-
}
|
|
370
|
-
txb.set_inputs(scriptInputsBuilder);
|
|
371
|
-
// Collateral + funding UTxO separation (from candidate sender UTxOs only)
|
|
372
|
-
const { fundingUtxos } = this._setupCollateral(txb, rest);
|
|
373
|
-
// FR-1: Combined spend+mint. When mintActions are present, set up a MintBuilder and
|
|
374
|
-
// (when no extraOutputs handle the assets) fold positive mints into the recipient output.
|
|
375
|
-
const hasMint = !!(req.mintActions && req.mintActions.length > 0 && req.mintingPolicyScript);
|
|
376
|
-
let mintedToPrimaryValue;
|
|
377
|
-
if (hasMint) {
|
|
378
|
-
const { plutusScript: mintScript, cslHash: mintScriptCslHash } = this._computeScriptHash(req.mintingPolicyScript);
|
|
379
|
-
const mintScriptSource = CSL.PlutusScriptSource.new(mintScript);
|
|
380
|
-
const mintBuilder = CSL.MintBuilder.new();
|
|
381
|
-
const mintExUnits = CSL.ExUnits.new(CSL.BigNum.from_str(exUnits.mem), CSL.BigNum.from_str(exUnits.cpu));
|
|
382
|
-
const mintRedeemerData = req.mintRedeemer
|
|
383
|
-
? this._toPlutusData(req.mintRedeemer)
|
|
384
|
-
: CSL.PlutusData.new_integer(CSL.BigInt.from_str('0'));
|
|
385
|
-
const mintRedeemer = CSL.Redeemer.new(CSL.RedeemerTag.new_mint(), CSL.BigNum.from_str('0'), mintRedeemerData, mintExUnits);
|
|
386
|
-
const mintWitness = CSL.MintWitness.new_plutus_script(mintScriptSource, mintRedeemer);
|
|
387
|
-
const positiveAssetsForPrimary = [];
|
|
388
|
-
const mintScriptHashHex = Buffer.from(mintScriptCslHash.to_bytes()).toString('hex');
|
|
389
|
-
for (const action of req.mintActions) {
|
|
390
|
-
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
|
|
391
|
-
const cslAssetName = CSL.AssetName.new(Buffer.from(assetName, 'hex'));
|
|
392
|
-
const qtyStr = String(action.quantity);
|
|
393
|
-
const mintQty = qtyStr.startsWith('-')
|
|
394
|
-
? CSL.Int.new_negative(CSL.BigNum.from_str(qtyStr.slice(1)))
|
|
395
|
-
: CSL.Int.new(CSL.BigNum.from_str(qtyStr));
|
|
396
|
-
mintBuilder.add_asset(mintWitness, cslAssetName, mintQty);
|
|
397
|
-
if (!qtyStr.startsWith('-') && (!req.extraOutputs || req.extraOutputs.length === 0)) {
|
|
398
|
-
positiveAssetsForPrimary.push({ unit: mintScriptHashHex + assetName, quantity: qtyStr });
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
txb.set_mint_builder(mintBuilder);
|
|
402
|
-
if (positiveAssetsForPrimary.length > 0) {
|
|
403
|
-
mintedToPrimaryValue = this._buildCslValue('0', positiveAssetsForPrimary);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
// Create output for recipient with multi-assets from the script UTxO
|
|
407
|
-
const outputValue = CSL.Value.new(CSL.BigNum.from_str(String(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE)));
|
|
408
|
-
if (scriptNonAdaAssets.length > 0) {
|
|
409
|
-
outputValue.set_multiasset(this._buildCslMultiAsset(scriptNonAdaAssets));
|
|
410
|
-
}
|
|
411
|
-
const finalOutputValue = mintedToPrimaryValue ? outputValue.checked_add(mintedToPrimaryValue) : outputValue;
|
|
412
|
-
const recipientOutput = CSL.TransactionOutput.new(recipientAddress, finalOutputValue);
|
|
413
|
-
this._attachInlineDatum(recipientOutput, req.inlineDatum);
|
|
414
|
-
this._attachReferenceScript(recipientOutput, req.referenceScript);
|
|
415
|
-
txb.add_output(recipientOutput);
|
|
416
|
-
// Append extra outputs (FR-2) — each is min-ADA checked before being added.
|
|
417
|
-
this._appendExtraOutputsCsl(txb, req.extraOutputs);
|
|
418
|
-
// Coin selection from candidate funding UTxOs
|
|
419
|
-
const cslFundingUtxos = this._mapMultiAssetUtxosToCslUtxos(fundingUtxos);
|
|
420
|
-
txb.add_inputs_from(cslFundingUtxos, CSL.CoinSelectionStrategyCIP2.LargestFirstMultiAsset);
|
|
421
|
-
const costModels = this._createCostModels('v3');
|
|
422
|
-
txb.calc_script_data_hash(costModels);
|
|
423
|
-
txb.add_change_if_needed(changeAddress);
|
|
424
|
-
const tx = txb.build_tx();
|
|
425
|
-
return this._patchScriptDataHash(tx);
|
|
426
|
-
}
|
|
427
|
-
/**
|
|
428
|
-
* Post-process a CSL-built Plutus transaction to fix the scriptDataHash.
|
|
429
|
-
* CSL v15's calc_script_data_hash() produces incorrect language view CBOR
|
|
430
|
-
* for Conway-era PlutusV3 transactions. This method recomputes the correct
|
|
431
|
-
* hash using costModelsToLanguageViewCbor from @harmoniclabs/cardano-costmodels-ts.
|
|
432
|
-
*/
|
|
433
|
-
_patchScriptDataHash(tx) {
|
|
434
|
-
const witnesses = tx.witness_set();
|
|
435
|
-
const redeemers = witnesses.redeemers();
|
|
436
|
-
if (!redeemers || redeemers.len() === 0)
|
|
437
|
-
return tx;
|
|
438
|
-
const redeemersBytes = Buffer.from(redeemers.to_bytes());
|
|
439
|
-
const plutusData = witnesses.plutus_data();
|
|
440
|
-
const datumsBytes = plutusData && plutusData.len() > 0
|
|
441
|
-
? Buffer.from(plutusData.to_bytes())
|
|
442
|
-
: Buffer.alloc(0);
|
|
443
|
-
const costModelsJson = JSON.parse(this.protocolParameters.costModels || '{}');
|
|
444
|
-
const costModelsObj = {};
|
|
445
|
-
const v3 = costModelsJson['plutus:v3'] || costModelsJson['PlutusV3'];
|
|
446
|
-
if (Array.isArray(v3) && v3.length > 0) {
|
|
447
|
-
costModelsObj.PlutusScriptV3 = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(v3)).map(Number);
|
|
448
|
-
}
|
|
449
|
-
const languageViews = Buffer.from((0, cardano_costmodels_ts_1.costModelsToLanguageViewCbor)(costModelsObj, { mustHaveV3: !!costModelsObj.PlutusScriptV3 }));
|
|
450
|
-
// blake2b256(redeemers || datums || languageViews)
|
|
451
|
-
const hashInput = Buffer.concat([redeemersBytes, datumsBytes, languageViews]);
|
|
452
|
-
const hashOutput = Buffer.alloc(32);
|
|
453
|
-
(0, blake2b_1.default)(32).update(hashInput).digest(hashOutput);
|
|
454
|
-
const wrongHash = tx.body().script_data_hash();
|
|
455
|
-
if (!wrongHash)
|
|
456
|
-
return tx;
|
|
457
|
-
const wrongHashBytes = Buffer.from(wrongHash.to_bytes());
|
|
458
|
-
if (wrongHashBytes.equals(hashOutput)) {
|
|
459
|
-
return tx;
|
|
460
|
-
}
|
|
461
|
-
const txBytes = Buffer.from(tx.to_bytes());
|
|
462
|
-
const idx = txBytes.indexOf(wrongHashBytes);
|
|
463
|
-
if (idx === -1) {
|
|
464
|
-
logger.warn('Could not find scriptDataHash in transaction bytes - skipping patch');
|
|
465
|
-
return tx;
|
|
466
|
-
}
|
|
467
|
-
hashOutput.copy(txBytes, idx);
|
|
468
|
-
logger.info(`_patchScriptDataHash: patched ${wrongHashBytes.toString('hex').slice(0, 16)}... → ${hashOutput.toString('hex').slice(0, 16)}...`);
|
|
469
|
-
return CSL.Transaction.from_bytes(txBytes);
|
|
470
|
-
}
|
|
471
|
-
//---------------------------------------------------------------------------
|
|
472
|
-
// Shared Helper Methods
|
|
473
|
-
//---------------------------------------------------------------------------
|
|
474
|
-
/** Convert JSON PlutusData to CSL PlutusData using DetailedSchema */
|
|
475
|
-
_toPlutusData(json) {
|
|
476
|
-
return CSL.PlutusData.from_json(JSON.stringify(json), CSL.PlutusDatumSchema.DetailedSchema);
|
|
477
|
-
}
|
|
478
|
-
/** Build CSL MultiAsset from an array of { unit, quantity } (skips lovelace entries) */
|
|
479
|
-
_buildCslMultiAsset(assets) {
|
|
480
|
-
const multiAsset = CSL.MultiAsset.new();
|
|
481
|
-
for (const asset of assets) {
|
|
482
|
-
if (asset.unit.toLowerCase() === 'lovelace')
|
|
483
|
-
continue;
|
|
484
|
-
const { policyId, assetName } = (0, tx_build_helper_1.parseAssetUnit)(asset.unit);
|
|
485
|
-
const policyHash = CSL.ScriptHash.from_bytes(Buffer.from(policyId, 'hex'));
|
|
486
|
-
let existing = multiAsset.get(policyHash);
|
|
487
|
-
if (!existing)
|
|
488
|
-
existing = CSL.Assets.new();
|
|
489
|
-
existing.insert(CSL.AssetName.new(Buffer.from(assetName, 'hex')), CSL.BigNum.from_str(asset.quantity));
|
|
490
|
-
multiAsset.insert(policyHash, existing);
|
|
491
|
-
}
|
|
492
|
-
return multiAsset;
|
|
493
|
-
}
|
|
494
|
-
/** Build CSL Value from lovelace + optional assets array */
|
|
495
|
-
_buildCslValue(lovelace, assets) {
|
|
496
|
-
const value = CSL.Value.new(CSL.BigNum.from_str(String(lovelace)));
|
|
497
|
-
const nonAda = assets?.filter(a => a.unit.toLowerCase() !== 'lovelace' && BigInt(a.quantity) > 0n);
|
|
498
|
-
if (nonAda && nonAda.length > 0) {
|
|
499
|
-
value.set_multiasset(this._buildCslMultiAsset(nonAda));
|
|
500
|
-
}
|
|
501
|
-
return value;
|
|
502
|
-
}
|
|
503
|
-
/** Extract CBOR, hash, fee, inputs and outputs from a built CSL Transaction */
|
|
504
|
-
_extractTxDetails(unsignedTx) {
|
|
505
|
-
const unsignedTxCbor = Buffer.from(unsignedTx.to_bytes()).toString("hex");
|
|
506
|
-
const body = unsignedTx.body();
|
|
507
|
-
const txBodyHash = (0, blake2b_1.default)(32).update(body.to_bytes()).digest('hex');
|
|
508
|
-
const feeLovelace = body.fee().to_str();
|
|
509
|
-
const txInputs = body.inputs();
|
|
510
|
-
const inputRefs = [];
|
|
511
|
-
for (let i = 0; i < txInputs.len(); i++) {
|
|
512
|
-
const inp = txInputs.get(i);
|
|
513
|
-
inputRefs.push({
|
|
514
|
-
txHash: Buffer.from(inp.transaction_id().to_bytes()).toString('hex'),
|
|
515
|
-
index: inp.index()
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
const outputs = [];
|
|
519
|
-
const txOuts = body.outputs();
|
|
520
|
-
for (let i = 0; i < txOuts.len(); i++) {
|
|
521
|
-
const o = txOuts.get(i);
|
|
522
|
-
outputs.push({ address: o.address().to_bech32(), lovelace: o.amount().coin().to_str() });
|
|
523
|
-
}
|
|
524
|
-
return { unsignedTxCbor, txBodyHash, feeLovelace, inputRefs, outputs, sizeBytes: unsignedTxCbor.length / 2 };
|
|
525
|
-
}
|
|
526
|
-
/** Build the standard TxBuildResult object */
|
|
527
|
-
_buildResult(req, ctx, txDetails, extra) {
|
|
528
|
-
// Map actual tx inputs (from built CBOR) back to context UTxOs for lovelace amounts
|
|
529
|
-
const inputs = txDetails.inputRefs.map(ref => {
|
|
530
|
-
const ctxUtxo = ctx.utxos.find(u => u.txHash === ref.txHash && u.outputIndex === ref.index);
|
|
531
|
-
return {
|
|
532
|
-
txHash: ref.txHash,
|
|
533
|
-
index: ref.index,
|
|
534
|
-
lovelace: ctxUtxo ? (0, tx_build_helper_1.getLovelace)(ctxUtxo).toString() : "0",
|
|
535
|
-
};
|
|
536
|
-
});
|
|
537
|
-
return {
|
|
538
|
-
unsignedTxCbor: txDetails.unsignedTxCbor,
|
|
539
|
-
txBodyHash: txDetails.txBodyHash,
|
|
540
|
-
senderAddress: req.senderAddress,
|
|
541
|
-
network: this.cardanoClient.network,
|
|
542
|
-
sizeBytes: txDetails.sizeBytes,
|
|
543
|
-
builderEngine: this.name,
|
|
544
|
-
feeLovelace: txDetails.feeLovelace,
|
|
545
|
-
inputs,
|
|
546
|
-
outputs: txDetails.outputs,
|
|
547
|
-
...extra,
|
|
548
|
-
warnings: [],
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
/** Add required signers (Ed25519 key hashes) to the transaction builder */
|
|
552
|
-
_addRequiredSigners(txb, signers) {
|
|
553
|
-
if (signers?.length) {
|
|
554
|
-
for (const signerHex of signers) {
|
|
555
|
-
txb.add_required_signer(CSL.Ed25519KeyHash.from_bytes(Buffer.from(signerHex, 'hex')));
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
/** Attach inline PlutusData datum to a transaction output */
|
|
560
|
-
_attachInlineDatum(output, datum) {
|
|
561
|
-
if (datum) {
|
|
562
|
-
output.set_plutus_data(this._toPlutusData(datum));
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Attach a PlutusV3 reference script (CIP-33) to a transaction output.
|
|
567
|
-
* Uses new_v3() per the CSL v15 hashing rule — the CBOR-wrapped flat UPLC hex
|
|
568
|
-
* from compilers matches blake2b_224(0x03 || cborBytes) only with new_v3.
|
|
569
|
-
*/
|
|
570
|
-
_attachReferenceScript(output, referenceScriptHex) {
|
|
571
|
-
if (!referenceScriptHex)
|
|
572
|
-
return;
|
|
573
|
-
// CSL.PlutusScript.new_v3 accepts any bytes without CBOR parse, so validate hex upfront.
|
|
574
|
-
if (!/^[a-f0-9]+$/i.test(referenceScriptHex) || referenceScriptHex.length % 2 !== 0) {
|
|
575
|
-
throw new errors_1.TransactionValidationError(`Invalid referenceScript CBOR: must be even-length hex`);
|
|
576
|
-
}
|
|
577
|
-
try {
|
|
578
|
-
const script = CSL.PlutusScript.new_v3(Buffer.from(referenceScriptHex, 'hex'));
|
|
579
|
-
output.set_script_ref(CSL.ScriptRef.new_plutus_script(script));
|
|
580
|
-
}
|
|
581
|
-
catch (err) {
|
|
582
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
583
|
-
throw new errors_1.TransactionValidationError(`Invalid referenceScript CBOR: ${msg}`);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
/**
|
|
587
|
-
* FR-3 guard: the CSL builder cannot resolve __INPUT_IDX__ placeholders because
|
|
588
|
-
* CSL's add_inputs_from selects funding internally and we cannot enumerate the
|
|
589
|
-
* resulting input order without a throwaway first-pass build. Reject up-front so
|
|
590
|
-
* consumers get a clear error pointing at the active builder.
|
|
591
|
-
*/
|
|
592
|
-
_rejectIndexPlaceholders(req) {
|
|
593
|
-
const candidates = [
|
|
594
|
-
req.plutusScriptExecution?.redeemer,
|
|
595
|
-
req.plutusScriptExecution?.datum,
|
|
596
|
-
req.inlineDatum,
|
|
597
|
-
req.mintRedeemer
|
|
598
|
-
];
|
|
599
|
-
if (req.extraOutputs) {
|
|
600
|
-
for (const e of req.extraOutputs)
|
|
601
|
-
candidates.push(e.inlineDatum);
|
|
602
|
-
}
|
|
603
|
-
for (const c of candidates) {
|
|
604
|
-
if (c !== undefined && (0, plutus_placeholders_1.containsIndexPlaceholder)(c)) {
|
|
605
|
-
throw new errors_1.TransactionValidationError('Input-index placeholders (__INPUT_IDX:...__) require the Buildooor transaction builder. Pre-resolve indices client-side or set TX_BUILDERS=buildooor.');
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
/**
|
|
610
|
-
* Append parsed extraOutputs (FR-2) to a CSL TransactionBuilder, enforcing min-ADA per entry.
|
|
611
|
-
* Mirrors BuildooorTxBuilder._appendExtraOutputs so both engines produce equivalent layouts.
|
|
612
|
-
*/
|
|
613
|
-
_appendExtraOutputsCsl(txb, extraOutputs) {
|
|
614
|
-
if (!extraOutputs || extraOutputs.length === 0)
|
|
615
|
-
return;
|
|
616
|
-
const coinsPerByte = this.protocolParameters.coinsPerUtxoSize;
|
|
617
|
-
if (!coinsPerByte) {
|
|
618
|
-
throw new errors_1.TransactionValidationError('Cannot enforce min-ADA on extraOutputs: coinsPerUtxoSize not set in protocol parameters');
|
|
619
|
-
}
|
|
620
|
-
const dataCost = CSL.DataCost.new_coins_per_byte(CSL.BigNum.from_str(String(coinsPerByte)));
|
|
621
|
-
for (let i = 0; i < extraOutputs.length; i++) {
|
|
622
|
-
const extra = extraOutputs[i];
|
|
623
|
-
const addr = CSL.Address.from_bech32(extra.address);
|
|
624
|
-
const value = this._buildCslValue(extra.lovelaceAmount, extra.assets);
|
|
625
|
-
const out = CSL.TransactionOutput.new(addr, value);
|
|
626
|
-
this._attachInlineDatum(out, extra.inlineDatum);
|
|
627
|
-
this._attachReferenceScript(out, extra.referenceScript);
|
|
628
|
-
const requiredMin = CSL.min_ada_for_output(out, dataCost);
|
|
629
|
-
const requestedLovelace = CSL.BigNum.from_str(String(extra.lovelaceAmount));
|
|
630
|
-
if (requestedLovelace.compare(requiredMin) < 0) {
|
|
631
|
-
throw new errors_1.TransactionValidationError(`extraOutputs[${i}].lovelaceAmount (${extra.lovelaceAmount}) is below required min-ADA ${requiredMin.to_str()} for the given address/assets/datum`);
|
|
632
|
-
}
|
|
633
|
-
txb.add_output(out);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
/** Parse PlutusV3 script hex and compute its hash */
|
|
637
|
-
_computeScriptHash(scriptHex) {
|
|
638
|
-
const plutusScript = CSL.PlutusScript.new_v3(Buffer.from(scriptHex, 'hex'));
|
|
639
|
-
const cslHash = plutusScript.hash();
|
|
640
|
-
return { plutusScript, hashHex: Buffer.from(cslHash.to_bytes()).toString('hex'), cslHash };
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Evaluate execution units via a two-pass build: first with high units for evaluation,
|
|
644
|
-
* then apply the evaluated budget with a safety buffer. Falls back to defaults on failure.
|
|
645
|
-
*/
|
|
646
|
-
async _evaluateExUnits(buildFn, evaluator) {
|
|
647
|
-
const defaultUnits = {
|
|
648
|
-
mem: String(const_1.DEFAULT_EXECUTION_UNITS.mem),
|
|
649
|
-
cpu: String(const_1.DEFAULT_EXECUTION_UNITS.cpu)
|
|
650
|
-
};
|
|
651
|
-
if (!evaluator) {
|
|
652
|
-
logger.debug('No evaluator available, using default execution units');
|
|
653
|
-
return defaultUnits;
|
|
654
|
-
}
|
|
655
|
-
logger.debug('Building evaluation pass with high execution units');
|
|
656
|
-
const evalTx = buildFn({
|
|
657
|
-
mem: String(const_1.HIGH_EXECUTION_UNITS.mem),
|
|
658
|
-
cpu: String(const_1.HIGH_EXECUTION_UNITS.cpu)
|
|
659
|
-
});
|
|
660
|
-
const evalTxCbor = Buffer.from(evalTx.to_bytes()).toString('hex');
|
|
661
|
-
try {
|
|
662
|
-
const evalResults = await evaluator(evalTxCbor);
|
|
663
|
-
logger.debug(`Evaluation results: ${JSON.stringify(evalResults)}`);
|
|
664
|
-
if (evalResults && evalResults.length > 0) {
|
|
665
|
-
const budget = evalResults[0].budget;
|
|
666
|
-
// Combined cushion: relative multiplier for large validators, absolute floor
|
|
667
|
-
// for small ones (sub-percent drift when metadata affects the tx body).
|
|
668
|
-
const result = {
|
|
669
|
-
mem: (Math.ceil(budget.memory * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_MEM_BUFFER).toString(),
|
|
670
|
-
cpu: (Math.ceil(budget.cpu * const_1.EXECUTION_UNIT_BUFFER) + const_1.ABS_CPU_BUFFER).toString()
|
|
671
|
-
};
|
|
672
|
-
logger.info(`Using evaluated execution units: mem=${result.mem}, cpu=${result.cpu}`);
|
|
673
|
-
return result;
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
catch (evalError) {
|
|
677
|
-
const msg = evalError instanceof Error ? evalError.message : String(evalError);
|
|
678
|
-
logger.warn(`Evaluation failed, using default units: ${msg}`);
|
|
679
|
-
}
|
|
680
|
-
return defaultUnits;
|
|
681
|
-
}
|
|
682
|
-
/**
|
|
683
|
-
* Split UTxOs into forced inputs (must be consumed) and remaining candidates.
|
|
684
|
-
* Refs in forceInputs not present in utxos are silently ignored.
|
|
685
|
-
*/
|
|
686
|
-
_partitionForcedInputs(utxos, forceInputs) {
|
|
687
|
-
if (!forceInputs || forceInputs.length === 0)
|
|
688
|
-
return { forced: [], rest: utxos };
|
|
689
|
-
const forcedKeys = new Set(forceInputs.map(r => `${r.txHash}#${r.outputIndex}`));
|
|
690
|
-
const forced = [];
|
|
691
|
-
const rest = [];
|
|
692
|
-
for (const u of utxos) {
|
|
693
|
-
if (forcedKeys.has(`${u.txHash}#${u.outputIndex}`))
|
|
694
|
-
forced.push(u);
|
|
695
|
-
else
|
|
696
|
-
rest.push(u);
|
|
697
|
-
}
|
|
698
|
-
return { forced, rest };
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* Build a TxInputsBuilder seeded with the given forced UTxOs. Caller is responsible
|
|
702
|
-
* for wiring the returned builder to the TransactionBuilder via set_inputs(). Coin
|
|
703
|
-
* selection (add_inputs_from) then appends additional candidates on top.
|
|
704
|
-
*/
|
|
705
|
-
_buildForcedInputsBuilder(forced) {
|
|
706
|
-
const builder = CSL.TxInputsBuilder.new();
|
|
707
|
-
for (const u of forced) {
|
|
708
|
-
const txHash = CSL.TransactionHash.from_bytes(Buffer.from(u.txHash, 'hex'));
|
|
709
|
-
const input = CSL.TransactionInput.new(txHash, u.outputIndex);
|
|
710
|
-
const address = CSL.Address.from_bech32(u.address);
|
|
711
|
-
const value = this._buildCslValue((0, tx_build_helper_1.getLovelace)(u), u.amount);
|
|
712
|
-
builder.add_regular_input(address, input, value);
|
|
713
|
-
}
|
|
714
|
-
return builder;
|
|
715
|
-
}
|
|
716
|
-
/**
|
|
717
|
-
* Find an ADA-only UTxO for collateral, set it on the builder,
|
|
718
|
-
* and return the remaining funding UTxOs with collateral excluded.
|
|
719
|
-
*/
|
|
720
|
-
_setupCollateral(txb, utxos) {
|
|
721
|
-
const collateralUtxo = utxos.find(u => u.amount.every(a => a.unit.toLowerCase() === 'lovelace'));
|
|
722
|
-
if (collateralUtxo) {
|
|
723
|
-
const collateralBuilder = CSL.TxInputsBuilder.new();
|
|
724
|
-
const txHash = CSL.TransactionHash.from_bytes(Buffer.from(collateralUtxo.txHash, 'hex'));
|
|
725
|
-
const input = CSL.TransactionInput.new(txHash, collateralUtxo.outputIndex);
|
|
726
|
-
const address = CSL.Address.from_bech32(collateralUtxo.address);
|
|
727
|
-
const value = CSL.Value.new(CSL.BigNum.from_str((0, tx_build_helper_1.getLovelace)(collateralUtxo).toString()));
|
|
728
|
-
collateralBuilder.add_regular_input(address, input, value);
|
|
729
|
-
txb.set_collateral(collateralBuilder);
|
|
730
|
-
}
|
|
731
|
-
let fundingUtxos = collateralUtxo
|
|
732
|
-
? utxos.filter(u => !(u.txHash === collateralUtxo.txHash && u.outputIndex === collateralUtxo.outputIndex))
|
|
733
|
-
: utxos;
|
|
734
|
-
if (fundingUtxos.length === 0 && utxos.length > 0) {
|
|
735
|
-
logger.debug('No funding UTxOs after collateral exclusion, including collateral in funding pool');
|
|
736
|
-
fundingUtxos = utxos;
|
|
737
|
-
}
|
|
738
|
-
return { collateralUtxo, fundingUtxos };
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Greedy coin selection: sort UTxOs by lovelace descending (largest first),
|
|
742
|
-
* collect until requiredLovelace is satisfied. Falls back to all UTxOs if
|
|
743
|
-
* the full set is needed.
|
|
744
|
-
*/
|
|
745
|
-
_selectMinimalUtxos(utxos, requiredLovelace) {
|
|
746
|
-
const sorted = [...utxos].sort((a, b) => {
|
|
747
|
-
const aLov = BigInt((0, tx_build_helper_1.getLovelace)(a));
|
|
748
|
-
const bLov = BigInt((0, tx_build_helper_1.getLovelace)(b));
|
|
749
|
-
return bLov > aLov ? 1 : bLov < aLov ? -1 : 0;
|
|
750
|
-
});
|
|
751
|
-
const selected = [];
|
|
752
|
-
let accumulated = 0n;
|
|
753
|
-
for (const u of sorted) {
|
|
754
|
-
selected.push(u);
|
|
755
|
-
accumulated += BigInt((0, tx_build_helper_1.getLovelace)(u));
|
|
756
|
-
if (accumulated >= requiredLovelace)
|
|
757
|
-
break;
|
|
758
|
-
}
|
|
759
|
-
return selected;
|
|
760
|
-
}
|
|
761
|
-
//---------------------------------------------------------------------------
|
|
762
|
-
// CSL Mapping & Configuration Helpers
|
|
763
|
-
//---------------------------------------------------------------------------
|
|
764
|
-
/**
|
|
765
|
-
* Map ODATANO UTxOs to CSL TransactionUnspentOutputs (with multi-asset support)
|
|
766
|
-
*/
|
|
767
|
-
_mapMultiAssetUtxosToCslUtxos(utxos) {
|
|
768
|
-
const outs = CSL.TransactionUnspentOutputs.new();
|
|
769
|
-
logger.debug(`Mapping ${utxos.length} UTxOs to CSL format`);
|
|
770
|
-
for (const u of utxos) {
|
|
771
|
-
logger.debug(`UTxO ${u.txHash}:${u.outputIndex} has ${u.amount.length} amounts: ${JSON.stringify(u.amount)}`);
|
|
772
|
-
const txHash = CSL.TransactionHash.from_bytes(Buffer.from(u.txHash, "hex"));
|
|
773
|
-
const input = CSL.TransactionInput.new(txHash, u.outputIndex);
|
|
774
|
-
const addr = CSL.Address.from_bech32(u.address);
|
|
775
|
-
const value = this._buildCslValue((0, tx_build_helper_1.getLovelace)(u), u.amount);
|
|
776
|
-
const output = CSL.TransactionOutput.new(addr, value);
|
|
777
|
-
outs.add(CSL.TransactionUnspentOutput.new(input, output));
|
|
778
|
-
}
|
|
779
|
-
return outs;
|
|
780
|
-
}
|
|
781
|
-
/**
|
|
782
|
-
* Create a CSL TransactionBuilderConfig from protocol parameters
|
|
783
|
-
*/
|
|
784
|
-
_createTxBuilderConfig(protocolParams) {
|
|
785
|
-
const minFeeA = protocolParams.minFeeA;
|
|
786
|
-
const minFeeB = protocolParams.minFeeB;
|
|
787
|
-
const poolDeposit = protocolParams.poolDeposit;
|
|
788
|
-
const keyDeposit = protocolParams.keyDeposit;
|
|
789
|
-
const maxTxSize = protocolParams.maxTxSize;
|
|
790
|
-
const maxValueSize = protocolParams.maxValSize;
|
|
791
|
-
const coinsPerUtxoByte = protocolParams.coinsPerUtxoSize;
|
|
792
|
-
const feeAlgo = CSL.LinearFee.new(CSL.BigNum.from_str(String(minFeeA)), CSL.BigNum.from_str(String(minFeeB)));
|
|
793
|
-
// Plutus execution unit prices for script fee calculation
|
|
794
|
-
const priceMemValue = protocolParams.priceMem;
|
|
795
|
-
const priceStepValue = protocolParams.priceStep;
|
|
796
|
-
const priceMemNumerator = (typeof priceMemValue === 'number' && priceMemValue < 1)
|
|
797
|
-
? Math.round(priceMemValue * 10000)
|
|
798
|
-
: (priceMemValue || 577);
|
|
799
|
-
const priceStepNumerator = (typeof priceStepValue === 'number' && priceStepValue < 1)
|
|
800
|
-
? Math.round(priceStepValue * 10000000)
|
|
801
|
-
: (priceStepValue || 721);
|
|
802
|
-
const exUnitPrices = CSL.ExUnitPrices.new(CSL.UnitInterval.new(CSL.BigNum.from_str(String(priceMemNumerator)), CSL.BigNum.from_str('10000')), CSL.UnitInterval.new(CSL.BigNum.from_str(String(priceStepNumerator)), CSL.BigNum.from_str('10000000')));
|
|
803
|
-
const cfg = CSL.TransactionBuilderConfigBuilder.new()
|
|
804
|
-
.fee_algo(feeAlgo)
|
|
805
|
-
.pool_deposit(CSL.BigNum.from_str(String(poolDeposit)))
|
|
806
|
-
.key_deposit(CSL.BigNum.from_str(String(keyDeposit)))
|
|
807
|
-
.max_tx_size(Number(maxTxSize))
|
|
808
|
-
.max_value_size(Number(maxValueSize))
|
|
809
|
-
.coins_per_utxo_byte(CSL.BigNum.from_str(String(coinsPerUtxoByte)))
|
|
810
|
-
.ex_unit_prices(exUnitPrices)
|
|
811
|
-
.build();
|
|
812
|
-
logger.info(`TransactionBuilderConfig created with Plutus execution unit prices.`);
|
|
813
|
-
return cfg;
|
|
814
|
-
}
|
|
815
|
-
/**
|
|
816
|
-
* Map ODATANO metadata JSON to CSL GeneralTransactionMetadata
|
|
817
|
-
*/
|
|
818
|
-
_mapOdatanoMetadataToCSLMetadata(metadataJson) {
|
|
819
|
-
if (typeof metadataJson !== 'object' || Array.isArray(metadataJson) || metadataJson === null) {
|
|
820
|
-
throw new errors_1.TransactionValidationError(`Invalid metadata format. Expected object, got ${typeof metadataJson}`);
|
|
821
|
-
}
|
|
822
|
-
const metadata = CSL.GeneralTransactionMetadata.new();
|
|
823
|
-
for (const [label, value] of Object.entries(metadataJson)) {
|
|
824
|
-
const numericLabel = parseInt(label, 10);
|
|
825
|
-
const txMetadatum = this._jsonToCSLMetadatum(value);
|
|
826
|
-
logger.debug(`Created TransactionMetadatum for label ${numericLabel}`);
|
|
827
|
-
metadata.insert(CSL.BigNum.from_str(String(numericLabel)), txMetadatum);
|
|
828
|
-
}
|
|
829
|
-
logger.debug(`Created metadata with ${metadata.len()} labels`);
|
|
830
|
-
return metadata;
|
|
831
|
-
}
|
|
832
|
-
/**
|
|
833
|
-
* Create Costmdls from protocol parameters for specific Plutus version
|
|
834
|
-
*/
|
|
835
|
-
_createCostModels(version) {
|
|
836
|
-
const costModels = CSL.Costmdls.new();
|
|
837
|
-
const toArray = (costs) => {
|
|
838
|
-
if (Array.isArray(costs))
|
|
839
|
-
return costs;
|
|
840
|
-
if (costs && typeof costs === 'object') {
|
|
841
|
-
return Object.keys(costs).sort().map(k => costs[k]);
|
|
842
|
-
}
|
|
843
|
-
return null;
|
|
844
|
-
};
|
|
845
|
-
const addCostModel = (language, costs, label) => {
|
|
846
|
-
const costModel = CSL.CostModel.new();
|
|
847
|
-
for (let i = 0; i < costs.length; i++) {
|
|
848
|
-
costModel.set(i, CSL.Int.new_i32(costs[i]));
|
|
849
|
-
}
|
|
850
|
-
costModels.insert(language, costModel);
|
|
851
|
-
logger.debug(`Added ${label} cost model with ${costs.length} parameters`);
|
|
852
|
-
};
|
|
853
|
-
try {
|
|
854
|
-
const costModelsJson = JSON.parse(this.protocolParameters.costModels || '{}');
|
|
855
|
-
if (!version || version === 'v1') {
|
|
856
|
-
const v1Costs = toArray(costModelsJson['plutus:v1'] || costModelsJson['PlutusV1']);
|
|
857
|
-
if (v1Costs)
|
|
858
|
-
addCostModel(CSL.Language.new_plutus_v1(), v1Costs, 'PlutusV1');
|
|
859
|
-
}
|
|
860
|
-
if (!version || version === 'v2') {
|
|
861
|
-
const v2Costs = toArray(costModelsJson['plutus:v2'] || costModelsJson['PlutusV2']);
|
|
862
|
-
if (v2Costs)
|
|
863
|
-
addCostModel(CSL.Language.new_plutus_v2(), v2Costs, 'PlutusV2');
|
|
864
|
-
}
|
|
865
|
-
if (!version || version === 'v3') {
|
|
866
|
-
const v3CostsRaw = toArray(costModelsJson['plutus:v3'] || costModelsJson['PlutusV3']);
|
|
867
|
-
if (v3CostsRaw) {
|
|
868
|
-
// Pad to 297 parameters (Conway Chang 2) using defaults from cardano-costmodels-ts
|
|
869
|
-
const v3Costs = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(v3CostsRaw)).map(Number);
|
|
870
|
-
addCostModel(CSL.Language.new_plutus_v3(), v3Costs, 'PlutusV3');
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
catch (error) {
|
|
875
|
-
logger.warn(`Failed to parse cost models: ${error}. Using empty cost models.`);
|
|
876
|
-
}
|
|
877
|
-
return costModels;
|
|
878
|
-
}
|
|
879
|
-
/**
|
|
880
|
-
* Convert JSON value to CSL TransactionMetadatum
|
|
881
|
-
*/
|
|
882
|
-
_jsonToCSLMetadatum(value) {
|
|
883
|
-
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
884
|
-
const s = String(value);
|
|
885
|
-
const intValue = s.startsWith('-')
|
|
886
|
-
? CSL.Int.new_negative(CSL.BigNum.from_str(s.slice(1)))
|
|
887
|
-
: CSL.Int.new(CSL.BigNum.from_str(s));
|
|
888
|
-
return CSL.TransactionMetadatum.new_int(intValue);
|
|
889
|
-
}
|
|
890
|
-
if (typeof value === 'string') {
|
|
891
|
-
return CSL.TransactionMetadatum.new_text(value);
|
|
892
|
-
}
|
|
893
|
-
if (Array.isArray(value)) {
|
|
894
|
-
const list = CSL.MetadataList.new();
|
|
895
|
-
for (const item of value) {
|
|
896
|
-
list.add(this._jsonToCSLMetadatum(item));
|
|
897
|
-
}
|
|
898
|
-
return CSL.TransactionMetadatum.new_list(list);
|
|
899
|
-
}
|
|
900
|
-
if (typeof value === 'object' && value !== null) {
|
|
901
|
-
const map = CSL.MetadataMap.new();
|
|
902
|
-
for (const [k, v] of Object.entries(value)) {
|
|
903
|
-
const key = CSL.TransactionMetadatum.new_text(k);
|
|
904
|
-
const val = this._jsonToCSLMetadatum(v);
|
|
905
|
-
map.insert(key, val);
|
|
906
|
-
}
|
|
907
|
-
return CSL.TransactionMetadatum.new_map(map);
|
|
908
|
-
}
|
|
909
|
-
throw new errors_1.TransactionValidationError(`Unsupported metadata value type: ${typeof value}`);
|
|
910
|
-
}
|
|
911
|
-
/**
|
|
912
|
-
* Reject CIP-31 reference inputs on the CSL builder — not yet supported.
|
|
913
|
-
* Consumers must use Buildooor (TX_BUILDERS=buildooor) for reference input support.
|
|
914
|
-
*/
|
|
915
|
-
_rejectReferenceInputs(ctx) {
|
|
916
|
-
if (ctx.referenceInputUtxos && ctx.referenceInputUtxos.length > 0) {
|
|
917
|
-
throw new errors_1.TransactionValidationError('CIP-31 reference inputs (referenceInputsJson) require the Buildooor transaction builder. Set TX_BUILDERS=buildooor to use reference inputs.');
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
exports.CSLTxBuilder = CSLTxBuilder;
|
|
922
|
-
//# sourceMappingURL=csl-tx.js.map
|