/
local-wallet.ts
894 lines (823 loc) · 27.2 KB
/
local-wallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
import { AsyncStorage, createAsyncLocalStorage } from "../../core";
import { Connector } from "../interfaces/connector";
import { walletIds } from "../constants/walletIds";
import { AbstractClientWallet, WalletOptions } from "./base";
import {
Chain,
defaultChains,
Ethereum,
updateChainRPCs,
} from "@thirdweb-dev/chains";
import { Wallet, utils } from "ethers";
import { aesEncrypt, aesDecryptCompat } from "@thirdweb-dev/crypto";
export type LocalWalletOptions = {
chain?: Chain;
storage?: AsyncStorage;
secretKey?: string;
};
export type WalletData = {
address: string;
strategy: "mnemonic" | "privateKey" | "encryptedJson";
data: string;
isEncrypted: boolean;
};
// eslint-disable-next-line @typescript-eslint/ban-types
export type LocalWalletConnectionArgs = {};
const STORAGE_KEY_WALLET_DATA = "localWalletData";
/**
* Allow users to connect to your app by generating a [Local Wallet](https://portal.thirdweb.com/glossary/local-wallet) directly in your application.
*
* A local wallet is a low-level wallet that allows you to create wallets within your application or project. It is a non-custodial solution that simplifies the onboarding process and improves the user experience for web3 apps in two ways:
*
* 1. It enables non-web3 native users to get started easily without having to create a wallet.
* 2. It hides transaction confirmations from users.
*
* After generating wallets for your users, you can offer multiple persistence and backup options.
*
* @example
* ```javascript
* import { ThirdwebSDK } from "@thirdweb-dev/sdk";
* import { LocalWallet } from "@thirdweb-dev/wallets";
*
* const wallet = new LocalWallet();
*
* // generate a random wallet
* await wallet.generate();
*
* // connect the wallet to the application
* await wallet.connect();
*
* // at any point, you can save the wallet to persistent storage
* await wallet.save(config);
* // and load it back up
* await wallet.load(config);
*
* // you can also export the wallet out of the application
* const exportedWallet = await wallet.export(config);
* // and import it back in
* await wallet.import(exportedWallet, config);
*
* // You can then use this wallet to perform transactions via the SDK
* const sdk = await ThirdwebSDK.fromWallet(wallet, "goerli");
* ```
*
* ## Local Wallet Backup
*
* Local wallets can be persisted on disk, or backed up to the cloud. Currently 3 formats are supported:
*
* - `encryptedJSON` - a standard format for encrypted wallets, this requires a password to encrypt/decrypt the wallet. Recommended for safe backups.
* - `privateKey` - the raw private key. This can be stored encrypted or un-encrypted. If not encrypted, make sure you store it somewhere safe.
* - `mnemonic` - the raw seed phrase. This can be stored encrypted or un-encrypted. If not encrypted, make sure you store it somewhere safe.
*
* We provide encryption capabilities out of the box, but you can customize the type of encryption, and also turn it off completely.
*
* The type of storage can also be overridden, allowing you to store wallets anywhere you want, including remote locations.
*
* By default, wallets will be stored on the browser's storage for web (React), and on the secure storage of the device for mobile (React Native).
*
* On Node.js, you can use `LocalWalletNode` which by default will save to the local file system of the machine.
*
* ```javascript
* import { LocalWalletNode } from "@thirdweb-dev/wallets/evm/wallets/local-wallet-node";
*
* // wallet data will be saved in 'wallet.json' by default
* // you can also pass a different file path by specifying 'storageJsonFile' in the constructor
* const wallet = new LocalWalletNode();
*
* await localWallet.loadOrCreate({
* strategy: "privateKey",
* encryption: false,
* });
* ```
*
* Customizing where the wallet data is persisted only requires implementing a simple interface. Here's an example of a Local Wallet with custom storage:
*
* ```typescript
* class MyStorage implements AsyncStorage {
* getItem(key: string): Promise<string | null> { ... }
* setItem(key: string, value: string): Promise<void> { ... }
* removeItem(key: string): Promise<void> { ... }
* }
*
* const wallet = new LocalWallet({
* storage: new MyStorage(),
* })
* ```
*
* You can implement this any way you like, file persistance, remote cloud storage, etc.
*
* ## Encryption examples
*
* #### Save an encrypted privateKey with default encryption a password as the encryption key:
*
* ```javascript
* localWallet.save({
* strategy: "privateKey",
* encryption: {
* password: "your-encryption-password", // uses default encryption
* },
* });
* ```
*
* #### Import a raw private key or mnemonic (seed phrase) with no encryption:
*
* ```javascript
* // privateKey
* localWallet.import({
* privateKey: "your-raw-privateKey",
* encryption: false, // no encryption
* });
*
* // mnemonic
* localWallet.import({
* mnemonic: "your-raw-mnemonic",
* encryption: false, // no encryption
* });
* ```
*
* #### Save an encrypted mnemonic with a custom encryption:
*
* ```javascript
* // privateKey
* localWallet.save({
* strategy: "mnemonic",
* encryption: {
* encrypt: (message: string, password: string) => {
* return yourCustomEncryption(message, password);
* },
* password: "your-encryption-password",
* },
* });
* ```
*
* @wallet
*/
export class LocalWallet extends AbstractClientWallet<
LocalWalletOptions,
LocalWalletConnectionArgs
> {
/**
* @internal
*/
connector?: Connector;
/**
* @internal
*/
options: WalletOptions<LocalWalletOptions>;
/**
* @internal
*/
ethersWallet?: Wallet;
/**
* @internal
*/
private _storage: AsyncStorage;
/**
* @internal
*/
static id = walletIds.localWallet as string;
/**
* @internal
*/
static meta = {
name: "Local Wallet",
iconURL:
"ipfs://QmbQzSNGvmNYZzem9jZRuYeLe9K2W4pqbdnVUp7Y6edQ8Y/local-wallet.svg",
};
/**
* @internal
*/
public get walletName() {
return "Local Wallet" as const;
}
/**
* Initialize the `LocalWallet` with the given `options`
*
* @param options - The `options` object contains the following properties:
* ### clientId or secretKey (recommended)
* Provide `clientId` or `secretKey` to use the thirdweb RPCs for given `chains`
*
* If you are using the `LocalWallet` in a in frontend - provide a `clientId`, If you are using the `LocalWallet` in backend - you can provide a `secretKey`.
*
* You can create a `clientId` / `secretKey` from [thirdweb dashboard](https://thirdweb.com/create-api-key).
*
* ### chain (optional)
* Must be a `Chain` object, from the [`@thirdweb-dev/chains`](https://www.npmjs.com/package/\@thirdweb-dev/chains) package.
* Defaults to `Ethereum`.
*
* ### chains (optional)
* Provide an array of chains you want to support.
*
* Must be an array of `Chain` objects, from the [`@thirdweb-dev/chains`](https://www.npmjs.com/package/\@thirdweb-dev/chains) package.
*
* Defaults to our [default chains](/react/react.thirdwebprovider#default-chains).
*
* ### storage (optional)
* This is the default storage for storing the private key, mnemonic or encrypted JSON. This can be implemented in any way you want, as long as it conforms to the `AsyncStorage` interface:
*
* If omitted, defaults to browser local storage.
*
*
* ```javascript
* import { LocalWallet } from "@thirdweb-dev/wallets";
*
* const customStorage = {
* getItem: (key) => {
* // Implement your own storage logic here
* },
* removeItem: (key) => {
* // Implement your own storage logic here
* },
* setItem: (key, value) => {
* // Implement your own storage logic here
* },
* };
*
* const walletWithOptions = new LocalWallet({
* storage: customStorage,
* });
* ```
*
*/
constructor(options?: WalletOptions<LocalWalletOptions>) {
super(LocalWallet.id, options);
if (options?.chain && options.clientId) {
options.chain = updateChainRPCs(options.chain, options.clientId);
}
this.options = options || {};
this._storage =
options?.storage || createAsyncLocalStorage(walletIds.localWallet);
}
protected async getConnector(): Promise<Connector> {
if (!this.connector) {
const { LocalWalletConnector: LocalWalletConnector } = await import(
"../connectors/local-wallet"
);
if (!this.ethersWallet) {
throw new Error("wallet is not initialized");
}
const defaults = (
this.options.chain
? [...defaultChains, this.options.chain]
: defaultChains
).map((c) => updateChainRPCs(c, this.options.clientId));
this.connector = new LocalWalletConnector({
chain:
this.options.chain ||
updateChainRPCs(Ethereum, this.options.clientId),
ethersWallet: this.ethersWallet,
chains: this.chains || defaults,
clientId: this.options.clientId,
secretKey: this.options.secretKey,
});
}
return this.connector;
}
/**
* Load the saved wallet data from storage, if it exists, or generate a new one and save it.
*
* @example
* ```js
* wallet.loadOrCreate({
* strategy: "encryptedJson",
* password: password,
* });
* ```
*
* @param options - The `options` object must be of type `LocalWalletLoadOrCreateOptions`. It takes a `strategy` property and other properties depending on the strategy.
*
* ### strategy "encryptedJson"
* Load the wallet from encrypted JSON. The `options` object takes the following properties:
* * `strategy` - must be "encryptedJson"
* * `password` - the password to decrypt the encrypted JSON
* * `storage` - optional storage to get the wallet data from. Must be of type `AsyncStorage`
*
* ### strategy "privateKey"
* Load the wallet from a private key. The `options` object takes the following properties:
* * `strategy` - must be "privateKey"
* * `encryption` - optional encryption object of type `DecryptOptions` to decrypt the private key. This is only required if the saved private key is encrypted.
*/
async loadOrCreate(options: LocalWalletLoadOrCreateOptions) {
if (await this.getSavedData(options.storage)) {
await this.load(options);
} else {
await this.generate();
await this.save(options);
}
}
/**
* Creates a new random wallet and returns the wallet address.
*
* @example
* ```ts
* const address = await wallet.generate();
* ```
*
* @returns Promise that resolves to the address of the wallet
*/
async generate() {
if (this.ethersWallet) {
throw new Error("wallet is already initialized");
}
const random = utils.randomBytes(32);
this.ethersWallet = new Wallet(random);
return this.ethersWallet.address;
}
/**
* Create local wallet by importing a private key, mnemonic or encrypted JSON.
* @example
* ```javascript
* const address = await localWallet.import({
* privateKey: "...",
* encryption: false,
* });
* ```
*
* @param options - The `options` object must be of type `LocalWalletImportOptions` which can have either `privateKey`, `mnemonic` or `encryptedJson` as a property.
* They all can be encrypted or un-encrypted. If encrypted, the `encryption` property must be provided with `password` property to decrypt the data.
*
* ### privateKey
* The Private Key of the wallet.
*
* ### mnemonic
* The mnemonic (seed phrase) of the wallet.
*
* ### encryptedJson
* The encrypted JSON of the wallet.
*
* ### encryption
* This is only required if the given `privateKey`, `mnemonic` or `encryptedJson` is encrypted.
* The `encryption` object of type `DecryptOptions` can be provided to decrypt the data. It is an object with the following properties:
*
* #### password
* The password to decrypt the data.
*
* #### decrypt
* A custom decrypt function that takes the encrypted data and password as arguments and returns the decrypted data.
*
* @returns Promise that resolves to the address of the wallet
*/
async import(options: LocalWalletImportOptions): Promise<string> {
if (this.ethersWallet) {
throw new Error("wallet is already initialized");
}
if ("encryptedJson" in options) {
this.ethersWallet = await Wallet.fromEncryptedJson(
options.encryptedJson,
options.password,
);
return this.ethersWallet.address;
}
if ("privateKey" in options) {
if (!options.encryption && !isValidPrivateKey(options.privateKey)) {
throw new Error("invalid private key");
}
const privateKey = await getDecryptor(options.encryption)(
options.privateKey,
);
if (
options.encryption &&
(privateKey === "" || !isValidPrivateKey(privateKey))
) {
throw new Error("invalid password");
}
this.ethersWallet = new Wallet(privateKey);
return this.ethersWallet.address;
}
if ("mnemonic" in options) {
if (!options.encryption && !utils.isValidMnemonic(options.mnemonic)) {
throw new Error("invalid mnemonic");
}
const mnemonic = await getDecryptor(options.encryption)(options.mnemonic);
if (
options.encryption &&
(mnemonic === "" || !utils.isValidMnemonic(mnemonic))
) {
throw new Error("invalid password");
}
this.ethersWallet = Wallet.fromMnemonic(mnemonic);
return this.ethersWallet.address;
}
throw new Error("invalid import strategy");
}
/**
* Initialize the wallet from saved data on storage
*
* ```js
* await wallet.load({
* strategy: "encryptedJson",
* password: "your-password",
* });
* ```
*
* @param options - The `options` object must be of type `LocalWalletLoadOptions` which contains a `strategy` property and other properties depending on the strategy.
*
* ### strategy "encryptedJson"
* Initialize the wallet from encrypted JSON. The `options` object takes the following properties:
* * `strategy` - must be "encryptedJson"
* * `password` - the password to decrypt the encrypted JSON
* * `storage` - optional storage to get the wallet data from. Must be of type `AsyncStorage`
*
* ### strategy "privateKey"
* Initialize the wallet from a private key. The `options` object takes the following properties:
* * `strategy` - must be "privateKey"
* * `encryption` - optional encryption object of type `DecryptOptions` to decrypt the private key. This is only required if the private key is encrypted.
* * `storage` - optional storage to get the wallet data from. Must be of type `AsyncStorage`
*
* ### strategy "mnemonic"
* Initialize the wallet from a mnemonic (seed phrase). The `options` object takes the following properties:
* * `strategy` - must be "mnemonic"
* * `encryption` - optional encryption object of type `DecryptOptions` to decrypt the mnemonic. This is only required if the mnemonic is encrypted.
* * `storage` - optional storage to get the wallet data from. Must be of type `AsyncStorage`
*
* @returns Promise that resolves to the address of the wallet
*/
async load(options: LocalWalletLoadOptions): Promise<string> {
if (this.ethersWallet) {
throw new Error("wallet is already initialized");
}
const walletData = await this.getSavedData(options.storage);
if (!walletData) {
throw new Error("No Saved wallet found in storage");
}
// strategy mismatch
if (walletData.strategy !== options.strategy) {
throw new Error(
`Saved wallet data is not ${options.strategy}, it is ${walletData.strategy}`,
);
}
if (options.strategy === "encryptedJson") {
return this.import({
encryptedJson: walletData.data,
password: options.password,
});
}
// encryption mismatch
if (walletData.isEncrypted && !options.encryption) {
throw new Error(
"Saved wallet data is encrypted, but no password is provided",
);
}
if (!walletData.isEncrypted && options.encryption) {
throw new Error(
"Saved wallet data is not encrypted, but encryption config is provided",
);
}
if (options.strategy === "privateKey") {
return this.import({
privateKey: walletData.data,
encryption: options.encryption,
});
}
if (options.strategy === "mnemonic") {
return this.import({
mnemonic: walletData.data,
encryption: options.encryption,
});
}
throw new Error("invalid load strategy");
}
/**
* Save the wallet data to storage
*
* @example
* ```javascript
* wallet.save({
* strategy: "encryptedJson",
* password: "password",
* });
* ```
*
* @param options - The `options` object must be of type `LocalWalletSaveOptions`. It takes a `strategy` property and other properties depending on the strategy.
*
* ### strategy "encryptedJson"
* Save the wallet data as encrypted JSON. The `options` object takes the following properties:
* * `strategy` - must be "encryptedJson"
* * `password` - the password to encrypt the wallet data
* * `storage` - optional storage to save the wallet data to. Must be of type `AsyncStorage`
*
* ### strategy "privateKey"
* Save the wallet data as a private key. The `options` object takes the following properties:
* * `strategy` - must be "privateKey"
* * `encryption` - optional encryption object of type `EncryptOptions` to encrypt the private key. This is only required if you want to encrypt the private key.
* * `storage` - optional storage to save the wallet data to. Must be of type `AsyncStorage`
*
* ### strategy "mnemonic"
* Save the wallet data as a mnemonic (seed phrase). The `options` object takes the following properties:
* * `strategy` - must be "mnemonic"
* * `encryption` - optional encryption object of type `EncryptOptions` to encrypt the mnemonic. This is only required if you want to encrypt the mnemonic.
* * `storage` - optional storage to save the wallet data to. Must be of type `AsyncStorage`
*
*/
async save(options: LocalWalletSaveOptions): Promise<void> {
const wallet = this.ethersWallet;
if (!wallet) {
throw new Error("Wallet is not initialized");
}
if (options.strategy === "encryptedJson") {
const encryptedData = await wallet.encrypt(options.password, {
scrypt: {
N: 1 << 32,
},
});
await this._saveData(
{
address: wallet.address,
data: encryptedData,
strategy: "encryptedJson",
isEncrypted: true,
},
options.storage,
);
}
if (options.strategy === "privateKey") {
const privateKey = await getEncryptor(options.encryption)(
wallet.privateKey,
);
await this._saveData(
{
address: wallet.address,
data: privateKey,
strategy: "privateKey",
isEncrypted: !!options.encryption,
},
options.storage,
);
}
if (options.strategy === "mnemonic") {
if (!wallet.mnemonic) {
throw new Error(
"mnemonic can not be computed if wallet is created from a private key or generated using generate()",
);
}
const mnemonic = await getEncryptor(options.encryption)(
wallet.mnemonic.phrase,
);
await this._saveData(
{
address: wallet.address,
data: mnemonic,
strategy: "mnemonic",
isEncrypted: !!options.encryption,
},
options.storage,
);
}
}
/**
* Check if the wallet data is saved in storage.
*
* @returns `true` if initialized wallet's data is saved in storage
*/
async isSaved() {
try {
const data = await this.getSavedData();
const address = await this.getAddress();
if (data?.address === address) {
return true;
}
return false;
} catch (e) {
return false;
}
}
/**
* Delete the saved wallet from storage. This action is irreversible, use with caution.
*
* @example
* ```ts
* await wallet.deleteSaved();
* ```
*/
async deleteSaved() {
await this._storage.removeItem(STORAGE_KEY_WALLET_DATA);
}
/**
* Encrypts the wallet with a password in various formats and return it.
*
* @example
* ```javascript
* const data = await wallet.export({
* strategy: "encryptedJson",
* password: "password",
* });
* ```
*
* @param options - The `options` object must be of type `LocalWalletExportOptions`. It takes a `strategy` and other properties depending on the strategy.
*
* ### strategy - "encryptedJson"
* Export wallet in encryptedJson format. The `options` object takes the following properties:
* * `strategy` - must be "encryptedJson"
* * `password` - the password to encrypt the wallet data
*
* ### strategy - "privateKey"
* Encrypt the private key of the wallet. The `options` object takes the following properties:
* * `strategy` - must be "privateKey"
* * `encryption` - encryption object of type `EncryptOptions` to encrypt the private key. It takes a `password` property to encrypt the private key and an optional `encrypt` function to encrypt the private key. If `encrypt` function is not provided, it uses the default encryption.
*
* ### strategy - "mnemonic"
* Encrypt the mnemonic (seed phrase) of the wallet. The `options` object takes the following properties:
* * `strategy` - must be "mnemonic"
* * `encryption` - encryption object of type `EncryptOptions` to encrypt the mnemonic. It takes a `password` property to encrypt the mnemonic and an optional `encrypt` function to encrypt the mnemonic. If `encrypt` function is not provided, it uses the default encryption.
*
* @returns Promise that resolves to a `string` that contains encrypted wallet data
*/
async export(options: LocalWalletExportOptions): Promise<string> {
const wallet = this.ethersWallet;
if (!wallet) {
throw new Error("Wallet is not initialized");
}
if (options.strategy === "encryptedJson") {
return wallet.encrypt(options.password, {
scrypt: {
N: 1 << 32,
},
});
}
if (options.strategy === "privateKey") {
return getEncryptor(options.encryption)(wallet.privateKey);
}
if (options.strategy === "mnemonic") {
if (!wallet.mnemonic) {
throw new Error(
"mnemonic can not be computed if wallet is created from a private key or generated using generate()",
);
}
return getEncryptor(options.encryption)(wallet.mnemonic.phrase);
}
throw new Error("Invalid export strategy");
}
/**
* Get the saved wallet data from storage
* @param storage - storage to get the wallet data from. Must be of type `AsyncStorage`
*
* @example
* ```javascript
* const someStorage = {
* getItem: (key) => {
* // Implement your own storage logic here
* },
* removeItem: (key) => {
* // Implement your own storage logic here
* },
* setItem: (key, value) => {
* // Implement your own storage logic here
* },
* }
*
* wallet.getSaved(someStorage);
* ```
*
* @returns `Promise` which resolves to a `WalletData` object containing the wallet data. It returns `null` if no wallet data is found in storage.
* ```ts
* {
* address: string;
* strategy: "mnemonic" | "privateKey" | "encryptedJson";
* data: string;
* isEncrypted: boolean;
* }
* ```
*/
async getSavedData(storage?: AsyncStorage): Promise<WalletData | null> {
const _storage = storage || this._storage;
try {
const savedDataStr = await _storage.getItem(STORAGE_KEY_WALLET_DATA);
if (!savedDataStr) {
return null;
}
const savedData = JSON.parse(savedDataStr);
if (!savedData) {
return null;
}
return savedData as WalletData;
} catch (e) {
return null;
}
}
/**
* store the wallet data to storage
*/
private async _saveData(data: WalletData, storage?: AsyncStorage) {
const _storage = storage || this._storage;
await _storage.setItem(STORAGE_KEY_WALLET_DATA, JSON.stringify(data));
}
/**
* Disconnect the wallet
*/
async disconnect() {
await super.disconnect();
this.ethersWallet = undefined;
}
}
export type LocalWalletDecryptOptions =
| {
decrypt?: (message: string, password: string) => Promise<string>;
password: string;
}
| false;
export type LocalWalletEncryptOptions =
| {
encrypt?: (message: string, password: string) => Promise<string>;
password: string;
}
| false;
export type LocalWalletImportOptions =
| {
privateKey: string;
encryption: LocalWalletDecryptOptions;
}
| {
mnemonic: string;
encryption: LocalWalletDecryptOptions;
}
| {
encryptedJson: string;
password: string;
};
export type LocalWalletLoadOptions =
| {
strategy: "encryptedJson";
password: string;
storage?: AsyncStorage;
}
| {
strategy: "privateKey";
storage?: AsyncStorage;
encryption: LocalWalletDecryptOptions;
}
| {
strategy: "mnemonic";
storage?: AsyncStorage;
encryption: LocalWalletDecryptOptions;
};
// omit the mnemonic strategy option from LoadOptions
export type LocalWalletLoadOrCreateOptions =
| {
strategy: "encryptedJson";
password: string;
storage?: AsyncStorage;
}
| {
strategy: "privateKey";
storage?: AsyncStorage;
encryption: LocalWalletDecryptOptions;
};
export type LocalWalletSaveOptions =
| { strategy: "encryptedJson"; password: string; storage?: AsyncStorage }
| {
strategy: "privateKey";
encryption: LocalWalletEncryptOptions;
storage?: AsyncStorage;
}
| {
strategy: "mnemonic";
encryption: LocalWalletEncryptOptions;
storage?: AsyncStorage;
};
export type LocalWalletExportOptions =
| { strategy: "encryptedJson"; password: string }
| {
strategy: "privateKey";
encryption: LocalWalletEncryptOptions;
}
| {
strategy: "mnemonic";
encryption: LocalWalletEncryptOptions;
};
// used in getDecryptor and getEncryptor below
async function noop(msg: string) {
return msg;
}
/**
* if encryption object is provided
* - return the encryption.decrypt function if given, else return the default decrypt function
* if encryption object is not provided
* - return a noop function
* @returns
*/
function getDecryptor(encryption: LocalWalletDecryptOptions | undefined) {
return encryption
? (msg: string) =>
// we're using aesDecryptCompat here because we want to support legacy crypto-js ciphertext for the moment
(encryption.decrypt || aesDecryptCompat)(msg, encryption.password)
: noop;
}
/**
* if encryption object is provided
* - return the encryption.encrypt function if given, else return the default encrypt function
* if encryption object is not provided
* - return a noop function
* @returns
*/
function getEncryptor(encryption: LocalWalletEncryptOptions | undefined) {
return encryption
? (msg: string) =>
(encryption.encrypt || aesEncrypt)(msg, encryption.password)
: noop;
}
/**
* @internal
*/
export function isValidPrivateKey(value: string) {
return !!value.match(/^(0x)?[0-9a-f]{64}$/i);
}