@meshsdk/core-cst 1.5.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1481 @@
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
+ Address: () => Address,
34
+ AddressType: () => AddressType,
35
+ AssetFingerprint: () => AssetFingerprint,
36
+ AssetId: () => AssetId,
37
+ AssetName: () => AssetName,
38
+ BaseAddress: () => BaseAddress,
39
+ Bip32PrivateKey: () => Bip32PrivateKey3,
40
+ Bip32PrivateKeyHex: () => Bip32PrivateKeyHex2,
41
+ Cardano: () => import_core7.Cardano,
42
+ CardanoSDK: () => CardanoSDK,
43
+ CardanoSDKSerializer: () => CardanoSDKSerializer,
44
+ CardanoSDKUtil: () => CardanoSDKUtil,
45
+ CborSet: () => CborSet,
46
+ CborWriter: () => CborWriter,
47
+ Certificate: () => Certificate,
48
+ CertificateType: () => CertificateType,
49
+ ConstrPlutusData: () => ConstrPlutusData,
50
+ CostModel: () => CostModel,
51
+ Costmdls: () => Costmdls,
52
+ Credential: () => Credential,
53
+ CredentialType: () => CredentialType,
54
+ Crypto: () => Crypto3,
55
+ Datum: () => Datum,
56
+ DatumHash: () => DatumHash,
57
+ DatumKind: () => DatumKind,
58
+ Ed25519KeyHash: () => Ed25519KeyHash2,
59
+ Ed25519KeyHashHex: () => Ed25519KeyHashHex2,
60
+ Ed25519PrivateExtendedKeyHex: () => Ed25519PrivateExtendedKeyHex,
61
+ Ed25519PrivateNormalKeyHex: () => Ed25519PrivateNormalKeyHex,
62
+ Ed25519PublicKey: () => Ed25519PublicKey2,
63
+ Ed25519PublicKeyHex: () => Ed25519PublicKeyHex2,
64
+ Ed25519Signature: () => Ed25519Signature2,
65
+ Ed25519SignatureHex: () => Ed25519SignatureHex2,
66
+ EnterpriseAddress: () => EnterpriseAddress,
67
+ ExUnits: () => ExUnits,
68
+ Hash: () => Hash,
69
+ Hash28ByteBase16: () => Hash28ByteBase162,
70
+ Hash32ByteBase16: () => Hash32ByteBase162,
71
+ NativeScript: () => NativeScript,
72
+ NetworkId: () => NetworkId,
73
+ PaymentAddress: () => PaymentAddress,
74
+ PlutusData: () => PlutusData,
75
+ PlutusLanguageVersion: () => PlutusLanguageVersion,
76
+ PlutusList: () => PlutusList,
77
+ PlutusMap: () => PlutusMap,
78
+ PlutusV1Script: () => PlutusV1Script,
79
+ PlutusV2Script: () => PlutusV2Script,
80
+ PlutusV3Script: () => PlutusV3Script,
81
+ PolicyId: () => PolicyId,
82
+ PoolId: () => PoolId,
83
+ PrivateKey: () => PrivateKey,
84
+ PublicKey: () => import_bip32ed25519.PublicKey,
85
+ Redeemer: () => Redeemer,
86
+ RedeemerPurpose: () => RedeemerPurpose,
87
+ RedeemerTag: () => RedeemerTag,
88
+ Redeemers: () => Redeemers,
89
+ RequireAllOf: () => RequireAllOf,
90
+ RequireAnyOf: () => RequireAnyOf,
91
+ RequireNOf: () => RequireNOf,
92
+ RequireSignature: () => RequireSignature,
93
+ RequireTimeAfter: () => RequireTimeAfter,
94
+ RequireTimeBefore: () => RequireTimeBefore,
95
+ RewardAccount: () => RewardAccount,
96
+ RewardAddress: () => RewardAddress,
97
+ Script: () => Script,
98
+ ScriptHash: () => ScriptHash,
99
+ ScriptPubkey: () => ScriptPubkey,
100
+ Serialization: () => import_core7.Serialization,
101
+ Slot: () => Slot,
102
+ StakeDelegation: () => StakeDelegation,
103
+ StakeRegistration: () => StakeRegistration,
104
+ Transaction: () => Transaction,
105
+ TransactionBody: () => TransactionBody,
106
+ TransactionId: () => TransactionId,
107
+ TransactionInput: () => TransactionInput,
108
+ TransactionOutput: () => TransactionOutput,
109
+ TransactionUnspentOutput: () => TransactionUnspentOutput,
110
+ TransactionWitnessSet: () => TransactionWitnessSet,
111
+ Value: () => Value,
112
+ VkeyWitness: () => VkeyWitness,
113
+ VrfVkBech32: () => VrfVkBech32,
114
+ addressToBech32: () => addressToBech32,
115
+ assetTypes: () => assetTypes,
116
+ buildBaseAddress: () => buildBaseAddress,
117
+ buildBip32PrivateKey: () => buildBip32PrivateKey,
118
+ buildEnterpriseAddress: () => buildEnterpriseAddress,
119
+ buildKeys: () => buildKeys,
120
+ buildRewardAddress: () => buildRewardAddress,
121
+ buildScriptPubkey: () => buildScriptPubkey,
122
+ checkSignature: () => checkSignature,
123
+ deserializeAddress: () => deserializeAddress,
124
+ deserializeDataHash: () => deserializeDataHash,
125
+ deserializeEd25519KeyHash: () => deserializeEd25519KeyHash,
126
+ deserializeNativeScript: () => deserializeNativeScript,
127
+ deserializePlutusData: () => deserializePlutusData,
128
+ deserializePlutusScript: () => deserializePlutusScript,
129
+ deserializeScriptHash: () => deserializeScriptHash,
130
+ deserializeScriptRef: () => deserializeScriptRef,
131
+ deserializeTx: () => deserializeTx,
132
+ deserializeTxHash: () => deserializeTxHash,
133
+ deserializeTxUnspentOutput: () => deserializeTxUnspentOutput,
134
+ deserializeValue: () => deserializeValue,
135
+ empty: () => empty,
136
+ fromNativeScript: () => fromNativeScript,
137
+ fromScriptRef: () => fromScriptRef,
138
+ fromTxUnspentOutput: () => fromTxUnspentOutput,
139
+ fromValue: () => fromValue,
140
+ mergeValue: () => mergeValue,
141
+ negateValue: () => negateValue,
142
+ negatives: () => negatives,
143
+ resolveDataHash: () => resolveDataHash,
144
+ resolveNativeScriptAddress: () => resolveNativeScriptAddress,
145
+ resolveNativeScriptHash: () => resolveNativeScriptHash,
146
+ resolvePaymentKeyHash: () => resolvePaymentKeyHash,
147
+ resolvePlutusScriptAddress: () => resolvePlutusScriptAddress,
148
+ resolvePlutusScriptHash: () => resolvePlutusScriptHash,
149
+ resolvePoolId: () => resolvePoolId,
150
+ resolvePrivateKey: () => resolvePrivateKey,
151
+ resolveRewardAddress: () => resolveRewardAddress,
152
+ resolveScriptRef: () => resolveScriptRef,
153
+ resolveStakeKeyHash: () => resolveStakeKeyHash,
154
+ resolveTxHash: () => resolveTxHash,
155
+ signData: () => signData,
156
+ subValue: () => subValue,
157
+ toAddress: () => toAddress,
158
+ toBaseAddress: () => toBaseAddress,
159
+ toEnterpriseAddress: () => toEnterpriseAddress,
160
+ toNativeScript: () => toNativeScript,
161
+ toPlutusData: () => toPlutusData,
162
+ toRewardAddress: () => toRewardAddress,
163
+ toScriptRef: () => toScriptRef,
164
+ toTxUnspentOutput: () => toTxUnspentOutput,
165
+ toValue: () => toValue
166
+ });
167
+ module.exports = __toCommonJS(src_exports);
168
+ var import_core7 = require("@cardano-sdk/core");
169
+
170
+ // src/stricahq/index.ts
171
+ var import_bip32ed25519 = require("@stricahq/bip32ed25519");
172
+ var import_hash = __toESM(require("hash.js"));
173
+ var PrivateKey = class extends import_bip32ed25519.PrivateKey {
174
+ constructor(privKey, extended = true) {
175
+ if (!extended) {
176
+ let extendedSecret = import_hash.default.sha512().update(privKey).digest();
177
+ if (extendedSecret[0] && extendedSecret[31]) {
178
+ extendedSecret[0] &= 248;
179
+ extendedSecret[31] &= 63;
180
+ extendedSecret[31] |= 64;
181
+ }
182
+ privKey = Buffer.from(extendedSecret);
183
+ }
184
+ super(privKey);
185
+ }
186
+ };
187
+
188
+ // src/types/cardano-sdk.ts
189
+ var import_core = require("@cardano-sdk/core");
190
+ var Crypto = __toESM(require("@cardano-sdk/crypto"));
191
+ var import_util = require("@cardano-sdk/util");
192
+ var Slot = import_core.Cardano.Slot;
193
+ var Value = import_core.Serialization.Value;
194
+ var Transaction = import_core.Serialization.Transaction;
195
+ var TransactionId = import_core.Cardano.TransactionId;
196
+ var TransactionBody = import_core.Serialization.TransactionBody;
197
+ var TransactionWitnessSet = import_core.Serialization.TransactionWitnessSet;
198
+ var TransactionUnspentOutput = import_core.Serialization.TransactionUnspentOutput;
199
+ var TransactionInput = import_core.Serialization.TransactionInput;
200
+ var TransactionOutput = import_core.Serialization.TransactionOutput;
201
+ var PlutusData = import_core.Serialization.PlutusData;
202
+ var PlutusList = import_core.Serialization.PlutusList;
203
+ var PlutusMap = import_core.Serialization.PlutusMap;
204
+ var Redeemers = import_core.Serialization.Redeemers;
205
+ var Redeemer = import_core.Serialization.Redeemer;
206
+ var RedeemerPurpose = import_core.Cardano.RedeemerPurpose;
207
+ var RedeemerTag = import_core.Serialization.RedeemerTag;
208
+ var Script = import_core.Serialization.Script;
209
+ var PolicyId = import_core.Cardano.PolicyId;
210
+ var AssetName = import_core.Cardano.AssetName;
211
+ var AssetId = import_core.Cardano.AssetId;
212
+ var ScriptHash = Crypto.Hash28ByteBase16;
213
+ var Address = import_core.Cardano.Address;
214
+ var RewardAddress = import_core.Cardano.RewardAddress;
215
+ var AddressType = import_core.Cardano.AddressType;
216
+ var BaseAddress = import_core.Cardano.BaseAddress;
217
+ var EnterpriseAddress = import_core.Cardano.EnterpriseAddress;
218
+ var PaymentAddress = import_core.Cardano.PaymentAddress;
219
+ var AssetFingerprint = import_core.Cardano.AssetFingerprint;
220
+ var Credential = import_core.Serialization.Credential;
221
+ var Ed25519PublicKeyHex2 = Crypto.Ed25519PublicKeyHex;
222
+ var Ed25519PrivateNormalKeyHex = (value) => (0, import_util.typedHex)(value, 64);
223
+ var Ed25519PrivateExtendedKeyHex = (value) => (0, import_util.typedHex)(value, 128);
224
+ var Ed25519KeyHash2 = Crypto.Ed25519KeyHash;
225
+ var Ed25519KeyHashHex2 = Crypto.Ed25519KeyHashHex;
226
+ var Hash28ByteBase162 = Crypto.Hash28ByteBase16;
227
+ var Hash32ByteBase162 = Crypto.Hash32ByteBase16;
228
+ var CredentialType = import_core.Cardano.CredentialType;
229
+ var Certificate = import_core.Serialization.Certificate;
230
+ var PoolId = import_core.Cardano.PoolId;
231
+ var StakeRegistration = import_core.Serialization.StakeRegistration;
232
+ var StakeDelegation = import_core.Serialization.StakeDelegation;
233
+ var CertificateType = import_core.Cardano.CertificateType;
234
+ var VkeyWitness = import_core.Serialization.VkeyWitness;
235
+ var Ed25519SignatureHex2 = Crypto.Ed25519SignatureHex;
236
+ var Ed25519PublicKey2 = Crypto.Ed25519PublicKey;
237
+ var Ed25519Signature2 = Crypto.Ed25519Signature;
238
+ var Bip32PrivateKey3 = Crypto.Bip32PrivateKey;
239
+ var Bip32PrivateKeyHex2 = Crypto.Bip32PrivateKeyHex;
240
+ var PlutusLanguageVersion = import_core.Cardano.PlutusLanguageVersion;
241
+ var NativeScript = import_core.Serialization.NativeScript;
242
+ var PlutusV1Script = import_core.Serialization.PlutusV1Script;
243
+ var PlutusV2Script = import_core.Serialization.PlutusV2Script;
244
+ var PlutusV3Script = import_core.Serialization.PlutusV3Script;
245
+ var Costmdls = import_core.Serialization.Costmdls;
246
+ var CostModel = import_core.Serialization.CostModel;
247
+ var CborWriter = import_core.Serialization.CborWriter;
248
+ var ConstrPlutusData = import_core.Serialization.ConstrPlutusData;
249
+ var RewardAccount = import_core.Cardano.RewardAccount;
250
+ var Hash = import_core.Serialization.Hash;
251
+ var DatumHash = Crypto.Hash32ByteBase16;
252
+ var Datum = import_core.Serialization.Datum;
253
+ var ExUnits = import_core.Serialization.ExUnits;
254
+ var NetworkId = import_core.Cardano.NetworkId;
255
+ var DatumKind = import_core.Serialization.DatumKind;
256
+ var CborSet = import_core.Serialization.CborSet;
257
+ var RequireAllOf = import_core.Cardano.NativeScriptKind.RequireAllOf;
258
+ var RequireAnyOf = import_core.Cardano.NativeScriptKind.RequireAnyOf;
259
+ var RequireNOf = import_core.Cardano.NativeScriptKind.RequireNOf;
260
+ var RequireSignature = import_core.Cardano.NativeScriptKind.RequireSignature;
261
+ var RequireTimeAfter = import_core.Cardano.NativeScriptKind.RequireTimeAfter;
262
+ var RequireTimeBefore = import_core.Cardano.NativeScriptKind.RequireTimeBefore;
263
+ var VrfVkBech32 = import_core.Cardano.VrfVkBech32;
264
+ var ScriptPubkey = import_core.Serialization.ScriptPubkey;
265
+
266
+ // src/cip8/index.ts
267
+ var signData = (data, privateKey) => {
268
+ const payload = Buffer.from(data);
269
+ const signature = privateKey.sign(payload);
270
+ return {
271
+ key: privateKey.toPublicKey().toBytes().toString("hex"),
272
+ signature: signature.toString("hex")
273
+ };
274
+ };
275
+ var checkSignature = (data, { key, signature }) => {
276
+ const publicKey = new import_bip32ed25519.PublicKey(Buffer.from(key, "hex"));
277
+ return publicKey.verify(Buffer.from(signature, "hex"), Buffer.from(data));
278
+ };
279
+
280
+ // src/resolvers/index.ts
281
+ var import_core4 = require("@cardano-sdk/core");
282
+ var import_crypto3 = require("@cardano-sdk/crypto");
283
+ var import_util4 = require("@cardano-sdk/util");
284
+
285
+ // src/utils/builder.ts
286
+ var import_pbkdf2 = require("pbkdf2");
287
+ var import_common = require("@meshsdk/common");
288
+ var buildBaseAddress = (networkId, paymentKeyHash, stakeKeyHash) => {
289
+ return BaseAddress.fromCredentials(
290
+ networkId,
291
+ {
292
+ hash: paymentKeyHash,
293
+ type: CredentialType.KeyHash
294
+ },
295
+ {
296
+ hash: stakeKeyHash,
297
+ type: CredentialType.KeyHash
298
+ }
299
+ );
300
+ };
301
+ var buildEnterpriseAddress = (networkId, paymentKeyHash) => {
302
+ return EnterpriseAddress.fromCredentials(networkId, {
303
+ hash: paymentKeyHash,
304
+ type: CredentialType.KeyHash
305
+ });
306
+ };
307
+ var buildBip32PrivateKey = (entropy, password = "") => {
308
+ const PBKDF2_ITERATIONS = 4096;
309
+ const PBKDF2_KEY_SIZE = 96;
310
+ const PBKDF2_DIGEST_ALGORITHM = "sha512";
311
+ const clampScalar = (scalar) => {
312
+ if (scalar[0] !== void 0) {
313
+ scalar[0] &= 248;
314
+ }
315
+ if (scalar[31] !== void 0) {
316
+ scalar[31] &= 31;
317
+ scalar[31] |= 64;
318
+ }
319
+ return scalar;
320
+ };
321
+ const _entropy = Buffer.from(entropy, "hex");
322
+ const xprv = (0, import_pbkdf2.pbkdf2Sync)(
323
+ password,
324
+ _entropy,
325
+ PBKDF2_ITERATIONS,
326
+ PBKDF2_KEY_SIZE,
327
+ PBKDF2_DIGEST_ALGORITHM
328
+ );
329
+ return Bip32PrivateKey3.fromBytes(clampScalar(xprv));
330
+ };
331
+ var buildRewardAddress = (networkId, stakeKeyHash) => {
332
+ const cred = {
333
+ type: CredentialType.KeyHash,
334
+ hash: stakeKeyHash
335
+ };
336
+ return RewardAddress.fromCredentials(networkId, cred);
337
+ };
338
+ var buildKeys = (entropy, accountIndex, keyIndex = 0) => {
339
+ if (typeof entropy === "string") {
340
+ const rootKey = new import_bip32ed25519.Bip32PrivateKey(Buffer.from(entropy, "hex"));
341
+ const accountKey = rootKey.derive(import_common.HARDENED_KEY_START + 1852).derive(import_common.HARDENED_KEY_START + 1815).derive(import_common.HARDENED_KEY_START + accountIndex);
342
+ const paymentKey = accountKey.derive(0).derive(keyIndex).toPrivateKey();
343
+ const stakeKey = accountKey.derive(2).derive(0).toPrivateKey();
344
+ return { paymentKey, stakeKey };
345
+ } else {
346
+ const paymentKey = new PrivateKey(Buffer.from(entropy[0], "hex"), false);
347
+ const stakeKey = new PrivateKey(Buffer.from(entropy[1], "hex"), false);
348
+ return { paymentKey, stakeKey };
349
+ }
350
+ };
351
+ var buildScriptPubkey = (keyHash) => {
352
+ const scriptPubkey = new ScriptPubkey(Ed25519KeyHashHex2(keyHash.hex()));
353
+ return NativeScript.newScriptPubkey(scriptPubkey);
354
+ };
355
+
356
+ // src/utils/converter.ts
357
+ var import_core3 = require("@cardano-sdk/core");
358
+ var import_crypto2 = require("@cardano-sdk/crypto");
359
+ var import_util3 = require("@cardano-sdk/util");
360
+ var import_common3 = require("@meshsdk/common");
361
+
362
+ // src/utils/deserializer.ts
363
+ var import_core2 = require("@cardano-sdk/core");
364
+ var import_crypto = require("@cardano-sdk/crypto");
365
+ var import_util2 = require("@cardano-sdk/util");
366
+ var import_common2 = require("@meshsdk/common");
367
+ var deserializeAddress = (address) => {
368
+ const _address = Address.fromString(address);
369
+ if (_address === null) throw new Error("Invalid address");
370
+ return _address;
371
+ };
372
+ var deserializeEd25519KeyHash = (ed25519KeyHash) => Ed25519KeyHash2.fromBytes((0, import_common2.toBytes)(ed25519KeyHash));
373
+ var deserializeDataHash = (dataHash) => DatumHash.fromHexBlob((0, import_util2.HexBlob)(dataHash));
374
+ var deserializePlutusData = (plutusData) => PlutusData.fromCbor((0, import_util2.HexBlob)(plutusData));
375
+ var deserializePlutusScript = (plutusScript, version) => {
376
+ switch (version) {
377
+ case "V1":
378
+ return PlutusV1Script.fromCbor((0, import_util2.HexBlob)(plutusScript));
379
+ case "V2":
380
+ return PlutusV2Script.fromCbor((0, import_util2.HexBlob)(plutusScript));
381
+ case "V3":
382
+ return PlutusV3Script.fromCbor((0, import_util2.HexBlob)(plutusScript));
383
+ default:
384
+ throw new Error("Invalid Plutus script version");
385
+ }
386
+ };
387
+ var deserializeNativeScript = (nativeScript) => NativeScript.fromCbor((0, import_util2.HexBlob)(nativeScript));
388
+ var deserializeScriptHash = (scriptHash) => ScriptHash.fromEd25519KeyHashHex((0, import_crypto.Ed25519KeyHashHex)(scriptHash));
389
+ var deserializeScriptRef = (scriptRef) => Script.fromCbor((0, import_util2.HexBlob)(scriptRef));
390
+ var deserializeTxUnspentOutput = (txUnspentOutput) => TransactionUnspentOutput.fromCbor((0, import_util2.HexBlob)(txUnspentOutput));
391
+ var deserializeValue = (value) => Value.fromCbor((0, import_util2.HexBlob)(value));
392
+ var deserializeTx = (tx) => Transaction.fromCbor((0, import_core2.TxCBOR)(tx));
393
+ var deserializeTxHash = (txHash) => TransactionId.fromHexBlob((0, import_util2.HexBlob)(txHash));
394
+
395
+ // src/utils/converter.ts
396
+ var toAddress = (bech32) => Address.fromBech32(bech32);
397
+ var toBaseAddress = (bech32) => {
398
+ return BaseAddress.fromAddress(toAddress(bech32));
399
+ };
400
+ var toEnterpriseAddress = (bech32) => {
401
+ return EnterpriseAddress.fromAddress(toAddress(bech32));
402
+ };
403
+ var toRewardAddress = (bech32) => RewardAddress.fromAddress(toAddress(bech32));
404
+ var fromTxUnspentOutput = (txUnspentOutput) => {
405
+ const dataHash = txUnspentOutput.output().datum() ? txUnspentOutput.output().datum()?.toCbor().toString() : void 0;
406
+ const scriptRef = txUnspentOutput.output().scriptRef() ? txUnspentOutput.output().scriptRef()?.toCbor().toString() : void 0;
407
+ const plutusData = txUnspentOutput.output().datum()?.asInlineData() ? txUnspentOutput.output().datum()?.asInlineData()?.toCbor().toString() : void 0;
408
+ return {
409
+ input: {
410
+ outputIndex: Number(txUnspentOutput.input().index()),
411
+ txHash: txUnspentOutput.input().transactionId()
412
+ },
413
+ output: {
414
+ address: txUnspentOutput.output().address().toBech32(),
415
+ amount: fromValue(txUnspentOutput.output().amount()),
416
+ dataHash,
417
+ // todo not sure if correct
418
+ plutusData,
419
+ // todo not sure if correct
420
+ scriptRef
421
+ // todo not sure if correct
422
+ }
423
+ };
424
+ };
425
+ var toTxUnspentOutput = (utxo) => {
426
+ const txInput = new TransactionInput(
427
+ deserializeTxHash(utxo.input.txHash),
428
+ BigInt(utxo.input.outputIndex)
429
+ );
430
+ const txOutput = new TransactionOutput(
431
+ toAddress(utxo.output.address),
432
+ toValue(utxo.output.amount)
433
+ );
434
+ if (utxo.output.dataHash !== void 0) {
435
+ txOutput.setDatum(
436
+ Datum.fromCore(deserializeDataHash(utxo.output.dataHash))
437
+ );
438
+ }
439
+ if (utxo.output.plutusData !== void 0) {
440
+ const plutusData = deserializePlutusData(utxo.output.plutusData);
441
+ const datum = new import_core3.Serialization.Datum(void 0, plutusData);
442
+ txOutput.setDatum(datum);
443
+ }
444
+ if (utxo.output.scriptRef !== void 0) {
445
+ txOutput.setScriptRef(deserializeScriptRef(utxo.output.scriptRef));
446
+ }
447
+ return new TransactionUnspentOutput(txInput, txOutput);
448
+ };
449
+ var addressToBech32 = (address) => {
450
+ return address.toBech32();
451
+ };
452
+ var fromValue = (value) => {
453
+ const assets = [
454
+ { unit: "lovelace", quantity: value.coin().toString() }
455
+ ];
456
+ const multiAsset = value.multiasset();
457
+ if (multiAsset !== void 0) {
458
+ const _assets = Array.from(multiAsset.keys());
459
+ for (let i = 0; i < _assets.length; i += 1) {
460
+ const assetId = _assets[i];
461
+ if (assetId !== void 0) {
462
+ const assetQuantity = multiAsset.get(assetId);
463
+ if (assetQuantity !== void 0) {
464
+ assets.push({
465
+ unit: assetId,
466
+ quantity: assetQuantity.toString()
467
+ });
468
+ }
469
+ }
470
+ }
471
+ }
472
+ return assets;
473
+ };
474
+ var toScriptRef = (script) => {
475
+ if ("code" in script) {
476
+ const plutusScript = deserializePlutusScript(script.code, script.version);
477
+ if (plutusScript instanceof PlutusV1Script)
478
+ return Script.newPlutusV1Script(plutusScript);
479
+ if (plutusScript instanceof PlutusV2Script)
480
+ return Script.newPlutusV2Script(plutusScript);
481
+ if (plutusScript instanceof PlutusV3Script)
482
+ return Script.newPlutusV3Script(plutusScript);
483
+ }
484
+ return Script.newNativeScript(toNativeScript(script));
485
+ };
486
+ var fromScriptRef = (scriptRef) => {
487
+ const script = Script.fromCbor((0, import_util3.HexBlob)(scriptRef));
488
+ const plutusScriptCodeV3 = script.asPlutusV3()?.toCbor().toString();
489
+ if (plutusScriptCodeV3) {
490
+ return {
491
+ code: plutusScriptCodeV3,
492
+ version: "V3"
493
+ };
494
+ }
495
+ const plutusScriptCodeV2 = script.asPlutusV2()?.toCbor().toString();
496
+ if (plutusScriptCodeV2) {
497
+ return {
498
+ code: plutusScriptCodeV2,
499
+ version: "V2"
500
+ };
501
+ }
502
+ const plutusScriptCodeV1 = script.asPlutusV1()?.toCbor().toString();
503
+ if (plutusScriptCodeV1) {
504
+ return {
505
+ code: plutusScriptCodeV1,
506
+ version: "V1"
507
+ };
508
+ }
509
+ const nativeScript = script.asNative();
510
+ if (!nativeScript) {
511
+ throw new Error("Invalid script");
512
+ }
513
+ return fromNativeScript(nativeScript);
514
+ };
515
+ var fromNativeScript = (script) => {
516
+ const fromNativeScripts = (scripts) => {
517
+ const nativeScripts = new Array();
518
+ for (let index = 0; index < scripts.length; index += 1) {
519
+ const script2 = scripts[index];
520
+ if (script2) {
521
+ nativeScripts.push(fromNativeScript(script2));
522
+ }
523
+ }
524
+ return nativeScripts;
525
+ };
526
+ switch (script.kind()) {
527
+ case RequireAllOf: {
528
+ const scriptAll = script.asScriptAll();
529
+ return {
530
+ type: "all",
531
+ scripts: fromNativeScripts(scriptAll.nativeScripts())
532
+ };
533
+ }
534
+ case RequireAnyOf: {
535
+ const scriptAny = script.asScriptAny();
536
+ return {
537
+ type: "any",
538
+ scripts: fromNativeScripts(scriptAny.nativeScripts())
539
+ };
540
+ }
541
+ case RequireNOf: {
542
+ const scriptNOfK = script.asScriptNOfK();
543
+ return {
544
+ type: "atLeast",
545
+ required: scriptNOfK.required(),
546
+ scripts: fromNativeScripts(scriptNOfK.nativeScripts())
547
+ };
548
+ }
549
+ case RequireTimeAfter: {
550
+ const timelockStart = script.asTimelockStart();
551
+ return {
552
+ type: "after",
553
+ slot: timelockStart.slot().toString()
554
+ };
555
+ }
556
+ case RequireTimeBefore: {
557
+ const timelockExpiry = script.asTimelockExpiry();
558
+ return {
559
+ type: "before",
560
+ slot: timelockExpiry.slot().toString()
561
+ };
562
+ }
563
+ case RequireSignature: {
564
+ const scriptPubkey = script.asScriptPubkey();
565
+ return {
566
+ type: "sig",
567
+ keyHash: scriptPubkey.keyHash().toString()
568
+ };
569
+ }
570
+ default:
571
+ throw new Error(`Script Kind: ${script.kind()}, is not supported`);
572
+ }
573
+ };
574
+ var toNativeScript = (script) => {
575
+ const toNativeScripts = (scripts) => {
576
+ const nativeScripts = [];
577
+ scripts.forEach((script2) => {
578
+ nativeScripts.push(toNativeScript(script2));
579
+ });
580
+ return nativeScripts;
581
+ };
582
+ switch (script.type) {
583
+ case "all":
584
+ return NativeScript.newScriptAll(
585
+ new import_core3.Serialization.ScriptAll(toNativeScripts(script.scripts))
586
+ );
587
+ case "any":
588
+ return NativeScript.newScriptAny(
589
+ new import_core3.Serialization.ScriptAny(toNativeScripts(script.scripts))
590
+ );
591
+ case "atLeast":
592
+ return NativeScript.newScriptNOfK(
593
+ new import_core3.Serialization.ScriptNOfK(
594
+ toNativeScripts(script.scripts),
595
+ script.required
596
+ )
597
+ );
598
+ case "after":
599
+ return NativeScript.newTimelockStart(
600
+ new import_core3.Serialization.TimelockStart(Slot(parseInt(script.slot)))
601
+ );
602
+ case "before":
603
+ return NativeScript.newTimelockExpiry(
604
+ new import_core3.Serialization.TimelockExpiry(Slot(parseInt(script.slot)))
605
+ );
606
+ case "sig":
607
+ return NativeScript.newScriptPubkey(
608
+ new import_core3.Serialization.ScriptPubkey(
609
+ import_crypto2.Ed25519KeyHash.fromBytes((0, import_common3.toBytes)(script.keyHash)).hex()
610
+ )
611
+ );
612
+ }
613
+ };
614
+ var toPlutusData = (data) => {
615
+ const toPlutusList = (data2) => {
616
+ const plutusList = new PlutusList();
617
+ data2.forEach((element) => {
618
+ plutusList.add(toPlutusData(element));
619
+ });
620
+ return plutusList;
621
+ };
622
+ switch (typeof data) {
623
+ case "string":
624
+ return PlutusData.newBytes((0, import_common3.toBytes)(data));
625
+ case "number":
626
+ return PlutusData.newInteger(BigInt(data));
627
+ case "bigint":
628
+ return PlutusData.newInteger(BigInt(data));
629
+ case "object":
630
+ if (data instanceof Array) {
631
+ const plutusList = toPlutusList(data);
632
+ return PlutusData.newList(plutusList);
633
+ } else if (data instanceof Map) {
634
+ const plutusMap = new PlutusMap();
635
+ data.forEach((value, key) => {
636
+ plutusMap.insert(toPlutusData(key), toPlutusData(value));
637
+ });
638
+ return PlutusData.newMap(plutusMap);
639
+ } else {
640
+ return PlutusData.newConstrPlutusData(
641
+ new ConstrPlutusData(
642
+ BigInt(data.alternative),
643
+ toPlutusList(data.fields)
644
+ )
645
+ );
646
+ }
647
+ }
648
+ };
649
+ var toValue = (assets) => {
650
+ const multiAsset = /* @__PURE__ */ new Map();
651
+ assets.filter((asset) => asset.unit !== "lovelace").forEach((asset) => {
652
+ multiAsset.set(AssetId(asset.unit), BigInt(asset.quantity));
653
+ });
654
+ const lovelace = assets.find((asset) => asset.unit === "lovelace");
655
+ const value = new Value(BigInt(lovelace ? lovelace.quantity : 0));
656
+ if (assets.length > 1 || !lovelace) {
657
+ value.setMultiasset(multiAsset);
658
+ }
659
+ return value;
660
+ };
661
+
662
+ // src/utils/value.ts
663
+ function mergeValue(a, b) {
664
+ const ma = a.multiasset() ?? /* @__PURE__ */ new Map();
665
+ b.multiasset()?.forEach((v, k) => {
666
+ const newVal = (ma.get(k) ?? 0n) + v;
667
+ if (newVal == 0n) {
668
+ ma.delete(k);
669
+ } else {
670
+ ma.set(k, newVal);
671
+ }
672
+ });
673
+ return new Value(
674
+ BigInt(a.coin()) + BigInt(b.coin()),
675
+ ma.size > 0 ? ma : void 0
676
+ );
677
+ }
678
+ function negateValue(v) {
679
+ const entries = v.multiasset()?.entries();
680
+ const tokenMap = /* @__PURE__ */ new Map();
681
+ if (entries) {
682
+ for (const entry of entries) {
683
+ tokenMap.set(entry[0], -entry[1]);
684
+ }
685
+ }
686
+ return new Value(-v.coin(), tokenMap);
687
+ }
688
+ function subValue(a, b) {
689
+ return mergeValue(a, negateValue(b));
690
+ }
691
+ function negatives(v) {
692
+ const entries = v.multiasset()?.entries();
693
+ const coin = v.coin() < 0n ? v.coin() : 0n;
694
+ const tokenMap = /* @__PURE__ */ new Map();
695
+ if (entries) {
696
+ for (const entry of entries) {
697
+ if (entry[1] < 0n) {
698
+ tokenMap.set(entry[0], entry[1]);
699
+ }
700
+ }
701
+ }
702
+ return new Value(coin, tokenMap);
703
+ }
704
+ function assetTypes(v) {
705
+ let count = v.coin() == 0n ? 0 : 1;
706
+ const entries = v.multiasset();
707
+ if (entries) {
708
+ entries.forEach(() => {
709
+ count += 1;
710
+ });
711
+ }
712
+ return count;
713
+ }
714
+ function empty(v) {
715
+ return assetTypes(v) == 0;
716
+ }
717
+
718
+ // src/utils/encoding.ts
719
+ var hexToBytes = (hex) => Buffer.from(hex, "hex");
720
+
721
+ // src/resolvers/index.ts
722
+ var resolveDataHash = (data) => {
723
+ const plutusData = toPlutusData(data);
724
+ return plutusData.hash().toString();
725
+ };
726
+ var resolveNativeScriptAddress = (script, networkId = 0) => {
727
+ const nativeScript = toNativeScript(script);
728
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
729
+ hash: nativeScript.hash(),
730
+ type: import_core4.Cardano.CredentialType.ScriptHash
731
+ });
732
+ return enterpriseAddress.toAddress().toBech32();
733
+ };
734
+ var resolveNativeScriptHash = (script) => {
735
+ return toNativeScript(script).hash().toString();
736
+ };
737
+ var resolvePaymentKeyHash = (bech32) => {
738
+ try {
739
+ const paymentKeyHash = [
740
+ toBaseAddress(bech32)?.getPaymentCredential().hash,
741
+ toEnterpriseAddress(bech32)?.getPaymentCredential().hash
742
+ ].find((kh) => kh !== void 0);
743
+ if (paymentKeyHash !== void 0) return paymentKeyHash.toString();
744
+ throw new Error(
745
+ `Couldn't resolve payment key hash from address: ${bech32}`
746
+ );
747
+ } catch (error) {
748
+ throw new Error(
749
+ `An error occurred during resolvePaymentKeyHash: ${error}.`
750
+ );
751
+ }
752
+ };
753
+ var resolvePlutusScriptAddress = (script, networkId = 0) => {
754
+ const plutusScript = deserializePlutusScript(script.code, script.version);
755
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
756
+ hash: plutusScript.hash(),
757
+ type: import_core4.Cardano.CredentialType.ScriptHash
758
+ });
759
+ return enterpriseAddress.toAddress().toBech32();
760
+ };
761
+ var resolvePlutusScriptHash = (bech32) => {
762
+ try {
763
+ const enterpriseAddress = toEnterpriseAddress(bech32);
764
+ const scriptHash = enterpriseAddress?.getPaymentCredential().hash;
765
+ if (scriptHash !== void 0) return scriptHash.toString();
766
+ throw new Error(`Couldn't resolve script hash from address: ${bech32}`);
767
+ } catch (error) {
768
+ throw new Error(`An error occurred during resolveScriptHash: ${error}.`);
769
+ }
770
+ };
771
+ var resolvePoolId = (hash2) => {
772
+ return Ed25519KeyHashHex2(hash2).toString();
773
+ };
774
+ var resolvePrivateKey = (words) => {
775
+ return "not implemented";
776
+ };
777
+ var resolveScriptRef = (script) => {
778
+ return toScriptRef(script).toCbor().toString();
779
+ };
780
+ var resolveRewardAddress = (bech32) => {
781
+ try {
782
+ const address = toAddress(bech32);
783
+ const baseAddress = toBaseAddress(bech32);
784
+ const stakeKeyHash = baseAddress?.getStakeCredential().hash;
785
+ if (stakeKeyHash !== void 0)
786
+ return buildRewardAddress(address.getNetworkId(), stakeKeyHash).toAddress().toBech32();
787
+ throw new Error(`Couldn't resolve reward address from address: ${bech32}`);
788
+ } catch (error) {
789
+ throw new Error(`An error occurred during resolveRewardAddress: ${error}.`);
790
+ }
791
+ };
792
+ var resolveStakeKeyHash = (bech32) => {
793
+ try {
794
+ const stakeKeyHash = [
795
+ toBaseAddress(bech32)?.getStakeCredential().hash,
796
+ toRewardAddress(bech32)?.getPaymentCredential().hash
797
+ ].find((kh) => kh !== void 0);
798
+ if (stakeKeyHash !== void 0) return stakeKeyHash.toString();
799
+ throw new Error(`Couldn't resolve stake key hash from address: ${bech32}`);
800
+ } catch (error) {
801
+ throw new Error(`An error occurred during resolveStakeKeyHash: ${error}.`);
802
+ }
803
+ };
804
+ var resolveTxHash = (txHex) => {
805
+ const txBody = deserializeTx(txHex).body();
806
+ const hash2 = (0, import_crypto3.blake2b)(import_crypto3.blake2b.BYTES).update(hexToBytes(txBody.toCbor())).digest();
807
+ return import_core4.Cardano.TransactionId.fromHexBlob(import_util4.HexBlob.fromBytes(hash2));
808
+ };
809
+
810
+ // src/serializer/index.ts
811
+ var import_core6 = require("@cardano-sdk/core");
812
+ var import_util6 = require("@cardano-sdk/util");
813
+ var import_common4 = require("@meshsdk/common");
814
+
815
+ // src/utils/script-data-hash.ts
816
+ var import_core5 = require("@cardano-sdk/core");
817
+ var Crypto2 = __toESM(require("@cardano-sdk/crypto"));
818
+ var import_crypto4 = require("@cardano-sdk/crypto");
819
+ var import_util5 = require("@cardano-sdk/util");
820
+ var CBOR_EMPTY_LIST = new Uint8Array([128]);
821
+ var CBOR_EMPTY_MAP = new Uint8Array([160]);
822
+ var getCborEncodedArray = (items) => {
823
+ const writer = new import_core5.Serialization.CborWriter();
824
+ writer.writeStartArray(items.length);
825
+ for (const item of items) {
826
+ writer.writeEncodedValue(Buffer.from(item.toCbor(), "hex"));
827
+ }
828
+ return writer.encode();
829
+ };
830
+ var hashScriptData = (costModels, redemeers, datums) => {
831
+ const writer = new import_core5.Serialization.CborWriter();
832
+ if (datums && datums.length > 0 && (!redemeers || redemeers.length === 0)) {
833
+ writer.writeEncodedValue(CBOR_EMPTY_LIST);
834
+ writer.writeEncodedValue(getCborEncodedArray(datums));
835
+ writer.writeEncodedValue(CBOR_EMPTY_MAP);
836
+ } else {
837
+ if (!redemeers || redemeers.length === 0) return void 0;
838
+ writer.writeEncodedValue(getCborEncodedArray(redemeers));
839
+ if (datums && datums.length > 0)
840
+ writer.writeEncodedValue(getCborEncodedArray(datums));
841
+ writer.writeEncodedValue(
842
+ Buffer.from(costModels.languageViewsEncoding(), "hex")
843
+ );
844
+ }
845
+ return import_crypto4.Hash32ByteBase16.fromHexBlob(
846
+ import_util5.HexBlob.fromBytes(
847
+ Crypto2.blake2b(Crypto2.blake2b.BYTES).update(writer.encode()).digest()
848
+ )
849
+ );
850
+ };
851
+
852
+ // src/serializer/index.ts
853
+ var CardanoSDKSerializer = class {
854
+ constructor() {
855
+ this.utxoContext = /* @__PURE__ */ new Map();
856
+ this.redeemerContext = /* @__PURE__ */ new Map();
857
+ this.scriptsProvided = /* @__PURE__ */ new Set();
858
+ this.datumsProvided = /* @__PURE__ */ new Set();
859
+ this.usedLanguages = {
860
+ [0]: false,
861
+ [1]: false,
862
+ [2]: false
863
+ };
864
+ this.deserializer = {
865
+ key: {
866
+ deserializeAddress: function(bech32) {
867
+ throw new Error("Function not implemented.");
868
+ }
869
+ },
870
+ script: {
871
+ deserializeNativeScript: function(script) {
872
+ throw new Error("Function not implemented.");
873
+ },
874
+ deserializePlutusScript: function(script) {
875
+ throw new Error("Function not implemented.");
876
+ }
877
+ }
878
+ };
879
+ this.resolver = {
880
+ keys: {
881
+ // resolvePaymentKeyHash: function (bech32: string): string {
882
+ // const cardanoAddress = toAddress(bech32);
883
+ // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
884
+ // CredentialType.KeyHash
885
+ // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
886
+ // : "";
887
+ // },
888
+ // resolvePlutusScriptHash: function (bech32: string): string {
889
+ // const cardanoAddress = toAddress(bech32);
890
+ // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
891
+ // CredentialType.ScriptHash
892
+ // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
893
+ // : "";
894
+ // },
895
+ resolveStakeKeyHash: function(bech32) {
896
+ const cardanoAddress = toAddress(bech32);
897
+ return cardanoAddress.asReward()?.getPaymentCredential().type === CredentialType.KeyHash ? cardanoAddress.asReward().getPaymentCredential().hash : "";
898
+ },
899
+ // resolveStakeScriptHash(bech32: string): string {
900
+ // const cardanoAddress = toAddress(bech32);
901
+ // return cardanoAddress.asReward()?.getPaymentCredential().type ===
902
+ // CredentialType.ScriptHash
903
+ // ? cardanoAddress.asReward()!.getPaymentCredential().hash
904
+ // : "";
905
+ // },
906
+ resolvePrivateKey: function(words) {
907
+ throw new Error("Function not implemented.");
908
+ },
909
+ resolveRewardAddress: function(bech32) {
910
+ throw new Error("Function not implemented.");
911
+ },
912
+ resolveEd25519KeyHash: function(bech32) {
913
+ throw new Error("Function not implemented.");
914
+ }
915
+ },
916
+ tx: {
917
+ resolveTxHash: function(txHex) {
918
+ return Transaction.fromCbor((0, import_core6.TxCBOR)(txHex)).getId();
919
+ }
920
+ },
921
+ data: {
922
+ resolveDataHash: function(data) {
923
+ throw new Error("Function not implemented.");
924
+ }
925
+ },
926
+ script: {
927
+ // resolveNativeScript: function (script: CommonNativeScript): string {
928
+ // return toNativeScript(script).toCbor();
929
+ // },
930
+ resolveScriptRef: function(script) {
931
+ throw new Error("Function not implemented.");
932
+ }
933
+ },
934
+ pool: {
935
+ resolvePoolId: function(hash2) {
936
+ throw new Error("Function not implemented.");
937
+ }
938
+ }
939
+ };
940
+ this.serializeTxBody = (txBuilderBody, protocolParams) => {
941
+ const {
942
+ inputs,
943
+ outputs,
944
+ extraInputs,
945
+ selectionThreshold,
946
+ collaterals,
947
+ referenceInputs,
948
+ mints,
949
+ changeAddress,
950
+ certificates,
951
+ validityRange,
952
+ requiredSignatures,
953
+ metadata
954
+ } = txBuilderBody;
955
+ mints.sort((a, b) => a.policyId.localeCompare(b.policyId));
956
+ inputs.sort((a, b) => {
957
+ if (a.txIn.txHash === b.txIn.txHash) {
958
+ return a.txIn.txIndex - b.txIn.txIndex;
959
+ } else {
960
+ return a.txIn.txHash.localeCompare(b.txIn.txHash);
961
+ }
962
+ });
963
+ this.addAllInputs(inputs);
964
+ this.addAllCollateralInputs(collaterals);
965
+ this.buildWitnessSet();
966
+ this.balanceTx(changeAddress, requiredSignatures.length, protocolParams);
967
+ return new Transaction(this.txBody, this.txWitnessSet).toCbor();
968
+ };
969
+ this.addSigningKeys = (txHex, signingKeys) => {
970
+ let cardanoTx = Transaction.fromCbor((0, import_core6.TxCBOR)(txHex));
971
+ let currentWitnessSet = cardanoTx.witnessSet();
972
+ let currentWitnessSetVkeys = currentWitnessSet.vkeys();
973
+ let currentWitnessSetVkeysValues = currentWitnessSetVkeys ? [...currentWitnessSetVkeys.values()] : [];
974
+ for (let i = 0; i < signingKeys.length; i++) {
975
+ let keyHex = signingKeys[i];
976
+ if (keyHex) {
977
+ if (keyHex.length === 68 && keyHex.substring(0, 4) === "5820") {
978
+ keyHex = keyHex.substring(4);
979
+ }
980
+ const cardanoSigner = new PrivateKey(Buffer.from(keyHex, "hex"), false);
981
+ const signature = cardanoSigner.sign(
982
+ Buffer.from(cardanoTx.getId(), "hex")
983
+ );
984
+ currentWitnessSetVkeysValues.push(
985
+ new VkeyWitness(
986
+ Ed25519PublicKeyHex2(
987
+ cardanoSigner.toPublicKey().toBytes().toString("hex")
988
+ ),
989
+ Ed25519SignatureHex2(signature.toString("hex"))
990
+ )
991
+ );
992
+ }
993
+ }
994
+ currentWitnessSet.setVkeys(
995
+ import_core6.Serialization.CborSet.fromCore(
996
+ currentWitnessSetVkeysValues.map((vkw) => vkw.toCore()),
997
+ VkeyWitness.fromCore
998
+ )
999
+ );
1000
+ cardanoTx.setWitnessSet(currentWitnessSet);
1001
+ return cardanoTx.toCbor();
1002
+ };
1003
+ this.addAllInputs = (inputs) => {
1004
+ for (let i = 0; i < inputs.length; i += 1) {
1005
+ const currentTxIn = inputs[i];
1006
+ if (!currentTxIn) continue;
1007
+ switch (currentTxIn.type) {
1008
+ case "PubKey":
1009
+ this.addTxIn(currentTxIn);
1010
+ break;
1011
+ case "Script":
1012
+ this.addScriptTxIn(
1013
+ currentTxIn
1014
+ );
1015
+ break;
1016
+ }
1017
+ }
1018
+ };
1019
+ this.addTxIn = (currentTxIn) => {
1020
+ let cardanoTxIn = new TransactionInput(
1021
+ TransactionId(currentTxIn.txIn.txHash),
1022
+ BigInt(currentTxIn.txIn.txIndex)
1023
+ );
1024
+ const inputs = this.txBody.inputs();
1025
+ const txInputsList = [...inputs.values()];
1026
+ if (txInputsList.find((input) => {
1027
+ input.index() == cardanoTxIn.index() && input.transactionId == cardanoTxIn.transactionId;
1028
+ })) {
1029
+ throw new Error("Duplicate input added to tx body");
1030
+ }
1031
+ txInputsList.push(cardanoTxIn);
1032
+ inputs.setValues(txInputsList);
1033
+ const cardanoTxOut = new TransactionOutput(
1034
+ Address.fromBech32(currentTxIn.txIn.address),
1035
+ toValue(currentTxIn.txIn.amount)
1036
+ );
1037
+ this.utxoContext.set(cardanoTxIn, cardanoTxOut);
1038
+ this.txBody.setInputs(inputs);
1039
+ };
1040
+ this.addScriptTxIn = (currentTxIn) => {
1041
+ this.addTxIn({
1042
+ type: "PubKey",
1043
+ txIn: currentTxIn.txIn
1044
+ });
1045
+ if (!currentTxIn.scriptTxIn.scriptSource) {
1046
+ throw new Error("A script input had no script source");
1047
+ }
1048
+ if (!currentTxIn.scriptTxIn.datumSource) {
1049
+ throw new Error("A script input had no datum source");
1050
+ }
1051
+ if (!currentTxIn.scriptTxIn.redeemer) {
1052
+ throw new Error("A script input had no redeemer");
1053
+ }
1054
+ if (currentTxIn.scriptTxIn.scriptSource.type === "Provided") {
1055
+ switch (currentTxIn.scriptTxIn.scriptSource.script.version) {
1056
+ case "V1": {
1057
+ this.scriptsProvided.add(
1058
+ Script.newPlutusV1Script(
1059
+ PlutusV1Script.fromCbor(
1060
+ (0, import_util6.HexBlob)(currentTxIn.scriptTxIn.scriptSource.script.code)
1061
+ )
1062
+ )
1063
+ );
1064
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
1065
+ break;
1066
+ }
1067
+ case "V2": {
1068
+ this.scriptsProvided.add(
1069
+ Script.newPlutusV2Script(
1070
+ PlutusV2Script.fromCbor(
1071
+ (0, import_util6.HexBlob)(currentTxIn.scriptTxIn.scriptSource.script.code)
1072
+ )
1073
+ )
1074
+ );
1075
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
1076
+ break;
1077
+ }
1078
+ case "V3": {
1079
+ this.scriptsProvided.add(
1080
+ Script.newPlutusV3Script(
1081
+ PlutusV3Script.fromCbor(
1082
+ (0, import_util6.HexBlob)(currentTxIn.scriptTxIn.scriptSource.script.code)
1083
+ )
1084
+ )
1085
+ );
1086
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
1087
+ break;
1088
+ }
1089
+ }
1090
+ } else if (currentTxIn.scriptTxIn.scriptSource.type === "Inline") {
1091
+ let referenceInputs = this.txBody.referenceInputs() ? this.txBody.referenceInputs() : import_core6.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
1092
+ let referenceInputsList = [...referenceInputs.values()];
1093
+ referenceInputsList.push(
1094
+ new TransactionInput(
1095
+ TransactionId(currentTxIn.scriptTxIn.scriptSource.txHash),
1096
+ BigInt(currentTxIn.scriptTxIn.scriptSource.txIndex)
1097
+ )
1098
+ );
1099
+ referenceInputs.setValues(referenceInputsList);
1100
+ this.txBody.setReferenceInputs(referenceInputs);
1101
+ switch (currentTxIn.scriptTxIn.scriptSource.version) {
1102
+ case "V1": {
1103
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
1104
+ break;
1105
+ }
1106
+ case "V2": {
1107
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
1108
+ break;
1109
+ }
1110
+ case "V3": {
1111
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
1112
+ break;
1113
+ }
1114
+ }
1115
+ }
1116
+ if (currentTxIn.scriptTxIn.datumSource.type === "Provided") {
1117
+ this.datumsProvided.add(
1118
+ toPlutusData(currentTxIn.scriptTxIn.datumSource.data.content)
1119
+ // TODO: handle json / raw datum
1120
+ );
1121
+ } else if (currentTxIn.scriptTxIn.datumSource.type === "Inline") {
1122
+ let referenceInputs = this.txBody.referenceInputs() ? this.txBody.referenceInputs() : import_core6.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
1123
+ let referenceInputsList = [...referenceInputs.values()];
1124
+ referenceInputsList.push(
1125
+ new TransactionInput(
1126
+ TransactionId(currentTxIn.txIn.txHash),
1127
+ BigInt(currentTxIn.txIn.txIndex)
1128
+ )
1129
+ );
1130
+ referenceInputs.setValues(referenceInputsList);
1131
+ this.txBody.setReferenceInputs(referenceInputs);
1132
+ }
1133
+ let cardanoTxIn = new TransactionInput(
1134
+ TransactionId(currentTxIn.txIn.txHash),
1135
+ BigInt(currentTxIn.txIn.txIndex)
1136
+ );
1137
+ let exUnits = currentTxIn.scriptTxIn.redeemer.exUnits;
1138
+ this.redeemerContext.set(
1139
+ cardanoTxIn,
1140
+ new Redeemer(
1141
+ RedeemerTag.Spend,
1142
+ BigInt(0),
1143
+ toPlutusData(currentTxIn.scriptTxIn.redeemer.data.content),
1144
+ // TODO: handle json / raw datum
1145
+ new ExUnits(BigInt(exUnits.mem), BigInt(exUnits.steps))
1146
+ )
1147
+ );
1148
+ };
1149
+ this.addSimpleScriptTxIn = (currentTxIn) => {
1150
+ };
1151
+ this.addAllCollateralInputs = (collaterals) => {
1152
+ for (let i = 0; i < collaterals.length; i++) {
1153
+ this.addCollateralInput(
1154
+ collaterals[i]
1155
+ );
1156
+ }
1157
+ };
1158
+ this.addCollateralInput = (collateral) => {
1159
+ let cardanoTxIn = new TransactionInput(
1160
+ TransactionId(collateral.txIn.txHash),
1161
+ BigInt(collateral.txIn.txIndex)
1162
+ );
1163
+ const collateralInputs = this.txBody.collateral() ? this.txBody.collateral() : import_core6.Serialization.CborSet.fromCore([], TransactionInput.fromCore);
1164
+ const collateralInputsList = [
1165
+ ...collateralInputs.values()
1166
+ ];
1167
+ if (collateralInputsList.find((input) => {
1168
+ input.index() == cardanoTxIn.index() && input.transactionId == cardanoTxIn.transactionId;
1169
+ })) {
1170
+ throw new Error("Duplicate input added to tx body");
1171
+ }
1172
+ collateralInputsList.push(cardanoTxIn);
1173
+ collateralInputs.setValues(collateralInputsList);
1174
+ const cardanoTxOut = new TransactionOutput(
1175
+ Address.fromBech32(collateral.txIn.address),
1176
+ toValue(collateral.txIn.amount)
1177
+ );
1178
+ this.utxoContext.set(cardanoTxIn, cardanoTxOut);
1179
+ this.txBody.setCollateral(collateralInputs);
1180
+ };
1181
+ this.buildWitnessSet = () => {
1182
+ const inputs = this.txBody.inputs();
1183
+ for (let i = 0; i < inputs.size(); i += 1) {
1184
+ const input = inputs.values().at(i);
1185
+ if (input) {
1186
+ let redeemer = this.redeemerContext.get(input);
1187
+ if (redeemer) {
1188
+ redeemer.setIndex(BigInt(i));
1189
+ }
1190
+ }
1191
+ }
1192
+ let redeemers = this.txWitnessSet.redeemers() ? this.txWitnessSet.redeemers() : Redeemers.fromCore([]);
1193
+ let redeemersList = [...redeemers.values()];
1194
+ this.redeemerContext.forEach((redeemer) => {
1195
+ redeemersList.push(redeemer);
1196
+ });
1197
+ redeemers.setValues(redeemersList);
1198
+ this.txWitnessSet.setRedeemers(redeemers);
1199
+ let nativeScripts = this.txWitnessSet.nativeScripts() ? this.txWitnessSet.nativeScripts() : import_core6.Serialization.CborSet.fromCore([], NativeScript.fromCore);
1200
+ let v1Scripts = this.txWitnessSet.plutusV1Scripts() ? this.txWitnessSet.plutusV1Scripts() : import_core6.Serialization.CborSet.fromCore([], PlutusV1Script.fromCore);
1201
+ let v2Scripts = this.txWitnessSet.plutusV2Scripts() ? this.txWitnessSet.plutusV2Scripts() : import_core6.Serialization.CborSet.fromCore([], PlutusV2Script.fromCore);
1202
+ let v3Scripts = this.txWitnessSet.plutusV3Scripts() ? this.txWitnessSet.plutusV3Scripts() : import_core6.Serialization.CborSet.fromCore([], PlutusV3Script.fromCore);
1203
+ this.scriptsProvided.forEach((script) => {
1204
+ if (script.asNative() !== void 0) {
1205
+ let nativeScriptsList = [...nativeScripts.values()];
1206
+ nativeScriptsList.push(script.asNative());
1207
+ nativeScripts.setValues(nativeScriptsList);
1208
+ } else if (script.asPlutusV1() !== void 0) {
1209
+ let v1ScriptsList = [...v1Scripts.values()];
1210
+ v1ScriptsList.push(script.asPlutusV1());
1211
+ v1Scripts.setValues(v1ScriptsList);
1212
+ } else if (script.asPlutusV2() !== void 0) {
1213
+ let v2ScriptsList = [...v2Scripts.values()];
1214
+ v2ScriptsList.push(script.asPlutusV2());
1215
+ v2Scripts.setValues(v2ScriptsList);
1216
+ } else if (script.asPlutusV3() !== void 0) {
1217
+ let v3ScriptsList = [...v3Scripts.values()];
1218
+ v3ScriptsList.push(script.asPlutusV3());
1219
+ v3Scripts.setValues(v3ScriptsList);
1220
+ }
1221
+ this.txWitnessSet.setNativeScripts(nativeScripts);
1222
+ this.txWitnessSet.setPlutusV1Scripts(v1Scripts);
1223
+ this.txWitnessSet.setPlutusV2Scripts(v2Scripts);
1224
+ this.txWitnessSet.setPlutusV3Scripts(v3Scripts);
1225
+ });
1226
+ let datums = this.txWitnessSet.plutusData() ? this.txWitnessSet.plutusData() : import_core6.Serialization.CborSet.fromCore([], PlutusData.fromCore);
1227
+ this.datumsProvided.forEach((datum) => {
1228
+ let datumsList = [...datums.values()];
1229
+ datumsList.push(datum);
1230
+ datums.setValues(datumsList);
1231
+ });
1232
+ this.txWitnessSet.setPlutusData(datums);
1233
+ let costModelV1 = import_core6.Serialization.CostModel.newPlutusV1(
1234
+ import_common4.DEFAULT_V1_COST_MODEL_LIST
1235
+ );
1236
+ let costModelV2 = import_core6.Serialization.CostModel.newPlutusV2(
1237
+ import_common4.DEFAULT_V2_COST_MODEL_LIST
1238
+ );
1239
+ let costModels = new import_core6.Serialization.Costmdls();
1240
+ if (this.usedLanguages[PlutusLanguageVersion.V1]) {
1241
+ costModels.insert(costModelV1);
1242
+ }
1243
+ if (this.usedLanguages[PlutusLanguageVersion.V2]) {
1244
+ costModels.insert(costModelV2);
1245
+ }
1246
+ if (this.usedLanguages[PlutusLanguageVersion.V3]) {
1247
+ }
1248
+ let scriptDataHash = hashScriptData(
1249
+ costModels,
1250
+ redeemers.size() > 0 ? [...redeemers.values()] : void 0,
1251
+ datums.size() > 0 ? [...datums.values()] : void 0
1252
+ );
1253
+ if (scriptDataHash) {
1254
+ this.txBody.setScriptDataHash(scriptDataHash);
1255
+ }
1256
+ };
1257
+ this.balanceTx = (changeAddress, numberOfRequiredWitnesses, protocolParams) => {
1258
+ if (changeAddress === "") {
1259
+ throw new Error("Can't balance tx without a change address");
1260
+ }
1261
+ const inputs = this.txBody.inputs().values();
1262
+ let remainingValue = new Value(BigInt(0));
1263
+ for (let i = 0; i < inputs.length; i++) {
1264
+ let input = inputs[i];
1265
+ if (!input) {
1266
+ throw new Error("Invalid input found");
1267
+ }
1268
+ const output = this.utxoContext.get(input);
1269
+ if (!output) {
1270
+ throw new Error(`Unable to resolve input: ${input.toCbor()}`);
1271
+ }
1272
+ remainingValue = mergeValue(remainingValue, output.amount());
1273
+ }
1274
+ const withdrawals = this.txBody.withdrawals();
1275
+ if (withdrawals) {
1276
+ withdrawals.forEach((coin) => {
1277
+ remainingValue = mergeValue(remainingValue, new Value(coin));
1278
+ });
1279
+ }
1280
+ remainingValue = mergeValue(
1281
+ remainingValue,
1282
+ new Value(BigInt(0), this.txBody.mint())
1283
+ );
1284
+ const currentOutputs = this.txBody.outputs();
1285
+ for (let i = 0; i < currentOutputs.length; i++) {
1286
+ let output = currentOutputs.at(i);
1287
+ if (output) {
1288
+ remainingValue = subValue(remainingValue, output.amount());
1289
+ }
1290
+ }
1291
+ if (remainingValue.coin() < 0 || !empty(negatives(remainingValue))) {
1292
+ throw new Error(`Not enough funds to satisfy outputs`);
1293
+ }
1294
+ currentOutputs.push(
1295
+ new TransactionOutput(Address.fromBech32(changeAddress), remainingValue)
1296
+ );
1297
+ this.txBody.setOutputs(currentOutputs);
1298
+ this.txBody.setFee(BigInt("10000000"));
1299
+ const dummyTx = this.createDummyTx(numberOfRequiredWitnesses);
1300
+ const fee = protocolParams.minFeeB + dummyTx.toCbor().length / 2 * Number(protocolParams.coinsPerUtxoSize);
1301
+ this.txBody.setFee(BigInt(fee));
1302
+ const changeOutput = currentOutputs.pop();
1303
+ if (!changeOutput) {
1304
+ throw new Error(
1305
+ "Somehow the output length was 0 after attempting to calculate fees"
1306
+ );
1307
+ }
1308
+ changeOutput.amount().setCoin(changeOutput.amount().coin() - BigInt(fee));
1309
+ currentOutputs.push(changeOutput);
1310
+ this.txBody.setOutputs(currentOutputs);
1311
+ };
1312
+ this.createDummyTx = (numberOfRequiredWitnesses) => {
1313
+ let dummyWitnessSet = new TransactionWitnessSet();
1314
+ const dummyVkeyWitnesses = [];
1315
+ for (let i = 0; i < numberOfRequiredWitnesses; i++) {
1316
+ dummyVkeyWitnesses.push([
1317
+ Ed25519PublicKeyHex2("0".repeat(64)),
1318
+ Ed25519SignatureHex2("0".repeat(128))
1319
+ ]);
1320
+ }
1321
+ dummyWitnessSet.setVkeys(
1322
+ import_core6.Serialization.CborSet.fromCore(dummyVkeyWitnesses, VkeyWitness.fromCore)
1323
+ );
1324
+ return new Transaction(this.txBody, dummyWitnessSet);
1325
+ };
1326
+ this.txBody = new TransactionBody(
1327
+ import_core6.Serialization.CborSet.fromCore([], TransactionInput.fromCore),
1328
+ [],
1329
+ BigInt(0),
1330
+ void 0
1331
+ );
1332
+ this.txWitnessSet = new TransactionWitnessSet();
1333
+ }
1334
+ serializeAddress(address, networkId) {
1335
+ throw new Error("Method not implemented.");
1336
+ }
1337
+ serializeData(data) {
1338
+ throw new Error("Method not implemented.");
1339
+ }
1340
+ };
1341
+
1342
+ // src/index.ts
1343
+ var CardanoSDKUtil = __toESM(require("@cardano-sdk/util"));
1344
+ var Crypto3 = __toESM(require("@cardano-sdk/crypto"));
1345
+ var CardanoSDK = __toESM(require("@cardano-sdk/core"));
1346
+ // Annotate the CommonJS export names for ESM import in node:
1347
+ 0 && (module.exports = {
1348
+ Address,
1349
+ AddressType,
1350
+ AssetFingerprint,
1351
+ AssetId,
1352
+ AssetName,
1353
+ BaseAddress,
1354
+ Bip32PrivateKey,
1355
+ Bip32PrivateKeyHex,
1356
+ Cardano,
1357
+ CardanoSDK,
1358
+ CardanoSDKSerializer,
1359
+ CardanoSDKUtil,
1360
+ CborSet,
1361
+ CborWriter,
1362
+ Certificate,
1363
+ CertificateType,
1364
+ ConstrPlutusData,
1365
+ CostModel,
1366
+ Costmdls,
1367
+ Credential,
1368
+ CredentialType,
1369
+ Crypto,
1370
+ Datum,
1371
+ DatumHash,
1372
+ DatumKind,
1373
+ Ed25519KeyHash,
1374
+ Ed25519KeyHashHex,
1375
+ Ed25519PrivateExtendedKeyHex,
1376
+ Ed25519PrivateNormalKeyHex,
1377
+ Ed25519PublicKey,
1378
+ Ed25519PublicKeyHex,
1379
+ Ed25519Signature,
1380
+ Ed25519SignatureHex,
1381
+ EnterpriseAddress,
1382
+ ExUnits,
1383
+ Hash,
1384
+ Hash28ByteBase16,
1385
+ Hash32ByteBase16,
1386
+ NativeScript,
1387
+ NetworkId,
1388
+ PaymentAddress,
1389
+ PlutusData,
1390
+ PlutusLanguageVersion,
1391
+ PlutusList,
1392
+ PlutusMap,
1393
+ PlutusV1Script,
1394
+ PlutusV2Script,
1395
+ PlutusV3Script,
1396
+ PolicyId,
1397
+ PoolId,
1398
+ PrivateKey,
1399
+ PublicKey,
1400
+ Redeemer,
1401
+ RedeemerPurpose,
1402
+ RedeemerTag,
1403
+ Redeemers,
1404
+ RequireAllOf,
1405
+ RequireAnyOf,
1406
+ RequireNOf,
1407
+ RequireSignature,
1408
+ RequireTimeAfter,
1409
+ RequireTimeBefore,
1410
+ RewardAccount,
1411
+ RewardAddress,
1412
+ Script,
1413
+ ScriptHash,
1414
+ ScriptPubkey,
1415
+ Serialization,
1416
+ Slot,
1417
+ StakeDelegation,
1418
+ StakeRegistration,
1419
+ Transaction,
1420
+ TransactionBody,
1421
+ TransactionId,
1422
+ TransactionInput,
1423
+ TransactionOutput,
1424
+ TransactionUnspentOutput,
1425
+ TransactionWitnessSet,
1426
+ Value,
1427
+ VkeyWitness,
1428
+ VrfVkBech32,
1429
+ addressToBech32,
1430
+ assetTypes,
1431
+ buildBaseAddress,
1432
+ buildBip32PrivateKey,
1433
+ buildEnterpriseAddress,
1434
+ buildKeys,
1435
+ buildRewardAddress,
1436
+ buildScriptPubkey,
1437
+ checkSignature,
1438
+ deserializeAddress,
1439
+ deserializeDataHash,
1440
+ deserializeEd25519KeyHash,
1441
+ deserializeNativeScript,
1442
+ deserializePlutusData,
1443
+ deserializePlutusScript,
1444
+ deserializeScriptHash,
1445
+ deserializeScriptRef,
1446
+ deserializeTx,
1447
+ deserializeTxHash,
1448
+ deserializeTxUnspentOutput,
1449
+ deserializeValue,
1450
+ empty,
1451
+ fromNativeScript,
1452
+ fromScriptRef,
1453
+ fromTxUnspentOutput,
1454
+ fromValue,
1455
+ mergeValue,
1456
+ negateValue,
1457
+ negatives,
1458
+ resolveDataHash,
1459
+ resolveNativeScriptAddress,
1460
+ resolveNativeScriptHash,
1461
+ resolvePaymentKeyHash,
1462
+ resolvePlutusScriptAddress,
1463
+ resolvePlutusScriptHash,
1464
+ resolvePoolId,
1465
+ resolvePrivateKey,
1466
+ resolveRewardAddress,
1467
+ resolveScriptRef,
1468
+ resolveStakeKeyHash,
1469
+ resolveTxHash,
1470
+ signData,
1471
+ subValue,
1472
+ toAddress,
1473
+ toBaseAddress,
1474
+ toEnterpriseAddress,
1475
+ toNativeScript,
1476
+ toPlutusData,
1477
+ toRewardAddress,
1478
+ toScriptRef,
1479
+ toTxUnspentOutput,
1480
+ toValue
1481
+ });