@meshsdk/transaction 1.5.28 → 1.5.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.
Files changed (3) hide show
  1. package/dist/index.js +1 -2029
  2. package/dist/index.mjs +1 -2014
  3. package/package.json +6 -2
package/dist/index.js CHANGED
@@ -1,2029 +1 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- ForgeScript: () => ForgeScript,
34
- MeshTxBuilder: () => MeshTxBuilder,
35
- Transaction: () => Transaction,
36
- UtxoSelection: () => UtxoSelection,
37
- experimentalSelectUtxos: () => experimentalSelectUtxos,
38
- keepRelevant: () => keepRelevant,
39
- largestFirst: () => largestFirst,
40
- largestFirstMultiAsset: () => largestFirstMultiAsset
41
- });
42
- module.exports = __toCommonJS(src_exports);
43
-
44
- // src/mesh-tx-builder/tx-builder-core.ts
45
- var import_common9 = require("@meshsdk/common");
46
- var import_json_bigint = __toESM(require("json-bigint"));
47
-
48
- // src/utxo-selection/keepRelevant.ts
49
- var import_common3 = require("@meshsdk/common");
50
-
51
- // src/utxo-selection/common.ts
52
- var import_common = require("@meshsdk/common");
53
- var import_common2 = require("@meshsdk/common");
54
- var enoughValueHasBeenSelected = (selection, assets) => {
55
- return Array.from(assets, (asset) => ({
56
- unit: asset[0],
57
- quantity: import_common.BigNum.new(asset[1])
58
- })).every((asset) => {
59
- return selection.filter((utxo) => {
60
- return utxo.output.amount.find((a) => a.unit === asset.unit) !== void 0;
61
- }).reduce((selectedQuantity, utxo) => {
62
- const utxoQuantity = utxo.output.amount.reduce(
63
- (quantity, a) => quantity.checkedAdd(
64
- import_common.BigNum.new(asset.unit === a.unit ? a.quantity : "0")
65
- ),
66
- import_common.BigNum.new("0")
67
- );
68
- return selectedQuantity.checkedAdd(utxoQuantity);
69
- }, import_common.BigNum.new("0")).lessThan(asset.quantity) === false;
70
- });
71
- };
72
- var largestLovelaceQuantity = (utxoA, utxoB) => {
73
- const aLovelaceQuantity = import_common.BigNum.new(
74
- utxoA.output.amount.find((asset) => asset.unit === "lovelace")?.quantity ?? "0"
75
- );
76
- const bLovelaceQuantity = import_common.BigNum.new(
77
- utxoB.output.amount.find((asset) => asset.unit === "lovelace")?.quantity ?? "0"
78
- );
79
- return bLovelaceQuantity.compare(aLovelaceQuantity);
80
- };
81
- var maxTxFees = (parameters) => {
82
- const { maxTxSize, minFeeA, minFeeB } = parameters;
83
- return import_common.BigNum.new((0, import_common2.resolveTxFees)(maxTxSize, minFeeA, minFeeB));
84
- };
85
- var multiAssetUTxO = (utxo) => utxo.output.amount.length > 1;
86
- var selectedLovelaceQuantity = (multiAsset) => {
87
- return multiAsset.reduce((sum, utxo) => {
88
- const lovelace = utxo.output.amount.find((asset) => asset.unit === "lovelace")?.quantity ?? "0";
89
- return sum.checkedAdd(import_common.BigNum.new(lovelace));
90
- }, import_common.BigNum.new("0"));
91
- };
92
- var remainingLovelace = (quantity, initialUTxOSet) => {
93
- const sortedUTxOs = initialUTxOSet.sort(largestLovelaceQuantity);
94
- const requestedOutputSet = /* @__PURE__ */ new Map([["lovelace", quantity]]);
95
- const selection = selectValue(sortedUTxOs, requestedOutputSet);
96
- return selection;
97
- };
98
- var selectValue = (inputUTxO, outputSet, selection = []) => {
99
- if (inputUTxO.length === 0 || enoughValueHasBeenSelected(selection, outputSet)) {
100
- return selection;
101
- }
102
- if (valueCanBeSelected(inputUTxO[0], outputSet)) {
103
- return selectValue(inputUTxO.slice(1), outputSet, [
104
- ...selection,
105
- inputUTxO[0]
106
- ]);
107
- }
108
- return selectValue(inputUTxO.slice(1), outputSet, selection);
109
- };
110
- var valueCanBeSelected = (utxo, assets) => {
111
- return Array.from(assets.keys()).some((unit) => {
112
- return utxo.output.amount.find((asset) => asset.unit === unit) !== void 0;
113
- });
114
- };
115
-
116
- // src/utxo-selection/keepRelevant.ts
117
- var keepRelevant = (requiredAssets, inputs, threshold = "5000000") => {
118
- const requestedLovelace = import_common3.BigNum.new(
119
- requiredAssets.get("lovelace") ?? "0"
120
- ).checkedAdd(import_common3.BigNum.new(threshold));
121
- const multiAsset = inputs.filter(
122
- (utxo) => utxo.output.amount.filter((asset) => asset.unit !== "lovelace").some((asset) => requiredAssets.has(asset.unit))
123
- );
124
- const selectedLovelace = selectedLovelaceQuantity(multiAsset);
125
- const lovelace = selectedLovelace.lessThan(requestedLovelace) ? remainingLovelace(
126
- requestedLovelace.clampedSub(selectedLovelace).toString(),
127
- inputs.filter((input) => {
128
- return !multiAsset.some(
129
- (selectedUtxo) => selectedUtxo.input.txHash === input.input.txHash && selectedUtxo.input.outputIndex === input.input.outputIndex
130
- );
131
- })
132
- ) : [];
133
- return [...lovelace, ...multiAsset];
134
- };
135
-
136
- // src/utxo-selection/largestFirst.ts
137
- var import_common5 = require("@meshsdk/common");
138
- var largestFirst = (lovelace, initialUTxOSet, includeTxFees = false, { maxTxSize, minFeeA, minFeeB } = import_common5.DEFAULT_PROTOCOL_PARAMETERS) => {
139
- const sortedUTxOs = initialUTxOSet.filter((utxo) => multiAssetUTxO(utxo) === false).sort(largestLovelaceQuantity);
140
- const maxTxFees2 = import_common5.BigNum.new((0, import_common5.resolveTxFees)(maxTxSize, minFeeA, minFeeB));
141
- const quantity = includeTxFees ? import_common5.BigNum.new(lovelace).checkedAdd(maxTxFees2).toString() : lovelace;
142
- const requestedOutputSet = /* @__PURE__ */ new Map([["lovelace", quantity]]);
143
- const selection = selectValue(sortedUTxOs, requestedOutputSet);
144
- return selection;
145
- };
146
-
147
- // src/utxo-selection/largestFirstMultiAsset.ts
148
- var import_common7 = require("@meshsdk/common");
149
- var largestFirstMultiAsset = (requestedOutputSet, initialUTxOSet, includeTxFees = false, parameters = import_common7.DEFAULT_PROTOCOL_PARAMETERS) => {
150
- const sortedMultiAssetUTxOs = initialUTxOSet.filter(multiAssetUTxO).sort(largestLovelaceQuantity);
151
- const txFees = maxTxFees(parameters);
152
- const lovelace = requestedOutputSet.get("lovelace") ?? "0";
153
- const quantity = includeTxFees ? import_common7.BigNum.new(lovelace).checkedAdd(txFees).toString() : lovelace;
154
- requestedOutputSet.set("lovelace", quantity);
155
- const selection = selectValue(sortedMultiAssetUTxOs, requestedOutputSet);
156
- return selection;
157
- };
158
-
159
- // src/utxo-selection/experimental.ts
160
- var experimentalSelectUtxos = (requiredAssets, inputs, threshold) => {
161
- const totalRequiredAssets = new Map(requiredAssets);
162
- totalRequiredAssets.set(
163
- "lovelace",
164
- String(Number(totalRequiredAssets.get("lovelace") || 0) + Number(threshold))
165
- );
166
- const utxoMap = /* @__PURE__ */ new Map();
167
- for (let i = 0; i < inputs.length; i++) {
168
- utxoMap.set(i, inputs[i]);
169
- }
170
- const selectedInputs = /* @__PURE__ */ new Set();
171
- const onlyLovelace = /* @__PURE__ */ new Set();
172
- const singletons = /* @__PURE__ */ new Set();
173
- const pairs = /* @__PURE__ */ new Set();
174
- const rest = /* @__PURE__ */ new Set();
175
- for (let i = 0; i < inputs.length; i++) {
176
- switch (inputs[i].output.amount.length) {
177
- case 1: {
178
- onlyLovelace.add(i);
179
- break;
180
- }
181
- case 2: {
182
- singletons.add(i);
183
- break;
184
- }
185
- case 3: {
186
- pairs.add(i);
187
- break;
188
- }
189
- default: {
190
- rest.add(i);
191
- break;
192
- }
193
- }
194
- }
195
- const addUtxoWithAssetAmount = (inputIndex, assetUnit, set) => {
196
- const utxo = utxoMap.get(inputIndex);
197
- if (!utxo) return;
198
- const amount = getAssetAmount(utxo, assetUnit);
199
- if (Number(amount) > 0) {
200
- selectedInputs.add(inputIndex);
201
- set.delete(inputIndex);
202
- for (const asset of utxo.output.amount) {
203
- totalRequiredAssets.set(
204
- asset.unit,
205
- String(
206
- Number(totalRequiredAssets.get(asset.unit)) - Number(asset.quantity)
207
- )
208
- );
209
- }
210
- }
211
- };
212
- for (const assetUnit of totalRequiredAssets.keys()) {
213
- if (assetUnit == "lovelace") continue;
214
- for (const inputIndex of singletons) {
215
- const assetRequired = totalRequiredAssets.get(assetUnit);
216
- if (!assetRequired || Number(assetRequired) <= 0) break;
217
- addUtxoWithAssetAmount(inputIndex, assetUnit, singletons);
218
- }
219
- for (const inputIndex of pairs) {
220
- const assetRequired = totalRequiredAssets.get(assetUnit);
221
- if (!assetRequired || Number(assetRequired) <= 0) break;
222
- addUtxoWithAssetAmount(inputIndex, assetUnit, pairs);
223
- }
224
- for (const inputIndex of rest) {
225
- const assetRequired = totalRequiredAssets.get(assetUnit);
226
- if (!assetRequired || Number(assetRequired) <= 0) break;
227
- addUtxoWithAssetAmount(inputIndex, assetUnit, rest);
228
- }
229
- }
230
- for (const inputIndex of onlyLovelace) {
231
- const assetRequired = totalRequiredAssets.get("lovelace");
232
- if (!assetRequired || Number(assetRequired) <= 0) break;
233
- addUtxoWithAssetAmount(inputIndex, "lovelace", onlyLovelace);
234
- }
235
- for (const inputIndex of singletons) {
236
- const assetRequired = totalRequiredAssets.get("lovelace");
237
- if (!assetRequired || Number(assetRequired) <= 0) break;
238
- addUtxoWithAssetAmount(inputIndex, "lovelace", singletons);
239
- }
240
- for (const inputIndex of pairs) {
241
- const assetRequired = totalRequiredAssets.get("lovelace");
242
- if (!assetRequired || Number(assetRequired) <= 0) break;
243
- addUtxoWithAssetAmount(inputIndex, "lovelace", pairs);
244
- }
245
- for (const inputIndex of rest) {
246
- const assetRequired = totalRequiredAssets.get("lovelace");
247
- if (!assetRequired || Number(assetRequired) <= 0) break;
248
- addUtxoWithAssetAmount(inputIndex, "lovelace", rest);
249
- }
250
- for (const assetUnit of totalRequiredAssets.keys()) {
251
- if (Number(totalRequiredAssets.get(assetUnit)) > 0) {
252
- console.log("Insufficient funds for", assetUnit);
253
- console.log(
254
- "Remaining quantity",
255
- Number(totalRequiredAssets.get(assetUnit))
256
- );
257
- return [];
258
- }
259
- }
260
- const selectedUtxos = [];
261
- for (const inputIndex of selectedInputs) {
262
- const utxo = utxoMap.get(inputIndex);
263
- if (utxo) {
264
- selectedUtxos.push(utxo);
265
- }
266
- }
267
- return selectedUtxos;
268
- };
269
- var getAssetAmount = (utxo, assetUnit) => {
270
- for (const utxoAsset of utxo.output.amount) {
271
- if (utxoAsset.unit == assetUnit) return utxoAsset.quantity;
272
- }
273
- return "0";
274
- };
275
-
276
- // src/utxo-selection/index.ts
277
- var UtxoSelection = class {
278
- constructor() {
279
- }
280
- largestFirst(requiredAssets, inputs, threshold = "5000000") {
281
- const lovelaceAmount = requiredAssets.get("lovelace") ?? "0";
282
- const requiredAssetWithThreshold = BigInt(lovelaceAmount) + BigInt(threshold);
283
- return largestFirst(requiredAssetWithThreshold.toString(), inputs, false);
284
- }
285
- keepRelevant(requiredAssets, inputs, threshold = "5000000") {
286
- return keepRelevant(requiredAssets, inputs, threshold);
287
- }
288
- largestFirstMultiAsset(requiredAssets, inputs, threshold) {
289
- const lovelaceAmount = requiredAssets.get("lovelace") ?? "0";
290
- requiredAssets.set(
291
- "lovelace",
292
- (BigInt(lovelaceAmount) + BigInt(threshold)).toString()
293
- );
294
- return largestFirstMultiAsset(requiredAssets, inputs, false);
295
- }
296
- experimental(requiredAssets, inputs, threshold) {
297
- return experimentalSelectUtxos(requiredAssets, inputs, threshold);
298
- }
299
- };
300
-
301
- // src/mesh-tx-builder/tx-builder-core.ts
302
- var MeshTxBuilderCore = class {
303
- constructor() {
304
- this.txEvaluationMultiplier = 1.1;
305
- this.addingPlutusScriptInput = false;
306
- this.addingPlutusMint = false;
307
- this.addingPlutusWithdrawal = false;
308
- this._protocolParams = import_common9.DEFAULT_PROTOCOL_PARAMETERS;
309
- /**
310
- * Set the input for transaction
311
- * @param txHash The transaction hash of the input UTxO
312
- * @param txIndex The transaction index of the input UTxO
313
- * @param amount The asset amount of index of the input UTxO
314
- * @param address The address of the input UTxO
315
- * @returns The MeshTxBuilder instance
316
- */
317
- this.txIn = (txHash, txIndex, amount, address) => {
318
- if (this.txInQueueItem) {
319
- this.queueInput();
320
- }
321
- if (!this.addingPlutusScriptInput) {
322
- this.txInQueueItem = {
323
- type: "PubKey",
324
- txIn: {
325
- txHash,
326
- txIndex,
327
- amount,
328
- address
329
- }
330
- };
331
- } else {
332
- this.txInQueueItem = {
333
- type: "Script",
334
- txIn: {
335
- txHash,
336
- txIndex,
337
- amount,
338
- address
339
- },
340
- scriptTxIn: {}
341
- };
342
- }
343
- this.addingPlutusScriptInput = false;
344
- return this;
345
- };
346
- /**
347
- * Set the script for transaction input
348
- * @param {string} scriptCbor The CborHex of the script
349
- * @param version Optional - The Plutus script version
350
- * @returns The MeshTxBuilder instance
351
- */
352
- this.txInScript = (scriptCbor) => {
353
- if (!this.txInQueueItem) throw Error("Undefined input");
354
- if (this.txInQueueItem.type === "PubKey") {
355
- this.txInQueueItem = {
356
- type: "SimpleScript",
357
- txIn: this.txInQueueItem.txIn,
358
- simpleScriptTxIn: {
359
- scriptSource: {
360
- type: "Provided",
361
- script: scriptCbor
362
- }
363
- }
364
- };
365
- }
366
- if (this.txInQueueItem.type === "Script") {
367
- this.txInQueueItem.scriptTxIn.scriptSource = {
368
- type: "Provided",
369
- script: {
370
- code: scriptCbor,
371
- version: this.plutusSpendingScriptVersion || "V2"
372
- }
373
- };
374
- }
375
- return this;
376
- };
377
- /**
378
- * Set the input datum for transaction input
379
- * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
380
- * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
381
- * @returns The MeshTxBuilder instance
382
- */
383
- this.txInDatumValue = (datum, type = "Mesh") => {
384
- if (!this.txInQueueItem) throw Error("Undefined input");
385
- if (this.txInQueueItem.type === "PubKey")
386
- throw Error("Datum value attempted to be called a non script input");
387
- if (this.txInQueueItem.type === "SimpleScript")
388
- throw Error(
389
- "Datum value attempted to be called on a simple script input"
390
- );
391
- let content = datum;
392
- if (type === "JSON") {
393
- content = this.castRawDataToJsonString(datum);
394
- }
395
- if (type === "Mesh") {
396
- this.txInQueueItem.scriptTxIn.datumSource = {
397
- type: "Provided",
398
- data: {
399
- type,
400
- content: datum
401
- }
402
- };
403
- return this;
404
- }
405
- this.txInQueueItem.scriptTxIn.datumSource = {
406
- type: "Provided",
407
- data: {
408
- type,
409
- content
410
- }
411
- };
412
- return this;
413
- };
414
- /**
415
- * Tell the transaction builder that the input UTxO has inlined datum
416
- * @returns The MeshTxBuilder instance
417
- */
418
- this.txInInlineDatumPresent = () => {
419
- if (!this.txInQueueItem) throw Error("Undefined input");
420
- if (this.txInQueueItem.type === "PubKey")
421
- throw Error(
422
- "Inline datum present attempted to be called a non script input"
423
- );
424
- if (this.txInQueueItem.type === "SimpleScript")
425
- throw Error(
426
- "Inline datum present attempted to be called on a simple script input"
427
- );
428
- const { txHash, txIndex } = this.txInQueueItem.txIn;
429
- if (txHash && txIndex.toString()) {
430
- this.txInQueueItem.scriptTxIn.datumSource = {
431
- type: "Inline",
432
- txHash,
433
- txIndex
434
- };
435
- }
436
- return this;
437
- };
438
- // /**
439
- // * Native script - Set the reference input where it would also be spent in the transaction
440
- // * @param txHash The transaction hash of the reference UTxO
441
- // * @param txIndex The transaction index of the reference UTxO
442
- // * @param spendingScriptHash The script hash of the spending script
443
- // * @returns The MeshTxBuilder instance
444
- // */
445
- // simpleScriptTxInReference = (
446
- // txHash: string,
447
- // txIndex: number,
448
- // spendingScriptHash?: string
449
- // ) => {
450
- // if (!this.txInQueueItem) throw Error('Undefined input');
451
- // if (this.txInQueueItem.type === 'PubKey')
452
- // throw Error(
453
- // 'Spending tx in reference attempted to be called a non script input'
454
- // );
455
- // this.txInQueueItem.scriptTxIn.scriptSource = {
456
- // type: 'Inline',
457
- // txInInfo: {
458
- // txHash,
459
- // txIndex,
460
- // spendingScriptHash,
461
- // },
462
- // };
463
- // return this;
464
- // };
465
- /**
466
- * Set the redeemer for the reference input to be spent in same transaction
467
- * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
468
- * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
469
- * @param exUnits The execution units budget for the redeemer
470
- * @returns The MeshTxBuilder instance
471
- */
472
- this.txInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
473
- if (!this.txInQueueItem) throw Error("Undefined input");
474
- if (this.txInQueueItem.type === "PubKey")
475
- throw Error(
476
- "Spending tx in reference redeemer attempted to be called a non script input"
477
- );
478
- if (this.txInQueueItem.type === "SimpleScript")
479
- throw Error(
480
- "Spending tx in reference redeemer attempted to be called on a simple script input"
481
- );
482
- this.txInQueueItem.scriptTxIn.redeemer = this.castBuilderDataToRedeemer(
483
- redeemer,
484
- type,
485
- exUnits
486
- );
487
- return this;
488
- };
489
- /**
490
- * Set the output for transaction
491
- * @param {string} address The recipient of the output
492
- * @param {Asset[]} amount The amount of other native assets attached with UTxO
493
- * @returns The MeshTxBuilder instance
494
- */
495
- this.txOut = (address, amount) => {
496
- if (this.txOutput) {
497
- this.meshTxBuilderBody.outputs.push(this.txOutput);
498
- this.txOutput = void 0;
499
- }
500
- this.txOutput = {
501
- address,
502
- amount
503
- };
504
- return this;
505
- };
506
- /**
507
- * Set the output datum hash for transaction
508
- * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
509
- * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
510
- * @returns The MeshTxBuilder instance
511
- */
512
- this.txOutDatumHashValue = (datum, type = "Mesh") => {
513
- let content = datum;
514
- if (this.txOutput) {
515
- if (type === "Mesh") {
516
- this.txOutput.datum = {
517
- type: "Hash",
518
- data: {
519
- type,
520
- content
521
- }
522
- };
523
- return this;
524
- }
525
- if (type === "JSON") {
526
- content = this.castRawDataToJsonString(datum);
527
- }
528
- this.txOutput.datum = {
529
- type: "Hash",
530
- data: {
531
- type,
532
- content
533
- }
534
- };
535
- }
536
- return this;
537
- };
538
- /**
539
- * Set the output inline datum for transaction
540
- * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
541
- * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
542
- * @returns The MeshTxBuilder instance
543
- */
544
- this.txOutInlineDatumValue = (datum, type = "Mesh") => {
545
- let content = datum;
546
- if (this.txOutput) {
547
- if (type === "Mesh") {
548
- this.txOutput.datum = {
549
- type: "Inline",
550
- data: {
551
- type,
552
- content
553
- }
554
- };
555
- return this;
556
- }
557
- if (type === "JSON") {
558
- content = this.castRawDataToJsonString(datum);
559
- }
560
- this.txOutput.datum = {
561
- type: "Inline",
562
- data: {
563
- type,
564
- content
565
- }
566
- };
567
- }
568
- return this;
569
- };
570
- /**
571
- * Set the reference script to be attached with the output
572
- * @param scriptCbor The CBOR hex of the script to be attached to UTxO as reference script
573
- * @param version Optional - The Plutus script version
574
- * @returns The MeshTxBuilder instance
575
- */
576
- this.txOutReferenceScript = (scriptCbor, version = "V2") => {
577
- if (this.txOutput) {
578
- this.txOutput.referenceScript = { code: scriptCbor, version };
579
- }
580
- return this;
581
- };
582
- /**
583
- * Set the instruction that it is currently using V1 Plutus spending scripts
584
- * @returns The MeshTxBuilder instance
585
- */
586
- this.spendingPlutusScriptV1 = () => {
587
- this.addingPlutusScriptInput = true;
588
- this.plutusSpendingScriptVersion = "V1";
589
- return this;
590
- };
591
- /**
592
- * Set the instruction that it is currently using V2 Plutus spending scripts
593
- * @returns The MeshTxBuilder instance
594
- */
595
- this.spendingPlutusScriptV2 = () => {
596
- this.addingPlutusScriptInput = true;
597
- this.plutusSpendingScriptVersion = "V2";
598
- return this;
599
- };
600
- /**
601
- * Set the instruction that it is currently using V3 Plutus spending scripts
602
- * @returns The MeshTxBuilder instance
603
- */
604
- this.spendingPlutusScriptV3 = () => {
605
- this.addingPlutusScriptInput = true;
606
- this.plutusSpendingScriptVersion = "V3";
607
- return this;
608
- };
609
- /**
610
- * Set the reference input where it would also be spent in the transaction
611
- * @param txHash The transaction hash of the reference UTxO
612
- * @param txIndex The transaction index of the reference UTxO
613
- * @param spendingScriptHash The script hash of the spending script
614
- * @returns The MeshTxBuilder instance
615
- */
616
- this.spendingTxInReference = (txHash, txIndex, spendingScriptHash) => {
617
- if (!this.txInQueueItem) throw Error("Undefined input");
618
- if (this.txInQueueItem.type === "PubKey")
619
- throw Error(
620
- "Spending tx in reference attempted to be called a non script input"
621
- );
622
- if (this.txInQueueItem.type === "SimpleScript")
623
- throw Error(
624
- "Spending tx in reference attempted to be called on a simple script input"
625
- );
626
- this.txInQueueItem.scriptTxIn.scriptSource = {
627
- type: "Inline",
628
- txHash,
629
- txIndex,
630
- scriptHash: spendingScriptHash,
631
- version: this.plutusSpendingScriptVersion || "V2",
632
- scriptSize: "0"
633
- // TODO
634
- };
635
- return this;
636
- };
637
- /**
638
- * [Alias of txInInlineDatumPresent] Set the instruction that the reference input has inline datum
639
- * @returns The MeshTxBuilder instance
640
- */
641
- // Unsure how this is different from the --tx-in-inline-datum-present flag
642
- // It seems to just be different based on if the script is a reference input
643
- this.spendingReferenceTxInInlineDatumPresent = () => {
644
- this.txInInlineDatumPresent();
645
- return this;
646
- };
647
- /**
648
- * [Alias of txInRedeemerValue] Set the redeemer for the reference input to be spent in same transaction
649
- * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
650
- * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
651
- * @param exUnits The execution units budget for the redeemer
652
- * @returns The MeshTxBuilder instance
653
- */
654
- this.spendingReferenceTxInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
655
- this.txInRedeemerValue(redeemer, type, exUnits);
656
- return this;
657
- };
658
- /**
659
- * Specify a read only reference input. This reference input is not witnessing anything it is simply provided in the plutus script context.
660
- * @param txHash The transaction hash of the reference UTxO
661
- * @param txIndex The transaction index of the reference UTxO
662
- * @returns The MeshTxBuilder instance
663
- */
664
- this.readOnlyTxInReference = (txHash, txIndex) => {
665
- this.meshTxBuilderBody.referenceInputs.push({ txHash, txIndex });
666
- return this;
667
- };
668
- /**
669
- * Set the instruction that it is currently using V1 Plutus minting scripts
670
- * @returns The MeshTxBuilder instance
671
- */
672
- this.mintPlutusScriptV1 = () => {
673
- this.addingPlutusMint = true;
674
- this.plutusMintingScriptVersion = "V1";
675
- return this;
676
- };
677
- /**
678
- * Set the instruction that it is currently using V2 Plutus minting scripts
679
- * @returns The MeshTxBuilder instance
680
- */
681
- this.mintPlutusScriptV2 = () => {
682
- this.addingPlutusMint = true;
683
- this.plutusMintingScriptVersion = "V2";
684
- return this;
685
- };
686
- /**
687
- * Set the instruction that it is currently using V3 Plutus minting scripts
688
- * @returns The MeshTxBuilder instance
689
- */
690
- this.mintPlutusScriptV3 = () => {
691
- this.addingPlutusMint = true;
692
- this.plutusMintingScriptVersion = "V3";
693
- return this;
694
- };
695
- /**
696
- * Set the minting value of transaction
697
- * @param quantity The quantity of asset to be minted
698
- * @param policy The policy id of the asset to be minted
699
- * @param name The hex of token name of the asset to be minted
700
- * @returns The MeshTxBuilder instance
701
- */
702
- this.mint = (quantity, policy, name) => {
703
- if (this.mintItem) {
704
- this.queueMint();
705
- }
706
- this.mintItem = {
707
- type: this.addingPlutusMint ? "Plutus" : "Native",
708
- policyId: policy,
709
- assetName: name,
710
- amount: quantity
711
- };
712
- this.addingPlutusMint = false;
713
- return this;
714
- };
715
- /**
716
- * Set the minting script of current mint
717
- * @param scriptCBOR The CBOR hex of the minting policy script
718
- * @param version Optional - The Plutus script version
719
- * @returns The MeshTxBuilder instance
720
- */
721
- this.mintingScript = (scriptCBOR) => {
722
- if (!this.mintItem) throw Error("Undefined mint");
723
- if (!this.mintItem.type) throw Error("Mint information missing");
724
- if (this.mintItem.type === "Native") {
725
- this.mintItem.scriptSource = {
726
- type: "Provided",
727
- scriptCode: scriptCBOR
728
- };
729
- }
730
- if (this.mintItem.type === "Plutus") {
731
- this.mintItem.scriptSource = {
732
- type: "Provided",
733
- script: {
734
- code: scriptCBOR,
735
- version: this.plutusMintingScriptVersion || "V2"
736
- }
737
- };
738
- }
739
- return this;
740
- };
741
- /**
742
- * Use reference script for minting
743
- * @param txHash The transaction hash of the UTxO
744
- * @param txIndex The transaction index of the UTxO
745
- * @returns The MeshTxBuilder instance
746
- */
747
- this.mintTxInReference = (txHash, txIndex) => {
748
- if (!this.mintItem) throw Error("Undefined mint");
749
- if (!this.mintItem.type) throw Error("Mint information missing");
750
- if (this.mintItem.type == "Native") {
751
- throw Error(
752
- "Mint tx in reference can only be used on plutus script tokens"
753
- );
754
- }
755
- if (!this.mintItem.policyId)
756
- throw Error("PolicyId information missing from mint asset");
757
- this.mintItem.scriptSource = {
758
- type: "Inline",
759
- txHash,
760
- txIndex,
761
- version: this.plutusMintingScriptVersion,
762
- scriptSize: "0",
763
- // TODO
764
- scriptHash: ""
765
- // TODO
766
- };
767
- return this;
768
- };
769
- /**
770
- * Set the redeemer for minting
771
- * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
772
- * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
773
- * @param exUnits The execution units budget for the redeemer
774
- * @returns The MeshTxBuilder instance
775
- */
776
- this.mintReferenceTxInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
777
- if (!this.mintItem) throw Error("Undefined mint");
778
- if (this.mintItem.type == "Native") {
779
- throw Error(
780
- "Mint tx in reference can only be used on plutus script tokens"
781
- );
782
- } else if (this.mintItem.type == "Plutus") {
783
- if (!this.mintItem.policyId)
784
- throw Error("PolicyId information missing from mint asset");
785
- }
786
- this.mintItem.redeemer = this.castBuilderDataToRedeemer(
787
- redeemer,
788
- type,
789
- exUnits
790
- );
791
- return this;
792
- };
793
- /**
794
- * Set the redeemer for the reference input to be spent in same transaction
795
- * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
796
- * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
797
- * @param exUnits The execution units budget for the redeemer
798
- * @returns The MeshTxBuilder instance
799
- */
800
- this.mintRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
801
- this.mintReferenceTxInRedeemerValue(redeemer, type, exUnits);
802
- return this;
803
- };
804
- /**
805
- * Set the required signer of the transaction
806
- * @param pubKeyHash The PubKeyHash of the required signer
807
- * @returns The MeshTxBuilder instance
808
- */
809
- this.requiredSignerHash = (pubKeyHash) => {
810
- this.meshTxBuilderBody.requiredSignatures.push(pubKeyHash);
811
- return this;
812
- };
813
- /**
814
- * Set the collateral UTxO for the transaction
815
- * @param txHash The transaction hash of the collateral UTxO
816
- * @param txIndex The transaction index of the collateral UTxO
817
- * @param amount The asset amount of index of the collateral UTxO
818
- * @param address The address of the collateral UTxO
819
- * @returns The MeshTxBuilder instance
820
- */
821
- this.txInCollateral = (txHash, txIndex, amount, address) => {
822
- if (this.collateralQueueItem) {
823
- this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem);
824
- }
825
- this.collateralQueueItem = {
826
- type: "PubKey",
827
- txIn: {
828
- txHash,
829
- txIndex,
830
- amount,
831
- address
832
- }
833
- };
834
- return this;
835
- };
836
- /**
837
- * Set the instruction that it is currently using V1 Plutus withdrawal scripts
838
- * @returns The MeshTxBuilder instance
839
- */
840
- this.withdrawalPlutusScriptV1 = () => {
841
- this.addingPlutusWithdrawal = true;
842
- this.plutusWithdrawalScriptVersion = "V1";
843
- return this;
844
- };
845
- /**
846
- * Set the instruction that it is currently using V2 Plutus withdrawal scripts
847
- * @returns The MeshTxBuilder instance
848
- */
849
- this.withdrawalPlutusScriptV2 = () => {
850
- this.addingPlutusWithdrawal = true;
851
- this.plutusWithdrawalScriptVersion = "V2";
852
- return this;
853
- };
854
- /**
855
- * Set the instruction that it is currently using V3 Plutus withdrawal scripts
856
- * @returns The MeshTxBuilder instance
857
- */
858
- this.withdrawalPlutusScriptV3 = () => {
859
- this.addingPlutusWithdrawal = true;
860
- this.plutusWithdrawalScriptVersion = "V3";
861
- return this;
862
- };
863
- /**
864
- * Withdraw stake rewards in the MeshTxBuilder instance
865
- * @param stakeAddress The address corresponding to the stake key
866
- * @param coin The amount of lovelaces in the withdrawal
867
- * @returns The MeshTxBuilder instance
868
- */
869
- this.withdrawal = (stakeAddress, coin) => {
870
- if (this.withdrawalItem) {
871
- this.queueWithdrawal();
872
- }
873
- if (this.addingPlutusWithdrawal) {
874
- const withdrawal2 = {
875
- plutusScriptWithdrawal: {
876
- address: stakeAddress,
877
- coin
878
- }
879
- };
880
- this.meshTxBuilderBody.withdrawals.push(withdrawal2);
881
- return this;
882
- }
883
- const withdrawal = {
884
- pubKeyWithdrawal: {
885
- address: stakeAddress,
886
- coin
887
- }
888
- };
889
- this.meshTxBuilderBody.withdrawals.push(withdrawal);
890
- return this;
891
- };
892
- /**
893
- * Add a withdrawal script to the MeshTxBuilder instance
894
- * @param scriptCbor The script in CBOR format
895
- * @param version The language version
896
- * @returns The MeshTxBuilder instance
897
- */
898
- this.withdrawalScript = (scriptCbor, version) => {
899
- if (!this.withdrawalItem)
900
- throw Error("withdrawalScript: Undefined withdrawal");
901
- if (!("plutusScriptWithdrawal" in this.withdrawalItem))
902
- throw Error("withdrawalScript: Adding script to non plutus withdrawal");
903
- this.withdrawalItem.plutusScriptWithdrawal.scriptSource = {
904
- type: "Provided",
905
- script: {
906
- code: scriptCbor,
907
- version: this.plutusWithdrawalScriptVersion || "V2"
908
- }
909
- };
910
- return this;
911
- };
912
- /**
913
- * Add a withdrawal reference to the MeshTxBuilder instance
914
- * @param txHash The transaction hash of reference UTxO
915
- * @param txIndex The transaction index of reference UTxO
916
- * @param withdrawalScriptHash The script hash of the withdrawal script
917
- * @param scriptSize The script size of the withdrawal script
918
- * @returns The MeshTxBuilder instance
919
- */
920
- this.withdrawalTxInReference = (txHash, txIndex, withdrawalScriptHash, scriptSize) => {
921
- if (!this.withdrawalItem)
922
- throw Error("withdrawalTxInReference: Undefined withdrawal");
923
- if (!("plutusScriptWithdrawal" in this.withdrawalItem))
924
- throw Error(
925
- "withdrawalTxInReference: Adding script reference to non plutus withdrawal"
926
- );
927
- this.withdrawalItem.plutusScriptWithdrawal.scriptSource = {
928
- type: "Inline",
929
- txHash,
930
- txIndex,
931
- scriptHash: withdrawalScriptHash,
932
- version: this.plutusWithdrawalScriptVersion || "V2",
933
- scriptSize: scriptSize || "0"
934
- };
935
- };
936
- /**
937
- * Set the transaction withdrawal redeemer value in the MeshTxBuilder instance
938
- * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
939
- * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
940
- * @param exUnits The execution units budget for the redeemer
941
- * @returns The MeshTxBuilder instance
942
- */
943
- this.withdrawalRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
944
- if (!this.withdrawalItem)
945
- throw Error("withdrawalRedeemerValue: Undefined withdrawal");
946
- if (!("plutusScriptWithdrawal" in this.withdrawalItem))
947
- throw Error(
948
- "withdrawalRedeemerValue: Adding redeemer to non plutus withdrawal"
949
- );
950
- this.withdrawalItem.plutusScriptWithdrawal.redeemer = this.castBuilderDataToRedeemer(redeemer, type, exUnits);
951
- return this;
952
- };
953
- /**
954
- * Creates a pool registration certificate, and adds it to the transaction
955
- * @param poolParams Parameters for pool registration
956
- * @returns The MeshTxBuilder instance
957
- */
958
- this.registerPoolCertificate = (poolParams) => {
959
- this.meshTxBuilderBody.certificates.push({
960
- type: "RegisterPool",
961
- poolParams
962
- });
963
- return this;
964
- };
965
- /**
966
- * Creates a stake registration certificate, and adds it to the transaction
967
- * @param stakeKeyHash The keyHash of the stake key
968
- * @returns The MeshTxBuilder instance
969
- */
970
- this.registerStakeCertificate = (stakeKeyHash) => {
971
- this.meshTxBuilderBody.certificates.push({
972
- type: "RegisterStake",
973
- stakeKeyHash
974
- });
975
- return this;
976
- };
977
- /**
978
- * Creates a stake delegation certificate, and adds it to the transaction
979
- * This will delegate stake from the corresponding stake address to the pool
980
- * @param stakeKeyHash The keyHash of the stake key
981
- * @param poolId poolId can be in either bech32 or hex form
982
- * @returns The MeshTxBuilder instance
983
- */
984
- this.delegateStakeCertificate = (stakeKeyHash, poolId) => {
985
- this.meshTxBuilderBody.certificates.push({
986
- type: "DelegateStake",
987
- stakeKeyHash,
988
- poolId
989
- });
990
- return this;
991
- };
992
- /**
993
- * Creates a stake deregister certificate, and adds it to the transaction
994
- * @param stakeKeyHash The keyHash of the stake key
995
- * @returns The MeshTxBuilder instance
996
- */
997
- this.deregisterStakeCertificate = (stakeKeyHash) => {
998
- this.meshTxBuilderBody.certificates.push({
999
- type: "DeregisterStake",
1000
- stakeKeyHash
1001
- });
1002
- return this;
1003
- };
1004
- /**
1005
- * Creates a pool retire certificate, and adds it to the transaction
1006
- * @param poolId poolId can be in either bech32 or hex form
1007
- * @param epoch The intended epoch to retire the pool
1008
- * @returns The MeshTxBuilder instance
1009
- */
1010
- this.retirePoolCertificate = (poolId, epoch) => {
1011
- this.meshTxBuilderBody.certificates.push({
1012
- type: "RetirePool",
1013
- poolId,
1014
- epoch
1015
- });
1016
- return this;
1017
- };
1018
- /**
1019
- * Configure the address to accept change UTxO
1020
- * @param addr The address to accept change UTxO
1021
- * @returns The MeshTxBuilder instance
1022
- */
1023
- this.changeAddress = (addr) => {
1024
- this.meshTxBuilderBody.changeAddress = addr;
1025
- return this;
1026
- };
1027
- /**
1028
- * Set the transaction valid interval to be valid only after the slot
1029
- * @param slot The transaction is valid only after this slot
1030
- * @returns The MeshTxBuilder instance
1031
- */
1032
- this.invalidBefore = (slot) => {
1033
- this.meshTxBuilderBody.validityRange.invalidBefore = slot;
1034
- return this;
1035
- };
1036
- /**
1037
- * Set the transaction valid interval to be valid only before the slot
1038
- * @param slot The transaction is valid only before this slot
1039
- * @returns The MeshTxBuilder instance
1040
- */
1041
- this.invalidHereafter = (slot) => {
1042
- this.meshTxBuilderBody.validityRange.invalidHereafter = slot;
1043
- return this;
1044
- };
1045
- /**
1046
- * Add metadata to the transaction
1047
- * @param tag The tag of the metadata
1048
- * @param metadata The metadata in any format
1049
- * @returns The MeshTxBuilder instance
1050
- */
1051
- this.metadataValue = (tag, metadata) => {
1052
- const metadataString = import_json_bigint.default.stringify(metadata);
1053
- this.meshTxBuilderBody.metadata.push({ tag, metadata: metadataString });
1054
- return this;
1055
- };
1056
- /**
1057
- * Sign the transaction with the private key
1058
- * @param skeyHex The private key in cborHex (with or without 5820 prefix, i.e. the format when generated from cardano-cli)
1059
- * @returns
1060
- */
1061
- this.signingKey = (skeyHex) => {
1062
- this.meshTxBuilderBody.signingKey.push(skeyHex);
1063
- return this;
1064
- };
1065
- /**
1066
- * EXPERIMENTAL - Selects utxos to fill output value and puts them into inputs
1067
- * @param extraInputs The inputs already placed into the object will remain, these extra inputs will be used to fill the remaining value needed
1068
- * @param threshold Extra value needed to be selected for, usually for paying fees and min UTxO value of change output
1069
- */
1070
- this.selectUtxosFrom = (extraInputs, threshold = 5e6) => {
1071
- this.meshTxBuilderBody.extraInputs = extraInputs;
1072
- this.meshTxBuilderBody.selectionThreshold = threshold;
1073
- return this;
1074
- };
1075
- /**
1076
- * Set the protocol parameters to be used for the transaction other than the default one
1077
- * @param params (Part of) the protocol parameters to be used for the transaction
1078
- * @returns The MeshTxBuilder instance
1079
- */
1080
- this.protocolParams = (params) => {
1081
- const updatedParams = { ...import_common9.DEFAULT_PROTOCOL_PARAMETERS, ...params };
1082
- this._protocolParams = updatedParams;
1083
- return this;
1084
- };
1085
- this.queueAllLastItem = () => {
1086
- if (this.txOutput) {
1087
- this.meshTxBuilderBody.outputs.push(this.txOutput);
1088
- this.txOutput = void 0;
1089
- }
1090
- if (this.txInQueueItem) {
1091
- this.queueInput();
1092
- }
1093
- if (this.collateralQueueItem) {
1094
- this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem);
1095
- this.collateralQueueItem = void 0;
1096
- }
1097
- if (this.mintItem) {
1098
- this.queueMint();
1099
- }
1100
- if (this.withdrawalItem) {
1101
- this.queueWithdrawal();
1102
- }
1103
- };
1104
- this.queueInput = () => {
1105
- if (!this.txInQueueItem) throw Error("queueInput: Undefined input");
1106
- if (this.txInQueueItem.type === "Script") {
1107
- if (!this.txInQueueItem.scriptTxIn) {
1108
- throw Error(
1109
- "queueInput: Script input does not contain script, datum, or redeemer information"
1110
- );
1111
- } else {
1112
- if (!this.txInQueueItem.scriptTxIn.datumSource)
1113
- throw Error(
1114
- "queueInput: Script input does not contain datum information"
1115
- );
1116
- if (!this.txInQueueItem.scriptTxIn.redeemer)
1117
- throw Error(
1118
- "queueInput: Script input does not contain redeemer information"
1119
- );
1120
- if (!this.txInQueueItem.scriptTxIn.scriptSource)
1121
- throw Error(
1122
- "queueInput: Script input does not contain script information"
1123
- );
1124
- }
1125
- }
1126
- this.meshTxBuilderBody.inputs.push(this.txInQueueItem);
1127
- this.txInQueueItem = void 0;
1128
- };
1129
- this.queueMint = () => {
1130
- if (!this.mintItem) throw Error("queueMint: Undefined mint");
1131
- if (!this.mintItem.scriptSource)
1132
- throw Error("queueMint: Missing mint script information");
1133
- this.meshTxBuilderBody.mints.push(this.mintItem);
1134
- this.mintItem = void 0;
1135
- };
1136
- this.queueWithdrawal = () => {
1137
- if (!this.withdrawalItem)
1138
- throw Error("queueWithdrawal: Undefined withdrawal");
1139
- if ("plutusScriptWithdrawal" in this.withdrawalItem) {
1140
- if (!this.withdrawalItem.plutusScriptWithdrawal.scriptSource) {
1141
- throw Error("queueWithdrawal: Missing withdrawal script information");
1142
- }
1143
- if (!this.withdrawalItem.plutusScriptWithdrawal.redeemer) {
1144
- throw Error("queueWithdrawal: Missing withdrawal redeemer information");
1145
- }
1146
- }
1147
- this.meshTxBuilderBody.withdrawals.push(this.withdrawalItem);
1148
- this.withdrawalItem = void 0;
1149
- };
1150
- this.castRawDataToJsonString = (rawData) => {
1151
- if (typeof rawData === "object") {
1152
- return import_json_bigint.default.stringify(rawData);
1153
- } else {
1154
- return rawData;
1155
- }
1156
- };
1157
- this.castBuilderDataToRedeemer = (redeemer, type = "Mesh", exUnits = { ...import_common9.DEFAULT_REDEEMER_BUDGET }) => {
1158
- let red;
1159
- let content = redeemer;
1160
- if (type === "Mesh") {
1161
- red = {
1162
- data: {
1163
- type,
1164
- content
1165
- },
1166
- exUnits
1167
- };
1168
- return red;
1169
- }
1170
- if (type === "JSON") {
1171
- content = this.castRawDataToJsonString(redeemer);
1172
- }
1173
- red = {
1174
- data: {
1175
- type,
1176
- content
1177
- },
1178
- exUnits
1179
- };
1180
- return red;
1181
- };
1182
- this.updateRedeemer = (meshTxBuilderBody, txEvaluation) => {
1183
- txEvaluation.forEach((redeemerEvaluation) => {
1184
- switch (redeemerEvaluation.tag) {
1185
- case "SPEND": {
1186
- const input = meshTxBuilderBody.inputs[redeemerEvaluation.index];
1187
- if (input.type == "Script" && input.scriptTxIn.redeemer) {
1188
- input.scriptTxIn.redeemer.exUnits.mem = Math.floor(
1189
- redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1190
- );
1191
- input.scriptTxIn.redeemer.exUnits.steps = Math.floor(
1192
- redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1193
- );
1194
- }
1195
- break;
1196
- }
1197
- case "MINT": {
1198
- const mint = meshTxBuilderBody.mints[redeemerEvaluation.index];
1199
- if (mint.type == "Plutus" && mint.redeemer) {
1200
- mint.redeemer.exUnits.mem = Math.floor(
1201
- redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1202
- );
1203
- mint.redeemer.exUnits.steps = Math.floor(
1204
- redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1205
- );
1206
- }
1207
- break;
1208
- }
1209
- case "CERT":
1210
- break;
1211
- case "REWARD":
1212
- break;
1213
- }
1214
- });
1215
- };
1216
- this.addUtxosFromSelection = () => {
1217
- const requiredAssets = this.meshTxBuilderBody.outputs.reduce(
1218
- (map, output) => {
1219
- const outputAmount = output.amount;
1220
- outputAmount.forEach((asset) => {
1221
- const { unit, quantity } = asset;
1222
- const existingQuantity = Number(map.get(unit)) || 0;
1223
- map.set(unit, String(existingQuantity + Number(quantity)));
1224
- });
1225
- return map;
1226
- },
1227
- /* @__PURE__ */ new Map()
1228
- );
1229
- this.meshTxBuilderBody.inputs.reduce((map, input) => {
1230
- const inputAmount = input.txIn.amount;
1231
- inputAmount?.forEach((asset) => {
1232
- const { unit, quantity } = asset;
1233
- const existingQuantity = Number(map.get(unit)) || 0;
1234
- map.set(unit, String(existingQuantity - Number(quantity)));
1235
- });
1236
- return map;
1237
- }, requiredAssets);
1238
- this.meshTxBuilderBody.mints.reduce((map, mint) => {
1239
- const mintAmount = {
1240
- unit: mint.policyId + mint.assetName,
1241
- quantity: String(mint.amount)
1242
- };
1243
- const existingQuantity = Number(map.get(mintAmount.unit)) || 0;
1244
- map.set(
1245
- mintAmount.unit,
1246
- String(existingQuantity - Number(mintAmount.quantity))
1247
- );
1248
- return map;
1249
- }, requiredAssets);
1250
- const selectedInputs = experimentalSelectUtxos(
1251
- requiredAssets,
1252
- this.meshTxBuilderBody.extraInputs,
1253
- this.meshTxBuilderBody.selectionThreshold.toString()
1254
- );
1255
- selectedInputs.forEach((input) => {
1256
- const pubKeyTxIn = {
1257
- type: "PubKey",
1258
- txIn: {
1259
- txHash: input.input.txHash,
1260
- txIndex: input.input.outputIndex,
1261
- amount: input.output.amount,
1262
- address: input.output.address
1263
- }
1264
- };
1265
- this.meshTxBuilderBody.inputs.push(pubKeyTxIn);
1266
- });
1267
- };
1268
- this.removeDuplicateInputs = () => {
1269
- const { inputs } = this.meshTxBuilderBody;
1270
- const getTxInId = (txIn) => `${txIn.txHash}#${txIn.txIndex}`;
1271
- const currentTxInIds = [];
1272
- const addedInputs = [];
1273
- for (let i = 0; i < inputs.length; i += 1) {
1274
- const currentInput = inputs[i];
1275
- const currentTxInId = getTxInId(currentInput.txIn);
1276
- if (currentTxInIds.includes(currentTxInId)) {
1277
- inputs.splice(i, 1);
1278
- i -= 1;
1279
- } else {
1280
- addedInputs.push(currentInput);
1281
- }
1282
- }
1283
- this.meshTxBuilderBody.inputs = addedInputs;
1284
- };
1285
- this.emptyTxBuilderBody = () => {
1286
- this.meshTxBuilderBody = (0, import_common9.emptyTxBuilderBody)();
1287
- return import_common9.emptyTxBuilderBody;
1288
- };
1289
- this.reset = () => {
1290
- this.meshTxBuilderBody = (0, import_common9.emptyTxBuilderBody)();
1291
- this.txEvaluationMultiplier = 1.1;
1292
- this.txOutput = void 0;
1293
- this.addingPlutusScriptInput = false;
1294
- this.plutusSpendingScriptVersion = void 0;
1295
- this.addingPlutusMint = false;
1296
- this.plutusMintingScriptVersion = void 0;
1297
- this.addingPlutusWithdrawal = false;
1298
- this.plutusWithdrawalScriptVersion = void 0;
1299
- this._protocolParams = import_common9.DEFAULT_PROTOCOL_PARAMETERS;
1300
- this.mintItem = void 0;
1301
- this.txInQueueItem = void 0;
1302
- this.withdrawalItem = void 0;
1303
- this.collateralQueueItem = void 0;
1304
- this.refScriptTxInQueueItem = void 0;
1305
- };
1306
- this.meshTxBuilderBody = (0, import_common9.emptyTxBuilderBody)();
1307
- }
1308
- };
1309
-
1310
- // src/mesh-tx-builder/index.ts
1311
- var import_core_csl = require("@meshsdk/core-csl");
1312
- var MeshTxBuilder = class extends MeshTxBuilderCore {
1313
- constructor({
1314
- serializer,
1315
- fetcher,
1316
- submitter,
1317
- evaluator,
1318
- params,
1319
- isHydra = false
1320
- } = {}) {
1321
- super();
1322
- this.txHex = "";
1323
- this.queriedTxHashes = /* @__PURE__ */ new Set();
1324
- this.queriedUTxOs = {};
1325
- /**
1326
- * It builds the transaction and query the blockchain for missing information
1327
- * @param customizedTx The optional customized transaction body
1328
- * @returns The signed transaction in hex ready to submit / signed by client
1329
- */
1330
- this.complete = async (customizedTx) => {
1331
- if (customizedTx) {
1332
- this.meshTxBuilderBody = customizedTx;
1333
- } else {
1334
- this.queueAllLastItem();
1335
- }
1336
- this.removeDuplicateInputs();
1337
- const { inputs, collaterals } = this.meshTxBuilderBody;
1338
- const incompleteTxIns = [...inputs, ...collaterals].filter(
1339
- (txIn) => !this.isInputComplete(txIn)
1340
- );
1341
- await this.queryAllTxInfo(incompleteTxIns);
1342
- incompleteTxIns.forEach((txIn) => {
1343
- this.completeTxInformation(txIn);
1344
- });
1345
- this.addUtxosFromSelection();
1346
- let txHex = this.serializer.serializeTxBody(
1347
- this.meshTxBuilderBody,
1348
- this._protocolParams
1349
- );
1350
- if (this.evaluator) {
1351
- const txEvaluation = await this.evaluator.evaluateTx(txHex).catch((error) => {
1352
- throw Error(`Tx evaluation failed: ${error}`);
1353
- });
1354
- this.updateRedeemer(this.meshTxBuilderBody, txEvaluation);
1355
- txHex = this.serializer.serializeTxBody(
1356
- this.meshTxBuilderBody,
1357
- this._protocolParams
1358
- );
1359
- }
1360
- console.log(txHex);
1361
- this.txHex = txHex;
1362
- return txHex;
1363
- };
1364
- /**
1365
- * It builds the transaction without dependencies
1366
- * @param customizedTx The optional customized transaction body
1367
- * @returns The signed transaction in hex ready to submit / signed by client
1368
- */
1369
- this.completeSync = (customizedTx) => {
1370
- if (customizedTx) {
1371
- this.meshTxBuilderBody = customizedTx;
1372
- } else {
1373
- this.queueAllLastItem();
1374
- }
1375
- return this.serializer.serializeTxBody(
1376
- this.meshTxBuilderBody,
1377
- this._protocolParams
1378
- );
1379
- };
1380
- /**
1381
- * Complete the signing process
1382
- * @returns The signed transaction in hex
1383
- */
1384
- this.completeSigning = () => {
1385
- const signedTxHex = this.serializer.addSigningKeys(
1386
- this.txHex,
1387
- this.meshTxBuilderBody.signingKey
1388
- );
1389
- this.txHex = signedTxHex;
1390
- return signedTxHex;
1391
- };
1392
- /**
1393
- * Submit transactions to the blockchain using the fetcher instance
1394
- * @param txHex The signed transaction in hex
1395
- * @returns
1396
- */
1397
- this.submitTx = async (txHex) => {
1398
- const txHash = await this.submitter?.submitTx(txHex);
1399
- return txHash;
1400
- };
1401
- /**
1402
- * Get the UTxO information from the blockchain
1403
- * @param TxHash The TxIn object that contains the txHash and txIndex, while missing amount and address information
1404
- */
1405
- this.getUTxOInfo = async (txHash) => {
1406
- let utxos = [];
1407
- if (!this.queriedTxHashes.has(txHash)) {
1408
- this.queriedTxHashes.add(txHash);
1409
- utxos = await this.fetcher?.fetchUTxOs(txHash) || [];
1410
- this.queriedUTxOs[txHash] = utxos;
1411
- }
1412
- };
1413
- this.queryAllTxInfo = (incompleteTxIns) => {
1414
- const queryUTxOPromises = [];
1415
- if (incompleteTxIns.length > 0 && !this.fetcher)
1416
- throw Error(
1417
- "Transaction information is incomplete while no fetcher instance is provided"
1418
- );
1419
- for (let i = 0; i < incompleteTxIns.length; i++) {
1420
- const currentTxIn = incompleteTxIns[i];
1421
- if (!this.isInputInfoComplete(currentTxIn)) {
1422
- queryUTxOPromises.push(this.getUTxOInfo(currentTxIn.txIn.txHash));
1423
- }
1424
- if (currentTxIn.type === "Script" && currentTxIn.scriptTxIn.scriptSource?.type === "Inline" && !this.isRefScriptInfoComplete(currentTxIn)) {
1425
- queryUTxOPromises.push(
1426
- this.getUTxOInfo(currentTxIn.scriptTxIn.scriptSource.txHash)
1427
- );
1428
- }
1429
- }
1430
- return Promise.all(queryUTxOPromises);
1431
- };
1432
- this.completeTxInformation = (input) => {
1433
- if (!this.isInputInfoComplete(input)) {
1434
- const utxos = this.queriedUTxOs[input.txIn.txHash];
1435
- const utxo = utxos?.find(
1436
- (utxo2) => utxo2.input.outputIndex === input.txIn.txIndex
1437
- );
1438
- const amount = utxo?.output.amount;
1439
- const address = utxo?.output.address;
1440
- if (!amount || amount.length === 0)
1441
- throw Error(
1442
- `Couldn't find value information for ${input.txIn.txHash}#${input.txIn.txIndex}`
1443
- );
1444
- input.txIn.amount = amount;
1445
- if (input.type === "PubKey") {
1446
- if (!address || address === "")
1447
- throw Error(
1448
- `Couldn't find address information for ${input.txIn.txHash}#${input.txIn.txIndex}`
1449
- );
1450
- input.txIn.address = address;
1451
- }
1452
- }
1453
- if (input.type === "Script" && input.scriptTxIn.scriptSource?.type == "Inline" && !this.isRefScriptInfoComplete(input)) {
1454
- const scriptSource = input.scriptTxIn.scriptSource;
1455
- const refUtxos = this.queriedUTxOs[scriptSource.txHash];
1456
- const scriptRefUtxo = refUtxos.find(
1457
- (utxo) => utxo.input.outputIndex === scriptSource.txIndex
1458
- );
1459
- if (!scriptRefUtxo)
1460
- throw Error(
1461
- `Couldn't find script reference utxo for ${scriptSource.txHash}#${scriptSource.txIndex}`
1462
- );
1463
- scriptSource.scriptHash = scriptRefUtxo?.output.scriptHash;
1464
- }
1465
- };
1466
- this.isInputComplete = (txIn) => {
1467
- if (txIn.type === "PubKey") return this.isInputInfoComplete(txIn);
1468
- if (txIn.type === "Script") {
1469
- return this.isInputInfoComplete(txIn) && this.isRefScriptInfoComplete(txIn);
1470
- }
1471
- return true;
1472
- };
1473
- this.isInputInfoComplete = (txIn) => {
1474
- const { amount, address } = txIn.txIn;
1475
- if (txIn.type === "PubKey" && (!amount || !address)) return false;
1476
- if (txIn.type === "Script") {
1477
- if (!amount) return false;
1478
- }
1479
- return true;
1480
- };
1481
- this.isRefScriptInfoComplete = (scriptTxIn) => {
1482
- const { scriptSource } = scriptTxIn.scriptTxIn;
1483
- if (scriptSource?.type === "Inline" && !scriptSource?.scriptHash)
1484
- return false;
1485
- return true;
1486
- };
1487
- if (serializer) {
1488
- this.serializer = serializer;
1489
- } else {
1490
- this.serializer = new import_core_csl.CSLSerializer();
1491
- }
1492
- if (fetcher) this.fetcher = fetcher;
1493
- if (submitter) this.submitter = submitter;
1494
- if (evaluator) this.evaluator = evaluator;
1495
- if (params) this.protocolParams(params);
1496
- if (isHydra)
1497
- this.protocolParams({
1498
- minFeeA: 0,
1499
- minFeeB: 0,
1500
- priceMem: 0,
1501
- priceStep: 0,
1502
- collateralPercent: 0,
1503
- coinsPerUtxoSize: 0
1504
- });
1505
- }
1506
- };
1507
-
1508
- // src/scripts/forge.script.ts
1509
- var import_core_cst = require("@meshsdk/core-cst");
1510
- var ForgeScript = class {
1511
- static withOneSignature(address) {
1512
- const keyHash = (0, import_core_cst.deserializeEd25519KeyHash)((0, import_core_cst.resolvePaymentKeyHash)(address));
1513
- return (0, import_core_cst.buildScriptPubkey)(keyHash).toCbor();
1514
- }
1515
- // static withAtLeastNSignatures(
1516
- // addresses: string[], minimumRequired: number,
1517
- // ): string {
1518
- // const nativeScripts = csl.NativeScripts.new();
1519
- // addresses.forEach((address) => {
1520
- // const keyHash = deserializeEd25519KeyHash(
1521
- // resolvePaymentKeyHash(address),
1522
- // );
1523
- // nativeScripts.add(buildScriptPubkey(keyHash));
1524
- // });
1525
- // const scriptNOfK = csl.ScriptNOfK.new(minimumRequired, nativeScripts);
1526
- // return csl.NativeScript.new_script_any(scriptNOfK).to_hex();
1527
- // }
1528
- // static withAnySignature(addresses: string[]): string {
1529
- // const nativeScripts = csl.NativeScripts.new();
1530
- // addresses.forEach((address) => {
1531
- // const keyHash = deserializeEd25519KeyHash(
1532
- // resolvePaymentKeyHash(address),
1533
- // );
1534
- // nativeScripts.add(buildScriptPubkey(keyHash));
1535
- // });
1536
- // const scriptAny = csl.ScriptAny.new(nativeScripts);
1537
- // return csl.NativeScript.new_script_any(scriptAny).to_hex();
1538
- // }
1539
- // static withAllSignatures(addresses: string[]): string {
1540
- // const nativeScripts = csl.NativeScripts.new();
1541
- // addresses.forEach((address) => {
1542
- // const keyHash = deserializeEd25519KeyHash(
1543
- // resolvePaymentKeyHash(address),
1544
- // );
1545
- // nativeScripts.add(buildScriptPubkey(keyHash));
1546
- // });
1547
- // const scriptAll = csl.ScriptAll.new(nativeScripts);
1548
- // return csl.NativeScript.new_script_any(scriptAll).to_hex();
1549
- // }
1550
- static fromNativeScript(script) {
1551
- return (0, import_core_cst.toNativeScript)(script).toCbor();
1552
- }
1553
- };
1554
-
1555
- // src/transaction/index.ts
1556
- var import_common10 = require("@meshsdk/common");
1557
- var import_core_cst2 = require("@meshsdk/core-cst");
1558
- var Transaction = class {
1559
- constructor(options) {
1560
- this.isCollateralNeeded = false;
1561
- this.txBuilder = new MeshTxBuilder(options);
1562
- this.initiator = options.initiator;
1563
- }
1564
- /**
1565
- * Adds an output to the transaction.
1566
- *
1567
- * @param recipient The recipient of the output.
1568
- * @param assets The assets to send. Provide string for lovelace and Asset[] for tokens and/or lovelace.
1569
- * @returns The transaction builder.
1570
- * @see {@link https://meshjs.dev/apis/transaction#sendAssets}
1571
- */
1572
- sendAssets(recipient, assets) {
1573
- if (typeof assets === "string") {
1574
- assets = [
1575
- {
1576
- unit: "lovelace",
1577
- quantity: assets
1578
- }
1579
- ];
1580
- }
1581
- if (typeof recipient === "string") {
1582
- this.txBuilder.txOut(recipient, assets);
1583
- }
1584
- if (typeof recipient === "object") {
1585
- this.txBuilder.txOut(recipient.address, assets);
1586
- if (recipient.datum) {
1587
- if (recipient.datum.inline) {
1588
- this.txBuilder.txOutInlineDatumValue(recipient.datum.value);
1589
- } else {
1590
- this.txBuilder.txOutDatumHashValue(recipient.datum.value);
1591
- }
1592
- }
1593
- }
1594
- return this;
1595
- }
1596
- /**
1597
- * Suggest deprecated - Adds a transaction output to the transaction.
1598
- * Use sendAssets instead:
1599
- * ```ts
1600
- * this.sendAssets(recipient, lovelace);
1601
- * ```
1602
- *
1603
- * Deprecation reason - Unnecessary implementation which might cause confusion.
1604
- *
1605
- * @param {Recipient} recipient The recipient of the transaction.
1606
- * @param {string} lovelace The amount of lovelace to send.
1607
- * @returns {Transaction} The Transaction object.
1608
- * @see {@link https://meshjs.dev/apis/transaction#sendAda}
1609
- */
1610
- sendLovelace(recipient, lovelace) {
1611
- return this.sendAssets(recipient, lovelace);
1612
- }
1613
- /**
1614
- * Suggest deprecated - Adds stable coins transaction output to the transaction.
1615
- * Please use sendAssets with helper function to obtain token unit instead:
1616
- * ```ts
1617
- * const assets = [{ unit: SUPPORTED_TOKENS.GIMBAL, quantity: "100" }]
1618
- * transaction.sendAssets(recipient, assets)
1619
- * ```
1620
- *
1621
- * Deprecation reason - Required maintenance on tokens.
1622
- *
1623
- * @param {Recipient} recipient The recipient of the transaction.
1624
- * @param {Token} ticker The ticker of the token to send.
1625
- * @param {string} amount The amount of the token to send.
1626
- * @returns {Transaction} The Transaction object.
1627
- * @see {@link https://meshjs.dev/apis/transaction#sendToken}
1628
- */
1629
- sendToken(recipient, ticker, amount) {
1630
- const assets = [{ unit: import_common10.SUPPORTED_TOKENS[ticker], quantity: amount }];
1631
- return this.sendAssets(recipient, assets);
1632
- }
1633
- /**
1634
- * Adds an output to the transaction.
1635
- * Suggest deprecated - use sendAssets instead:
1636
- *
1637
- * ```ts
1638
- * const assets = value.output.amount;
1639
- * this.sendAssets(recipient, assets);
1640
- * ```
1641
- * Deprecation reason - Unnecessary implementation which might cause confusion.
1642
- *
1643
- * @param {Recipient} recipient The recipient of the output.
1644
- * @param {UTxO} value The UTxO value of the output.
1645
- * @returns {Transaction} The Transaction object.
1646
- */
1647
- sendValue(recipient, value) {
1648
- const assets = value.output.amount;
1649
- return this.sendAssets(recipient, assets);
1650
- }
1651
- /**
1652
- * Sets the inputs for the transaction.
1653
- *
1654
- * @param {UTxO[]} inputs The inputs to set.
1655
- * @returns {Transaction} The transaction.
1656
- */
1657
- setTxInputs(inputs) {
1658
- inputs.forEach((input) => {
1659
- this.txBuilder.txIn(
1660
- input.input.txHash,
1661
- input.input.outputIndex,
1662
- input.output.amount,
1663
- input.output.address
1664
- );
1665
- });
1666
- return this;
1667
- }
1668
- /**
1669
- * Sets the reference inputs for the transaction.
1670
- *
1671
- * @param {UTxO[]} inputs The reference inputs to set.
1672
- * @returns {Transaction} The transaction.
1673
- */
1674
- setTxRefInputs(inputs) {
1675
- inputs.forEach((input) => {
1676
- this.txBuilder.readOnlyTxInReference(
1677
- input.input.txHash,
1678
- input.input.outputIndex
1679
- );
1680
- });
1681
- return this;
1682
- }
1683
- /**
1684
- * Sets the native script for the transaction.
1685
- * @param {NativeScript} script The native script to spend from.
1686
- * @param {UTxO} utxo The UTxO attached to the script.
1687
- * @returns {Transaction} The Transaction object.
1688
- */
1689
- setNativeScriptInput(script, utxo) {
1690
- const { scriptCbor } = this.txBuilder.serializer.deserializer.script.deserializeNativeScript(
1691
- script
1692
- );
1693
- this.txBuilder.txIn(
1694
- utxo.input.txHash,
1695
- utxo.input.outputIndex,
1696
- utxo.output.amount,
1697
- utxo.output.address
1698
- ).txInScript(scriptCbor);
1699
- return this;
1700
- }
1701
- // TODO: nuke this probably as the input type is too confusing
1702
- redeemValue(options) {
1703
- const { value, script, datum, redeemer } = options;
1704
- const red = redeemer || {
1705
- data: { alternative: 0, fields: ["mesh"] },
1706
- budget: import_common10.DEFAULT_REDEEMER_BUDGET
1707
- };
1708
- if ("code" in script) {
1709
- this.isCollateralNeeded = true;
1710
- this.spendingPlutusScript(script).txIn(
1711
- value.input.txHash,
1712
- value.input.outputIndex,
1713
- value.output.amount,
1714
- value.output.address
1715
- ).txInScript(script.code).txInRedeemerValue(red.data, "Mesh", red.budget);
1716
- }
1717
- if ("output" in script) {
1718
- if (!script.output.scriptRef) {
1719
- throw new Error("redeemValue: No script reference found in UTxO");
1720
- }
1721
- const scriptRef = (0, import_core_cst2.fromScriptRef)(script.output.scriptRef);
1722
- if (!scriptRef || !("code" in scriptRef)) {
1723
- throw new Error("redeemValue: Script reference not found");
1724
- }
1725
- this.isCollateralNeeded = true;
1726
- this.spendingPlutusScript(scriptRef).txIn(
1727
- value.input.txHash,
1728
- value.input.outputIndex,
1729
- value.output.amount,
1730
- value.output.address
1731
- ).spendingTxInReference(
1732
- script.input.txHash,
1733
- script.input.outputIndex,
1734
- script.output.scriptHash
1735
- ).txInRedeemerValue(red.data, "Mesh", red.budget);
1736
- }
1737
- if (datum) {
1738
- this.txBuilder.txInDatumValue(datum);
1739
- } else {
1740
- this.txBuilder.txInInlineDatumPresent();
1741
- }
1742
- return this;
1743
- }
1744
- // TODO: nuke this probably as the input type is too confusing
1745
- mintAsset(forgeScript, mint, redeemer) {
1746
- const assetQuantity = mint.assetQuantity;
1747
- let assetNameHex = (0, import_common10.stringToHex)(mint.assetName);
1748
- const referenceAssetNameHex = (0, import_common10.CIP68_100)(assetNameHex);
1749
- if (mint.cip68ScriptAddress) {
1750
- assetNameHex = (0, import_common10.CIP68_222)(assetNameHex);
1751
- }
1752
- let policyId = "";
1753
- switch (typeof forgeScript) {
1754
- case "string":
1755
- policyId = (0, import_core_cst2.deserializeNativeScript)(forgeScript).hash().toString();
1756
- this.txBuilder.mint(assetQuantity, policyId, assetNameHex).mintingScript(forgeScript);
1757
- if (mint.cip68ScriptAddress) {
1758
- this.txBuilder.mint(assetQuantity, policyId, referenceAssetNameHex).mintingScript(forgeScript);
1759
- }
1760
- break;
1761
- case "object":
1762
- if (!redeemer)
1763
- throw new Error(
1764
- "burnAsset: Redeemer data is required for Plutus minting"
1765
- );
1766
- if ("code" in forgeScript) {
1767
- policyId = (0, import_core_cst2.deserializePlutusScript)(
1768
- forgeScript.code,
1769
- forgeScript.version
1770
- ).hash().toString();
1771
- this.isCollateralNeeded = true;
1772
- this.mintPlutusScript(forgeScript).mint(assetQuantity, policyId, assetNameHex).mintingScript(forgeScript.code).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1773
- if (mint.cip68ScriptAddress) {
1774
- this.mintPlutusScript(forgeScript).mint(assetQuantity, policyId, referenceAssetNameHex).mintingScript(forgeScript.code).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1775
- }
1776
- break;
1777
- }
1778
- if ("output" in forgeScript) {
1779
- if (!forgeScript.output.scriptRef) {
1780
- throw new Error("mintAsset: No script reference found in UTxO");
1781
- }
1782
- const script = (0, import_core_cst2.fromScriptRef)(forgeScript.output.scriptRef);
1783
- if (!script) {
1784
- throw new Error("mintAsset: Script reference not found");
1785
- }
1786
- if ("code" in script) {
1787
- policyId = (0, import_core_cst2.deserializePlutusScript)(script.code, script.version).hash().toString();
1788
- this.isCollateralNeeded = true;
1789
- this.mintPlutusScript(script).mint(assetQuantity, policyId, assetNameHex).mintTxInReference(
1790
- forgeScript.input.txHash,
1791
- forgeScript.input.outputIndex
1792
- ).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1793
- if (mint.cip68ScriptAddress) {
1794
- this.mintPlutusScript(script).mint(assetQuantity, policyId, referenceAssetNameHex).mintTxInReference(
1795
- forgeScript.input.txHash,
1796
- forgeScript.input.outputIndex
1797
- ).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1798
- break;
1799
- }
1800
- break;
1801
- } else {
1802
- throw new Error(
1803
- "mintAsset: Reference script minting not implemented"
1804
- );
1805
- }
1806
- }
1807
- break;
1808
- }
1809
- if (mint.metadata && mint.label) {
1810
- this.setMetadata(Number(mint.label), {
1811
- [policyId]: {
1812
- [mint.assetName]: mint.metadata
1813
- },
1814
- version: 1
1815
- });
1816
- }
1817
- if (mint.recipient) {
1818
- this.sendAssets(mint.recipient, [
1819
- { unit: policyId + assetNameHex, quantity: mint.assetQuantity }
1820
- ]);
1821
- }
1822
- if (mint.cip68ScriptAddress) {
1823
- this.sendAssets(
1824
- {
1825
- address: mint.cip68ScriptAddress,
1826
- datum: { inline: true, value: (0, import_common10.metadataToCip68)(mint.metadata) }
1827
- },
1828
- [
1829
- {
1830
- unit: policyId + referenceAssetNameHex,
1831
- quantity: mint.assetQuantity
1832
- }
1833
- ]
1834
- );
1835
- }
1836
- return this;
1837
- }
1838
- // TODO: nuke this probably as the input type is too confusing
1839
- // TO be deprecated as it doesnt support reference script minting native assets
1840
- burnAsset(forgeScript, asset, redeemer) {
1841
- const assetQuantity = "-" + asset.quantity;
1842
- const mint = {
1843
- assetName: (0, import_common10.hexToString)(asset.unit.slice(import_common10.POLICY_ID_LENGTH)),
1844
- assetQuantity
1845
- };
1846
- try {
1847
- this.mintAsset(forgeScript, mint, redeemer);
1848
- } catch (error) {
1849
- throw new Error("burnAsset: " + error);
1850
- }
1851
- return this;
1852
- }
1853
- /**
1854
- * Sets the change address for the transaction.
1855
- *
1856
- * @param {string} changeAddress The change address.
1857
- * @returns {Transaction} The Transaction object.
1858
- */
1859
- setChangeAddress(changeAddress) {
1860
- this.txBuilder.changeAddress(changeAddress);
1861
- return this;
1862
- }
1863
- /**
1864
- * Sets the collateral for the transaction.
1865
- *
1866
- * @param {UTxO[]} collateral - Set the UTxO for collateral.
1867
- * @returns {Transaction} The Transaction object.
1868
- */
1869
- setCollateral(collateral) {
1870
- collateral.forEach((collateralUtxo) => {
1871
- this.txBuilder.txInCollateral(
1872
- collateralUtxo.input.txHash,
1873
- collateralUtxo.input.outputIndex,
1874
- collateralUtxo.output.amount,
1875
- collateralUtxo.output.address
1876
- );
1877
- });
1878
- return this;
1879
- }
1880
- /**
1881
- * Sets the required signers for the transaction.
1882
- *
1883
- * @param {string[]} addresses The addresses of the required signers.
1884
- * @returns {Transaction} The Transaction object.
1885
- */
1886
- setRequiredSigners(addresses) {
1887
- addresses.forEach((address) => {
1888
- const { pubKeyHash } = this.txBuilder.serializer.deserializer.key.deserializeAddress(address);
1889
- this.txBuilder.requiredSignerHash(pubKeyHash);
1890
- });
1891
- return this;
1892
- }
1893
- /**
1894
- * Set the time to live for the transaction.
1895
- *
1896
- * @param {string} slot The slot number to expire the transaction at.
1897
- * @returns {Transaction} The Transaction object.
1898
- * @see {@link https://meshjs.dev/apis/transaction#setTimeLimit}
1899
- */
1900
- setTimeToExpire(slot) {
1901
- this.txBuilder.invalidHereafter(Number(slot));
1902
- return this;
1903
- }
1904
- /**
1905
- * Sets the start slot for the transaction.
1906
- *
1907
- * @param {string} slot The start slot for the transaction.
1908
- * @returns {Transaction} The Transaction object.
1909
- * @see {@link https://meshjs.dev/apis/transaction#setTimeLimit}
1910
- */
1911
- setTimeToStart(slot) {
1912
- this.txBuilder.invalidBefore(Number(slot));
1913
- return this;
1914
- }
1915
- /**
1916
- * Add a JSON metadata entry to the transaction.
1917
- *
1918
- * @param {number} key The key to use for the metadata entry.
1919
- * @param {unknown} value The value to use for the metadata entry.
1920
- * @returns {Transaction} The Transaction object.
1921
- * @see {@link https://meshjs.dev/apis/transaction#setMetadata}
1922
- */
1923
- setMetadata(key, value) {
1924
- this.txBuilder.metadataValue(key.toString(), value);
1925
- return this;
1926
- }
1927
- withdrawRewards(rewardAddress, lovelace) {
1928
- this.txBuilder.withdrawal(rewardAddress, lovelace);
1929
- return this;
1930
- }
1931
- delegateStake(rewardAddress, poolId) {
1932
- this.txBuilder.delegateStakeCertificate(
1933
- this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(
1934
- rewardAddress
1935
- ),
1936
- this.txBuilder.serializer.resolver.keys.resolveEd25519KeyHash(poolId)
1937
- );
1938
- return this;
1939
- }
1940
- deregisterStake(rewardAddress) {
1941
- this.txBuilder.deregisterStakeCertificate(
1942
- this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(rewardAddress)
1943
- );
1944
- return this;
1945
- }
1946
- registerStake(rewardAddress) {
1947
- this.txBuilder.registerStakeCertificate(
1948
- this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(rewardAddress)
1949
- );
1950
- return this;
1951
- }
1952
- // TODO: test
1953
- registerPool(params) {
1954
- this.txBuilder.registerPoolCertificate(params);
1955
- return this;
1956
- }
1957
- // TODO: test
1958
- retirePool(poolId, epochNo) {
1959
- this.txBuilder.retirePoolCertificate(poolId, epochNo);
1960
- return this;
1961
- }
1962
- async build() {
1963
- try {
1964
- await this.addCollateralIfNeeded();
1965
- await this.addTxInputsAsNeeded();
1966
- await this.addChangeAddress();
1967
- return this.txBuilder.complete();
1968
- } catch (error) {
1969
- throw new Error(
1970
- `[Transaction] An error occurred during build: ${error}.`
1971
- );
1972
- }
1973
- }
1974
- mintPlutusScript(script) {
1975
- switch (script.version) {
1976
- case "V1":
1977
- this.txBuilder.mintPlutusScriptV1();
1978
- break;
1979
- case "V2":
1980
- this.txBuilder.mintPlutusScriptV2();
1981
- break;
1982
- case "V3":
1983
- this.txBuilder.mintPlutusScriptV3();
1984
- break;
1985
- }
1986
- return this.txBuilder;
1987
- }
1988
- spendingPlutusScript(script) {
1989
- switch (script.version) {
1990
- case "V1":
1991
- this.txBuilder.spendingPlutusScriptV1();
1992
- break;
1993
- case "V2":
1994
- this.txBuilder.spendingPlutusScriptV2();
1995
- break;
1996
- case "V3":
1997
- this.txBuilder.spendingPlutusScriptV3();
1998
- break;
1999
- }
2000
- return this.txBuilder;
2001
- }
2002
- async addCollateralIfNeeded() {
2003
- if (this.isCollateralNeeded) {
2004
- const collaterals = await this.initiator.getCollateral();
2005
- this.setCollateral(collaterals);
2006
- }
2007
- }
2008
- async addTxInputsAsNeeded() {
2009
- const utxos = await this.initiator.getUtxos();
2010
- this.txBuilder.selectUtxosFrom(utxos);
2011
- }
2012
- async addChangeAddress() {
2013
- if (this.txBuilder.meshTxBuilderBody.changeAddress === "") {
2014
- const changeAddress = await this.initiator.getChangeAddress();
2015
- this.setChangeAddress(changeAddress);
2016
- }
2017
- }
2018
- };
2019
- // Annotate the CommonJS export names for ESM import in node:
2020
- 0 && (module.exports = {
2021
- ForgeScript,
2022
- MeshTxBuilder,
2023
- Transaction,
2024
- UtxoSelection,
2025
- experimentalSelectUtxos,
2026
- keepRelevant,
2027
- largestFirst,
2028
- largestFirstMultiAsset
2029
- });
1
+ "use strict";var _=Object.create;var v=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Y=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},H=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $(e))!G.call(n,r)&&r!==t&&v(n,r,{get:()=>e[r],enumerable:!(i=J(e,r))||i.enumerable});return n};var X=(n,e,t)=>(t=n!=null?_(j(n)):{},H(e||!n||!n.__esModule?v(t,"default",{value:n,enumerable:!0}):t,n)),Z=n=>H(v({},"__esModule",{value:!0}),n);var rt={};Y(rt,{ForgeScript:()=>N,MeshTxBuilder:()=>B,Transaction:()=>D,UtxoSelection:()=>k,experimentalSelectUtxos:()=>S,keepRelevant:()=>E,largestFirst:()=>V,largestFirstMultiAsset:()=>Q});module.exports=Z(rt);var h=require("@meshsdk/common"),q=X(require("json-bigint"));var A=require("@meshsdk/common");var x=require("@meshsdk/common"),C=require("@meshsdk/common"),tt=(n,e)=>Array.from(e,t=>({unit:t[0],quantity:x.BigNum.new(t[1])})).every(t=>n.filter(i=>i.output.amount.find(r=>r.unit===t.unit)!==void 0).reduce((i,r)=>{let s=r.output.amount.reduce((a,u)=>a.checkedAdd(x.BigNum.new(t.unit===u.unit?u.quantity:"0")),x.BigNum.new("0"));return i.checkedAdd(s)},x.BigNum.new("0")).lessThan(t.quantity)===!1),w=(n,e)=>{let t=x.BigNum.new(n.output.amount.find(r=>r.unit==="lovelace")?.quantity??"0");return x.BigNum.new(e.output.amount.find(r=>r.unit==="lovelace")?.quantity??"0").compare(t)},W=n=>{let{maxTxSize:e,minFeeA:t,minFeeB:i}=n;return x.BigNum.new((0,C.resolveTxFees)(e,t,i))},P=n=>n.output.amount.length>1,L=n=>n.reduce((e,t)=>{let i=t.output.amount.find(r=>r.unit==="lovelace")?.quantity??"0";return e.checkedAdd(x.BigNum.new(i))},x.BigNum.new("0")),z=(n,e)=>{let t=e.sort(w);return T(t,new Map([["lovelace",n]]))},T=(n,e,t=[])=>n.length===0||tt(t,e)?t:et(n[0],e)?T(n.slice(1),e,[...t,n[0]]):T(n.slice(1),e,t),et=(n,e)=>Array.from(e.keys()).some(t=>n.output.amount.find(i=>i.unit===t)!==void 0);var E=(n,e,t="5000000")=>{let i=A.BigNum.new(n.get("lovelace")??"0").checkedAdd(A.BigNum.new(t)),r=e.filter(u=>u.output.amount.filter(d=>d.unit!=="lovelace").some(d=>n.has(d.unit))),s=L(r);return[...s.lessThan(i)?z(i.clampedSub(s).toString(),e.filter(u=>!r.some(d=>d.input.txHash===u.input.txHash&&d.input.outputIndex===u.input.outputIndex))):[],...r]};var y=require("@meshsdk/common");var V=(n,e,t=!1,{maxTxSize:i,minFeeA:r,minFeeB:s}=y.DEFAULT_PROTOCOL_PARAMETERS)=>{let a=e.filter(b=>P(b)===!1).sort(w),u=y.BigNum.new((0,y.resolveTxFees)(i,r,s)),d=t?y.BigNum.new(n).checkedAdd(u).toString():n;return T(a,new Map([["lovelace",d]]))};var U=require("@meshsdk/common");var Q=(n,e,t=!1,i=U.DEFAULT_PROTOCOL_PARAMETERS)=>{let r=e.filter(P).sort(w),s=W(i),a=n.get("lovelace")??"0",u=t?U.BigNum.new(a).checkedAdd(s).toString():a;return n.set("lovelace",u),T(r,n)};var S=(n,e,t)=>{let i=new Map(n);i.set("lovelace",String(Number(i.get("lovelace")||0)+Number(t)));let r=new Map;for(let o=0;o<e.length;o++)r.set(o,e[o]);let s=new Set,a=new Set,u=new Set,d=new Set,p=new Set;for(let o=0;o<e.length;o++)switch(e[o].output.amount.length){case 1:{a.add(o);break}case 2:{u.add(o);break}case 3:{d.add(o);break}default:{p.add(o);break}}let f=(o,l,m)=>{let M=r.get(o);if(!M)return;let F=it(M,l);if(Number(F)>0){s.add(o),m.delete(o);for(let R of M.output.amount)i.set(R.unit,String(Number(i.get(R.unit))-Number(R.quantity)))}};for(let o of i.keys())if(o!="lovelace"){for(let l of u){let m=i.get(o);if(!m||Number(m)<=0)break;f(l,o,u)}for(let l of d){let m=i.get(o);if(!m||Number(m)<=0)break;f(l,o,d)}for(let l of p){let m=i.get(o);if(!m||Number(m)<=0)break;f(l,o,p)}}for(let o of a){let l=i.get("lovelace");if(!l||Number(l)<=0)break;f(o,"lovelace",a)}for(let o of u){let l=i.get("lovelace");if(!l||Number(l)<=0)break;f(o,"lovelace",u)}for(let o of d){let l=i.get("lovelace");if(!l||Number(l)<=0)break;f(o,"lovelace",d)}for(let o of p){let l=i.get("lovelace");if(!l||Number(l)<=0)break;f(o,"lovelace",p)}for(let o of i.keys())if(Number(i.get(o))>0)return console.log("Insufficient funds for",o),console.log("Remaining quantity",Number(i.get(o))),[];let b=[];for(let o of s){let l=r.get(o);l&&b.push(l)}return b},it=(n,e)=>{for(let t of n.output.amount)if(t.unit==e)return t.quantity;return"0"};var k=class{constructor(){}largestFirst(e,t,i="5000000"){let r=e.get("lovelace")??"0",s=BigInt(r)+BigInt(i);return V(s.toString(),t,!1)}keepRelevant(e,t,i="5000000"){return E(e,t,i)}largestFirstMultiAsset(e,t,i){let r=e.get("lovelace")??"0";return e.set("lovelace",(BigInt(r)+BigInt(i)).toString()),Q(e,t,!1)}experimental(e,t,i){return S(e,t,i)}};var O=class{constructor(){this.txEvaluationMultiplier=1.1;this.addingPlutusScriptInput=!1;this.addingPlutusMint=!1;this.addingPlutusWithdrawal=!1;this._protocolParams=h.DEFAULT_PROTOCOL_PARAMETERS;this.txIn=(e,t,i,r)=>(this.txInQueueItem&&this.queueInput(),this.addingPlutusScriptInput?this.txInQueueItem={type:"Script",txIn:{txHash:e,txIndex:t,amount:i,address:r},scriptTxIn:{}}:this.txInQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:i,address:r}},this.addingPlutusScriptInput=!1,this);this.txInScript=e=>{if(!this.txInQueueItem)throw Error("Undefined input");return this.txInQueueItem.type==="PubKey"&&(this.txInQueueItem={type:"SimpleScript",txIn:this.txInQueueItem.txIn,simpleScriptTxIn:{scriptSource:{type:"Provided",script:e}}}),this.txInQueueItem.type==="Script"&&(this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:e,version:this.plutusSpendingScriptVersion||"V2"}}),this};this.txInDatumValue=(e,t="Mesh")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Datum value attempted to be called a non script input");if(this.txInQueueItem.type==="SimpleScript")throw Error("Datum value attempted to be called on a simple script input");let i=e;return t==="JSON"&&(i=this.castRawDataToJsonString(e)),t==="Mesh"?(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:e}},this):(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:i}},this)};this.txInInlineDatumPresent=()=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Inline datum present attempted to be called a non script input");if(this.txInQueueItem.type==="SimpleScript")throw Error("Inline datum present attempted to be called on a simple script input");let{txHash:e,txIndex:t}=this.txInQueueItem.txIn;return e&&t.toString()&&(this.txInQueueItem.scriptTxIn.datumSource={type:"Inline",txHash:e,txIndex:t}),this};this.txInRedeemerValue=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference redeemer attempted to be called a non script input");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference redeemer attempted to be called on a simple script input");return this.txInQueueItem.scriptTxIn.redeemer=this.castBuilderDataToRedeemer(e,t,i),this};this.txOut=(e,t)=>(this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txOutput={address:e,amount:t},this);this.txOutDatumHashValue=(e,t="Mesh")=>{let i=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Hash",data:{type:t,content:i}},this;t==="JSON"&&(i=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Hash",data:{type:t,content:i}}}return this};this.txOutInlineDatumValue=(e,t="Mesh")=>{let i=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Inline",data:{type:t,content:i}},this;t==="JSON"&&(i=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Inline",data:{type:t,content:i}}}return this};this.txOutReferenceScript=(e,t="V2")=>(this.txOutput&&(this.txOutput.referenceScript={code:e,version:t}),this);this.spendingPlutusScriptV1=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V1",this);this.spendingPlutusScriptV2=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V2",this);this.spendingPlutusScriptV3=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V3",this);this.spendingTxInReference=(e,t,i)=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference attempted to be called a non script input");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference attempted to be called on a simple script input");return this.txInQueueItem.scriptTxIn.scriptSource={type:"Inline",txHash:e,txIndex:t,scriptHash:i,version:this.plutusSpendingScriptVersion||"V2",scriptSize:"0"},this};this.spendingReferenceTxInInlineDatumPresent=()=>(this.txInInlineDatumPresent(),this);this.spendingReferenceTxInRedeemerValue=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>(this.txInRedeemerValue(e,t,i),this);this.readOnlyTxInReference=(e,t)=>(this.meshTxBuilderBody.referenceInputs.push({txHash:e,txIndex:t}),this);this.mintPlutusScriptV1=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V1",this);this.mintPlutusScriptV2=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V2",this);this.mintPlutusScriptV3=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V3",this);this.mint=(e,t,i)=>(this.mintItem&&this.queueMint(),this.mintItem={type:this.addingPlutusMint?"Plutus":"Native",policyId:t,assetName:i,amount:e},this.addingPlutusMint=!1,this);this.mintingScript=e=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");return this.mintItem.type==="Native"&&(this.mintItem.scriptSource={type:"Provided",scriptCode:e}),this.mintItem.type==="Plutus"&&(this.mintItem.scriptSource={type:"Provided",script:{code:e,version:this.plutusMintingScriptVersion||"V2"}}),this};this.mintTxInReference=(e,t)=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");return this.mintItem.scriptSource={type:"Inline",txHash:e,txIndex:t,version:this.plutusMintingScriptVersion,scriptSize:"0",scriptHash:""},this};this.mintReferenceTxInRedeemerValue=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>{if(!this.mintItem)throw Error("Undefined mint");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(this.mintItem.type=="Plutus"&&!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");return this.mintItem.redeemer=this.castBuilderDataToRedeemer(e,t,i),this};this.mintRedeemerValue=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>(this.mintReferenceTxInRedeemerValue(e,t,i),this);this.requiredSignerHash=e=>(this.meshTxBuilderBody.requiredSignatures.push(e),this);this.txInCollateral=(e,t,i,r)=>(this.collateralQueueItem&&this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:i,address:r}},this);this.withdrawalPlutusScriptV1=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V1",this);this.withdrawalPlutusScriptV2=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V2",this);this.withdrawalPlutusScriptV3=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V3",this);this.withdrawal=(e,t)=>{if(this.withdrawalItem&&this.queueWithdrawal(),this.addingPlutusWithdrawal){let r={plutusScriptWithdrawal:{address:e,coin:t}};return this.meshTxBuilderBody.withdrawals.push(r),this}let i={pubKeyWithdrawal:{address:e,coin:t}};return this.meshTxBuilderBody.withdrawals.push(i),this};this.withdrawalScript=(e,t)=>{if(!this.withdrawalItem)throw Error("withdrawalScript: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalScript: Adding script to non plutus withdrawal");return this.withdrawalItem.plutusScriptWithdrawal.scriptSource={type:"Provided",script:{code:e,version:this.plutusWithdrawalScriptVersion||"V2"}},this};this.withdrawalTxInReference=(e,t,i,r)=>{if(!this.withdrawalItem)throw Error("withdrawalTxInReference: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalTxInReference: Adding script reference to non plutus withdrawal");this.withdrawalItem.plutusScriptWithdrawal.scriptSource={type:"Inline",txHash:e,txIndex:t,scriptHash:i,version:this.plutusWithdrawalScriptVersion||"V2",scriptSize:r||"0"}};this.withdrawalRedeemerValue=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>{if(!this.withdrawalItem)throw Error("withdrawalRedeemerValue: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalRedeemerValue: Adding redeemer to non plutus withdrawal");return this.withdrawalItem.plutusScriptWithdrawal.redeemer=this.castBuilderDataToRedeemer(e,t,i),this};this.registerPoolCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterPool",poolParams:e}),this);this.registerStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterStake",stakeKeyHash:e}),this);this.delegateStakeCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"DelegateStake",stakeKeyHash:e,poolId:t}),this);this.deregisterStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"DeregisterStake",stakeKeyHash:e}),this);this.retirePoolCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"RetirePool",poolId:e,epoch:t}),this);this.changeAddress=e=>(this.meshTxBuilderBody.changeAddress=e,this);this.invalidBefore=e=>(this.meshTxBuilderBody.validityRange.invalidBefore=e,this);this.invalidHereafter=e=>(this.meshTxBuilderBody.validityRange.invalidHereafter=e,this);this.metadataValue=(e,t)=>{let i=q.default.stringify(t);return this.meshTxBuilderBody.metadata.push({tag:e,metadata:i}),this};this.signingKey=e=>(this.meshTxBuilderBody.signingKey.push(e),this);this.selectUtxosFrom=(e,t=5e6)=>(this.meshTxBuilderBody.extraInputs=e,this.meshTxBuilderBody.selectionThreshold=t,this);this.protocolParams=e=>{let t={...h.DEFAULT_PROTOCOL_PARAMETERS,...e};return this._protocolParams=t,this};this.queueAllLastItem=()=>{this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txInQueueItem&&this.queueInput(),this.collateralQueueItem&&(this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem=void 0),this.mintItem&&this.queueMint(),this.withdrawalItem&&this.queueWithdrawal()};this.queueInput=()=>{if(!this.txInQueueItem)throw Error("queueInput: Undefined input");if(this.txInQueueItem.type==="Script")if(this.txInQueueItem.scriptTxIn){if(!this.txInQueueItem.scriptTxIn.datumSource)throw Error("queueInput: Script input does not contain datum information");if(!this.txInQueueItem.scriptTxIn.redeemer)throw Error("queueInput: Script input does not contain redeemer information");if(!this.txInQueueItem.scriptTxIn.scriptSource)throw Error("queueInput: Script input does not contain script information")}else throw Error("queueInput: Script input does not contain script, datum, or redeemer information");this.meshTxBuilderBody.inputs.push(this.txInQueueItem),this.txInQueueItem=void 0};this.queueMint=()=>{if(!this.mintItem)throw Error("queueMint: Undefined mint");if(!this.mintItem.scriptSource)throw Error("queueMint: Missing mint script information");this.meshTxBuilderBody.mints.push(this.mintItem),this.mintItem=void 0};this.queueWithdrawal=()=>{if(!this.withdrawalItem)throw Error("queueWithdrawal: Undefined withdrawal");if("plutusScriptWithdrawal"in this.withdrawalItem){if(!this.withdrawalItem.plutusScriptWithdrawal.scriptSource)throw Error("queueWithdrawal: Missing withdrawal script information");if(!this.withdrawalItem.plutusScriptWithdrawal.redeemer)throw Error("queueWithdrawal: Missing withdrawal redeemer information")}this.meshTxBuilderBody.withdrawals.push(this.withdrawalItem),this.withdrawalItem=void 0};this.castRawDataToJsonString=e=>typeof e=="object"?q.default.stringify(e):e;this.castBuilderDataToRedeemer=(e,t="Mesh",i={...h.DEFAULT_REDEEMER_BUDGET})=>{let r,s=e;return t==="Mesh"?(r={data:{type:t,content:s},exUnits:i},r):(t==="JSON"&&(s=this.castRawDataToJsonString(e)),r={data:{type:t,content:s},exUnits:i},r)};this.updateRedeemer=(e,t)=>{t.forEach(i=>{switch(i.tag){case"SPEND":{let r=e.inputs[i.index];r.type=="Script"&&r.scriptTxIn.redeemer&&(r.scriptTxIn.redeemer.exUnits.mem=Math.floor(i.budget.mem*this.txEvaluationMultiplier),r.scriptTxIn.redeemer.exUnits.steps=Math.floor(i.budget.steps*this.txEvaluationMultiplier));break}case"MINT":{let r=e.mints[i.index];r.type=="Plutus"&&r.redeemer&&(r.redeemer.exUnits.mem=Math.floor(i.budget.mem*this.txEvaluationMultiplier),r.redeemer.exUnits.steps=Math.floor(i.budget.steps*this.txEvaluationMultiplier));break}case"CERT":break;case"REWARD":break}})};this.addUtxosFromSelection=()=>{let e=this.meshTxBuilderBody.outputs.reduce((i,r)=>(r.amount.forEach(a=>{let{unit:u,quantity:d}=a,p=Number(i.get(u))||0;i.set(u,String(p+Number(d)))}),i),new Map);this.meshTxBuilderBody.inputs.reduce((i,r)=>(r.txIn.amount?.forEach(a=>{let{unit:u,quantity:d}=a,p=Number(i.get(u))||0;i.set(u,String(p-Number(d)))}),i),e),this.meshTxBuilderBody.mints.reduce((i,r)=>{let s={unit:r.policyId+r.assetName,quantity:String(r.amount)},a=Number(i.get(s.unit))||0;return i.set(s.unit,String(a-Number(s.quantity))),i},e),S(e,this.meshTxBuilderBody.extraInputs,this.meshTxBuilderBody.selectionThreshold.toString()).forEach(i=>{let r={type:"PubKey",txIn:{txHash:i.input.txHash,txIndex:i.input.outputIndex,amount:i.output.amount,address:i.output.address}};this.meshTxBuilderBody.inputs.push(r)})};this.removeDuplicateInputs=()=>{let{inputs:e}=this.meshTxBuilderBody,t=s=>`${s.txHash}#${s.txIndex}`,i=[],r=[];for(let s=0;s<e.length;s+=1){let a=e[s],u=t(a.txIn);i.includes(u)?(e.splice(s,1),s-=1):r.push(a)}this.meshTxBuilderBody.inputs=r};this.emptyTxBuilderBody=()=>(this.meshTxBuilderBody=(0,h.emptyTxBuilderBody)(),h.emptyTxBuilderBody);this.reset=()=>{this.meshTxBuilderBody=(0,h.emptyTxBuilderBody)(),this.txEvaluationMultiplier=1.1,this.txOutput=void 0,this.addingPlutusScriptInput=!1,this.plutusSpendingScriptVersion=void 0,this.addingPlutusMint=!1,this.plutusMintingScriptVersion=void 0,this.addingPlutusWithdrawal=!1,this.plutusWithdrawalScriptVersion=void 0,this._protocolParams=h.DEFAULT_PROTOCOL_PARAMETERS,this.mintItem=void 0,this.txInQueueItem=void 0,this.withdrawalItem=void 0,this.collateralQueueItem=void 0,this.refScriptTxInQueueItem=void 0};this.meshTxBuilderBody=(0,h.emptyTxBuilderBody)()}};var K=require("@meshsdk/core-csl"),B=class extends O{constructor({serializer:t,fetcher:i,submitter:r,evaluator:s,params:a,isHydra:u=!1}={}){super();this.txHex="";this.queriedTxHashes=new Set;this.queriedUTxOs={};this.complete=async t=>{t?this.meshTxBuilderBody=t:this.queueAllLastItem(),this.removeDuplicateInputs();let{inputs:i,collaterals:r}=this.meshTxBuilderBody,s=[...i,...r].filter(u=>!this.isInputComplete(u));await this.queryAllTxInfo(s),s.forEach(u=>{this.completeTxInformation(u)}),this.addUtxosFromSelection();let a=this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams);if(this.evaluator){let u=await this.evaluator.evaluateTx(a).catch(d=>{throw Error(`Tx evaluation failed: ${d}`)});this.updateRedeemer(this.meshTxBuilderBody,u),a=this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams)}return console.log(a),this.txHex=a,a};this.completeSync=t=>(t?this.meshTxBuilderBody=t:this.queueAllLastItem(),this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams));this.completeSigning=()=>{let t=this.serializer.addSigningKeys(this.txHex,this.meshTxBuilderBody.signingKey);return this.txHex=t,t};this.submitTx=async t=>await this.submitter?.submitTx(t);this.getUTxOInfo=async t=>{let i=[];this.queriedTxHashes.has(t)||(this.queriedTxHashes.add(t),i=await this.fetcher?.fetchUTxOs(t)||[],this.queriedUTxOs[t]=i)};this.queryAllTxInfo=t=>{let i=[];if(t.length>0&&!this.fetcher)throw Error("Transaction information is incomplete while no fetcher instance is provided");for(let r=0;r<t.length;r++){let s=t[r];this.isInputInfoComplete(s)||i.push(this.getUTxOInfo(s.txIn.txHash)),s.type==="Script"&&s.scriptTxIn.scriptSource?.type==="Inline"&&!this.isRefScriptInfoComplete(s)&&i.push(this.getUTxOInfo(s.scriptTxIn.scriptSource.txHash))}return Promise.all(i)};this.completeTxInformation=t=>{if(!this.isInputInfoComplete(t)){let r=this.queriedUTxOs[t.txIn.txHash]?.find(u=>u.input.outputIndex===t.txIn.txIndex),s=r?.output.amount,a=r?.output.address;if(!s||s.length===0)throw Error(`Couldn't find value information for ${t.txIn.txHash}#${t.txIn.txIndex}`);if(t.txIn.amount=s,t.type==="PubKey"){if(!a||a==="")throw Error(`Couldn't find address information for ${t.txIn.txHash}#${t.txIn.txIndex}`);t.txIn.address=a}}if(t.type==="Script"&&t.scriptTxIn.scriptSource?.type=="Inline"&&!this.isRefScriptInfoComplete(t)){let i=t.scriptTxIn.scriptSource,s=this.queriedUTxOs[i.txHash].find(a=>a.input.outputIndex===i.txIndex);if(!s)throw Error(`Couldn't find script reference utxo for ${i.txHash}#${i.txIndex}`);i.scriptHash=s?.output.scriptHash}};this.isInputComplete=t=>t.type==="PubKey"?this.isInputInfoComplete(t):t.type==="Script"?this.isInputInfoComplete(t)&&this.isRefScriptInfoComplete(t):!0;this.isInputInfoComplete=t=>{let{amount:i,address:r}=t.txIn;return!(t.type==="PubKey"&&(!i||!r)||t.type==="Script"&&!i)};this.isRefScriptInfoComplete=t=>{let{scriptSource:i}=t.scriptTxIn;return!(i?.type==="Inline"&&!i?.scriptHash)};t?this.serializer=t:this.serializer=new K.CSLSerializer,i&&(this.fetcher=i),r&&(this.submitter=r),s&&(this.evaluator=s),a&&this.protocolParams(a),u&&this.protocolParams({minFeeA:0,minFeeB:0,priceMem:0,priceStep:0,collateralPercent:0,coinsPerUtxoSize:0})}};var I=require("@meshsdk/core-cst"),N=class{static withOneSignature(e){let t=(0,I.deserializeEd25519KeyHash)((0,I.resolvePaymentKeyHash)(e));return(0,I.buildScriptPubkey)(t).toCbor()}static fromNativeScript(e){return(0,I.toNativeScript)(e).toCbor()}};var c=require("@meshsdk/common");var g=require("@meshsdk/core-cst"),D=class{constructor(e){this.isCollateralNeeded=!1;this.txBuilder=new B(e),this.initiator=e.initiator}sendAssets(e,t){return typeof t=="string"&&(t=[{unit:"lovelace",quantity:t}]),typeof e=="string"&&this.txBuilder.txOut(e,t),typeof e=="object"&&(this.txBuilder.txOut(e.address,t),e.datum&&(e.datum.inline?this.txBuilder.txOutInlineDatumValue(e.datum.value):this.txBuilder.txOutDatumHashValue(e.datum.value))),this}sendLovelace(e,t){return this.sendAssets(e,t)}sendToken(e,t,i){let r=[{unit:c.SUPPORTED_TOKENS[t],quantity:i}];return this.sendAssets(e,r)}sendValue(e,t){let i=t.output.amount;return this.sendAssets(e,i)}setTxInputs(e){return e.forEach(t=>{this.txBuilder.txIn(t.input.txHash,t.input.outputIndex,t.output.amount,t.output.address)}),this}setTxRefInputs(e){return e.forEach(t=>{this.txBuilder.readOnlyTxInReference(t.input.txHash,t.input.outputIndex)}),this}setNativeScriptInput(e,t){let{scriptCbor:i}=this.txBuilder.serializer.deserializer.script.deserializeNativeScript(e);return this.txBuilder.txIn(t.input.txHash,t.input.outputIndex,t.output.amount,t.output.address).txInScript(i),this}redeemValue(e){let{value:t,script:i,datum:r,redeemer:s}=e,a=s||{data:{alternative:0,fields:["mesh"]},budget:c.DEFAULT_REDEEMER_BUDGET};if("code"in i&&(this.isCollateralNeeded=!0,this.spendingPlutusScript(i).txIn(t.input.txHash,t.input.outputIndex,t.output.amount,t.output.address).txInScript(i.code).txInRedeemerValue(a.data,"Mesh",a.budget)),"output"in i){if(!i.output.scriptRef)throw new Error("redeemValue: No script reference found in UTxO");let u=(0,g.fromScriptRef)(i.output.scriptRef);if(!u||!("code"in u))throw new Error("redeemValue: Script reference not found");this.isCollateralNeeded=!0,this.spendingPlutusScript(u).txIn(t.input.txHash,t.input.outputIndex,t.output.amount,t.output.address).spendingTxInReference(i.input.txHash,i.input.outputIndex,i.output.scriptHash).txInRedeemerValue(a.data,"Mesh",a.budget)}return r?this.txBuilder.txInDatumValue(r):this.txBuilder.txInInlineDatumPresent(),this}mintAsset(e,t,i){let r=t.assetQuantity,s=(0,c.stringToHex)(t.assetName),a=(0,c.CIP68_100)(s);t.cip68ScriptAddress&&(s=(0,c.CIP68_222)(s));let u="";switch(typeof e){case"string":u=(0,g.deserializeNativeScript)(e).hash().toString(),this.txBuilder.mint(r,u,s).mintingScript(e),t.cip68ScriptAddress&&this.txBuilder.mint(r,u,a).mintingScript(e);break;case"object":if(!i)throw new Error("burnAsset: Redeemer data is required for Plutus minting");if("code"in e){u=(0,g.deserializePlutusScript)(e.code,e.version).hash().toString(),this.isCollateralNeeded=!0,this.mintPlutusScript(e).mint(r,u,s).mintingScript(e.code).mintRedeemerValue(i.data,"Mesh",i.budget),t.cip68ScriptAddress&&this.mintPlutusScript(e).mint(r,u,a).mintingScript(e.code).mintRedeemerValue(i.data,"Mesh",i.budget);break}if("output"in e){if(!e.output.scriptRef)throw new Error("mintAsset: No script reference found in UTxO");let d=(0,g.fromScriptRef)(e.output.scriptRef);if(!d)throw new Error("mintAsset: Script reference not found");if("code"in d){if(u=(0,g.deserializePlutusScript)(d.code,d.version).hash().toString(),this.isCollateralNeeded=!0,this.mintPlutusScript(d).mint(r,u,s).mintTxInReference(e.input.txHash,e.input.outputIndex).mintRedeemerValue(i.data,"Mesh",i.budget),t.cip68ScriptAddress){this.mintPlutusScript(d).mint(r,u,a).mintTxInReference(e.input.txHash,e.input.outputIndex).mintRedeemerValue(i.data,"Mesh",i.budget);break}break}else throw new Error("mintAsset: Reference script minting not implemented")}break}return t.metadata&&t.label&&this.setMetadata(Number(t.label),{[u]:{[t.assetName]:t.metadata},version:1}),t.recipient&&this.sendAssets(t.recipient,[{unit:u+s,quantity:t.assetQuantity}]),t.cip68ScriptAddress&&this.sendAssets({address:t.cip68ScriptAddress,datum:{inline:!0,value:(0,c.metadataToCip68)(t.metadata)}},[{unit:u+a,quantity:t.assetQuantity}]),this}burnAsset(e,t,i){let r="-"+t.quantity,s={assetName:(0,c.hexToString)(t.unit.slice(c.POLICY_ID_LENGTH)),assetQuantity:r};try{this.mintAsset(e,s,i)}catch(a){throw new Error("burnAsset: "+a)}return this}setChangeAddress(e){return this.txBuilder.changeAddress(e),this}setCollateral(e){return e.forEach(t=>{this.txBuilder.txInCollateral(t.input.txHash,t.input.outputIndex,t.output.amount,t.output.address)}),this}setRequiredSigners(e){return e.forEach(t=>{let{pubKeyHash:i}=this.txBuilder.serializer.deserializer.key.deserializeAddress(t);this.txBuilder.requiredSignerHash(i)}),this}setTimeToExpire(e){return this.txBuilder.invalidHereafter(Number(e)),this}setTimeToStart(e){return this.txBuilder.invalidBefore(Number(e)),this}setMetadata(e,t){return this.txBuilder.metadataValue(e.toString(),t),this}withdrawRewards(e,t){return this.txBuilder.withdrawal(e,t),this}delegateStake(e,t){return this.txBuilder.delegateStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(e),this.txBuilder.serializer.resolver.keys.resolveEd25519KeyHash(t)),this}deregisterStake(e){return this.txBuilder.deregisterStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(e)),this}registerStake(e){return this.txBuilder.registerStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(e)),this}registerPool(e){return this.txBuilder.registerPoolCertificate(e),this}retirePool(e,t){return this.txBuilder.retirePoolCertificate(e,t),this}async build(){try{return await this.addCollateralIfNeeded(),await this.addTxInputsAsNeeded(),await this.addChangeAddress(),this.txBuilder.complete()}catch(e){throw new Error(`[Transaction] An error occurred during build: ${e}.`)}}mintPlutusScript(e){switch(e.version){case"V1":this.txBuilder.mintPlutusScriptV1();break;case"V2":this.txBuilder.mintPlutusScriptV2();break;case"V3":this.txBuilder.mintPlutusScriptV3();break}return this.txBuilder}spendingPlutusScript(e){switch(e.version){case"V1":this.txBuilder.spendingPlutusScriptV1();break;case"V2":this.txBuilder.spendingPlutusScriptV2();break;case"V3":this.txBuilder.spendingPlutusScriptV3();break}return this.txBuilder}async addCollateralIfNeeded(){if(this.isCollateralNeeded){let e=await this.initiator.getCollateral();this.setCollateral(e)}}async addTxInputsAsNeeded(){let e=await this.initiator.getUtxos();this.txBuilder.selectUtxosFrom(e)}async addChangeAddress(){if(this.txBuilder.meshTxBuilderBody.changeAddress===""){let e=await this.initiator.getChangeAddress();this.setChangeAddress(e)}}};0&&(module.exports={ForgeScript,MeshTxBuilder,Transaction,UtxoSelection,experimentalSelectUtxos,keepRelevant,largestFirst,largestFirstMultiAsset});