-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwallet-manager.ts
121 lines (103 loc) · 2.75 KB
/
wallet-manager.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
import { IStorage } from "../wallet-storage/type";
import { WalletBase } from "./wallet-base";
class WalletManager {
private wallets: Array<WalletBase> = [];
private Wallet: typeof WalletBase;
private password?: string;
private storage: IStorage;
constructor(Wallet: typeof WalletBase, storage: IStorage) {
this.Wallet = Wallet;
this.storage = storage;
}
async create() {
const wallet = new this.Wallet();
wallet.random();
this.wallets.push(wallet);
await this.encrypt(this.wallets.length - 1);
}
async remove(index: number) {
this.wallets = this.wallets.filter((_, i) => {
return i !== index;
});
await this.store();
}
async decrypt(index: number) {
const wallet = this.wallets[index];
if (!wallet.isAlive() && this.password) {
await wallet.decrypt(this.password);
}
}
async encrypt(index: number) {
const wallet = this.wallets[index];
if (wallet.isAlive() && this.password) {
await wallet.encrypt(this.password);
}
await this.store();
}
async getPrivateKey(index: number) {
const wallet = this.wallets[index];
if (!wallet.isAlive() && this.password) {
await wallet.decrypt(this.password);
}
return wallet.getPrivateKey();
}
private async store() {
const data = this.wallets.map((wallet) => {
return {
address: wallet.getAddress(),
encrypted: wallet.getEncrypted(),
};
});
await this.storage.set("wallet", data);
}
loadFromStorage() {
const data: { address: string; encrypted: string }[] = this.storage.get(
"wallet"
) as { address: string; encrypted: string }[];
if (data) {
data.forEach((e) => {
const wallet = new this.Wallet();
wallet.loadJson(e.address, e.encrypted);
this.wallets.push(wallet);
});
}
return data || [];
}
updatePassword(password: string) {
this.password = password;
}
isSamePassword(password: string) {
return this.password === password;
}
async ensurePassword(password: string): Promise<boolean> {
if (this.wallets.length > 0) {
const wallet = this.wallets[0];
try {
await wallet.decrypt(password, true);
return true;
} catch (error) {
return false;
}
}
return true;
}
getData(): { address: string; encrypted: string }[] {
return this.wallets.map((wallet) => {
return {
address: wallet.getAddress() || "",
encrypted: wallet.getEncrypted() || "",
};
});
}
async clear() {
this.wallets = [];
this.storage.set('wallet', [])
}
__test__make_dead(index: number) {
const wallet = this.wallets[index];
if(wallet) {
wallet.__test__make_dead();
}
}
}
export default WalletManager;