-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
privatekey-vault.ts
68 lines (53 loc) · 1.58 KB
/
privatekey-vault.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
import type { AbstractAddress } from '@fuel-ts/interfaces';
import { Wallet } from '@fuel-ts/wallet';
import type { Account, Vault } from '../types';
interface PkVaultOptions {
secret?: string;
accounts?: Array<string>;
}
export class PrivateKeyVault implements Vault<PkVaultOptions> {
static readonly type = 'privateKey';
#privateKeys: Array<string> = [];
/**
* If privateKey vault is initialized with a secretKey, it creates
* one account with the fallowing secret
*/
constructor(options: PkVaultOptions) {
if (options.secret) {
this.#privateKeys = [options.secret];
} else {
this.#privateKeys = options.accounts || [Wallet.generate().privateKey];
}
}
serialize(): PkVaultOptions {
return {
accounts: this.#privateKeys,
};
}
getPublicAccount(privateKey: string) {
const wallet = new Wallet(privateKey);
return {
address: wallet.address,
publicKey: wallet.publicKey,
};
}
getAccounts(): Account[] {
return this.#privateKeys.map(this.getPublicAccount);
}
addAccount() {
const wallet = Wallet.generate();
this.#privateKeys.push(wallet.privateKey);
return this.getPublicAccount(wallet.privateKey);
}
exportAccount(address: AbstractAddress): string {
const privateKey = this.#privateKeys.find((pk) => new Wallet(pk).address.equals(address));
if (!privateKey) {
throw new Error('Address not found');
}
return privateKey;
}
getWallet(address: AbstractAddress): Wallet {
const privateKey = this.exportAccount(address);
return new Wallet(privateKey);
}
}