@meshsdk/wallet 1.6.0-alpha.11

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.
@@ -0,0 +1,440 @@
1
+ import {
2
+ Asset,
3
+ AssetExtended,
4
+ DataSignature,
5
+ DEFAULT_PROTOCOL_PARAMETERS,
6
+ fromUTF8,
7
+ IInitiator,
8
+ ISigner,
9
+ ISubmitter,
10
+ POLICY_ID_LENGTH,
11
+ resolveFingerprint,
12
+ UTxO,
13
+ Wallet,
14
+ } from "@meshsdk/common";
15
+ import {
16
+ Address,
17
+ addressToBech32,
18
+ CardanoSDKUtil,
19
+ deserializeAddress,
20
+ deserializeTx,
21
+ deserializeTxUnspentOutput,
22
+ deserializeValue,
23
+ fromTxUnspentOutput,
24
+ fromValue,
25
+ Serialization,
26
+ toAddress,
27
+ Transaction,
28
+ TransactionUnspentOutput,
29
+ VkeyWitness,
30
+ } from "@meshsdk/core-cst";
31
+
32
+ import { Cardano, WalletInstance } from "../types";
33
+
34
+ declare global {
35
+ interface Window {
36
+ cardano: Cardano;
37
+ }
38
+ }
39
+
40
+ export class BrowserWallet implements IInitiator, ISigner, ISubmitter {
41
+ walletInstance: WalletInstance;
42
+
43
+ private constructor(
44
+ readonly _walletInstance: WalletInstance,
45
+ readonly _walletName: string,
46
+ ) {
47
+ this.walletInstance = { ..._walletInstance };
48
+ }
49
+
50
+ /**
51
+ * Returns a list of wallets installed on user's device. Each wallet is an object with the following properties:
52
+ * - A name is provided to display wallet's name on the user interface.
53
+ * - A version is provided to display wallet's version on the user interface.
54
+ * - An icon is provided to display wallet's icon on the user interface.
55
+ *
56
+ * @returns a list of wallet names
57
+ */
58
+ static getInstalledWallets(): Wallet[] {
59
+ if (window === undefined) return [];
60
+ if (window.cardano === undefined) return [];
61
+
62
+ let wallets: Wallet[] = [];
63
+ for (const key in window.cardano) {
64
+ try {
65
+ const _wallet = window.cardano[key];
66
+ if (_wallet === undefined) continue;
67
+ if (_wallet.name === undefined) continue;
68
+ if (_wallet.icon === undefined) continue;
69
+ if (_wallet.apiVersion === undefined) continue;
70
+ wallets.push({
71
+ id: key,
72
+ name: _wallet.name,
73
+ icon: _wallet.icon,
74
+ version: _wallet.apiVersion,
75
+ });
76
+ } catch (e) {}
77
+ }
78
+
79
+ return wallets;
80
+ }
81
+
82
+ /**
83
+ * 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.
84
+ *
85
+ * 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.
86
+ *
87
+ * @param walletName
88
+ * @returns WalletInstance
89
+ */
90
+ static async enable(walletName: string): Promise<BrowserWallet> {
91
+ try {
92
+ const walletInstance = await BrowserWallet.resolveInstance(walletName);
93
+
94
+ if (walletInstance !== undefined)
95
+ return new BrowserWallet(walletInstance, walletName);
96
+
97
+ throw new Error(`Couldn't create an instance of wallet: ${walletName}`);
98
+ } catch (error) {
99
+ throw new Error(
100
+ `[BrowserWallet] An error occurred during enable: ${JSON.stringify(
101
+ error,
102
+ )}.`,
103
+ );
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Retrieves the total available balance of the wallet, encoded in CBOR.
109
+ * @returns {Promise<Value>} - The balance of the wallet.
110
+ */
111
+ // async _getBalance(): Promise<Value> {
112
+ // const balance = await this._walletInstance.getBalance();
113
+ // return Value.fromCbor(HexBlob(balance));
114
+ // }
115
+
116
+ /**
117
+ * 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:
118
+ * - A unit is provided to display asset's name on the user interface.
119
+ * - A quantity is provided to display asset's quantity on the user interface.
120
+ *
121
+ * @returns a list of assets and their quantities
122
+ */
123
+ async getBalance(): Promise<Asset[]> {
124
+ const balance = await this._walletInstance.getBalance();
125
+ return fromValue(deserializeValue(balance));
126
+ }
127
+
128
+ /**
129
+ * 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.
130
+ *
131
+ * @returns an address
132
+ */
133
+ async getChangeAddress(): Promise<string> {
134
+ const changeAddress = await this._walletInstance.getChangeAddress();
135
+ return addressToBech32(deserializeAddress(changeAddress));
136
+ }
137
+
138
+ /**
139
+ * 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).
140
+ *
141
+ * 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.
142
+ *
143
+ * @param limit
144
+ * @returns a list of UTXOs
145
+ */
146
+ async getCollateral(): Promise<UTxO[]> {
147
+ const deserializedCollateral = await this.getCollateralUnspentOutput();
148
+ return deserializedCollateral.map((dc) => fromTxUnspentOutput(dc));
149
+ }
150
+
151
+ /**
152
+ * 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.
153
+ *
154
+ * @returns network ID
155
+ */
156
+ getNetworkId(): Promise<number> {
157
+ return this._walletInstance.getNetworkId();
158
+ }
159
+
160
+ /**
161
+ * 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.
162
+ *
163
+ * @returns a list of reward addresses
164
+ */
165
+ async getRewardAddresses(): Promise<string[]> {
166
+ const rewardAddresses = await this._walletInstance.getRewardAddresses();
167
+ return rewardAddresses.map((ra) => addressToBech32(deserializeAddress(ra)));
168
+ }
169
+
170
+ /**
171
+ * Returns a list of unused addresses controlled by the wallet.
172
+ *
173
+ * @returns a list of unused addresses
174
+ */
175
+ async getUnusedAddresses(): Promise<string[]> {
176
+ const unusedAddresses = await this._walletInstance.getUnusedAddresses();
177
+ return unusedAddresses.map((una) =>
178
+ addressToBech32(deserializeAddress(una)),
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Returns a list of used addresses controlled by the wallet.
184
+ *
185
+ * @returns a list of used addresses
186
+ */
187
+ async getUsedAddresses(): Promise<string[]> {
188
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
189
+ return usedAddresses.map((usa) => addressToBech32(deserializeAddress(usa)));
190
+ }
191
+
192
+ /**
193
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
194
+ *
195
+ * This is used in transaction building.
196
+ *
197
+ * @returns a list of UTXOs
198
+ */
199
+ async getUsedCollateral(
200
+ limit = DEFAULT_PROTOCOL_PARAMETERS.maxCollateralInputs,
201
+ ): Promise<TransactionUnspentOutput[]> {
202
+ const collateral =
203
+ (await this._walletInstance.experimental.getCollateral()) ?? [];
204
+ return collateral.map((c) => deserializeTxUnspentOutput(c)).slice(0, limit);
205
+ }
206
+
207
+ /**
208
+ * Return a list of all UTXOs (unspent transaction outputs) controlled by the wallet.
209
+ *
210
+ * @returns a list of UTXOs
211
+ */
212
+ async getUtxos(): Promise<UTxO[]> {
213
+ const deserializedUTxOs = await this.getUsedUTxOs();
214
+ return deserializedUTxOs.map((du) => fromTxUnspentOutput(du));
215
+ }
216
+
217
+ /**
218
+ * 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.
219
+ *
220
+ * 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.
221
+ *
222
+ * @param address
223
+ * @param payload
224
+ * @returns a signature
225
+ */
226
+ signData(address: string, payload: string): Promise<DataSignature> {
227
+ const signerAddress = toAddress(address).toBytes().toString();
228
+ return this._walletInstance.signData(signerAddress, fromUTF8(payload));
229
+ }
230
+
231
+ /**
232
+ * 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.
233
+ *
234
+ * @param unsignedTx
235
+ * @param partialSign
236
+ * @returns a signed transaction in CBOR
237
+ */
238
+ async signTx(unsignedTx: string, partialSign = false): Promise<string> {
239
+ const witness = await this._walletInstance.signTx(unsignedTx, partialSign);
240
+ console.log("witness", witness);
241
+
242
+ return BrowserWallet.addBrowserWitnesses(unsignedTx, witness);
243
+ }
244
+
245
+ /**
246
+ * Experimental feature - sign multiple transactions at once (Supported wallet(s): Typhon)
247
+ *
248
+ * @param unsignedTxs - array of unsigned transactions in CborHex string
249
+ * @param partialSign - if the transactions are signed partially
250
+ * @returns array of signed transactions CborHex string
251
+ */
252
+ async signTxs(unsignedTxs: string[], partialSign = false): Promise<string[]> {
253
+ let witnessSets: string[] | undefined = undefined;
254
+ // Hardcoded behavior customized for different wallet for now as there is no standard confirmed
255
+ switch (this._walletName) {
256
+ case "Typhon Wallet":
257
+ if (this._walletInstance.signTxs) {
258
+ witnessSets = await this._walletInstance.signTxs(
259
+ unsignedTxs,
260
+ partialSign,
261
+ );
262
+ }
263
+ break;
264
+ default:
265
+ if (this._walletInstance.signTxs) {
266
+ witnessSets = await this._walletInstance.signTxs(
267
+ unsignedTxs.map((cbor) => ({
268
+ cbor,
269
+ partialSign,
270
+ })),
271
+ );
272
+ } else if (this._walletInstance.experimental.signTxs) {
273
+ witnessSets = await this._walletInstance.experimental.signTxs(
274
+ unsignedTxs.map((cbor) => ({
275
+ cbor,
276
+ partialSign,
277
+ })),
278
+ );
279
+ }
280
+ break;
281
+ }
282
+
283
+ if (!witnessSets) throw new Error("Wallet does not support signTxs");
284
+
285
+ const signedTxs: string[] = [];
286
+ for (let i = 0; i < witnessSets.length; i++) {
287
+ const unsignedTx = unsignedTxs[i]!;
288
+ const cWitness = witnessSets[i]!;
289
+ const signedTx = BrowserWallet.addBrowserWitnesses(unsignedTx, cWitness);
290
+ signedTxs.push(signedTx);
291
+ }
292
+
293
+ return signedTxs;
294
+ }
295
+
296
+ /**
297
+ * Submits the signed transaction to the blockchain network.
298
+ *
299
+ * 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.
300
+ *
301
+ * @param tx
302
+ * @returns a transaction hash
303
+ */
304
+ submitTx(tx: string): Promise<string> {
305
+ return this._walletInstance.submitTx(tx);
306
+ }
307
+
308
+ /**
309
+ * Get a used address of type Address from the wallet.
310
+ *
311
+ * This is used in transaction building.
312
+ *
313
+ * @returns an Address object
314
+ */
315
+ async getUsedAddress(): Promise<Address> {
316
+ const usedAddresses = await this._walletInstance.getUsedAddresses();
317
+ if (usedAddresses.length === 0) throw new Error("No used addresses found");
318
+ return deserializeAddress(usedAddresses[0]!);
319
+ }
320
+
321
+ /**
322
+ * Get a list of UTXOs to be used as collateral inputs for transactions with plutus script inputs.
323
+ *
324
+ * This is used in transaction building.
325
+ *
326
+ * @returns a list of UTXOs
327
+ */
328
+ async getCollateralUnspentOutput(): Promise<TransactionUnspentOutput[]> {
329
+ const collateral =
330
+ (await this._walletInstance.experimental.getCollateral()) ?? [];
331
+ return collateral.map((c) => deserializeTxUnspentOutput(c));
332
+ }
333
+
334
+ /**
335
+ * Get a list of UTXOs to be used for transaction building.
336
+ *
337
+ * This is used in transaction building.
338
+ *
339
+ * @returns a list of UTXOs
340
+ */
341
+ async getUsedUTxOs(): Promise<TransactionUnspentOutput[]> {
342
+ const utxos = (await this._walletInstance.getUtxos()) ?? [];
343
+ return utxos.map((u) => deserializeTxUnspentOutput(u));
344
+ }
345
+
346
+ /**
347
+ * A helper function to get the assets in the wallet.
348
+ *
349
+ * @returns a list of assets
350
+ */
351
+ async getAssets(): Promise<AssetExtended[]> {
352
+ const balance = await this.getBalance();
353
+ return balance
354
+ .filter((v) => v.unit !== "lovelace")
355
+ .map((v) => {
356
+ const policyId = v.unit.slice(0, POLICY_ID_LENGTH);
357
+ const assetName = v.unit.slice(POLICY_ID_LENGTH);
358
+ const fingerprint = resolveFingerprint(policyId, assetName);
359
+
360
+ return {
361
+ unit: v.unit,
362
+ policyId,
363
+ assetName,
364
+ fingerprint,
365
+ quantity: v.quantity,
366
+ };
367
+ });
368
+ }
369
+
370
+ /**
371
+ * A helper function to get the lovelace balance in the wallet.
372
+ *
373
+ * @returns lovelace balance
374
+ */
375
+ async getLovelace(): Promise<string> {
376
+ const balance = await this.getBalance();
377
+ const nativeAsset = balance.find((v) => v.unit === "lovelace");
378
+
379
+ return nativeAsset !== undefined ? nativeAsset.quantity : "0";
380
+ }
381
+
382
+ /**
383
+ * A helper function to get the assets of a specific policy ID in the wallet.
384
+ *
385
+ * @param policyId
386
+ * @returns a list of assets
387
+ */
388
+ async getPolicyIdAssets(policyId: string): Promise<AssetExtended[]> {
389
+ const assets = await this.getAssets();
390
+ return assets.filter((v) => v.policyId === policyId);
391
+ }
392
+
393
+ /**
394
+ * A helper function to get the policy IDs of all the assets in the wallet.
395
+ *
396
+ * @returns a list of policy IDs
397
+ */
398
+ async getPolicyIds(): Promise<string[]> {
399
+ const balance = await this.getBalance();
400
+ return Array.from(
401
+ new Set(balance.map((v) => v.unit.slice(0, POLICY_ID_LENGTH))),
402
+ ).filter((p) => p !== "lovelace");
403
+ }
404
+
405
+ private static resolveInstance(walletName: string) {
406
+ if (window.cardano === undefined) return undefined;
407
+ if (window.cardano[walletName] === undefined) return undefined;
408
+
409
+ const wallet = window.cardano[walletName];
410
+ return wallet?.enable();
411
+ }
412
+
413
+ static addBrowserWitnesses(unsignedTx: string, witnesses: string) {
414
+ const cWitness = Serialization.TransactionWitnessSet.fromCbor(
415
+ CardanoSDKUtil.HexBlob(witnesses),
416
+ )
417
+ .vkeys()
418
+ ?.values();
419
+
420
+ if (cWitness === undefined) {
421
+ return unsignedTx;
422
+ }
423
+
424
+ let tx = deserializeTx(unsignedTx);
425
+ // let tx = Transaction.fromCbor(CardanoSDK.TxCBOR(txHex));
426
+ let witnessSet = tx.witnessSet();
427
+ let witnessSetVkeys = witnessSet.vkeys();
428
+ let witnessSetVkeysValues: Serialization.VkeyWitness[] = witnessSetVkeys
429
+ ? [...witnessSetVkeys.values(), ...cWitness]
430
+ : [...cWitness];
431
+ witnessSet.setVkeys(
432
+ Serialization.CborSet.fromCore(
433
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
434
+ VkeyWitness.fromCore,
435
+ ),
436
+ );
437
+
438
+ return new Transaction(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
439
+ }
440
+ }
@@ -0,0 +1,258 @@
1
+ import * as BaseEncoding from "@scure/base";
2
+
3
+ import {
4
+ bytesToHex,
5
+ DataSignature,
6
+ generateMnemonic,
7
+ mnemonicToEntropy,
8
+ } from "@meshsdk/common";
9
+ import {
10
+ Address,
11
+ Bip32PrivateKey,
12
+ buildBaseAddress,
13
+ buildBip32PrivateKey,
14
+ buildEnterpriseAddress,
15
+ buildKeys,
16
+ buildRewardAddress,
17
+ deserializeTx,
18
+ deserializeTxHash,
19
+ Ed25519KeyHashHex,
20
+ Ed25519PublicKeyHex,
21
+ Ed25519SignatureHex,
22
+ Hash28ByteBase16,
23
+ PrivateKey,
24
+ resolveTxHash,
25
+ Serialization,
26
+ signData,
27
+ Transaction,
28
+ VkeyWitness,
29
+ } from "@meshsdk/core-cst";
30
+
31
+ export type Account = {
32
+ baseAddress: Address;
33
+ enterpriseAddress: Address;
34
+ rewardAddress: Address;
35
+ baseAddressBech32: string;
36
+ enterpriseAddressBech32: string;
37
+ rewardAddressBech32: string;
38
+ paymentKey: PrivateKey;
39
+ stakeKey: PrivateKey;
40
+ paymentKeyHex: string;
41
+ stakeKeyHex: string;
42
+ };
43
+
44
+ export type EmbeddedWalletKeyType =
45
+ | {
46
+ type: "root";
47
+ bech32: string;
48
+ }
49
+ | {
50
+ type: "cli";
51
+ payment: string;
52
+ stake?: string;
53
+ }
54
+ | {
55
+ type: "mnemonic";
56
+ words: string[];
57
+ };
58
+
59
+ export type CreateEmbeddedWalletOptions = {
60
+ networkId: number;
61
+ key: EmbeddedWalletKeyType;
62
+ };
63
+
64
+ export class WalletStaticMethods {
65
+ static privateKeyToEntropy(bech32: string): string {
66
+ const bech32DecodedBytes = BaseEncoding.bech32.decodeToBytes(bech32).bytes;
67
+ const bip32PrivateKey = Bip32PrivateKey.fromBytes(bech32DecodedBytes);
68
+ return bytesToHex(bip32PrivateKey.bytes());
69
+ }
70
+
71
+ static mnemonicToEntropy(words: string[]): string {
72
+ const entropy = mnemonicToEntropy(words.join(" "));
73
+ const bip32PrivateKey = buildBip32PrivateKey(entropy);
74
+ return bytesToHex(bip32PrivateKey.bytes());
75
+ }
76
+
77
+ static signingKeyToEntropy(
78
+ paymentKey: string,
79
+ stakeKey: string,
80
+ ): [string, string] {
81
+ return [
82
+ paymentKey.startsWith("5820") ? paymentKey.slice(4) : paymentKey,
83
+ stakeKey.startsWith("5820") ? stakeKey.slice(4) : stakeKey,
84
+ ];
85
+ }
86
+
87
+ static getAddresses(
88
+ paymentKey: PrivateKey,
89
+ stakingKey: PrivateKey,
90
+ networkId = 0,
91
+ ): {
92
+ baseAddress: Address;
93
+ enterpriseAddress: Address;
94
+ rewardAddress: Address;
95
+ } {
96
+ const baseAddress = buildBaseAddress(
97
+ networkId,
98
+ Hash28ByteBase16.fromEd25519KeyHashHex(
99
+ Ed25519KeyHashHex(paymentKey.toPublicKey().hash().toString("hex")),
100
+ ),
101
+ Hash28ByteBase16.fromEd25519KeyHashHex(
102
+ Ed25519KeyHashHex(stakingKey.toPublicKey().hash().toString("hex")),
103
+ ),
104
+ );
105
+
106
+ const enterpriseAddress = buildEnterpriseAddress(
107
+ networkId,
108
+ Hash28ByteBase16.fromEd25519KeyHashHex(
109
+ Ed25519KeyHashHex(paymentKey.toPublicKey().hash().toString("hex")),
110
+ ),
111
+ );
112
+
113
+ const rewardAddress = buildRewardAddress(
114
+ networkId,
115
+ Hash28ByteBase16.fromEd25519KeyHashHex(
116
+ Ed25519KeyHashHex(stakingKey.toPublicKey().hash().toString("hex")),
117
+ ),
118
+ );
119
+
120
+ return {
121
+ baseAddress: baseAddress.toAddress(),
122
+ enterpriseAddress: enterpriseAddress.toAddress(),
123
+ rewardAddress: rewardAddress.toAddress(),
124
+ };
125
+ }
126
+
127
+ static generateMnemonic(strength = 256): string[] {
128
+ const mnemonic = generateMnemonic(strength);
129
+ return mnemonic.split(" ");
130
+ }
131
+
132
+ static addWitnessSets(txHex: string, witnesses: VkeyWitness[]): string {
133
+ let tx = deserializeTx(txHex);
134
+ let witnessSet = tx.witnessSet();
135
+ let witnessSetVkeys = witnessSet.vkeys();
136
+ let witnessSetVkeysValues: Serialization.VkeyWitness[] = witnessSetVkeys
137
+ ? [...witnessSetVkeys.values(), ...witnesses]
138
+ : witnesses;
139
+ witnessSet.setVkeys(
140
+ Serialization.CborSet.fromCore(
141
+ witnessSetVkeysValues.map((vkw) => vkw.toCore()),
142
+ VkeyWitness.fromCore,
143
+ ),
144
+ );
145
+ return new Transaction(tx.body(), witnessSet, tx.auxiliaryData()).toCbor();
146
+ }
147
+ }
148
+
149
+ export class EmbeddedWallet extends WalletStaticMethods {
150
+ private readonly _entropy?: string | [string, string];
151
+ private readonly _networkId: number;
152
+
153
+ constructor(options: CreateEmbeddedWalletOptions) {
154
+ super();
155
+ this._networkId = options.networkId;
156
+
157
+ switch (options.key.type) {
158
+ case "mnemonic":
159
+ this._entropy = WalletStaticMethods.mnemonicToEntropy(
160
+ options.key.words,
161
+ );
162
+ break;
163
+ case "root":
164
+ this._entropy = WalletStaticMethods.privateKeyToEntropy(
165
+ options.key.bech32,
166
+ );
167
+ break;
168
+ case "cli":
169
+ this._entropy = WalletStaticMethods.signingKeyToEntropy(
170
+ options.key.payment,
171
+ options.key.stake ?? "f0".repeat(32),
172
+ );
173
+ break;
174
+ }
175
+ }
176
+
177
+ getAccount(accountIndex = 0, keyIndex = 0): Account {
178
+ if (this._entropy == undefined)
179
+ throw new Error("[EmbeddedWallet] No keys initialized");
180
+
181
+ const { paymentKey, stakeKey } = buildKeys(
182
+ this._entropy,
183
+ accountIndex,
184
+ keyIndex,
185
+ );
186
+
187
+ const { baseAddress, enterpriseAddress, rewardAddress } =
188
+ WalletStaticMethods.getAddresses(paymentKey, stakeKey, this._networkId);
189
+
190
+ return {
191
+ baseAddress: baseAddress,
192
+ enterpriseAddress: enterpriseAddress,
193
+ rewardAddress: rewardAddress,
194
+ baseAddressBech32: baseAddress.toBech32(),
195
+ enterpriseAddressBech32: enterpriseAddress.toBech32(),
196
+ rewardAddressBech32: rewardAddress.toBech32(),
197
+ paymentKey: paymentKey,
198
+ stakeKey: stakeKey,
199
+ paymentKeyHex: paymentKey.toBytes().toString("hex"),
200
+ stakeKeyHex: stakeKey.toBytes().toString("hex"),
201
+ };
202
+ }
203
+
204
+ getNetworkId(): number {
205
+ return this._networkId;
206
+ }
207
+
208
+ signData(
209
+ address: string,
210
+ payload: string,
211
+ accountIndex = 0,
212
+ keyIndex = 0,
213
+ ): DataSignature {
214
+ try {
215
+ const account = this.getAccount(accountIndex, keyIndex);
216
+
217
+ const foundAddress = [
218
+ account.baseAddress,
219
+ account.enterpriseAddress,
220
+ account.rewardAddress,
221
+ ].find((a) => a.toBech32() === address);
222
+
223
+ if (foundAddress === undefined)
224
+ throw new Error(
225
+ `[EmbeddedWallet] Address: ${address} doesn't belong to this account.`,
226
+ );
227
+
228
+ return signData(payload, account.paymentKey);
229
+ } catch (error) {
230
+ throw new Error(
231
+ `[EmbeddedWallet] An error occurred during signData: ${error}.`,
232
+ );
233
+ }
234
+ }
235
+
236
+ signTx(unsignedTx: string, accountIndex = 0, keyIndex = 0): VkeyWitness {
237
+ try {
238
+ const txHash = deserializeTxHash(resolveTxHash(unsignedTx));
239
+
240
+ const account = this.getAccount(accountIndex, keyIndex);
241
+
242
+ const vKeyWitness = new VkeyWitness(
243
+ Ed25519PublicKeyHex(
244
+ account.paymentKey.toPublicKey().toBytes().toString("hex"),
245
+ ),
246
+ Ed25519SignatureHex(
247
+ account.paymentKey.sign(Buffer.from(txHash, "hex")).toString("hex"),
248
+ ),
249
+ );
250
+
251
+ return vKeyWitness;
252
+ } catch (error) {
253
+ throw new Error(
254
+ `[EmbeddedWallet] An error occurred during signTx: ${error}.`,
255
+ );
256
+ }
257
+ }
258
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./app";
2
+ export * from "./browser";
3
+ export * from "./embedded";
4
+ export * from "./mesh";