-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathindex.ts
More file actions
201 lines (175 loc) · 6.1 KB
/
index.ts
File metadata and controls
201 lines (175 loc) · 6.1 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import ExtendedKeyringTypes from '../../constants/keyringTypes';
import Engine from '../../core/Engine';
import { KeyringSelector } from '@metamask/keyring-controller';
import { InternalAccount } from '@metamask/keyring-internal-api';
import {
endPerformanceTrace,
startPerformanceTrace,
} from '../../core/redux/slices/performance';
import { PerformanceEventNames } from '../../core/redux/slices/performance/constants';
import { store } from '../../store';
import { getTraceTags } from '../../util/sentry/tags';
import ReduxService from '../../core/redux';
import { TraceName, TraceOperation, trace, endTrace } from '../../util/trace';
import { selectSeedlessOnboardingLoginFlow } from '../../selectors/seedlessOnboardingController';
import { SecretType } from '@metamask/seedless-onboarding-controller';
import Logger from '../../util/Logger';
import { discoverAccounts } from '../../multichain-accounts/discovery';
import { captureException } from '@sentry/core';
import { mnemonicPhraseToBytes } from '@metamask/key-tree';
export interface ImportNewSecretRecoveryPhraseOptions {
shouldSelectAccount: boolean;
}
export interface ImportNewSecretRecoveryPhraseReturnType {
address: string;
discoveredAccountsCount: number;
}
export async function importNewSecretRecoveryPhrase(
seed: string,
options: ImportNewSecretRecoveryPhraseOptions = {
shouldSelectAccount: true,
},
callback?: (
options: ImportNewSecretRecoveryPhraseReturnType & { error?: Error },
) => Promise<void>,
): Promise<ImportNewSecretRecoveryPhraseReturnType> {
const { KeyringController, MultichainAccountService } = Engine.context;
const { shouldSelectAccount } = options;
// Convert mnemonic
const seedLower = seed.toLowerCase();
const mnemonic = mnemonicPhraseToBytes(seedLower);
const wallet = await MultichainAccountService.createMultichainAccountWallet({
type: 'import',
mnemonic,
});
const entropySource = wallet.entropySource;
const [newAccount] = await KeyringController.withKeyringV2(
{
id: entropySource,
},
async ({ keyring }) => keyring.getAccounts(),
);
const { SeedlessOnboardingController } = Engine.context;
// TODO: to use loginCompleted
if (selectSeedlessOnboardingLoginFlow(ReduxService.store.getState())) {
// on Error, wallet should notify user that the newly added seed phrase is not synced properly
// user can try manual sync again (phase 2)
let addSeedPhraseSuccess = false;
try {
trace({
name: TraceName.OnboardingAddSrp,
op: TraceOperation.OnboardingSecurityOp,
});
await SeedlessOnboardingController.addNewSecretData(
mnemonic,
SecretType.Mnemonic,
{
keyringId: entropySource,
},
);
addSeedPhraseSuccess = true;
} catch (error) {
await MultichainAccountService.removeMultichainAccountWallet(
entropySource,
newAccount.address,
);
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
// Log the error but don't let it crash the import process
Logger.error(new Error(`Failed to backup seed phrase: ${errorMessage}`));
trace({
name: TraceName.OnboardingAddSrpError,
op: TraceOperation.OnboardingError,
tags: { errorMessage },
});
endTrace({
name: TraceName.OnboardingAddSrpError,
});
throw error;
} finally {
endTrace({
name: TraceName.OnboardingAddSrp,
data: { success: addSeedPhraseSuccess },
});
}
}
// This function will return 0 discovered account immediately, so we have to use
// the `callback` instead to get this information.
let discoveredAccountsCount: number = 0;
// We use an IIFE to be able to use async/await but not block the main thread.
(async () => {
let capturedError;
try {
// HACK: Force Snap keyring instantiation.
await Engine.getSnapKeyring();
// We need to dispatch a full sync here since this is a new SRP
await Engine.context.AccountTreeController.syncWithUserStorage();
// Then we discover accounts
discoveredAccountsCount = await discoverAccounts(entropySource);
} catch (error) {
capturedError = new Error(
`Unable to sync, discover and create accounts: ${error}`,
);
discoveredAccountsCount = 0;
captureException(capturedError);
} finally {
// We trigger the callback with the results, even in case of error (0 discovered accounts)
await callback?.({
address: newAccount.address,
discoveredAccountsCount,
error: capturedError,
});
}
})();
if (shouldSelectAccount) {
Engine.setSelectedAddress(newAccount.address);
}
return { address: newAccount.address, discoveredAccountsCount };
}
export async function addNewHdAccount(
keyringId?: string,
name?: string,
): Promise<InternalAccount> {
store.dispatch(
startPerformanceTrace({
eventName: PerformanceEventNames.AddHdAccount,
}),
);
trace({
name: TraceName.CreateHdAccount,
op: TraceOperation.CreateAccount,
tags: getTraceTags(store.getState()),
});
const { KeyringController, AccountsController } = Engine.context;
const keyringSelector: KeyringSelector = keyringId
? {
id: keyringId,
}
: {
type: ExtendedKeyringTypes.hd,
};
const [addedAccountAddress] = await KeyringController.withKeyring(
keyringSelector,
async ({ keyring }) => await keyring.addAccounts(1),
);
Engine.setSelectedAddress(addedAccountAddress);
if (name) {
Engine.setAccountLabel(addedAccountAddress, name);
}
const account = AccountsController.getAccountByAddress(addedAccountAddress);
// This should always be true. If it's not, we have a bug.
// We query the account that was newly created and return it.
if (!account) {
throw new Error('Account not found after creation');
}
// We consider the account to be created once it got selected and renamed.
endTrace({
name: TraceName.CreateHdAccount,
});
store.dispatch(
endPerformanceTrace({
eventName: PerformanceEventNames.AddHdAccount,
}),
);
return account;
}