@metamask/snaps-controllers 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +3 -0
  3. package/dist/cronjob/CronjobController.d.ts +115 -0
  4. package/dist/cronjob/CronjobController.js +231 -0
  5. package/dist/cronjob/CronjobController.js.map +1 -0
  6. package/dist/cronjob/index.d.ts +1 -0
  7. package/dist/cronjob/index.js +18 -0
  8. package/dist/cronjob/index.js.map +1 -0
  9. package/dist/fsm.d.ts +24 -0
  10. package/dist/fsm.js +75 -0
  11. package/dist/fsm.js.map +1 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.js +22 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/multichain/MultiChainController.d.ts +135 -0
  16. package/dist/multichain/MultiChainController.js +348 -0
  17. package/dist/multichain/MultiChainController.js.map +1 -0
  18. package/dist/multichain/index.d.ts +3 -0
  19. package/dist/multichain/index.js +20 -0
  20. package/dist/multichain/index.js.map +1 -0
  21. package/dist/multichain/matching.d.ts +9 -0
  22. package/dist/multichain/matching.js +58 -0
  23. package/dist/multichain/matching.js.map +1 -0
  24. package/dist/multichain/middleware.d.ts +14 -0
  25. package/dist/multichain/middleware.js +42 -0
  26. package/dist/multichain/middleware.js.map +1 -0
  27. package/dist/services/AbstractExecutionService.d.ts +124 -0
  28. package/dist/services/AbstractExecutionService.js +316 -0
  29. package/dist/services/AbstractExecutionService.js.map +1 -0
  30. package/dist/services/ExecutionService.d.ts +68 -0
  31. package/dist/services/ExecutionService.js +4 -0
  32. package/dist/services/ExecutionService.js.map +1 -0
  33. package/dist/services/browser.d.ts +3 -0
  34. package/dist/services/browser.js +21 -0
  35. package/dist/services/browser.js.map +1 -0
  36. package/dist/services/iframe/IframeExecutionService.d.ts +25 -0
  37. package/dist/services/iframe/IframeExecutionService.js +82 -0
  38. package/dist/services/iframe/IframeExecutionService.js.map +1 -0
  39. package/dist/services/iframe/index.d.ts +1 -0
  40. package/dist/services/iframe/index.js +18 -0
  41. package/dist/services/iframe/index.js.map +1 -0
  42. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.d.ts +3 -0
  43. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js +74 -0
  44. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js.map +1 -0
  45. package/dist/services/iframe/test/server.d.ts +11 -0
  46. package/dist/services/iframe/test/server.js +71 -0
  47. package/dist/services/iframe/test/server.js.map +1 -0
  48. package/dist/services/index.d.ts +4 -0
  49. package/dist/services/index.js +21 -0
  50. package/dist/services/index.js.map +1 -0
  51. package/dist/services/node/NodeProcessExecutionService.d.ts +11 -0
  52. package/dist/services/node/NodeProcessExecutionService.js +18 -0
  53. package/dist/services/node/NodeProcessExecutionService.js.map +1 -0
  54. package/dist/services/node/NodeThreadExecutionService.d.ts +11 -0
  55. package/dist/services/node/NodeThreadExecutionService.js +18 -0
  56. package/dist/services/node/NodeThreadExecutionService.js.map +1 -0
  57. package/dist/services/node/index.d.ts +2 -0
  58. package/dist/services/node/index.js +19 -0
  59. package/dist/services/node/index.js.map +1 -0
  60. package/dist/snaps/RequestQueue.d.ts +24 -0
  61. package/dist/snaps/RequestQueue.js +47 -0
  62. package/dist/snaps/RequestQueue.js.map +1 -0
  63. package/dist/snaps/SnapController.d.ts +600 -0
  64. package/dist/snaps/SnapController.js +1314 -0
  65. package/dist/snaps/SnapController.js.map +1 -0
  66. package/dist/snaps/Timer.d.ts +39 -0
  67. package/dist/snaps/Timer.js +86 -0
  68. package/dist/snaps/Timer.js.map +1 -0
  69. package/dist/snaps/endowments/cronjob.d.ts +49 -0
  70. package/dist/snaps/endowments/cronjob.js +105 -0
  71. package/dist/snaps/endowments/cronjob.js.map +1 -0
  72. package/dist/snaps/endowments/enum.d.ts +8 -0
  73. package/dist/snaps/endowments/enum.js +13 -0
  74. package/dist/snaps/endowments/enum.js.map +1 -0
  75. package/dist/snaps/endowments/ethereum-provider.d.ts +13 -0
  76. package/dist/snaps/endowments/ethereum-provider.js +31 -0
  77. package/dist/snaps/endowments/ethereum-provider.js.map +1 -0
  78. package/dist/snaps/endowments/index.d.ts +67 -0
  79. package/dist/snaps/endowments/index.js +39 -0
  80. package/dist/snaps/endowments/index.js.map +1 -0
  81. package/dist/snaps/endowments/keyring.d.ts +39 -0
  82. package/dist/snaps/endowments/keyring.js +103 -0
  83. package/dist/snaps/endowments/keyring.js.map +1 -0
  84. package/dist/snaps/endowments/long-running.d.ts +13 -0
  85. package/dist/snaps/endowments/long-running.js +28 -0
  86. package/dist/snaps/endowments/long-running.js.map +1 -0
  87. package/dist/snaps/endowments/network-access.d.ts +13 -0
  88. package/dist/snaps/endowments/network-access.js +29 -0
  89. package/dist/snaps/endowments/network-access.js.map +1 -0
  90. package/dist/snaps/endowments/transaction-insight.d.ts +38 -0
  91. package/dist/snaps/endowments/transaction-insight.js +106 -0
  92. package/dist/snaps/endowments/transaction-insight.js.map +1 -0
  93. package/dist/snaps/index.d.ts +4 -0
  94. package/dist/snaps/index.js +21 -0
  95. package/dist/snaps/index.js.map +1 -0
  96. package/dist/snaps/selectors.d.ts +2 -0
  97. package/dist/snaps/selectors.js +6 -0
  98. package/dist/snaps/selectors.js.map +1 -0
  99. package/dist/snaps/utils/index.d.ts +2 -0
  100. package/dist/snaps/utils/index.js +19 -0
  101. package/dist/snaps/utils/index.js.map +1 -0
  102. package/dist/snaps/utils/npm.d.ts +14 -0
  103. package/dist/snaps/utils/npm.js +81 -0
  104. package/dist/snaps/utils/npm.js.map +1 -0
  105. package/dist/snaps/utils/stream.d.ts +30 -0
  106. package/dist/snaps/utils/stream.js +124 -0
  107. package/dist/snaps/utils/stream.js.map +1 -0
  108. package/dist/utils.d.ts +128 -0
  109. package/dist/utils.js +92 -0
  110. package/dist/utils.js.map +1 -0
  111. package/package.json +99 -0
@@ -0,0 +1,135 @@
1
+ import { AddApprovalRequest, BaseControllerV2 as BaseController, GetPermissions, GrantPermissions, HasPermission, RestrictedControllerMessenger } from '@metamask/controllers';
2
+ import { ChainId, ConnectArguments, NamespaceId, RequestArguments, RequestNamespace, Session, SnapId } from '@metamask/snaps-utils';
3
+ import { GetAllSnaps, HandleSnapRequest, IncrementActiveReferences, DecrementActiveReferences } from '../snaps';
4
+ declare const controllerName = "MultiChainController";
5
+ declare type AllowedActions = GetAllSnaps | IncrementActiveReferences | DecrementActiveReferences | HandleSnapRequest | GetPermissions | HasPermission | AddApprovalRequest | GrantPermissions;
6
+ declare type MultiChainControllerMessenger = RestrictedControllerMessenger<typeof controllerName, AllowedActions, never, AllowedActions['type'], never>;
7
+ declare type SessionData = {
8
+ origin: string;
9
+ requestedNamespaces: Record<NamespaceId, RequestNamespace>;
10
+ providedNamespaces: Record<NamespaceId, RequestNamespace>;
11
+ handlingSnaps: Record<NamespaceId, SnapId>;
12
+ };
13
+ declare type MultiChainControllerState = {
14
+ sessions: {
15
+ [origin: string]: SessionData;
16
+ };
17
+ };
18
+ declare type Notify = (origin: string, data: {
19
+ method: string;
20
+ params?: Record<string, unknown>;
21
+ }) => Promise<void>;
22
+ declare type MultiChainControllerArgs = {
23
+ notify: Notify;
24
+ messenger: MultiChainControllerMessenger;
25
+ };
26
+ export declare class MultiChainController extends BaseController<typeof controllerName, MultiChainControllerState, MultiChainControllerMessenger> {
27
+ #private;
28
+ /**
29
+ * Construct a new {@link MultiChainController} instance.
30
+ *
31
+ * @param args - The arguments to construct the controller with.
32
+ * @param args.messenger - The controller messenger to use.
33
+ * @param args.notify - A function that should handle JSON-RPC notifications.
34
+ */
35
+ constructor({ messenger, notify }: MultiChainControllerArgs);
36
+ /**
37
+ * Get an open session for the given origin.
38
+ *
39
+ * @param origin - The origin to get the session for.
40
+ * @returns The session, if it exists, or `undefined` otherwise.
41
+ */
42
+ getSession(origin: string): SessionData | undefined;
43
+ /**
44
+ * Close a session for the given origin.
45
+ *
46
+ * @param origin - The origin to close the session for.
47
+ * @throws If the session does not exist.
48
+ */
49
+ closeSession(origin: string): Promise<void>;
50
+ /**
51
+ * Handles a new connection from the given origin. This will create a new
52
+ * session, and close any existing session for the origin.
53
+ *
54
+ * @param origin - The origin to create the session for.
55
+ * @param connection - The connection arguments.
56
+ * @param connection.requiredNamespaces - The namespaces that the origin
57
+ * requires.
58
+ * @returns The session that was created.
59
+ */
60
+ onConnect(origin: string, connection: ConnectArguments): Promise<Session>;
61
+ /**
62
+ * Handle an incoming multichain request from the given origin. This will
63
+ * forward the request to the appropriate Snap, and return the response.
64
+ *
65
+ * @param origin - The origin to handle the request for.
66
+ * @param data - The request data.
67
+ * @param data.chainId - The chain ID for the request.
68
+ * @param data.request - The request arguments, i.e., the method and params.
69
+ * @returns The response from the Snap.
70
+ * @throws If the session does not exist, or the session does not provide the
71
+ * requested namespace.
72
+ */
73
+ onRequest(origin: string, data: {
74
+ chainId: ChainId;
75
+ request: RequestArguments;
76
+ }): Promise<unknown>;
77
+ /**
78
+ * Send a request to the given Snap. This calls the given method with the
79
+ * given arguments on the keyring class in the given Snap.
80
+ *
81
+ * @param options - The request options.
82
+ * @param options.snapId - The ID of the Snap to send the request to.
83
+ * @param options.origin - The origin of the request.
84
+ * @param options.method - The request method.
85
+ * @param options.args - The request params.
86
+ * @returns The response from the Snap.
87
+ */
88
+ private snapRequest;
89
+ /**
90
+ * Get the accounts exposed by the Snap's keyring.
91
+ *
92
+ * This also verifies that the accounts returned by the snap are valid CAIP-10
93
+ * account IDs.
94
+ *
95
+ * @param origin - The origin of the request.
96
+ * @param snapId - The ID of the Snap to get the accounts from.
97
+ * @returns The accounts, or `null` if the Snap does not have any accounts, or
98
+ * the accounts are invalid (i.e., not valid CAIP-10 account IDs).
99
+ */
100
+ private getSnapAccounts;
101
+ /**
102
+ * Get the namespaces for the given Snap, as described in the Snap's manifest.
103
+ *
104
+ * @param snap - The Snap to get the namespaces for.
105
+ * @returns The namespaces, or `null` if the Snap does not have any
106
+ * namespaces.
107
+ */
108
+ private snapToNamespaces;
109
+ /**
110
+ * Maps from an object of namespace IDs and Snap IDs, and an object of
111
+ * namespace IDs and requested namespaces, to an object of namespace IDs and
112
+ * resolved accounts, with the Snap ID providing the accounts.
113
+ *
114
+ * @param origin - The origin of the request.
115
+ * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs
116
+ * providing the namespace.
117
+ * @param requestedNamespaces - An object of namespace IDs and requested
118
+ * namespaces.
119
+ * @returns An object of namespace IDs and resolved accounts, with the Snap ID
120
+ * providing the accounts.
121
+ */
122
+ private namespacesToAccounts;
123
+ /**
124
+ * If multiple Snap IDs are provided for a namespace, this method will
125
+ * determine which Snap ID to use for the namespace, by showing the user a
126
+ * prompt.
127
+ *
128
+ * @param origin - The origin of the request.
129
+ * @param possibleAccounts - An object containing the accounts provided by
130
+ * each Snap ID for each namespace.
131
+ * @returns An object containing the Snap ID to use for each namespace.
132
+ */
133
+ private resolveConflicts;
134
+ }
135
+ export {};
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _MultiChainController_notify;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MultiChainController = void 0;
16
+ const controllers_1 = require("@metamask/controllers");
17
+ const snaps_utils_1 = require("@metamask/snaps-utils");
18
+ const utils_1 = require("@metamask/utils");
19
+ const nanoid_1 = require("nanoid");
20
+ const snaps_1 = require("../snaps");
21
+ const keyring_1 = require("../snaps/endowments/keyring");
22
+ const matching_1 = require("./matching");
23
+ const controllerName = 'MultiChainController';
24
+ const defaultState = {
25
+ sessions: {},
26
+ };
27
+ // TODO(ritave): Support for legacy ethereum operations, not just snaps
28
+ class MultiChainController extends controllers_1.BaseControllerV2 {
29
+ /**
30
+ * Construct a new {@link MultiChainController} instance.
31
+ *
32
+ * @param args - The arguments to construct the controller with.
33
+ * @param args.messenger - The controller messenger to use.
34
+ * @param args.notify - A function that should handle JSON-RPC notifications.
35
+ */
36
+ constructor({ messenger, notify }) {
37
+ super({
38
+ messenger,
39
+ metadata: {
40
+ sessions: { persist: false, anonymous: false },
41
+ },
42
+ name: controllerName,
43
+ state: defaultState,
44
+ });
45
+ _MultiChainController_notify.set(this, void 0);
46
+ __classPrivateFieldSet(this, _MultiChainController_notify, notify, "f");
47
+ }
48
+ /**
49
+ * Get an open session for the given origin.
50
+ *
51
+ * @param origin - The origin to get the session for.
52
+ * @returns The session, if it exists, or `undefined` otherwise.
53
+ */
54
+ getSession(origin) {
55
+ return this.state.sessions[origin];
56
+ }
57
+ /**
58
+ * Close a session for the given origin.
59
+ *
60
+ * @param origin - The origin to close the session for.
61
+ * @throws If the session does not exist.
62
+ */
63
+ async closeSession(origin) {
64
+ const session = this.getSession(origin);
65
+ (0, utils_1.assert)(session, 'No session to close.');
66
+ await __classPrivateFieldGet(this, _MultiChainController_notify, "f").call(this, origin, {
67
+ method: 'multichainHack_metamask_disconnect',
68
+ });
69
+ this.update((state) => {
70
+ delete state.sessions[origin];
71
+ });
72
+ await Promise.all(Object.values(session.handlingSnaps).map((snapId) => this.messagingSystem.call('SnapController:decrementActiveReferences', snapId)));
73
+ }
74
+ /**
75
+ * Handles a new connection from the given origin. This will create a new
76
+ * session, and close any existing session for the origin.
77
+ *
78
+ * @param origin - The origin to create the session for.
79
+ * @param connection - The connection arguments.
80
+ * @param connection.requiredNamespaces - The namespaces that the origin
81
+ * requires.
82
+ * @returns The session that was created.
83
+ */
84
+ async onConnect(origin, connection) {
85
+ const existingSession = this.getSession(origin);
86
+ if (existingSession) {
87
+ await this.closeSession(origin);
88
+ }
89
+ const snaps = await this.messagingSystem.call('SnapController:getAll');
90
+ const filteredSnaps = (0, snaps_1.getRunnableSnaps)(snaps);
91
+ // Get available namespaces supported by currently installed Snaps.
92
+ const availableNamespaces = (0, snaps_utils_1.fromEntries)(await Promise.all(filteredSnaps.map(async (snap) => [
93
+ snap.id,
94
+ await this.snapToNamespaces(snap),
95
+ ])));
96
+ // The magical matching algorithm specified in SIP-2.
97
+ const namespaceToSnaps = (0, matching_1.findMatchingKeyringSnaps)(connection.requiredNamespaces, availableNamespaces);
98
+ const permissions = await this.messagingSystem.call('PermissionController:getPermissions', origin);
99
+ // Find namespaces that can be satisfied with existing approved Snaps.
100
+ const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce((acc, [namespace, snapIds]) => {
101
+ const approvedSnaps = snapIds.filter((snapId) => {
102
+ return (permissions && (0, utils_1.hasProperty)(permissions, (0, snaps_utils_1.getSnapPermissionName)(snapId)));
103
+ });
104
+ if (approvedSnaps.length > 0) {
105
+ acc[namespace] = approvedSnaps;
106
+ }
107
+ return acc;
108
+ }, {});
109
+ // If we either don't have a snap to handle a namespace or we have multiple we have conflicts
110
+ const hasConflicts = Object.keys(namespaceToSnaps).some((namespace) => {
111
+ var _a;
112
+ return !(0, utils_1.hasProperty)(approvedNamespacesAndSnaps, namespace) ||
113
+ ((_a = approvedNamespacesAndSnaps[namespace]) === null || _a === void 0 ? void 0 : _a.length) > 1;
114
+ });
115
+ // Use already approved snaps if they satisfy the requested namespaces.
116
+ const filteredNamespacesAndSnaps = hasConflicts
117
+ ? namespaceToSnaps
118
+ : approvedNamespacesAndSnaps;
119
+ // Fetch possible accounts from snaps.
120
+ const possibleAccounts = await this.namespacesToAccounts(origin, filteredNamespacesAndSnaps, connection.requiredNamespaces);
121
+ // For now we fail here if no namespaces could be matched to a snap.
122
+ // We don't fail if at least one namespace is matched to a snap.
123
+ // TODO: Decide whether this is what we want
124
+ (0, utils_1.assert)(Object.values(possibleAccounts).some((possibleAccount) => possibleAccount.length > 0), 'No installed snaps found for any requested namespace.');
125
+ // If currently installed Snaps / configuration doesn't solve request, we
126
+ // need to show a prompt. This is handled by `resolveConflicts`.
127
+ const resolvedAccounts = hasConflicts
128
+ ? await this.resolveConflicts(origin, possibleAccounts)
129
+ : (0, snaps_utils_1.fromEntries)(Object.entries(possibleAccounts).map(([namespace, snapAndAccounts]) => {
130
+ var _a;
131
+ return [
132
+ namespace,
133
+ (_a = snapAndAccounts[0]) !== null && _a !== void 0 ? _a : null,
134
+ ];
135
+ }));
136
+ // Aggregate information about session namespaces.
137
+ const providedNamespaces = Object.entries(connection.requiredNamespaces).reduce((acc, [namespaceId, namespace]) => {
138
+ var _a;
139
+ const accounts = (_a = resolvedAccounts[namespaceId]) === null || _a === void 0 ? void 0 : _a.accounts;
140
+ if (accounts) {
141
+ acc[namespaceId] = {
142
+ accounts,
143
+ chains: namespace.chains,
144
+ events: namespace.events,
145
+ methods: namespace.methods,
146
+ };
147
+ }
148
+ return acc;
149
+ }, {});
150
+ // Collect information about handler Snaps for each namespace.
151
+ const handlingSnaps = Object.entries(resolvedAccounts).reduce((acc, [namespaceId, accountsAndSnap]) => {
152
+ if (accountsAndSnap) {
153
+ acc[namespaceId] = accountsAndSnap.snapId;
154
+ }
155
+ return acc;
156
+ }, {});
157
+ const session = {
158
+ origin,
159
+ requestedNamespaces: connection.requiredNamespaces,
160
+ providedNamespaces,
161
+ handlingSnaps,
162
+ };
163
+ // Makes sure used Snaps aren't killed while they are serving the session.
164
+ await Promise.all(Object.values(session.handlingSnaps).map((snapId) => this.messagingSystem.call('SnapController:incrementActiveReferences', snapId)));
165
+ this.update((state) => {
166
+ state.sessions[origin] = session;
167
+ });
168
+ return { namespaces: providedNamespaces };
169
+ }
170
+ /**
171
+ * Handle an incoming multichain request from the given origin. This will
172
+ * forward the request to the appropriate Snap, and return the response.
173
+ *
174
+ * @param origin - The origin to handle the request for.
175
+ * @param data - The request data.
176
+ * @param data.chainId - The chain ID for the request.
177
+ * @param data.request - The request arguments, i.e., the method and params.
178
+ * @returns The response from the Snap.
179
+ * @throws If the session does not exist, or the session does not provide the
180
+ * requested namespace.
181
+ */
182
+ async onRequest(origin, data) {
183
+ var _a, _b;
184
+ const session = this.getSession(origin);
185
+ (0, utils_1.assert)(session, `Session for "${origin}" doesn't exist.`);
186
+ const { namespace } = (0, snaps_utils_1.parseChainId)(data.chainId);
187
+ const sessionNamespace = session.providedNamespaces[namespace];
188
+ (0, utils_1.assert)((_a = session.providedNamespaces[namespace]) === null || _a === void 0 ? void 0 : _a.chains.includes(data.chainId), `Session for "${origin}" is not connected to "${data.chainId}" chain.`);
189
+ const { method } = data.request;
190
+ (0, utils_1.assert)((_b = sessionNamespace === null || sessionNamespace === void 0 ? void 0 : sessionNamespace.methods) === null || _b === void 0 ? void 0 : _b.includes(method), `Session for "${origin}" does not support ${method}`);
191
+ const snapId = session.handlingSnaps[namespace];
192
+ (0, utils_1.assert)(snapId !== undefined);
193
+ const permissionName = (0, snaps_utils_1.getSnapPermissionName)(snapId);
194
+ // Check if origin has permission to communicate with this Snap.
195
+ const hasPermission = await this.messagingSystem.call('PermissionController:hasPermission', origin, permissionName);
196
+ // TODO: Get permission for origin connecting to snap, or get user approval.
197
+ // In the future this is where we should prompt for this permission.
198
+ // In this iteration, we will grant this permission in `onConnect`.
199
+ (0, utils_1.assert)(hasPermission, `${origin} does not have permission to communicate with ${snapId}.`);
200
+ return this.snapRequest({
201
+ snapId,
202
+ origin,
203
+ method: 'handleRequest',
204
+ args: data,
205
+ });
206
+ }
207
+ /**
208
+ * Send a request to the given Snap. This calls the given method with the
209
+ * given arguments on the keyring class in the given Snap.
210
+ *
211
+ * @param options - The request options.
212
+ * @param options.snapId - The ID of the Snap to send the request to.
213
+ * @param options.origin - The origin of the request.
214
+ * @param options.method - The request method.
215
+ * @param options.args - The request params.
216
+ * @returns The response from the Snap.
217
+ */
218
+ async snapRequest({ snapId, origin, method, args, }) {
219
+ return this.messagingSystem.call('SnapController:handleRequest', {
220
+ snapId,
221
+ origin,
222
+ handler: snaps_utils_1.HandlerType.SnapKeyring,
223
+ request: { method, params: args ? [args] : [] },
224
+ });
225
+ }
226
+ /**
227
+ * Get the accounts exposed by the Snap's keyring.
228
+ *
229
+ * This also verifies that the accounts returned by the snap are valid CAIP-10
230
+ * account IDs.
231
+ *
232
+ * @param origin - The origin of the request.
233
+ * @param snapId - The ID of the Snap to get the accounts from.
234
+ * @returns The accounts, or `null` if the Snap does not have any accounts, or
235
+ * the accounts are invalid (i.e., not valid CAIP-10 account IDs).
236
+ */
237
+ async getSnapAccounts(origin, snapId) {
238
+ try {
239
+ const result = await this.snapRequest({
240
+ snapId,
241
+ origin,
242
+ method: 'getAccounts',
243
+ });
244
+ if ((0, snaps_utils_1.isAccountIdArray)(result)) {
245
+ return result;
246
+ }
247
+ }
248
+ catch (error) {
249
+ // Ignore errors for now
250
+ console.error(error);
251
+ }
252
+ return null;
253
+ }
254
+ /**
255
+ * Get the namespaces for the given Snap, as described in the Snap's manifest.
256
+ *
257
+ * @param snap - The Snap to get the namespaces for.
258
+ * @returns The namespaces, or `null` if the Snap does not have any
259
+ * namespaces.
260
+ */
261
+ async snapToNamespaces(snap) {
262
+ const permissions = await this.messagingSystem.call('PermissionController:getPermissions', snap.id);
263
+ const keyringPermission = permissions === null || permissions === void 0 ? void 0 : permissions[snaps_1.SnapEndowments.Keyring];
264
+ return (0, keyring_1.getKeyringCaveatNamespaces)(keyringPermission);
265
+ }
266
+ /**
267
+ * Maps from an object of namespace IDs and Snap IDs, and an object of
268
+ * namespace IDs and requested namespaces, to an object of namespace IDs and
269
+ * resolved accounts, with the Snap ID providing the accounts.
270
+ *
271
+ * @param origin - The origin of the request.
272
+ * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs
273
+ * providing the namespace.
274
+ * @param requestedNamespaces - An object of namespace IDs and requested
275
+ * namespaces.
276
+ * @returns An object of namespace IDs and resolved accounts, with the Snap ID
277
+ * providing the accounts.
278
+ */
279
+ async namespacesToAccounts(origin, namespacesAndSnaps, requestedNamespaces) {
280
+ const dedupedSnaps = [
281
+ ...new Set((0, snaps_utils_1.flatten)(Object.values(namespacesAndSnaps))),
282
+ ];
283
+ const allAccounts = await dedupedSnaps.reduce(async (previousPromise, snapId) => {
284
+ const result = await this.getSnapAccounts(origin, snapId);
285
+ const acc = await previousPromise;
286
+ if (result) {
287
+ acc[snapId] = result;
288
+ }
289
+ return acc;
290
+ }, Promise.resolve({}));
291
+ return Object.keys(namespacesAndSnaps).reduce((acc, namespaceId) => {
292
+ const { chains } = requestedNamespaces[namespaceId];
293
+ const accountInAnyRequestedChain = (account) => {
294
+ const { chainId: parsedChainId } = (0, snaps_utils_1.parseAccountId)(account);
295
+ return chains.some((chainId) => chainId === parsedChainId);
296
+ };
297
+ const result = Object.entries(allAccounts)
298
+ .map(([snapId, accounts]) => ({
299
+ snapId,
300
+ accounts: accounts.filter(accountInAnyRequestedChain),
301
+ }))
302
+ .filter(({ accounts }) => accounts.length > 0);
303
+ acc[namespaceId] = result;
304
+ return acc;
305
+ }, {});
306
+ }
307
+ /**
308
+ * If multiple Snap IDs are provided for a namespace, this method will
309
+ * determine which Snap ID to use for the namespace, by showing the user a
310
+ * prompt.
311
+ *
312
+ * @param origin - The origin of the request.
313
+ * @param possibleAccounts - An object containing the accounts provided by
314
+ * each Snap ID for each namespace.
315
+ * @returns An object containing the Snap ID to use for each namespace.
316
+ */
317
+ async resolveConflicts(origin, possibleAccounts) {
318
+ // Get user approval for connection.
319
+ const id = (0, nanoid_1.nanoid)();
320
+ const resolvedAccounts = (await this.messagingSystem.call('ApprovalController:addRequest', {
321
+ origin,
322
+ id,
323
+ type: 'multichain_connect',
324
+ requestData: {
325
+ possibleAccounts,
326
+ },
327
+ }, true));
328
+ // TODO: In the future, use another permission here to not give full
329
+ // permission after handshake.
330
+ // Instead we should give origin only a read-only access to list of accounts
331
+ // without allowing provider.request() talking to a snap before additional
332
+ // user approval. The additional approval would be requested in `onRequest`.
333
+ const approvedPermissions = Object.values(resolvedAccounts).reduce((acc, cur) => {
334
+ if (cur !== null) {
335
+ acc[(0, snaps_utils_1.getSnapPermissionName)(cur.snapId)] = {};
336
+ }
337
+ return acc;
338
+ }, {});
339
+ await this.messagingSystem.call('PermissionController:grantPermissions', {
340
+ approvedPermissions,
341
+ subject: { origin },
342
+ });
343
+ return resolvedAccounts;
344
+ }
345
+ }
346
+ exports.MultiChainController = MultiChainController;
347
+ _MultiChainController_notify = new WeakMap();
348
+ //# sourceMappingURL=MultiChainController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MultiChainController.js","sourceRoot":"","sources":["../../src/multichain/MultiChainController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAQ+B;AAC/B,uDAmB+B;AAE/B,2CAAsD;AACtD,mCAAgC;AAChC,oCAOkB;AAClB,yDAAyE;AACzE,yCAAsD;AAEtD,MAAM,cAAc,GAAG,sBAAsB,CAAC;AAE9C,MAAM,YAAY,GAA8B;IAC9C,QAAQ,EAAE,EAAE;CACb,CAAC;AAyCF,uEAAuE;AACvE,MAAa,oBAAqB,SAAQ,8BAIzC;IAGC;;;;;;OAMG;IACH,YAAY,EAAE,SAAS,EAAE,MAAM,EAA4B;QACzD,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;aAC/C;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,YAAY;SACpB,CAAC,CAAC;QAjBL,+CAAyB;QAmBvB,uBAAA,IAAI,gCAAW,MAAM,MAAA,CAAC;IACxB,CAAC;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B,MAAc,EACd,gBAGC;QAID,oCAAoC;QACpC,MAAM,EAAE,GAAG,IAAA,eAAM,GAAE,CAAC;QACpB,MAAM,gBAAgB,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACvD,+BAA+B,EAC/B;YACE,MAAM;YACN,EAAE;YACF,IAAI,EAAE,oBAAoB;YAC1B,WAAW,EAAE;gBACX,gBAAgB;aACjB;SACF,EACD,IAAI,CACL,CAA0E,CAAC;QAE5E,oEAAoE;QACpE,8BAA8B;QAC9B,4EAA4E;QAC5E,0EAA0E;QAC1E,4EAA4E;QAC5E,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAEhE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YACb,IAAI,GAAG,KAAK,IAAI,EAAE;gBAChB,GAAG,CAAC,IAAA,mCAAqB,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC;aAC7C;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EAAE,EAAE,CAAC,CAAC;QAEP,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,EAAE;YACvE,mBAAmB;YACnB,OAAO,EAAE,EAAE,MAAM,EAAE;SACpB,CAAC,CAAC;QAEH,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAxdD,oDAwdC","sourcesContent":["import {\n AddApprovalRequest,\n BaseControllerV2 as BaseController,\n GetPermissions,\n GrantPermissions,\n HasPermission,\n PermissionConstraint,\n RestrictedControllerMessenger,\n} from '@metamask/controllers';\nimport {\n parseAccountId,\n AccountId,\n parseChainId,\n ChainId,\n ConnectArguments,\n HandlerType,\n NamespaceId,\n RequestArguments,\n RequestNamespace,\n Session,\n TruncatedSnap,\n SnapId,\n fromEntries,\n SessionNamespace,\n flatten,\n getSnapPermissionName,\n isAccountIdArray,\n Namespaces,\n} from '@metamask/snaps-utils';\nimport { SnapKeyring } from '@metamask/snaps-types';\nimport { hasProperty, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport {\n GetAllSnaps,\n HandleSnapRequest,\n IncrementActiveReferences,\n DecrementActiveReferences,\n SnapEndowments,\n getRunnableSnaps,\n} from '../snaps';\nimport { getKeyringCaveatNamespaces } from '../snaps/endowments/keyring';\nimport { findMatchingKeyringSnaps } from './matching';\n\nconst controllerName = 'MultiChainController';\n\nconst defaultState: MultiChainControllerState = {\n sessions: {},\n};\n\ntype AllowedActions =\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences\n | HandleSnapRequest\n | GetPermissions\n | HasPermission\n | AddApprovalRequest\n | GrantPermissions;\n\ntype MultiChainControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\ntype SessionData = {\n origin: string;\n requestedNamespaces: Record<NamespaceId, RequestNamespace>;\n providedNamespaces: Record<NamespaceId, RequestNamespace>;\n handlingSnaps: Record<NamespaceId, SnapId>;\n};\n\ntype MultiChainControllerState = {\n sessions: { [origin: string]: SessionData };\n};\n\ntype Notify = (\n origin: string,\n data: { method: string; params?: Record<string, unknown> },\n) => Promise<void>;\n\ntype MultiChainControllerArgs = {\n notify: Notify;\n messenger: MultiChainControllerMessenger;\n};\n\n// TODO(ritave): Support for legacy ethereum operations, not just snaps\nexport class MultiChainController extends BaseController<\n typeof controllerName,\n MultiChainControllerState,\n MultiChainControllerMessenger\n> {\n readonly #notify: Notify;\n\n /**\n * Construct a new {@link MultiChainController} instance.\n *\n * @param args - The arguments to construct the controller with.\n * @param args.messenger - The controller messenger to use.\n * @param args.notify - A function that should handle JSON-RPC notifications.\n */\n constructor({ messenger, notify }: MultiChainControllerArgs) {\n super({\n messenger,\n metadata: {\n sessions: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: defaultState,\n });\n\n this.#notify = notify;\n }\n\n /**\n * Get an open session for the given origin.\n *\n * @param origin - The origin to get the session for.\n * @returns The session, if it exists, or `undefined` otherwise.\n */\n getSession(origin: string): SessionData | undefined {\n return this.state.sessions[origin];\n }\n\n /**\n * Close a session for the given origin.\n *\n * @param origin - The origin to close the session for.\n * @throws If the session does not exist.\n */\n async closeSession(origin: string): Promise<void> {\n const session = this.getSession(origin);\n assert(session, 'No session to close.');\n\n await this.#notify(origin, {\n method: 'multichainHack_metamask_disconnect',\n });\n\n this.update((state) => {\n delete state.sessions[origin];\n });\n\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:decrementActiveReferences',\n snapId,\n ),\n ),\n );\n }\n\n /**\n * Handles a new connection from the given origin. This will create a new\n * session, and close any existing session for the origin.\n *\n * @param origin - The origin to create the session for.\n * @param connection - The connection arguments.\n * @param connection.requiredNamespaces - The namespaces that the origin\n * requires.\n * @returns The session that was created.\n */\n async onConnect(\n origin: string,\n connection: ConnectArguments,\n ): Promise<Session> {\n const existingSession = this.getSession(origin);\n if (existingSession) {\n await this.closeSession(origin);\n }\n\n const snaps = await this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n // Get available namespaces supported by currently installed Snaps.\n const availableNamespaces = fromEntries(\n await Promise.all(\n filteredSnaps.map(async (snap) => [\n snap.id,\n await this.snapToNamespaces(snap),\n ]),\n ),\n );\n\n // The magical matching algorithm specified in SIP-2.\n const namespaceToSnaps = findMatchingKeyringSnaps(\n connection.requiredNamespaces,\n availableNamespaces,\n );\n\n const permissions = await this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n );\n\n // Find namespaces that can be satisfied with existing approved Snaps.\n const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [namespace, snapIds]) => {\n const approvedSnaps = snapIds.filter((snapId) => {\n return (\n permissions && hasProperty(permissions, getSnapPermissionName(snapId))\n );\n });\n\n if (approvedSnaps.length > 0) {\n acc[namespace] = approvedSnaps;\n }\n return acc;\n }, {});\n\n // If we either don't have a snap to handle a namespace or we have multiple we have conflicts\n const hasConflicts = Object.keys(namespaceToSnaps).some(\n (namespace) =>\n !hasProperty(approvedNamespacesAndSnaps, namespace) ||\n approvedNamespacesAndSnaps[namespace]?.length > 1,\n );\n\n // Use already approved snaps if they satisfy the requested namespaces.\n const filteredNamespacesAndSnaps = hasConflicts\n ? namespaceToSnaps\n : approvedNamespacesAndSnaps;\n\n // Fetch possible accounts from snaps.\n const possibleAccounts = await this.namespacesToAccounts(\n origin,\n filteredNamespacesAndSnaps,\n connection.requiredNamespaces,\n );\n\n // For now we fail here if no namespaces could be matched to a snap.\n // We don't fail if at least one namespace is matched to a snap.\n // TODO: Decide whether this is what we want\n assert(\n Object.values(possibleAccounts).some(\n (possibleAccount) => possibleAccount.length > 0,\n ),\n 'No installed snaps found for any requested namespace.',\n );\n\n // If currently installed Snaps / configuration doesn't solve request, we\n // need to show a prompt. This is handled by `resolveConflicts`.\n const resolvedAccounts = hasConflicts\n ? await this.resolveConflicts(origin, possibleAccounts)\n : fromEntries(\n Object.entries(possibleAccounts).map(\n ([namespace, snapAndAccounts]) => [\n namespace,\n snapAndAccounts[0] ?? null,\n ],\n ),\n );\n\n // Aggregate information about session namespaces.\n const providedNamespaces = Object.entries(\n connection.requiredNamespaces,\n ).reduce<Record<NamespaceId, SessionNamespace>>(\n (acc, [namespaceId, namespace]) => {\n const accounts = resolvedAccounts[namespaceId]?.accounts;\n if (accounts) {\n acc[namespaceId] = {\n accounts,\n chains: namespace.chains,\n events: namespace.events,\n methods: namespace.methods,\n };\n }\n return acc;\n },\n {},\n );\n\n // Collect information about handler Snaps for each namespace.\n const handlingSnaps = Object.entries(resolvedAccounts).reduce<\n Record<NamespaceId, SnapId>\n >((acc, [namespaceId, accountsAndSnap]) => {\n if (accountsAndSnap) {\n acc[namespaceId] = accountsAndSnap.snapId;\n }\n return acc;\n }, {});\n\n const session: SessionData = {\n origin,\n requestedNamespaces: connection.requiredNamespaces,\n providedNamespaces,\n handlingSnaps,\n };\n\n // Makes sure used Snaps aren't killed while they are serving the session.\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:incrementActiveReferences',\n snapId,\n ),\n ),\n );\n\n this.update((state) => {\n state.sessions[origin] = session;\n });\n\n return { namespaces: providedNamespaces };\n }\n\n /**\n * Handle an incoming multichain request from the given origin. This will\n * forward the request to the appropriate Snap, and return the response.\n *\n * @param origin - The origin to handle the request for.\n * @param data - The request data.\n * @param data.chainId - The chain ID for the request.\n * @param data.request - The request arguments, i.e., the method and params.\n * @returns The response from the Snap.\n * @throws If the session does not exist, or the session does not provide the\n * requested namespace.\n */\n async onRequest(\n origin: string,\n data: { chainId: ChainId; request: RequestArguments },\n ): Promise<unknown> {\n const session = this.getSession(origin);\n assert(session, `Session for \"${origin}\" doesn't exist.`);\n\n const { namespace } = parseChainId(data.chainId);\n const sessionNamespace = session.providedNamespaces[namespace];\n assert(\n session.providedNamespaces[namespace]?.chains.includes(data.chainId),\n `Session for \"${origin}\" is not connected to \"${data.chainId}\" chain.`,\n );\n\n const { method } = data.request;\n assert(\n sessionNamespace?.methods?.includes(method),\n `Session for \"${origin}\" does not support ${method}`,\n );\n\n const snapId = session.handlingSnaps[namespace];\n assert(snapId !== undefined);\n\n const permissionName = getSnapPermissionName(snapId);\n\n // Check if origin has permission to communicate with this Snap.\n const hasPermission = await this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n );\n\n // TODO: Get permission for origin connecting to snap, or get user approval.\n // In the future this is where we should prompt for this permission.\n // In this iteration, we will grant this permission in `onConnect`.\n assert(\n hasPermission,\n `${origin} does not have permission to communicate with ${snapId}.`,\n );\n\n return this.snapRequest({\n snapId,\n origin,\n method: 'handleRequest',\n args: data,\n });\n }\n\n /**\n * Send a request to the given Snap. This calls the given method with the\n * given arguments on the keyring class in the given Snap.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.origin - The origin of the request.\n * @param options.method - The request method.\n * @param options.args - The request params.\n * @returns The response from the Snap.\n */\n private async snapRequest({\n snapId,\n origin,\n method,\n args,\n }: {\n snapId: SnapId;\n origin: string;\n method: keyof SnapKeyring;\n args?: unknown;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin,\n handler: HandlerType.SnapKeyring,\n request: { method, params: args ? [args] : [] },\n });\n }\n\n /**\n * Get the accounts exposed by the Snap's keyring.\n *\n * This also verifies that the accounts returned by the snap are valid CAIP-10\n * account IDs.\n *\n * @param origin - The origin of the request.\n * @param snapId - The ID of the Snap to get the accounts from.\n * @returns The accounts, or `null` if the Snap does not have any accounts, or\n * the accounts are invalid (i.e., not valid CAIP-10 account IDs).\n */\n private async getSnapAccounts(\n origin: string,\n snapId: SnapId,\n ): Promise<AccountId[] | null> {\n try {\n const result = await this.snapRequest({\n snapId,\n origin,\n method: 'getAccounts',\n });\n\n if (isAccountIdArray(result)) {\n return result;\n }\n } catch (error) {\n // Ignore errors for now\n console.error(error);\n }\n\n return null;\n }\n\n /**\n * Get the namespaces for the given Snap, as described in the Snap's manifest.\n *\n * @param snap - The Snap to get the namespaces for.\n * @returns The namespaces, or `null` if the Snap does not have any\n * namespaces.\n */\n private async snapToNamespaces(\n snap: TruncatedSnap,\n ): Promise<Namespaces | null> {\n const permissions = await this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n const keyringPermission = permissions?.[SnapEndowments.Keyring];\n return getKeyringCaveatNamespaces(keyringPermission);\n }\n\n /**\n * Maps from an object of namespace IDs and Snap IDs, and an object of\n * namespace IDs and requested namespaces, to an object of namespace IDs and\n * resolved accounts, with the Snap ID providing the accounts.\n *\n * @param origin - The origin of the request.\n * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs\n * providing the namespace.\n * @param requestedNamespaces - An object of namespace IDs and requested\n * namespaces.\n * @returns An object of namespace IDs and resolved accounts, with the Snap ID\n * providing the accounts.\n */\n private async namespacesToAccounts(\n origin: string,\n namespacesAndSnaps: Record<NamespaceId, SnapId[]>,\n requestedNamespaces: Record<NamespaceId, RequestNamespace>,\n ): Promise<Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>> {\n const dedupedSnaps = [\n ...new Set(flatten(Object.values(namespacesAndSnaps))),\n ] as SnapId[];\n\n const allAccounts = await dedupedSnaps.reduce<\n Promise<Record<string, AccountId[]>>\n >(async (previousPromise, snapId) => {\n const result = await this.getSnapAccounts(origin, snapId);\n const acc = await previousPromise;\n if (result) {\n acc[snapId] = result;\n }\n return acc;\n }, Promise.resolve({}));\n\n return Object.keys(namespacesAndSnaps).reduce<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>\n >((acc, namespaceId) => {\n const { chains } = requestedNamespaces[namespaceId];\n\n const accountInAnyRequestedChain = (account: AccountId) => {\n const { chainId: parsedChainId } = parseAccountId(account);\n return chains.some((chainId) => chainId === parsedChainId);\n };\n\n const result = Object.entries(allAccounts)\n .map(([snapId, accounts]) => ({\n snapId,\n accounts: accounts.filter(accountInAnyRequestedChain),\n }))\n .filter(({ accounts }) => accounts.length > 0);\n\n acc[namespaceId] = result;\n\n return acc;\n }, {});\n }\n\n /**\n * If multiple Snap IDs are provided for a namespace, this method will\n * determine which Snap ID to use for the namespace, by showing the user a\n * prompt.\n *\n * @param origin - The origin of the request.\n * @param possibleAccounts - An object containing the accounts provided by\n * each Snap ID for each namespace.\n * @returns An object containing the Snap ID to use for each namespace.\n */\n private async resolveConflicts(\n origin: string,\n possibleAccounts: Record<\n NamespaceId,\n { snapId: SnapId; accounts: AccountId[] }[]\n >,\n ): Promise<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>\n > {\n // Get user approval for connection.\n const id = nanoid();\n const resolvedAccounts = (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: 'multichain_connect',\n requestData: {\n possibleAccounts,\n },\n },\n true,\n )) as Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>;\n\n // TODO: In the future, use another permission here to not give full\n // permission after handshake.\n // Instead we should give origin only a read-only access to list of accounts\n // without allowing provider.request() talking to a snap before additional\n // user approval. The additional approval would be requested in `onRequest`.\n const approvedPermissions = Object.values(resolvedAccounts).reduce<\n Record<string, Partial<PermissionConstraint>>\n >((acc, cur) => {\n if (cur !== null) {\n acc[getSnapPermissionName(cur.snapId)] = {};\n }\n return acc;\n }, {});\n\n await this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin },\n });\n\n return resolvedAccounts;\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export * from './matching';
2
+ export * from './middleware';
3
+ export * from './MultiChainController';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./matching"), exports);
18
+ __exportStar(require("./middleware"), exports);
19
+ __exportStar(require("./MultiChainController"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/multichain/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAA2B;AAC3B,+CAA6B;AAC7B,yDAAuC","sourcesContent":["export * from './matching';\nexport * from './middleware';\nexport * from './MultiChainController';\n"]}
@@ -0,0 +1,9 @@
1
+ import { ConnectArguments, NamespaceId, SnapId, Namespace } from '@metamask/snaps-utils';
2
+ /**
3
+ * Finds a keyring snap for each namespace implements at a minimum the requested functionality.
4
+ *
5
+ * @param requestedNamespaces - The requested namespaces.
6
+ * @param snaps - All snaps and their exposed keyring namespaces.
7
+ * @returns A mapping between namespaces and snap ids.
8
+ */
9
+ export declare function findMatchingKeyringSnaps(requestedNamespaces: ConnectArguments['requiredNamespaces'], snaps: Record<SnapId, Record<NamespaceId, Namespace> | null>): Record<NamespaceId, SnapId[]>;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findMatchingKeyringSnaps = void 0;
4
+ /**
5
+ * Finds a keyring snap for each namespace implements at a minimum the requested functionality.
6
+ *
7
+ * @param requestedNamespaces - The requested namespaces.
8
+ * @param snaps - All snaps and their exposed keyring namespaces.
9
+ * @returns A mapping between namespaces and snap ids.
10
+ */
11
+ function findMatchingKeyringSnaps(requestedNamespaces, snaps) {
12
+ const snapEntries = Object.entries(snaps);
13
+ return Object.entries(requestedNamespaces).reduce((acc, [requestedNamespaceId, currentRequestedNamespace]) => {
14
+ const matchedSnaps = snapEntries
15
+ .filter(([, namespaces]) => {
16
+ const potentialMatch = namespaces === null || namespaces === void 0 ? void 0 : namespaces[requestedNamespaceId];
17
+ return (potentialMatch !== undefined &&
18
+ matchNamespace(currentRequestedNamespace, potentialMatch));
19
+ })
20
+ .map(([snapId]) => snapId);
21
+ acc[requestedNamespaceId] = matchedSnaps;
22
+ return acc;
23
+ }, {});
24
+ }
25
+ exports.findMatchingKeyringSnaps = findMatchingKeyringSnaps;
26
+ /**
27
+ * Determines whether a keyring namespace is a match given a potential match and the requested namespace.
28
+ *
29
+ * This function assumes that the namespace ID has already been matched.
30
+ *
31
+ * @param requestedNamespace - The requested namespace information.
32
+ * @param potentialMatchNamespace - The potential match.
33
+ * @returns True if the potentially matching namespace is a match.
34
+ */
35
+ function matchNamespace(requestedNamespace, potentialMatchNamespace) {
36
+ var _a, _b, _c, _d;
37
+ if (!requestedNamespace.chains.every((requestedChain) => potentialMatchNamespace.chains.some((potentialMatchChain) => potentialMatchChain.id === requestedChain))) {
38
+ return false;
39
+ }
40
+ if (!isSubset((_a = requestedNamespace.events) !== null && _a !== void 0 ? _a : [], (_b = potentialMatchNamespace.events) !== null && _b !== void 0 ? _b : [])) {
41
+ return false;
42
+ }
43
+ if (!isSubset((_c = requestedNamespace.methods) !== null && _c !== void 0 ? _c : [], (_d = potentialMatchNamespace.methods) !== null && _d !== void 0 ? _d : [])) {
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+ /**
49
+ * Determines whether an array is a subset of another array.
50
+ *
51
+ * @param potentialSubset - The potential subset.
52
+ * @param array - The other array.
53
+ * @returns True if the first argument is a subset of second argument.
54
+ */
55
+ function isSubset(potentialSubset, array) {
56
+ return potentialSubset.every((item) => array.includes(item));
57
+ }
58
+ //# sourceMappingURL=matching.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matching.js","sourceRoot":"","sources":["../../src/multichain/matching.ts"],"names":[],"mappings":";;;AAOA;;;;;;GAMG;AACH,SAAgB,wBAAwB,CACtC,mBAA2D,EAC3D,KAA4D;IAE5D,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAE/C,CAAC,GAAG,EAAE,CAAC,oBAAoB,EAAE,yBAAyB,CAAC,EAAE,EAAE;QAC3D,MAAM,YAAY,GAAG,WAAW;aAC7B,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,EAAE;YACzB,MAAM,cAAc,GAAG,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAG,oBAAoB,CAAC,CAAC;YAC1D,OAAO,CACL,cAAc,KAAK,SAAS;gBAC5B,cAAc,CAAC,yBAAyB,EAAE,cAAc,CAAC,CAC1D,CAAC;QACJ,CAAC,CAAC;aACD,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;QAC7B,GAAG,CAAC,oBAAoB,CAAC,GAAG,YAAY,CAAC;QACzC,OAAO,GAAG,CAAC;IACb,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC;AApBD,4DAoBC;AAED;;;;;;;;GAQG;AACH,SAAS,cAAc,CACrB,kBAAuE,EACvE,uBAAkC;;IAElC,IACE,CAAC,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,EAAE,CAClD,uBAAuB,CAAC,MAAM,CAAC,IAAI,CACjC,CAAC,mBAAmB,EAAE,EAAE,CAAC,mBAAmB,CAAC,EAAE,KAAK,cAAc,CACnE,CACF,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,IACE,CAAC,QAAQ,CACP,MAAA,kBAAkB,CAAC,MAAM,mCAAI,EAAE,EAC/B,MAAA,uBAAuB,CAAC,MAAM,mCAAI,EAAE,CACrC,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,IACE,CAAC,QAAQ,CACP,MAAA,kBAAkB,CAAC,OAAO,mCAAI,EAAE,EAChC,MAAA,uBAAuB,CAAC,OAAO,mCAAI,EAAE,CACtC,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,QAAQ,CAAI,eAAoB,EAAE,KAAU;IACnD,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import {\n ConnectArguments,\n NamespaceId,\n SnapId,\n Namespace,\n} from '@metamask/snaps-utils';\n\n/**\n * Finds a keyring snap for each namespace implements at a minimum the requested functionality.\n *\n * @param requestedNamespaces - The requested namespaces.\n * @param snaps - All snaps and their exposed keyring namespaces.\n * @returns A mapping between namespaces and snap ids.\n */\nexport function findMatchingKeyringSnaps(\n requestedNamespaces: ConnectArguments['requiredNamespaces'],\n snaps: Record<SnapId, Record<NamespaceId, Namespace> | null>,\n): Record<NamespaceId, SnapId[]> {\n const snapEntries = Object.entries(snaps);\n return Object.entries(requestedNamespaces).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [requestedNamespaceId, currentRequestedNamespace]) => {\n const matchedSnaps = snapEntries\n .filter(([, namespaces]) => {\n const potentialMatch = namespaces?.[requestedNamespaceId];\n return (\n potentialMatch !== undefined &&\n matchNamespace(currentRequestedNamespace, potentialMatch)\n );\n })\n .map(([snapId]) => snapId);\n acc[requestedNamespaceId] = matchedSnaps;\n return acc;\n }, {});\n}\n\n/**\n * Determines whether a keyring namespace is a match given a potential match and the requested namespace.\n *\n * This function assumes that the namespace ID has already been matched.\n *\n * @param requestedNamespace - The requested namespace information.\n * @param potentialMatchNamespace - The potential match.\n * @returns True if the potentially matching namespace is a match.\n */\nfunction matchNamespace(\n requestedNamespace: ConnectArguments['requiredNamespaces'][NamespaceId],\n potentialMatchNamespace: Namespace,\n) {\n if (\n !requestedNamespace.chains.every((requestedChain) =>\n potentialMatchNamespace.chains.some(\n (potentialMatchChain) => potentialMatchChain.id === requestedChain,\n ),\n )\n ) {\n return false;\n }\n\n if (\n !isSubset(\n requestedNamespace.events ?? [],\n potentialMatchNamespace.events ?? [],\n )\n ) {\n return false;\n }\n\n if (\n !isSubset(\n requestedNamespace.methods ?? [],\n potentialMatchNamespace.methods ?? [],\n )\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Determines whether an array is a subset of another array.\n *\n * @param potentialSubset - The potential subset.\n * @param array - The other array.\n * @returns True if the first argument is a subset of second argument.\n */\nfunction isSubset<T>(potentialSubset: T[], array: T[]) {\n return potentialSubset.every((item) => array.includes(item));\n}\n"]}