-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
mnemonic-vault.ts
80 lines (65 loc) · 2.11 KB
/
mnemonic-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
69
70
71
72
73
74
75
76
77
78
79
80
import { Mnemonic } from '@fuel-ts/mnemonic';
import { Wallet } from '@fuel-ts/wallet';
import type { Vault } from '../types';
interface MnemonicVaultOptions {
secret?: string;
rootPath?: string;
numberOfAccounts?: number | null;
}
export class MnemonicVault implements Vault<MnemonicVaultOptions> {
static readonly type = 'mnemonic';
readonly #secret: string;
rootPath: string = `m/44'/1179993420'/0'/0`;
numberOfAccounts: number = 0;
constructor(options: MnemonicVaultOptions) {
this.#secret = options.secret || Mnemonic.generate();
this.rootPath = options.rootPath || this.rootPath;
// On creating the vault also adds one account
this.numberOfAccounts = options.numberOfAccounts || 1;
}
serialize(): MnemonicVaultOptions {
return {
secret: this.#secret,
rootPath: this.rootPath,
numberOfAccounts: this.numberOfAccounts,
};
}
getAccounts() {
const accounts = [];
let numberOfAccounts = 0;
// Create all accounts to current vault
do {
const wallet = Wallet.fromMnemonic(this.#secret, `${this.rootPath}/${numberOfAccounts}`);
accounts.push({
publicKey: wallet.publicKey,
address: wallet.address,
});
numberOfAccounts += 1;
} while (numberOfAccounts < this.numberOfAccounts);
return accounts;
}
addAccount() {
this.numberOfAccounts += 1;
const wallet = Wallet.fromMnemonic(this.#secret, `${this.rootPath}/${this.numberOfAccounts}`);
return {
publicKey: wallet.publicKey,
address: wallet.address,
};
}
exportAccount(address: string): string {
let numberOfAccounts = 0;
// Look for the account that has the same address
do {
const wallet = Wallet.fromMnemonic(this.#secret, `${this.rootPath}/${numberOfAccounts}`);
if (wallet.address === address) {
return wallet.privateKey;
}
numberOfAccounts += 1;
} while (numberOfAccounts < this.numberOfAccounts);
throw new Error('Account not found');
}
getWallet(address: string): Wallet {
const privateKey = this.exportAccount(address);
return new Wallet(privateKey);
}
}