-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
260 lines (222 loc) · 7.33 KB
/
Copy pathindex.ts
File metadata and controls
260 lines (222 loc) · 7.33 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
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
/* eslint-disable no-restricted-globals */
import { MESSAGE_SIGNING_SNAP_ID } from '@metamask/7715-permissions-shared/constants';
import type { GetSnapsResponse } from '@metamask/7715-permissions-shared/types';
import { logger } from '@metamask/7715-permissions-shared/utils';
import {
AuthType,
JwtBearerAuth,
Platform,
UserStorage,
} from '@metamask/profile-sync-controller/sdk';
import type {
OnHomePageHandler,
OnInstallHandler,
Json,
JsonRpcParams,
OnRpcRequestHandler,
OnUserInputHandler,
} from '@metamask/snaps-sdk';
import {
EoaAccountController,
SmartAccountController,
type AccountController,
} from './accountController';
import { AccountApiClient } from './clients/accountApiClient';
import { BlockchainTokenMetadataClient } from './clients/blockchainMetadataClient';
import { PriceApiClient } from './clients/priceApiClient';
import { ConfirmationDialogFactory } from './core/confirmationFactory';
import { PermissionHandlerFactory } from './core/permissionHandlerFactory';
import { PermissionRequestLifecycleOrchestrator } from './core/permissionRequestLifecycleOrchestrator';
import { HomePage } from './homepage';
import {
createProfileSyncOptions,
getProfileSyncSdkEnv,
createProfileSyncManager,
} from './profileSync';
import { isMethodAllowedForOrigin } from './rpc/permissions';
import { createRpcHandler } from './rpc/rpcHandler';
import { RpcMethod } from './rpc/rpcMethod';
import { TokenMetadataService } from './services/tokenMetadataService';
import { TokenPricesService } from './services/tokenPricesService';
import { createStateManager } from './stateManagement';
import { UserEventDispatcher } from './userEventDispatcher';
const isStorePermissionsFeatureEnabled =
process.env.STORE_PERMISSIONS_ENABLED === 'true';
const useEoaAccountController = process.env.USE_EOA_ACCOUNT === 'true';
const snapEnv = process.env.SNAP_ENV;
const accountApiBaseUrl = process.env.ACCOUNT_API_BASE_URL;
if (!accountApiBaseUrl) {
throw new Error('ACCOUNT_API_BASE_URL is not set');
}
const priceApiBaseUrl = process.env.PRICE_API_BASE_URL;
if (!priceApiBaseUrl) {
throw new Error('PRICE_API_BASE_URL is not set');
}
const supportedChainsString = process.env.SUPPORTED_CHAINS;
if (!supportedChainsString) {
throw new Error('SUPPORTED_CHAINS is not set');
}
const supportedChains = supportedChainsString.split(',').map(Number);
// set up dependencies
const accountApiClient = new AccountApiClient({
baseUrl: accountApiBaseUrl,
});
const tokenMetadataClient = new BlockchainTokenMetadataClient({
ethereumProvider: ethereum,
});
const tokenMetadataService = new TokenMetadataService({
accountApiClient,
tokenMetadataClient,
});
const accountController: AccountController = useEoaAccountController
? new EoaAccountController({
snapsProvider: snap,
ethereumProvider: ethereum,
supportedChains,
})
: new SmartAccountController({
snapsProvider: snap,
supportedChains,
deploymentSalt: '0x',
});
const stateManager = createStateManager(snap);
const profileSyncOptions = createProfileSyncOptions(
stateManager,
snap,
MESSAGE_SIGNING_SNAP_ID,
);
const profileSyncSdkEnv = getProfileSyncSdkEnv(snapEnv);
const auth = new JwtBearerAuth(
{
type: AuthType.SRP,
platform: Platform.EXTENSION,
env: profileSyncSdkEnv,
},
{
storage: profileSyncOptions.authStorageOptions,
signing: profileSyncOptions.authSigningOptions,
},
);
const profileSyncManager = createProfileSyncManager({
isFeatureEnabled: isStorePermissionsFeatureEnabled,
auth,
userStorage: new UserStorage(
{
auth,
env: profileSyncSdkEnv,
},
{
storage: profileSyncOptions.keyStorageOptions,
},
),
});
const homepage = new HomePage({
accountController,
snapsProvider: snap,
profileSyncManager,
});
const userEventDispatcher = new UserEventDispatcher();
const priceApiClient = new PriceApiClient(priceApiBaseUrl);
const tokenPricesService = new TokenPricesService(priceApiClient, snap);
const confirmationDialogFactory = new ConfirmationDialogFactory({
snap,
userEventDispatcher,
});
const orchestrator = new PermissionRequestLifecycleOrchestrator({
accountController,
confirmationDialogFactory,
});
const permissionHandlerFactory = new PermissionHandlerFactory({
accountController,
tokenPricesService,
tokenMetadataService,
userEventDispatcher,
orchestrator,
});
const rpcHandler = createRpcHandler({
permissionHandlerFactory,
profileSyncManager,
});
// configure RPC methods bindings
const boundRpcHandlers: {
[RpcMethod: string]: (params?: JsonRpcParams) => Promise<Json>;
} = {
[RpcMethod.PermissionProviderGrantPermissions]:
rpcHandler.grantPermission.bind(rpcHandler),
[RpcMethod.PermissionProviderGetPermissionOffers]:
rpcHandler.getPermissionOffers.bind(rpcHandler),
[RpcMethod.PermissionProviderGetGrantedPermissions]:
rpcHandler.getGrantedPermissions.bind(rpcHandler),
};
/**
* 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 The result of the request.
* @throws If the request method is not valid for this snap, or the origin is not allowed to call the method.
*/
export const onRpcRequest: OnRpcRequestHandler = async ({
origin,
request,
}) => {
logger.debug(
`RPC request (origin="${origin}"):`,
JSON.stringify(request, undefined, 2),
);
if (!isMethodAllowedForOrigin(origin, request.method)) {
throw new Error(
`Origin '${origin}' is not allowed to call '${request.method}'`,
);
}
const handler = boundRpcHandlers[request.method];
if (!handler) {
throw new Error(`Method ${request.method} not found.`);
}
const result = await handler(request.params);
return result;
};
/**
* Handle incoming user input events.
*
* @param args - The user input handler args as object.
* @param args.id - The id of the interface.
* @param args.event - The user input event.
* @returns Resolves once any registered event handlers have completed.
*/
export const onUserInput: OnUserInputHandler =
userEventDispatcher.createUserInputEventHandler();
export const onHomePage: OnHomePageHandler = async () => {
return {
content: await homepage.buildHomepage(),
};
};
export const onInstall: OnInstallHandler = async () => {
/**
* Local Development Only
*
* The message signing snap must be installed and the gator permissions snap must
* have permission to communicate with the message signing snap, or the request is rejected.
*
* Since the message signing snap is preinstalled in production, and has
* initialConnections configured to automatically connect to the gator snap, this is not needed in production.
*/
// eslint-disable-next-line no-restricted-globals
if (snapEnv === 'local' && isStorePermissionsFeatureEnabled) {
const installedSnaps = (await snap.request({
method: 'wallet_getSnaps',
})) as unknown as GetSnapsResponse;
if (!installedSnaps[MESSAGE_SIGNING_SNAP_ID]) {
logger.debug('Installing local message signing snap');
await snap.request({
method: 'wallet_requestSnaps',
params: {
[MESSAGE_SIGNING_SNAP_ID]: {},
},
});
}
}
await homepage.showWelcomeScreen();
};