-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
282 lines (245 loc) · 8.01 KB
/
index.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
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
/* eslint-disable @typescript-eslint/no-throw-literal */
import type { JsonRpcRequest } from '@metamask/keyring-api';
import { handleKeyringRequest } from '@metamask/keyring-api';
import {
type UserInputEvent,
type OnCronjobHandler,
type OnUserInputHandler,
type OnHomePageHandler,
UnauthorizedError,
MethodNotFoundError,
} from '@metamask/snaps-sdk';
import type {
Json,
OnKeyringRequestHandler,
OnRpcRequestHandler,
} from '@metamask/snaps-types';
import { assert } from '@metamask/superstruct';
import config from './config';
import { getKeyring, getRequestManager } from './context';
import { getHomePageContext } from './features/homepage/context';
import {
eventHandles as homePageEvents,
prefixEventHandles as homePagePrefixEvents,
} from './features/homepage/events';
import { renderHomePage } from './features/homepage/render';
import { eventHandlers as onboardingEvents } from './features/onboarding/events';
import { renderOnboarding } from './features/onboarding/render';
import type { OnboardingAccount } from './features/onboarding/types';
import type { CreateAccountOptions } from './lib/structs/CustodialKeyringStructs';
import { OnBoardingRpcRequest } from './lib/structs/CustodialKeyringStructs';
import type { SnapContext } from './lib/types/Context';
import { CustodianApiMap, CustodianType } from './lib/types/CustodianType';
import logger from './logger';
import { InternalMethod, originPermissions } from './permissions';
// @audit - this file needs unittests
/**
* Verify if the caller can call the requested method.
*
* @param origin - Caller origin.
* @param method - Method being called.
* @returns True if the caller is allowed to call the method, false otherwise.
*/
function hasPermission(origin: string, method: string): boolean {
return originPermissions.get(origin)?.has(method) ?? false;
}
export const handleOnboarding = async (request: OnBoardingRpcRequest) => {
assert(request, OnBoardingRpcRequest);
const CustodianApiClass = CustodianApiMap[request.custodianType];
const keyring = await getKeyring();
if (!Object.values(CustodianType).includes(request.custodianType)) {
throw new Error(`Custodian type ${request.custodianType} not supported`);
}
const custodianApi = new CustodianApiClass(
{
refreshToken: request.token,
refreshTokenUrl: request.refreshTokenUrl,
},
request.custodianApiUrl,
1000,
);
let accounts = await custodianApi.getEthereumAccounts();
// Filter out accounts that already exist in the keyring
const existingAccounts = await keyring.listAccounts();
for (const existingAccount of existingAccounts) {
accounts = accounts.filter(
(account) => account.address !== existingAccount.address,
);
}
let result: OnboardingAccount[];
try {
result = await renderOnboarding({
selectedAccounts: [],
request,
accounts,
activity: 'onboarding',
});
} catch (error) {
logger.error('Error choosing account', error);
throw error;
}
if (result === null) {
// No accounts selected, show error dialog
return [];
}
const accountsToAdd: CreateAccountOptions[] = result.map((account) => ({
address: account.address,
name: account.name,
details: { ...request },
}));
for (const account of accountsToAdd) {
try {
await keyring.createAccount(account);
} catch (error) {
logger.error('Error creating account', error);
}
}
return accountsToAdd;
};
/**
* Handle incoming JSON-RPC requests, sent through `wallet_invokeSnap`.
*
* @param args - The request handler args as object.
* @param args.origin - The origin of the request, e.g., the website that
* invoked the snap.
* @param args.request - A validated JSON-RPC request object.
* @returns A promise that resolves to the result of the RPC request.
* @throws If the request method is not valid for this snap.
*/
export const onRpcRequest: OnRpcRequestHandler = async ({
origin,
request,
}: {
origin: string;
request: JsonRpcRequest;
}): Promise<void | CreateAccountOptions[]> => {
logger.debug(
`RPC request (origin="${origin}"): method="${request.method}"`,
JSON.stringify(request, undefined, 2),
);
// Check if origin is allowed to call method.
if (!hasPermission(origin, request.method)) {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw new UnauthorizedError(
`Origin '${origin}' is not allowed to call '${request.method}'`,
);
}
// `@audit-info` try-catch wrap and throw SnapError (https://docs.metamask.io/snaps/how-to/communicate-errors/#import-and-throw-errors) instead of internal exception.
// Handle custom methods.
switch (request.method) {
case InternalMethod.Onboard: {
assert(request.params, OnBoardingRpcRequest);
return await handleOnboarding(request.params);
}
case InternalMethod.ClearAllRequests: {
if (config.dev) {
// eslint-disable-next-line @typescript-eslint/no-shadow
const requestManager = await getRequestManager();
return await requestManager.clearAllRequests();
}
throw new MethodNotFoundError(request.method);
}
default: {
throw new MethodNotFoundError(request.method);
}
}
};
export const onKeyringRequest: OnKeyringRequestHandler = async ({
origin,
request,
}: {
origin: string;
request: JsonRpcRequest;
}) => {
logger.debug(
`Keyring request (origin="${origin}"):`,
JSON.stringify(request, undefined, 2),
);
// assert(request.params, KeyringRequestStruct);
// Check if origin is allowed to call method.
if (!hasPermission(origin, request.method)) {
throw new Error(
`Origin '${origin}' is not allowed to call '${request.method}'`,
);
}
const keyring = await getKeyring();
return handleKeyringRequest(keyring, request);
};
// Improved polling function
const pollRequests = async (): Promise<void> => {
logger.info('Polling requests');
try {
await (await getRequestManager()).poll();
} catch (error) {
logger.error('Error polling requests', error);
throw error;
}
};
export const onCronjob: OnCronjobHandler = async ({ request }) => {
switch (
request.method // @audit-info this is execute every minute * * * * * acc. to manifest
) {
case 'execute': {
const startTime = Date.now();
const timeoutDuration = 60000; // 1 minute in milliseconds //@audit will this work with mm snap scheduling?
// Run pollTransactions 6 times with 10-second intervals
for (let i = 0; i < 6; i++) {
// Check if we've exceeded the timeout
if (Date.now() - startTime >= timeoutDuration) {
return;
}
await pollRequests(); // @audit - what if there is nothing to poll?
// If this isn't the last iteration, wait 10 seconds
if (i < 5) {
await new Promise((resolve) => setTimeout(resolve, 10000)); // @audit-info sleep(10sec)
}
}
return;
}
default:
throw new Error('Method not found.');
}
};
export const onUserInput: OnUserInputHandler = async ({
id,
event,
context,
}: {
id: string;
event: UserInputEvent;
context: Record<string, Json> | null;
}) => {
/**
* Using the name of the component, route it to the correct handler
*/
if (!event.name) {
return;
}
const uiEventHandlers: Record<string, (...args: any) => Promise<void>> = {
...onboardingEvents,
...homePageEvents,
};
const prefixEventHandlers: Record<string, (...args: any) => Promise<void>> = {
...homePagePrefixEvents,
};
const handler =
uiEventHandlers[event.name] ??
prefixEventHandlers[
Object.keys(prefixEventHandlers).find((key) =>
event.name?.startsWith(key),
) ?? ''
];
if (!handler) {
return;
}
const keyring = await getKeyring();
const snapContext: SnapContext = {
keyring,
};
await handler({ id, event, context, snapContext });
};
export const onHomePage: OnHomePageHandler = async () => {
const keyring = await getKeyring();
const context = await getHomePageContext({ keyring });
return { id: await renderHomePage(context) };
};