-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathSuiWalletUtil.ts
More file actions
76 lines (61 loc) · 1.93 KB
/
Copy pathSuiWalletUtil.ts
File metadata and controls
76 lines (61 loc) · 1.93 KB
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
import * as bip39 from 'bip39';
import SuiLib from '../lib/SuiLib';
import { storage } from './storage';
import SettingsStore from '@/store/SettingsStore';
export let wallet1: SuiLib;
export let suiAddresses: string[];
/**
* Utilities
*/
export async function createOrRestoreSuiWallet() {
const mnemonic1 = await storage.getItem('SUI_MNEMONIC_1');
if (mnemonic1) {
wallet1 = await SuiLib.init({ mnemonic: mnemonic1 });
} else {
wallet1 = await SuiLib.init({});
// Don't store private keys in local storage in a production project!
await storage.setItem('SUI_MNEMONIC_1', wallet1.getMnemonic());
}
suiAddresses = [wallet1.getAddress()];
return {
suiWallet: wallet1,
suiAddresses,
};
}
export const getWallet = async () => {
return wallet1;
};
export async function loadSuiWallet(input: string): Promise<{
address: string;
wallet: SuiLib;
}> {
const trimmedInput = input.trim();
// Validate mnemonic word count
const words = trimmedInput.split(/\s+/).filter(w => w.length > 0);
if (![12, 15, 18, 21, 24].includes(words.length)) {
throw new Error(
`Mnemonic must be 12, 15, 18, 21, or 24 words (got ${words.length})`,
);
}
// Validate BIP39 mnemonic
if (!bip39.validateMnemonic(trimmedInput)) {
throw new Error('Invalid mnemonic phrase');
}
// Create wallet from mnemonic
const newWallet = await SuiLib.init({ mnemonic: trimmedInput });
const newAddress = newWallet.getAddress();
// Update module-level exports
wallet1 = newWallet;
suiAddresses = [newAddress];
// Persist to storage
await storage.setItem('SUI_MNEMONIC_1', trimmedInput);
if (__DEV__) {
console.warn(
'[SECURITY] SUI mnemonic stored in encrypted MMKV on native (key in Keychain/Keystore); unencrypted localStorage on web.',
);
}
// Update store
SettingsStore.setSuiAddress(newAddress);
SettingsStore.setSuiWallet(newWallet);
return { address: newAddress, wallet: newWallet };
}