UNPKG

2.16 kBJavaScriptView Raw
1const { assert } = require('../util');
2const Account = require('./Account');
3const PrivateKeyAccount = require('./PrivateKeyAccount');
4
5/**
6 * Wallet to manager accounts.
7 */
8class Wallet extends Map {
9 /**
10 * Check if key exist
11 *
12 * @param key {string}
13 * @return {boolean}
14 */
15 has(key) {
16 return super.has(key); // XXX: for jsdoc
17 }
18
19 /**
20 * Drop one account by key
21 *
22 * @param key {string}
23 * @return {boolean}
24 */
25 delete(key) {
26 return super.delete(key); // XXX: for jsdoc
27 }
28
29 /**
30 * Drop all account in wallet
31 */
32 clear() {
33 return super.clear();
34 }
35
36 /**
37 * @param key {string} - Key of account, usually is `address`
38 * @param account {Account} - Account instance
39 * @return {Wallet}
40 */
41 set(key, account) {
42 assert(!this.has(key), `Wallet already has account "${key}"`);
43 assert(account instanceof Account, `value not instance of Account, got ${account}`);
44 return super.set(key, account);
45 }
46
47 /**
48 * @param key {string}
49 * @return {Account}
50 */
51 get(key) {
52 const account = super.get(key);
53 assert(account instanceof Account, `can not found Account by "${key}"`);
54 return account;
55 }
56
57 /**
58 * @param privateKey {string|Buffer} - Private key of account
59 * @return {PrivateKeyAccount}
60 */
61 addPrivateKey(privateKey) {
62 const account = new PrivateKeyAccount(privateKey);
63 this.set(account.address, account);
64 return account;
65 }
66
67 /**
68 * @param [entropy] {string|Buffer} - Entropy of random account
69 * @return {PrivateKeyAccount}
70 */
71 addRandom(entropy) {
72 const account = PrivateKeyAccount.random(entropy);
73 this.set(account.address, account);
74 return account;
75 }
76
77 /**
78 * @param keystore {object} - Keystore version 3 object.
79 * @param password {string|Buffer} - Password for keystore to decrypt with.
80 * @return {PrivateKeyAccount}
81 */
82 addKeystore(keystore, password) {
83 const account = PrivateKeyAccount.decrypt(keystore, password);
84 this.set(account.address, account);
85 return account;
86 }
87}
88
89module.exports = Wallet;