-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathExportAccount.tsx
363 lines (333 loc) · 9.59 KB
/
ExportAccount.tsx
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import React, { Fragment, useEffect, useState } from "react";
import type {
BrowserWalletBehaviour,
InjectedWalletBehaviour,
ModuleState,
Wallet,
WalletSelector,
AccountImportData,
InjectedWalletMetadata,
} from "@near-wallet-selector/core";
import * as nearAPI from "near-api-js";
import type {
FunctionCallPermissionView,
AccessKeyView,
AccountView,
} from "near-api-js/lib/providers/provider";
import { AccountSelect } from "./AccountSelect";
import { Passphrase } from "./Passphrase";
import { NoInterface } from "./NoInterface";
import { Complete } from "./Complete";
import { encryptAccountData } from "../helpers";
type CompleteProps = {
accounts: Array<string>;
walletName: string;
};
interface ExportAccountProps {
alertMessage: string | null;
module?: ModuleState;
onCloseModal: () => void;
onWarning: () => void;
onBack: () => void;
accounts: Array<AccountImportData>;
selector: WalletSelector;
wallet: ModuleState<Wallet>;
onComplete?: (object: CompleteProps) => void;
}
const EXPORT_ACCOUNT_STEPS = {
ACCOUNT_SELECTION: "ACCOUNT_SELECTION",
GET_PASSPHRASE: "GET_PASSPHRASE",
NO_INTERFACE: "NO_INTERFACE",
COMPLETE: "COMPLETE",
};
export const ACCESS_KEY_TYPES = {
LEDGER: "Ledger",
FULL_ACCESS_KEY: "Full Access Key",
MULTI_SIG: "Multi-Sig",
UNKNOWN: "Unknown",
};
const permissionToType = (
permission: string | FunctionCallPermissionView
): string => {
if (permission === "FullAccess") {
return ACCESS_KEY_TYPES.FULL_ACCESS_KEY;
}
//@ts-ignore
if (permission?.FunctionCall?.method_names.includes("__wallet__metadata")) {
return ACCESS_KEY_TYPES.LEDGER;
}
const multiSigMethods = [
"add_request",
"add_request_and_confirm",
"delete_request",
"confirm",
];
if (
//@ts-ignore
permission?.FunctionCall?.method_names.every((method: string) =>
multiSigMethods.includes(method)
)
) {
return ACCESS_KEY_TYPES.MULTI_SIG;
}
return ACCESS_KEY_TYPES.UNKNOWN;
};
interface getAccountTypeProps {
provider: nearAPI.providers.Provider;
accountId: string;
publicKey: string;
}
const getAccountType = async ({
provider,
accountId,
publicKey,
}: getAccountTypeProps) => {
try {
const { permission } = await provider.query<AccessKeyView>({
request_type: "view_access_key",
account_id: accountId,
public_key: publicKey,
finality: "final",
});
const type = permissionToType(permission);
return { type };
} catch {
return { type: ACCESS_KEY_TYPES.UNKNOWN };
}
};
interface getAccountBalanceProps {
provider: nearAPI.providers.Provider;
accountId: string;
}
const getAccountBalance = async ({
provider,
accountId,
}: getAccountBalanceProps) => {
try {
const { amount } = await provider.query<AccountView>({
request_type: "view_account",
finality: "final",
account_id: accountId,
});
const bn = BigInt(amount);
return { hasBalance: bn !== BigInt(0) };
} catch {
return { hasBalance: false };
}
};
export interface ExportAccountData {
accountId: string;
privateKey: string;
hasBalance: boolean;
type: string;
}
export const ExportAccount: React.FC<ExportAccountProps> = ({
alertMessage,
module,
onCloseModal,
onWarning,
accounts,
selector,
wallet,
onBack,
onComplete,
}) => {
const [selectedAccounts, setSelectedAccounts] = useState<Array<string>>([]);
const [isLoading, setIsLoading] = useState(false);
const [accountsWithDetail, setAccountsWithDetail] = useState<
Array<ExportAccountData>
>([]);
const [disabledAccounts, setDisabledAccounts] = useState<
Array<ExportAccountData>
>([]);
const [passphrase, setPassphrase] = useState<string>("");
//@ts-ignore
const [exportInterfaces, setExportInterfaces] = useState<{
buildImportAccountsUrl?: BrowserWalletBehaviour["buildImportAccountsUrl"];
importAccountsInSecureContext?: InjectedWalletBehaviour["importAccountsInSecureContext"];
}>({});
useEffect(() => {
const getExportInterfaces = async () => {
try {
const {
// @ts-ignore
buildImportAccountsUrl,
// @ts-ignore
importAccountsInSecureContext,
} = await wallet.wallet();
setExportInterfaces({
buildImportAccountsUrl,
importAccountsInSecureContext,
});
if (!buildImportAccountsUrl && !importAccountsInSecureContext) {
onWarning();
}
} catch (e) {
onWarning();
}
};
getExportInterfaces();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [module?.metadata.name, alertMessage]);
const { network } = selector.options;
const provider = new nearAPI.providers.JsonRpcProvider({
url: network.nodeUrl,
});
const [hasCopied, setHasCopied] = useState(false);
useEffect(() => {
const initialize = async () => {
setIsLoading(true);
const accountsWithDetails = await Promise.all(
accounts.map(async ({ accountId, privateKey }) => {
const keyPair = nearAPI.utils.KeyPair.fromString(
privateKey as nearAPI.utils.KeyPairString
);
const { type } = await getAccountType({
provider,
accountId,
publicKey: keyPair.getPublicKey().toString(),
});
const { hasBalance } = await getAccountBalance({
provider,
accountId,
});
return {
accountId,
privateKey,
type,
hasBalance,
};
})
);
const availableAccounts = accountsWithDetails.filter(
({ hasBalance, type }) => {
return hasBalance && type === ACCESS_KEY_TYPES.FULL_ACCESS_KEY;
}
);
setAccountsWithDetail(availableAccounts);
const unavailableAccounts = accountsWithDetails.filter(
({ hasBalance, type }) => {
return !hasBalance || type !== ACCESS_KEY_TYPES.FULL_ACCESS_KEY;
}
);
setDisabledAccounts(unavailableAccounts);
setIsLoading(false);
};
if (accountsWithDetail.length === 0) {
initialize();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
exportInterfaces.buildImportAccountsUrl,
exportInterfaces.importAccountsInSecureContext,
]);
const [step, setStep] = useState(EXPORT_ACCOUNT_STEPS.ACCOUNT_SELECTION);
useEffect(() => {
if (alertMessage) {
setStep(EXPORT_ACCOUNT_STEPS.NO_INTERFACE);
} else {
setStep(EXPORT_ACCOUNT_STEPS.ACCOUNT_SELECTION);
}
}, [alertMessage]);
const showAccountSelection = () =>
setStep(EXPORT_ACCOUNT_STEPS.ACCOUNT_SELECTION);
const showPassPhrase = () => {
setStep(EXPORT_ACCOUNT_STEPS.GET_PASSPHRASE);
};
const { buildImportAccountsUrl, importAccountsInSecureContext } =
exportInterfaces;
const onAccountSelectNext = () => {
if (
wallet.type === "injected" &&
!(wallet.metadata as InjectedWalletMetadata).useUrlAccountImport
) {
injectedWalletInterface();
setStep(EXPORT_ACCOUNT_STEPS.COMPLETE);
} else {
showPassPhrase();
}
};
const injectedWalletInterface = async () => {
if (importAccountsInSecureContext) {
await importAccountsInSecureContext({
accounts: accounts.filter(({ accountId }) =>
selectedAccounts.includes(accountId)
),
});
} else {
setStep(EXPORT_ACCOUNT_STEPS.NO_INTERFACE);
}
};
const browserOrMobileInterface = () => {
const encryptedAccountData = encryptAccountData({
accountData: accounts.filter(({ accountId }) =>
selectedAccounts.includes(accountId)
),
secretKey: passphrase,
});
const isUrlCompatible =
wallet.type === "browser" ||
(wallet.metadata as InjectedWalletMetadata).useUrlAccountImport;
if (isUrlCompatible && buildImportAccountsUrl) {
const url = `${buildImportAccountsUrl()}#${encryptedAccountData}`;
window.open(url, "_blank");
}
setStep(EXPORT_ACCOUNT_STEPS.COMPLETE);
};
const onTransferComplete = () => {
if (onComplete) {
onComplete({
accounts: selectedAccounts,
walletName: module?.metadata.name || "Unknown",
});
}
};
return (
<Fragment>
{step === EXPORT_ACCOUNT_STEPS.NO_INTERFACE && (
<NoInterface
src={module?.metadata.iconUrl}
name={module?.metadata.name}
alertMessage={alertMessage}
onBack={onBack}
onCloseModal={onCloseModal}
/>
)}
{step === EXPORT_ACCOUNT_STEPS.ACCOUNT_SELECTION && (
<AccountSelect
onCloseModal={onCloseModal}
onBack={onBack}
selectedAccounts={selectedAccounts}
setSelectedAccounts={setSelectedAccounts}
accountsWithDetail={accountsWithDetail}
disabledAccounts={disabledAccounts}
onNextStep={onAccountSelectNext}
isLoading={isLoading}
buttonLabel={
wallet.type === "injected"
? "modal.exportAccounts.getPassphrase.button"
: "modal.exportAccounts.selectAccounts.button"
}
/>
)}
{step === EXPORT_ACCOUNT_STEPS.GET_PASSPHRASE && (
<Passphrase
onNextStep={browserOrMobileInterface}
hasCopied={hasCopied}
setHasCopied={setHasCopied}
onCloseModal={onCloseModal}
onBack={showAccountSelection}
onPassphraseSave={setPassphrase}
/>
)}
{step === EXPORT_ACCOUNT_STEPS.COMPLETE && (
<Complete
onCloseModal={onCloseModal}
onBack={showPassPhrase}
onComplete={onTransferComplete}
onStartOver={onBack}
/>
)}
</Fragment>
);
};