@meshsdk/wallet 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.mjs ADDED
@@ -0,0 +1,1234 @@
1
+ // src/app/index.ts
2
+ import {
3
+ deserializeTx as deserializeTx2,
4
+ toAddress,
5
+ toTxUnspentOutput
6
+ } from "@meshsdk/core-cst";
7
+
8
+ // ../../node_modules/@scure/base/lib/esm/index.js
9
+ // @__NO_SIDE_EFFECTS__
10
+ function assertNumber(n) {
11
+ if (!Number.isSafeInteger(n))
12
+ throw new Error(`Wrong integer: ${n}`);
13
+ }
14
+ function isBytes(a) {
15
+ return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
16
+ }
17
+ // @__NO_SIDE_EFFECTS__
18
+ function chain(...args) {
19
+ const id = (a) => a;
20
+ const wrap = (a, b) => (c) => a(b(c));
21
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
22
+ const decode = args.map((x) => x.decode).reduce(wrap, id);
23
+ return { encode, decode };
24
+ }
25
+ // @__NO_SIDE_EFFECTS__
26
+ function alphabet(alphabet2) {
27
+ return {
28
+ encode: (digits) => {
29
+ if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
30
+ throw new Error("alphabet.encode input should be an array of numbers");
31
+ return digits.map((i) => {
32
+ /* @__PURE__ */ assertNumber(i);
33
+ if (i < 0 || i >= alphabet2.length)
34
+ throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet2.length})`);
35
+ return alphabet2[i];
36
+ });
37
+ },
38
+ decode: (input) => {
39
+ if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
40
+ throw new Error("alphabet.decode input should be array of strings");
41
+ return input.map((letter) => {
42
+ if (typeof letter !== "string")
43
+ throw new Error(`alphabet.decode: not string element=${letter}`);
44
+ const index = alphabet2.indexOf(letter);
45
+ if (index === -1)
46
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`);
47
+ return index;
48
+ });
49
+ }
50
+ };
51
+ }
52
+ // @__NO_SIDE_EFFECTS__
53
+ function join(separator = "") {
54
+ if (typeof separator !== "string")
55
+ throw new Error("join separator should be string");
56
+ return {
57
+ encode: (from) => {
58
+ if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
59
+ throw new Error("join.encode input should be array of strings");
60
+ for (let i of from)
61
+ if (typeof i !== "string")
62
+ throw new Error(`join.encode: non-string input=${i}`);
63
+ return from.join(separator);
64
+ },
65
+ decode: (to) => {
66
+ if (typeof to !== "string")
67
+ throw new Error("join.decode input should be string");
68
+ return to.split(separator);
69
+ }
70
+ };
71
+ }
72
+ var gcd = /* @__NO_SIDE_EFFECTS__ */ (a, b) => !b ? a : /* @__PURE__ */ gcd(b, a % b);
73
+ var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - /* @__PURE__ */ gcd(from, to));
74
+ // @__NO_SIDE_EFFECTS__
75
+ function convertRadix2(data, from, to, padding) {
76
+ if (!Array.isArray(data))
77
+ throw new Error("convertRadix2: data should be array");
78
+ if (from <= 0 || from > 32)
79
+ throw new Error(`convertRadix2: wrong from=${from}`);
80
+ if (to <= 0 || to > 32)
81
+ throw new Error(`convertRadix2: wrong to=${to}`);
82
+ if (/* @__PURE__ */ radix2carry(from, to) > 32) {
83
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`);
84
+ }
85
+ let carry = 0;
86
+ let pos = 0;
87
+ const mask = 2 ** to - 1;
88
+ const res = [];
89
+ for (const n of data) {
90
+ /* @__PURE__ */ assertNumber(n);
91
+ if (n >= 2 ** from)
92
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
93
+ carry = carry << from | n;
94
+ if (pos + from > 32)
95
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
96
+ pos += from;
97
+ for (; pos >= to; pos -= to)
98
+ res.push((carry >> pos - to & mask) >>> 0);
99
+ carry &= 2 ** pos - 1;
100
+ }
101
+ carry = carry << to - pos & mask;
102
+ if (!padding && pos >= from)
103
+ throw new Error("Excess padding");
104
+ if (!padding && carry)
105
+ throw new Error(`Non-zero padding: ${carry}`);
106
+ if (padding && pos > 0)
107
+ res.push(carry >>> 0);
108
+ return res;
109
+ }
110
+ // @__NO_SIDE_EFFECTS__
111
+ function radix2(bits, revPadding = false) {
112
+ /* @__PURE__ */ assertNumber(bits);
113
+ if (bits <= 0 || bits > 32)
114
+ throw new Error("radix2: bits should be in (0..32]");
115
+ if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
116
+ throw new Error("radix2: carry overflow");
117
+ return {
118
+ encode: (bytes) => {
119
+ if (!isBytes(bytes))
120
+ throw new Error("radix2.encode input should be Uint8Array");
121
+ return /* @__PURE__ */ convertRadix2(Array.from(bytes), 8, bits, !revPadding);
122
+ },
123
+ decode: (digits) => {
124
+ if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
125
+ throw new Error("radix2.decode input should be array of numbers");
126
+ return Uint8Array.from(/* @__PURE__ */ convertRadix2(digits, bits, 8, revPadding));
127
+ }
128
+ };
129
+ }
130
+ // @__NO_SIDE_EFFECTS__
131
+ function unsafeWrapper(fn) {
132
+ if (typeof fn !== "function")
133
+ throw new Error("unsafeWrapper fn should be function");
134
+ return function(...args) {
135
+ try {
136
+ return fn.apply(null, args);
137
+ } catch (e) {
138
+ }
139
+ };
140
+ }
141
+ var BECH_ALPHABET = /* @__PURE__ */ chain(/* @__PURE__ */ alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), /* @__PURE__ */ join(""));
142
+ var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
143
+ // @__NO_SIDE_EFFECTS__
144
+ function bech32Polymod(pre) {
145
+ const b = pre >> 25;
146
+ let chk = (pre & 33554431) << 5;
147
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
148
+ if ((b >> i & 1) === 1)
149
+ chk ^= POLYMOD_GENERATORS[i];
150
+ }
151
+ return chk;
152
+ }
153
+ // @__NO_SIDE_EFFECTS__
154
+ function bechChecksum(prefix, words, encodingConst = 1) {
155
+ const len = prefix.length;
156
+ let chk = 1;
157
+ for (let i = 0; i < len; i++) {
158
+ const c = prefix.charCodeAt(i);
159
+ if (c < 33 || c > 126)
160
+ throw new Error(`Invalid prefix (${prefix})`);
161
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ c >> 5;
162
+ }
163
+ chk = /* @__PURE__ */ bech32Polymod(chk);
164
+ for (let i = 0; i < len; i++)
165
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
166
+ for (let v of words)
167
+ chk = /* @__PURE__ */ bech32Polymod(chk) ^ v;
168
+ for (let i = 0; i < 6; i++)
169
+ chk = /* @__PURE__ */ bech32Polymod(chk);
170
+ chk ^= encodingConst;
171
+ return BECH_ALPHABET.encode(/* @__PURE__ */ convertRadix2([chk % 2 ** 30], 30, 5, false));
172
+ }
173
+ // @__NO_SIDE_EFFECTS__
174
+ function genBech32(encoding) {
175
+ const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
176
+ const _words = /* @__PURE__ */ radix2(5);
177
+ const fromWords = _words.decode;
178
+ const toWords = _words.encode;
179
+ const fromWordsUnsafe = /* @__PURE__ */ unsafeWrapper(fromWords);
180
+ function encode(prefix, words, limit = 90) {
181
+ if (typeof prefix !== "string")
182
+ throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
183
+ if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
184
+ throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
185
+ if (prefix.length === 0)
186
+ throw new TypeError(`Invalid prefix length ${prefix.length}`);
187
+ const actualLength = prefix.length + 7 + words.length;
188
+ if (limit !== false && actualLength > limit)
189
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
190
+ const lowered = prefix.toLowerCase();
191
+ const sum = /* @__PURE__ */ bechChecksum(lowered, words, ENCODING_CONST);
192
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
193
+ }
194
+ function decode(str, limit = 90) {
195
+ if (typeof str !== "string")
196
+ throw new Error(`bech32.decode input should be string, not ${typeof str}`);
197
+ if (str.length < 8 || limit !== false && str.length > limit)
198
+ throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
199
+ const lowered = str.toLowerCase();
200
+ if (str !== lowered && str !== str.toUpperCase())
201
+ throw new Error(`String must be lowercase or uppercase`);
202
+ const sepIndex = lowered.lastIndexOf("1");
203
+ if (sepIndex === 0 || sepIndex === -1)
204
+ throw new Error(`Letter "1" must be present between prefix and data only`);
205
+ const prefix = lowered.slice(0, sepIndex);
206
+ const data = lowered.slice(sepIndex + 1);
207
+ if (data.length < 6)
208
+ throw new Error("Data must be at least 6 characters long");
209
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
210
+ const sum = /* @__PURE__ */ bechChecksum(prefix, words, ENCODING_CONST);
211
+ if (!data.endsWith(sum))
212
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
213
+ return { prefix, words };
214
+ }
215
+ const decodeUnsafe = /* @__PURE__ */ unsafeWrapper(decode);
216
+ function decodeToBytes(str) {
217
+ const { prefix, words } = decode(str, false);
218
+ return { prefix, words, bytes: fromWords(words) };
219
+ }
220
+ return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
221
+ }
222
+ var bech32 = /* @__PURE__ */ genBech32("bech32");
223
+
224
+ // src/embedded/index.ts
225
+ import {
226
+ bytesToHex,
227
+ generateMnemonic,
228
+ mnemonicToEntropy
229
+ } from "@meshsdk/common";
230
+ import {
231
+ Bip32PrivateKey,
232
+ buildBaseAddress,
233
+ buildBip32PrivateKey,
234
+ buildEnterpriseAddress,
235
+ buildKeys,
236
+ buildRewardAddress,
237
+ deserializeTx,
238
+ deserializeTxHash,
239
+ Ed25519KeyHashHex,
240
+ Ed25519PublicKeyHex,
241
+ Ed25519SignatureHex,
242
+ Hash28ByteBase16,
243
+ resolveTxHash,
244
+ Serialization,
245
+ signData,
246
+ Transaction,
247
+ VkeyWitness
248
+ } from "@meshsdk/core-cst";
249
+ var WalletStaticMethods = class {
250
+ static privateKeyToEntropy(bech322) {
251
+ const bech32DecodedBytes = bech32.decodeToBytes(bech322).bytes;
252
+ const bip32PrivateKey = Bip32PrivateKey.fromBytes(bech32DecodedBytes);
253
+ return bytesToHex(bip32PrivateKey.bytes());
254
+ }
255
+ static mnemonicToEntropy(words) {
256
+ const entropy = mnemonicToEntropy(words.join(" "));
257
+ const bip32PrivateKey = buildBip32PrivateKey(entropy);
258
+ return bytesToHex(bip32PrivateKey.bytes());
259
+ }
260
+ static signingKeyToEntropy(paymentKey, stakeKey) {
261
+ return [
262
+ paymentKey.startsWith("5820") ? paymentKey.slice(4) : paymentKey,
263
+ stakeKey.startsWith("5820") ? stakeKey.slice(4) : stakeKey
264
+ ];
265
+ }
266
+ static getAddresses(paymentKey, stakingKey, networkId = 0) {
267
+ const baseAddress = buildBaseAddress(
268
+ networkId,
269
+ Hash28ByteBase16.fromEd25519KeyHashHex(
270
+ Ed25519KeyHashHex(paymentKey.toPublicKey().hash().toString("hex"))
271
+ ),
272
+ Hash28ByteBase16.fromEd25519KeyHashHex(
273
+ Ed25519KeyHashHex(stakingKey.toPublicKey().hash().toString("hex"))
274
+ )
275
+ );
276
+ const enterpriseAddress = buildEnterpriseAddress(
277
+ networkId,
278
+ Hash28ByteBase16.fromEd25519KeyHashHex(
279
+ Ed25519KeyHashHex(paymentKey.toPublicKey().hash().toString("hex"))
280
+ )
281
+ );
282
+ const rewardAddress = buildRewardAddress(
283
+ networkId,
284
+ Hash28ByteBase16.fromEd25519KeyHashHex(
285
+ Ed25519KeyHashHex(stakingKey.toPublicKey().hash().toString("hex"))
286
+ )
287
+ );
288
+ return {
289
+ baseAddress: baseAddress.toAddress(),
290
+ enterpriseAddress: enterpriseAddress.toAddress(),
291
+ rewardAddress: rewardAddress.toAddress()
292
+ };
293
+ }
294
+ static generateMnemonic(strength = 256) {
295
+ const mnemonic = generateMnemonic(strength);
296
+ return mnemonic.split(" ");
297
+ }
298
+ static addWitnessSets(txHex, witnesses) {
299
+ let tx = deserializeTx(txHex);
300
+ let witnessSet = tx.witnessSet();
301
+ let witnessSetVkeys = witnessSet.vkeys();
302
+ let witnessSetVkeysValues = witnessSetVkeys ? [...witnessSetVkeys.values(), ...witnesses] : witnesses;
303
+ witnessSet.setVkeys(
304
+ Serialization.CborSet.fromCore(
305
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
306
+ VkeyWitness.fromCore
307
+ )
308
+ );
309
+ return new Transaction(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
310
+ }
311
+ };
312
+ var EmbeddedWallet = class extends WalletStaticMethods {
313
+ constructor(options) {
314
+ super();
315
+ this._networkId = options.networkId;
316
+ switch (options.key.type) {
317
+ case "mnemonic":
318
+ this._entropy = WalletStaticMethods.mnemonicToEntropy(
319
+ options.key.words
320
+ );
321
+ break;
322
+ case "root":
323
+ this._entropy = WalletStaticMethods.privateKeyToEntropy(
324
+ options.key.bech32
325
+ );
326
+ break;
327
+ case "cli":
328
+ this._entropy = WalletStaticMethods.signingKeyToEntropy(
329
+ options.key.payment,
330
+ options.key.stake ?? "f0".repeat(32)
331
+ );
332
+ break;
333
+ }
334
+ }
335
+ getAccount(accountIndex = 0, keyIndex = 0) {
336
+ if (this._entropy == void 0)
337
+ throw new Error("[EmbeddedWallet] No keys initialized");
338
+ const { paymentKey, stakeKey } = buildKeys(
339
+ this._entropy,
340
+ accountIndex,
341
+ keyIndex
342
+ );
343
+ const { baseAddress, enterpriseAddress, rewardAddress } = WalletStaticMethods.getAddresses(paymentKey, stakeKey, this._networkId);
344
+ return {
345
+ baseAddress,
346
+ enterpriseAddress,
347
+ rewardAddress,
348
+ baseAddressBech32: baseAddress.toBech32(),
349
+ enterpriseAddressBech32: enterpriseAddress.toBech32(),
350
+ rewardAddressBech32: rewardAddress.toBech32(),
351
+ paymentKey,
352
+ stakeKey,
353
+ paymentKeyHex: paymentKey.toBytes().toString("hex"),
354
+ stakeKeyHex: stakeKey.toBytes().toString("hex")
355
+ };
356
+ }
357
+ getNetworkId() {
358
+ return this._networkId;
359
+ }
360
+ signData(address, payload, accountIndex = 0, keyIndex = 0) {
361
+ try {
362
+ const account = this.getAccount(accountIndex, keyIndex);
363
+ const foundAddress = [
364
+ account.baseAddress,
365
+ account.enterpriseAddress,
366
+ account.rewardAddress
367
+ ].find((a) => a.toBech32() === address);
368
+ if (foundAddress === void 0)
369
+ throw new Error(
370
+ `[EmbeddedWallet] Address: ${address} doesn't belong to this account.`
371
+ );
372
+ return signData(payload, account.paymentKey);
373
+ } catch (error) {
374
+ throw new Error(
375
+ `[EmbeddedWallet] An error occurred during signData: ${error}.`
376
+ );
377
+ }
378
+ }
379
+ signTx(unsignedTx, accountIndex = 0, keyIndex = 0) {
380
+ try {
381
+ const txHash = deserializeTxHash(resolveTxHash(unsignedTx));
382
+ const account = this.getAccount(accountIndex, keyIndex);
383
+ const vKeyWitness = new VkeyWitness(
384
+ Ed25519PublicKeyHex(
385
+ account.paymentKey.toPublicKey().toBytes().toString("hex")
386
+ ),
387
+ Ed25519SignatureHex(
388
+ account.paymentKey.sign(Buffer.from(txHash, "hex")).toString("hex")
389
+ )
390
+ );
391
+ return vKeyWitness;
392
+ } catch (error) {
393
+ throw new Error(
394
+ `[EmbeddedWallet] An error occurred during signTx: ${error}.`
395
+ );
396
+ }
397
+ }
398
+ };
399
+
400
+ // src/app/index.ts
401
+ var AppWallet = class {
402
+ constructor(options) {
403
+ this._fetcher = options.fetcher;
404
+ this._submitter = options.submitter;
405
+ switch (options.key.type) {
406
+ case "mnemonic":
407
+ this._wallet = new EmbeddedWallet({
408
+ networkId: options.networkId,
409
+ key: {
410
+ type: "mnemonic",
411
+ words: options.key.words
412
+ }
413
+ });
414
+ break;
415
+ case "root":
416
+ this._wallet = new EmbeddedWallet({
417
+ networkId: options.networkId,
418
+ key: {
419
+ type: "root",
420
+ bech32: options.key.bech32
421
+ }
422
+ });
423
+ break;
424
+ case "cli":
425
+ this._wallet = new EmbeddedWallet({
426
+ networkId: options.networkId,
427
+ key: {
428
+ type: "cli",
429
+ payment: options.key.payment,
430
+ stake: options.key.stake
431
+ }
432
+ });
433
+ }
434
+ }
435
+ /**
436
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
437
+ *
438
+ * This is used in transaction building.
439
+ *
440
+ * @returns a list of UTXOs
441
+ */
442
+ async getCollateralUnspentOutput(accountIndex = 0, addressType = "payment") {
443
+ const utxos = await this.getUnspentOutputs(accountIndex, addressType);
444
+ const pureAdaUtxos = utxos.filter((utxo) => {
445
+ return utxo.output().amount().multiasset() === void 0;
446
+ });
447
+ pureAdaUtxos.sort((a, b) => {
448
+ return Number(a.output().amount().coin()) - Number(b.output().amount().coin());
449
+ });
450
+ for (const utxo of pureAdaUtxos) {
451
+ if (Number(utxo.output().amount().coin()) >= 5e6) {
452
+ return [utxo];
453
+ }
454
+ }
455
+ return [];
456
+ }
457
+ getEnterpriseAddress(accountIndex = 0, keyIndex = 0) {
458
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
459
+ return account.enterpriseAddressBech32;
460
+ }
461
+ getPaymentAddress(accountIndex = 0, keyIndex = 0) {
462
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
463
+ return account.baseAddressBech32;
464
+ }
465
+ getRewardAddress(accountIndex = 0, keyIndex = 0) {
466
+ const account = this._wallet.getAccount(accountIndex, keyIndex);
467
+ return account.rewardAddressBech32;
468
+ }
469
+ getNetworkId() {
470
+ return this._wallet.getNetworkId();
471
+ }
472
+ getUsedAddress(accountIndex = 0, keyIndex = 0, addressType = "payment") {
473
+ if (addressType === "enterprise") {
474
+ return toAddress(this.getEnterpriseAddress(accountIndex, keyIndex));
475
+ } else {
476
+ return toAddress(this.getPaymentAddress(accountIndex, keyIndex));
477
+ }
478
+ }
479
+ async getUnspentOutputs(accountIndex = 0, addressType = "payment") {
480
+ if (!this._fetcher) {
481
+ throw new Error(
482
+ "[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher."
483
+ );
484
+ }
485
+ const account = this._wallet.getAccount(accountIndex);
486
+ const utxos = await this._fetcher.fetchAddressUTxOs(
487
+ addressType == "enterprise" ? account.enterpriseAddressBech32 : account.baseAddressBech32
488
+ );
489
+ return utxos.map((utxo) => toTxUnspentOutput(utxo));
490
+ }
491
+ signData(address, payload, accountIndex = 0, keyIndex = 0) {
492
+ try {
493
+ return this._wallet.signData(address, payload, accountIndex, keyIndex);
494
+ } catch (error) {
495
+ throw new Error(
496
+ `[AppWallet] An error occurred during signData: ${error}.`
497
+ );
498
+ }
499
+ }
500
+ signTx(unsignedTx, partialSign = false, accountIndex = 0, keyIndex = 0) {
501
+ try {
502
+ const tx = deserializeTx2(unsignedTx);
503
+ if (!partialSign && tx.witnessSet().vkeys() !== void 0 && tx.witnessSet().vkeys().size() !== 0)
504
+ throw new Error(
505
+ "Signatures already exist in the transaction in a non partial sign call"
506
+ );
507
+ const newSignatures = this._wallet.signTx(
508
+ unsignedTx,
509
+ accountIndex,
510
+ keyIndex
511
+ );
512
+ let signedTx = EmbeddedWallet.addWitnessSets(unsignedTx, [newSignatures]);
513
+ return signedTx;
514
+ } catch (error) {
515
+ throw new Error(`[AppWallet] An error occurred during signTx: ${error}.`);
516
+ }
517
+ }
518
+ signTxSync(unsignedTx, partialSign = false, accountIndex = 0, keyIndex = 0) {
519
+ try {
520
+ return "signedTx";
521
+ } catch (error) {
522
+ throw new Error(`[AppWallet] An error occurred during signTx: ${error}.`);
523
+ }
524
+ }
525
+ async signTxs(unsignedTxs, partialSign) {
526
+ throw new Error(`[AppWallet] signTxs() is not implemented.`);
527
+ }
528
+ submitTx(tx) {
529
+ if (!this._submitter) {
530
+ throw new Error(
531
+ "[AppWallet] Submitter is required to submit transactions. Please provide a submitter."
532
+ );
533
+ }
534
+ return this._submitter.submitTx(tx);
535
+ }
536
+ static brew(strength = 256) {
537
+ return EmbeddedWallet.generateMnemonic(strength);
538
+ }
539
+ };
540
+
541
+ // src/browser/index.ts
542
+ import {
543
+ DEFAULT_PROTOCOL_PARAMETERS,
544
+ fromUTF8,
545
+ POLICY_ID_LENGTH,
546
+ resolveFingerprint
547
+ } from "@meshsdk/common";
548
+ import {
549
+ addressToBech32,
550
+ CardanoSDKUtil,
551
+ deserializeAddress,
552
+ deserializeTx as deserializeTx3,
553
+ deserializeTxUnspentOutput,
554
+ deserializeValue,
555
+ fromTxUnspentOutput,
556
+ fromValue,
557
+ Serialization as Serialization2,
558
+ toAddress as toAddress2,
559
+ Transaction as Transaction2,
560
+ VkeyWitness as VkeyWitness2
561
+ } from "@meshsdk/core-cst";
562
+ var BrowserWallet = class _BrowserWallet {
563
+ constructor(_walletInstance, _walletName) {
564
+ this._walletInstance = _walletInstance;
565
+ this._walletName = _walletName;
566
+ this.walletInstance = { ..._walletInstance };
567
+ }
568
+ /**
569
+ * Returns a list of wallets installed on user's device. Each wallet is an object with the following properties:
570
+ * - A name is provided to display wallet's name on the user interface.
571
+ * - A version is provided to display wallet's version on the user interface.
572
+ * - An icon is provided to display wallet's icon on the user interface.
573
+ *
574
+ * @returns a list of wallet names
575
+ */
576
+ static getInstalledWallets() {
577
+ if (window === void 0) return [];
578
+ if (window.cardano === void 0) return [];
579
+ let wallets = [];
580
+ for (const key in window.cardano) {
581
+ try {
582
+ const _wallet = window.cardano[key];
583
+ if (_wallet === void 0) continue;
584
+ if (_wallet.name === void 0) continue;
585
+ if (_wallet.icon === void 0) continue;
586
+ if (_wallet.apiVersion === void 0) continue;
587
+ wallets.push({
588
+ id: key,
589
+ name: _wallet.name,
590
+ icon: _wallet.icon,
591
+ version: _wallet.apiVersion
592
+ });
593
+ } catch (e) {
594
+ }
595
+ }
596
+ return wallets;
597
+ }
598
+ /**
599
+ * This is the entrypoint to start communication with the user's wallet. The wallet should request the user's permission to connect the web page to the user's wallet, and if permission has been granted, the wallet will be returned and exposing the full API for the dApp to use.
600
+ *
601
+ * Query BrowserWallet.getInstalledWallets() to get a list of available wallets, then provide the wallet name for which wallet the user would like to connect with.
602
+ *
603
+ * @param walletName
604
+ * @returns WalletInstance
605
+ */
606
+ static async enable(walletName) {
607
+ try {
608
+ const walletInstance = await _BrowserWallet.resolveInstance(walletName);
609
+ if (walletInstance !== void 0)
610
+ return new _BrowserWallet(walletInstance, walletName);
611
+ throw new Error(`Couldn't create an instance of wallet: ${walletName}`);
612
+ } catch (error) {
613
+ throw new Error(
614
+ `[BrowserWallet] An error occurred during enable: ${JSON.stringify(
615
+ error
616
+ )}.`
617
+ );
618
+ }
619
+ }
620
+ /**
621
+ * Retrieves the total available balance of the wallet, encoded in CBOR.
622
+ * @returns {Promise<Value>} - The balance of the wallet.
623
+ */
624
+ // async _getBalance(): Promise<Value> {
625
+ // const balance = await this._walletInstance.getBalance();
626
+ // return Value.fromCbor(HexBlob(balance));
627
+ // }
628
+ /**
629
+ * Returns a list of assets in the wallet. This API will return every assets in the wallet. Each asset is an object with the following properties:
630
+ * - A unit is provided to display asset's name on the user interface.
631
+ * - A quantity is provided to display asset's quantity on the user interface.
632
+ *
633
+ * @returns a list of assets and their quantities
634
+ */
635
+ async getBalance() {
636
+ const balance = await this._walletInstance.getBalance();
637
+ return fromValue(deserializeValue(balance));
638
+ }
639
+ /**
640
+ * Returns an address owned by the wallet that should be used as a change address to return leftover assets during transaction creation back to the connected wallet.
641
+ *
642
+ * @returns an address
643
+ */
644
+ async getChangeAddress() {
645
+ const changeAddress = await this._walletInstance.getChangeAddress();
646
+ return addressToBech32(deserializeAddress(changeAddress));
647
+ }
648
+ /**
649
+ * This function shall return a list of one or more UTXOs (unspent transaction outputs) controlled by the wallet that are required to reach AT LEAST the combined ADA value target specified in amount AND the best suitable to be used as collateral inputs for transactions with plutus script inputs (pure ADA-only UTXOs).
650
+ *
651
+ * If this cannot be attained, an error message with an explanation of the blocking problem shall be returned. NOTE: wallets are free to return UTXOs that add up to a greater total ADA value than requested in the amount parameter, but wallets must never return any result where UTXOs would sum up to a smaller total ADA value, instead in a case like that an error message must be returned.
652
+ *
653
+ * @param limit
654
+ * @returns a list of UTXOs
655
+ */
656
+ async getCollateral() {
657
+ const deserializedCollateral = await this.getCollateralUnspentOutput();
658
+ return deserializedCollateral.map((dc) => fromTxUnspentOutput(dc));
659
+ }
660
+ /**
661
+ * Returns the network ID of the currently connected account. 0 is testnet and 1 is mainnet but other networks can possibly be returned by wallets. Those other network ID values are not governed by CIP-30. This result will stay the same unless the connected account has changed.
662
+ *
663
+ * @returns network ID
664
+ */
665
+ getNetworkId() {
666
+ return this._walletInstance.getNetworkId();
667
+ }
668
+ /**
669
+ * Returns a list of reward addresses owned by the wallet. A reward address is a stake address that is used to receive rewards from staking, generally starts from `stake` prefix.
670
+ *
671
+ * @returns a list of reward addresses
672
+ */
673
+ async getRewardAddresses() {
674
+ const rewardAddresses = await this._walletInstance.getRewardAddresses();
675
+ return rewardAddresses.map((ra) => addressToBech32(deserializeAddress(ra)));
676
+ }
677
+ /**
678
+ * Returns a list of unused addresses controlled by the wallet.
679
+ *
680
+ * @returns a list of unused addresses
681
+ */
682
+ async getUnusedAddresses() {
683
+ const unusedAddresses = await this._walletInstance.getUnusedAddresses();
684
+ return unusedAddresses.map(
685
+ (una) => addressToBech32(deserializeAddress(una))
686
+ );
687
+ }
688
+ /**
689
+ * Returns a list of used addresses controlled by the wallet.
690
+ *
691
+ * @returns a list of used addresses
692
+ */
693
+ async getUsedAddresses() {
694
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
695
+ return usedAddresses.map((usa) => addressToBech32(deserializeAddress(usa)));
696
+ }
697
+ /**
698
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
699
+ *
700
+ * This is used in transaction building.
701
+ *
702
+ * @returns a list of UTXOs
703
+ */
704
+ async getUsedCollateral(limit = DEFAULT_PROTOCOL_PARAMETERS.maxCollateralInputs) {
705
+ const collateral = await this._walletInstance.experimental.getCollateral() ?? [];
706
+ return collateral.map((c) => deserializeTxUnspentOutput(c)).slice(0, limit);
707
+ }
708
+ /**
709
+ * Return a list of all UTXOs (unspent transaction outputs) controlled by the wallet.
710
+ *
711
+ * @returns a list of UTXOs
712
+ */
713
+ async getUtxos() {
714
+ const deserializedUTxOs = await this.getUsedUTxOs();
715
+ return deserializedUTxOs.map((du) => fromTxUnspentOutput(du));
716
+ }
717
+ /**
718
+ * This endpoint utilizes the [CIP-8 - Message Signing](https://github.com/cardano-foundation/CIPs/tree/master/CIP-0030) to sign arbitrary data, to verify the data was signed by the owner of the private key.
719
+ *
720
+ * Here, we get the first wallet's address with wallet.getUsedAddresses(), alternativelly you can use reward addresses (getRewardAddresses()) too. It's really up to you as the developer which address you want to use in your application.
721
+ *
722
+ * @param address
723
+ * @param payload
724
+ * @returns a signature
725
+ */
726
+ signData(address, payload) {
727
+ const signerAddress = toAddress2(address).toBytes().toString();
728
+ return this._walletInstance.signData(signerAddress, fromUTF8(payload));
729
+ }
730
+ /**
731
+ * Requests user to sign the provided transaction (tx). The wallet should ask the user for permission, and if given, try to sign the supplied body and return a signed transaction. partialSign should be true if the transaction provided requires multiple signatures.
732
+ *
733
+ * @param unsignedTx
734
+ * @param partialSign
735
+ * @returns a signed transaction in CBOR
736
+ */
737
+ async signTx(unsignedTx, partialSign = false) {
738
+ const witness = await this._walletInstance.signTx(unsignedTx, partialSign);
739
+ console.log("witness", witness);
740
+ return _BrowserWallet.addBrowserWitnesses(unsignedTx, witness);
741
+ }
742
+ /**
743
+ * Experimental feature - sign multiple transactions at once (Supported wallet(s): Typhon)
744
+ *
745
+ * @param unsignedTxs - array of unsigned transactions in CborHex string
746
+ * @param partialSign - if the transactions are signed partially
747
+ * @returns array of signed transactions CborHex string
748
+ */
749
+ async signTxs(unsignedTxs, partialSign = false) {
750
+ let witnessSets = void 0;
751
+ switch (this._walletName) {
752
+ case "Typhon Wallet":
753
+ if (this._walletInstance.signTxs) {
754
+ witnessSets = await this._walletInstance.signTxs(
755
+ unsignedTxs,
756
+ partialSign
757
+ );
758
+ }
759
+ break;
760
+ default:
761
+ if (this._walletInstance.signTxs) {
762
+ witnessSets = await this._walletInstance.signTxs(
763
+ unsignedTxs.map((cbor) => ({
764
+ cbor,
765
+ partialSign
766
+ }))
767
+ );
768
+ } else if (this._walletInstance.experimental.signTxs) {
769
+ witnessSets = await this._walletInstance.experimental.signTxs(
770
+ unsignedTxs.map((cbor) => ({
771
+ cbor,
772
+ partialSign
773
+ }))
774
+ );
775
+ }
776
+ break;
777
+ }
778
+ if (!witnessSets) throw new Error("Wallet does not support signTxs");
779
+ const signedTxs = [];
780
+ for (let i = 0; i < witnessSets.length; i++) {
781
+ const unsignedTx = unsignedTxs[i];
782
+ const cWitness = witnessSets[i];
783
+ const signedTx = _BrowserWallet.addBrowserWitnesses(unsignedTx, cWitness);
784
+ signedTxs.push(signedTx);
785
+ }
786
+ return signedTxs;
787
+ }
788
+ /**
789
+ * Submits the signed transaction to the blockchain network.
790
+ *
791
+ * As wallets should already have this ability to submit transaction, we allow dApps to request that a transaction be sent through it. If the wallet accepts the transaction and tries to send it, it shall return the transaction ID for the dApp to track. The wallet can return error messages or failure if there was an error in sending it.
792
+ *
793
+ * @param tx
794
+ * @returns a transaction hash
795
+ */
796
+ submitTx(tx) {
797
+ return this._walletInstance.submitTx(tx);
798
+ }
799
+ /**
800
+ * Get a used address of type Address from the wallet.
801
+ *
802
+ * This is used in transaction building.
803
+ *
804
+ * @returns an Address object
805
+ */
806
+ async getUsedAddress() {
807
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
808
+ if (usedAddresses.length === 0) throw new Error("No used addresses found");
809
+ return deserializeAddress(usedAddresses[0]);
810
+ }
811
+ /**
812
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
813
+ *
814
+ * This is used in transaction building.
815
+ *
816
+ * @returns a list of UTXOs
817
+ */
818
+ async getCollateralUnspentOutput() {
819
+ const collateral = await this._walletInstance.experimental.getCollateral() ?? [];
820
+ return collateral.map((c) => deserializeTxUnspentOutput(c));
821
+ }
822
+ /**
823
+ * Get a list of UTXOs to be used for transaction building.
824
+ *
825
+ * This is used in transaction building.
826
+ *
827
+ * @returns a list of UTXOs
828
+ */
829
+ async getUsedUTxOs() {
830
+ const utxos = await this._walletInstance.getUtxos() ?? [];
831
+ return utxos.map((u) => deserializeTxUnspentOutput(u));
832
+ }
833
+ /**
834
+ * A helper function to get the assets in the wallet.
835
+ *
836
+ * @returns a list of assets
837
+ */
838
+ async getAssets() {
839
+ const balance = await this.getBalance();
840
+ return balance.filter((v) => v.unit !== "lovelace").map((v) => {
841
+ const policyId = v.unit.slice(0, POLICY_ID_LENGTH);
842
+ const assetName = v.unit.slice(POLICY_ID_LENGTH);
843
+ const fingerprint = resolveFingerprint(policyId, assetName);
844
+ return {
845
+ unit: v.unit,
846
+ policyId,
847
+ assetName,
848
+ fingerprint,
849
+ quantity: v.quantity
850
+ };
851
+ });
852
+ }
853
+ /**
854
+ * A helper function to get the lovelace balance in the wallet.
855
+ *
856
+ * @returns lovelace balance
857
+ */
858
+ async getLovelace() {
859
+ const balance = await this.getBalance();
860
+ const nativeAsset = balance.find((v) => v.unit === "lovelace");
861
+ return nativeAsset !== void 0 ? nativeAsset.quantity : "0";
862
+ }
863
+ /**
864
+ * A helper function to get the assets of a specific policy ID in the wallet.
865
+ *
866
+ * @param policyId
867
+ * @returns a list of assets
868
+ */
869
+ async getPolicyIdAssets(policyId) {
870
+ const assets = await this.getAssets();
871
+ return assets.filter((v) => v.policyId === policyId);
872
+ }
873
+ /**
874
+ * A helper function to get the policy IDs of all the assets in the wallet.
875
+ *
876
+ * @returns a list of policy IDs
877
+ */
878
+ async getPolicyIds() {
879
+ const balance = await this.getBalance();
880
+ return Array.from(
881
+ new Set(balance.map((v) => v.unit.slice(0, POLICY_ID_LENGTH)))
882
+ ).filter((p) => p !== "lovelace");
883
+ }
884
+ static resolveInstance(walletName) {
885
+ if (window.cardano === void 0) return void 0;
886
+ if (window.cardano[walletName] === void 0) return void 0;
887
+ const wallet = window.cardano[walletName];
888
+ return wallet?.enable();
889
+ }
890
+ static addBrowserWitnesses(unsignedTx, witnesses) {
891
+ const cWitness = Serialization2.TransactionWitnessSet.fromCbor(
892
+ CardanoSDKUtil.HexBlob(witnesses)
893
+ ).vkeys()?.values();
894
+ if (cWitness === void 0) {
895
+ return unsignedTx;
896
+ }
897
+ let tx = deserializeTx3(unsignedTx);
898
+ let witnessSet = tx.witnessSet();
899
+ let witnessSetVkeys = witnessSet.vkeys();
900
+ let witnessSetVkeysValues = witnessSetVkeys ? [...witnessSetVkeys.values(), ...cWitness] : [...cWitness];
901
+ witnessSet.setVkeys(
902
+ Serialization2.CborSet.fromCore(
903
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
904
+ VkeyWitness2.fromCore
905
+ )
906
+ );
907
+ return new Transaction2(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
908
+ }
909
+ };
910
+
911
+ // src/mesh/index.ts
912
+ import {
913
+ POLICY_ID_LENGTH as POLICY_ID_LENGTH2,
914
+ resolveFingerprint as resolveFingerprint2,
915
+ toUTF8
916
+ } from "@meshsdk/common";
917
+ import {
918
+ fromTxUnspentOutput as fromTxUnspentOutput2,
919
+ resolvePrivateKey,
920
+ toTxUnspentOutput as toTxUnspentOutput2
921
+ } from "@meshsdk/core-cst";
922
+ import { Transaction as Transaction3 } from "@meshsdk/transaction";
923
+ var MeshWallet = class {
924
+ constructor(options) {
925
+ switch (options.key.type) {
926
+ case "root":
927
+ this._wallet = new AppWallet({
928
+ networkId: options.networkId,
929
+ fetcher: options.fetcher,
930
+ submitter: options.submitter,
931
+ key: {
932
+ type: "root",
933
+ bech32: options.key.bech32
934
+ }
935
+ });
936
+ break;
937
+ case "cli":
938
+ this._wallet = new AppWallet({
939
+ networkId: options.networkId,
940
+ fetcher: options.fetcher,
941
+ submitter: options.submitter,
942
+ key: {
943
+ type: "cli",
944
+ payment: options.key.payment,
945
+ stake: options.key.stake
946
+ }
947
+ });
948
+ break;
949
+ case "mnemonic":
950
+ this._wallet = new AppWallet({
951
+ networkId: options.networkId,
952
+ fetcher: options.fetcher,
953
+ submitter: options.submitter,
954
+ key: {
955
+ type: "mnemonic",
956
+ words: options.key.words
957
+ }
958
+ });
959
+ break;
960
+ }
961
+ }
962
+ /**
963
+ * Returns a list of assets in the wallet. This API will return every assets in the wallet. Each asset is an object with the following properties:
964
+ * - A unit is provided to display asset's name on the user interface.
965
+ * - A quantity is provided to display asset's quantity on the user interface.
966
+ *
967
+ * @returns a list of assets and their quantities
968
+ */
969
+ async getBalance() {
970
+ const utxos = await this.getUnspentOutputs();
971
+ const assets = /* @__PURE__ */ new Map();
972
+ utxos.map((utxo) => {
973
+ const _utxo = fromTxUnspentOutput2(utxo);
974
+ _utxo.output.amount.map((asset) => {
975
+ const assetId = asset.unit;
976
+ const amount = Number(asset.quantity);
977
+ if (assets.has(assetId)) {
978
+ const quantity = assets.get(assetId);
979
+ assets.set(assetId, quantity + amount);
980
+ } else {
981
+ assets.set(assetId, amount);
982
+ }
983
+ });
984
+ });
985
+ const arrayAssets = Array.from(assets, ([unit, quantity]) => ({
986
+ unit,
987
+ quantity: quantity.toString()
988
+ }));
989
+ return arrayAssets;
990
+ }
991
+ /**
992
+ * Returns an address owned by the wallet that should be used as a change address to return leftover assets during transaction creation back to the connected wallet.
993
+ *
994
+ * @returns an address
995
+ */
996
+ getChangeAddress() {
997
+ return this._wallet.getPaymentAddress();
998
+ }
999
+ /**
1000
+ * This function shall return a list of one or more UTXOs (unspent transaction outputs) controlled by the wallet that are required to reach AT LEAST the combined ADA value target specified in amount AND the best suitable to be used as collateral inputs for transactions with plutus script inputs (pure ADA-only UTXOs).
1001
+ *
1002
+ * If this cannot be attained, an error message with an explanation of the blocking problem shall be returned. NOTE: wallets are free to return UTXOs that add up to a greater total ADA value than requested in the amount parameter, but wallets must never return any result where UTXOs would sum up to a smaller total ADA value, instead in a case like that an error message must be returned.
1003
+ *
1004
+ * @returns a list of UTXOs
1005
+ */
1006
+ async getCollateral(addressType = "payment") {
1007
+ const utxos = await this._wallet.getCollateralUnspentOutput(0, addressType);
1008
+ return utxos.map((utxo, i) => {
1009
+ return fromTxUnspentOutput2(utxo);
1010
+ });
1011
+ }
1012
+ /**
1013
+ * Returns the network ID of the currently connected account. 0 is testnet and 1 is mainnet but other networks can possibly be returned by wallets. Those other network ID values are not governed by CIP-30. This result will stay the same unless the connected account has changed.
1014
+ *
1015
+ * @returns network ID
1016
+ */
1017
+ getNetworkId() {
1018
+ return this._wallet.getNetworkId();
1019
+ }
1020
+ /**
1021
+ * Returns a list of reward addresses owned by the wallet. A reward address is a stake address that is used to receive rewards from staking, generally starts from `stake` prefix.
1022
+ *
1023
+ * @returns a list of reward addresses
1024
+ */
1025
+ getRewardAddresses() {
1026
+ return [this._wallet.getRewardAddress()];
1027
+ }
1028
+ /**
1029
+ * Returns a list of unused addresses controlled by the wallet.
1030
+ *
1031
+ * @returns a list of unused addresses
1032
+ */
1033
+ getUnusedAddresses() {
1034
+ return [this.getChangeAddress()];
1035
+ }
1036
+ /**
1037
+ * Returns a list of used addresses controlled by the wallet.
1038
+ *
1039
+ * @returns a list of used addresses
1040
+ */
1041
+ getUsedAddresses() {
1042
+ return [this.getChangeAddress()];
1043
+ }
1044
+ /**
1045
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
1046
+ *
1047
+ * This is used in transaction building.
1048
+ *
1049
+ * @returns a list of UTXOs
1050
+ */
1051
+ async getUsedCollateral() {
1052
+ const collateralUtxo = await this.getCollateral();
1053
+ const unspentOutput = collateralUtxo.map((utxo) => {
1054
+ return toTxUnspentOutput2(utxo);
1055
+ });
1056
+ return unspentOutput;
1057
+ }
1058
+ /**
1059
+ * Get a list of UTXOs to be used for transaction building.
1060
+ *
1061
+ * This is used in transaction building.
1062
+ *
1063
+ * @returns a list of UTXOs
1064
+ */
1065
+ async getUsedUTxOs(addressType) {
1066
+ return await this.getUnspentOutputs(addressType);
1067
+ }
1068
+ /**
1069
+ * Return a list of all UTXOs (unspent transaction outputs) controlled by the wallet.
1070
+ *
1071
+ * @returns a list of UTXOs
1072
+ */
1073
+ async getUtxos(addressType) {
1074
+ const utxos = await this.getUsedUTxOs(addressType);
1075
+ return utxos.map((c) => fromTxUnspentOutput2(c));
1076
+ }
1077
+ /**
1078
+ * This endpoint utilizes the [CIP-8 - Message Signing](https://github.com/cardano-foundation/CIPs/tree/master/CIP-0030) to sign arbitrary data, to verify the data was signed by the owner of the private key.
1079
+ *
1080
+ * Here, we get the first wallet's address with wallet.getUsedAddresses(), alternativelly you can use reward addresses (getRewardAddresses()) too. It's really up to you as the developer which address you want to use in your application.
1081
+ *
1082
+ * @param address
1083
+ * @param payload
1084
+ * @returns a signature
1085
+ */
1086
+ signData(payload) {
1087
+ return this._wallet.signData(this.getChangeAddress(), payload);
1088
+ }
1089
+ /**
1090
+ * Requests user to sign the provided transaction (tx). The wallet should ask the user for permission, and if given, try to sign the supplied body and return a signed transaction. partialSign should be true if the transaction provided requires multiple signatures.
1091
+ *
1092
+ * @param unsignedTx
1093
+ * @param partialSign
1094
+ * @returns a signed transaction in CBOR
1095
+ */
1096
+ signTx(unsignedTx, partialSign = false) {
1097
+ return this._wallet.signTx(unsignedTx, partialSign);
1098
+ }
1099
+ /**
1100
+ * Experimental feature - sign multiple transactions at once.
1101
+ *
1102
+ * @param unsignedTxs - array of unsigned transactions in CborHex string
1103
+ * @param partialSign - if the transactions are signed partially
1104
+ * @returns array of signed transactions CborHex string
1105
+ */
1106
+ signTxs(unsignedTxs, partialSign = false) {
1107
+ const signedTxs = [];
1108
+ for (const unsignedTx of unsignedTxs) {
1109
+ const signedTx = this.signTx(unsignedTx, partialSign);
1110
+ signedTxs.push(signedTx);
1111
+ }
1112
+ return signedTxs;
1113
+ }
1114
+ /**
1115
+ * Submits the signed transaction to the blockchain network.
1116
+ *
1117
+ * As wallets should already have this ability to submit transaction, we allow dApps to request that a transaction be sent through it. If the wallet accepts the transaction and tries to send it, it shall return the transaction ID for the dApp to track. The wallet can return error messages or failure if there was an error in sending it.
1118
+ *
1119
+ * @param tx
1120
+ * @returns a transaction hash
1121
+ */
1122
+ async submitTx(tx) {
1123
+ return await this._wallet.submitTx(tx);
1124
+ }
1125
+ /**
1126
+ * Get a used address of type Address from the wallet.
1127
+ *
1128
+ * This is used in transaction building.
1129
+ *
1130
+ * @returns an Address object
1131
+ */
1132
+ getUsedAddress(addressType) {
1133
+ return this._wallet.getUsedAddress(0, 0, addressType);
1134
+ }
1135
+ /**
1136
+ * Get a list of UTXOs to be used for transaction building.
1137
+ *
1138
+ * This is used in transaction building.
1139
+ *
1140
+ * @returns a list of UTXOs
1141
+ */
1142
+ async getUnspentOutputs(addressType) {
1143
+ return await this._wallet.getUnspentOutputs(0, addressType);
1144
+ }
1145
+ /**
1146
+ * A helper function to get the assets in the wallet.
1147
+ *
1148
+ * @returns a list of assets
1149
+ */
1150
+ async getAssets() {
1151
+ const balance = await this.getBalance();
1152
+ return balance.filter((v) => v.unit !== "lovelace").map((v) => {
1153
+ const policyId = v.unit.slice(0, POLICY_ID_LENGTH2);
1154
+ const assetName = v.unit.slice(POLICY_ID_LENGTH2);
1155
+ const fingerprint = resolveFingerprint2(policyId, assetName);
1156
+ return {
1157
+ unit: v.unit,
1158
+ policyId,
1159
+ assetName: toUTF8(assetName),
1160
+ fingerprint,
1161
+ quantity: v.quantity
1162
+ };
1163
+ });
1164
+ }
1165
+ /**
1166
+ * A helper function to get the lovelace balance in the wallet.
1167
+ *
1168
+ * @returns lovelace balance
1169
+ */
1170
+ async getLovelace() {
1171
+ const balance = await this.getBalance();
1172
+ const nativeAsset = balance.find((v) => v.unit === "lovelace");
1173
+ return nativeAsset !== void 0 ? nativeAsset.quantity : "0";
1174
+ }
1175
+ /**
1176
+ * A helper function to get the assets of a specific policy ID in the wallet.
1177
+ *
1178
+ * @param policyId
1179
+ * @returns a list of assets
1180
+ */
1181
+ async getPolicyIdAssets(policyId) {
1182
+ const assets = await this.getAssets();
1183
+ return assets.filter((v) => v.policyId === policyId);
1184
+ }
1185
+ /**
1186
+ * A helper function to get the policy IDs of all the assets in the wallet.
1187
+ *
1188
+ * @returns a list of policy IDs
1189
+ */
1190
+ async getPolicyIds() {
1191
+ const balance = await this.getBalance();
1192
+ return Array.from(
1193
+ new Set(balance.map((v) => v.unit.slice(0, POLICY_ID_LENGTH2)))
1194
+ ).filter((p) => p !== "lovelace");
1195
+ }
1196
+ /**
1197
+ * A helper function to create a collateral input for a transaction.
1198
+ *
1199
+ * @returns a transaction hash
1200
+ */
1201
+ async createCollateral() {
1202
+ const tx = new Transaction3({ initiator: this });
1203
+ tx.sendLovelace(this.getChangeAddress(), "5000000");
1204
+ const unsignedTx = await tx.build();
1205
+ const signedTx = await this.signTx(unsignedTx);
1206
+ const txHash = await this.submitTx(signedTx);
1207
+ return txHash;
1208
+ }
1209
+ /**
1210
+ * Generate mnemonic or private key
1211
+ *
1212
+ * @param privateKey return private key if true
1213
+ * @returns a transaction hash
1214
+ */
1215
+ static brew(privateKey = false, strength = 256) {
1216
+ const mnemonic = EmbeddedWallet.generateMnemonic(strength);
1217
+ if (privateKey) {
1218
+ return resolvePrivateKey(mnemonic);
1219
+ }
1220
+ return mnemonic;
1221
+ }
1222
+ };
1223
+ export {
1224
+ AppWallet,
1225
+ BrowserWallet,
1226
+ EmbeddedWallet,
1227
+ MeshWallet,
1228
+ WalletStaticMethods
1229
+ };
1230
+ /*! Bundled license information:
1231
+
1232
+ @scure/base/lib/esm/index.js:
1233
+ (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1234
+ */