@metamask/snaps-controllers 12.3.1 → 13.1.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 (128) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/dist/cronjob/CronjobController.cjs +250 -276
  3. package/dist/cronjob/CronjobController.cjs.map +1 -1
  4. package/dist/cronjob/CronjobController.d.cts +61 -78
  5. package/dist/cronjob/CronjobController.d.cts.map +1 -1
  6. package/dist/cronjob/CronjobController.d.mts +61 -78
  7. package/dist/cronjob/CronjobController.d.mts.map +1 -1
  8. package/dist/cronjob/CronjobController.mjs +251 -277
  9. package/dist/cronjob/CronjobController.mjs.map +1 -1
  10. package/dist/cronjob/utils.cjs +79 -0
  11. package/dist/cronjob/utils.cjs.map +1 -0
  12. package/dist/cronjob/utils.d.cts +25 -0
  13. package/dist/cronjob/utils.d.cts.map +1 -0
  14. package/dist/cronjob/utils.d.mts +25 -0
  15. package/dist/cronjob/utils.d.mts.map +1 -0
  16. package/dist/cronjob/utils.mjs +75 -0
  17. package/dist/cronjob/utils.mjs.map +1 -0
  18. package/dist/index.cjs +1 -0
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -0
  21. package/dist/index.d.cts.map +1 -1
  22. package/dist/index.d.mts +1 -0
  23. package/dist/index.d.mts.map +1 -1
  24. package/dist/index.mjs +1 -0
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/insights/SnapInsightsController.cjs +199 -149
  27. package/dist/insights/SnapInsightsController.cjs.map +1 -1
  28. package/dist/insights/SnapInsightsController.mjs +198 -148
  29. package/dist/insights/SnapInsightsController.mjs.map +1 -1
  30. package/dist/interface/SnapInterfaceController.cjs +160 -101
  31. package/dist/interface/SnapInterfaceController.cjs.map +1 -1
  32. package/dist/interface/SnapInterfaceController.mjs +160 -101
  33. package/dist/interface/SnapInterfaceController.mjs.map +1 -1
  34. package/dist/multichain/MultichainRouter.cjs +117 -114
  35. package/dist/multichain/MultichainRouter.cjs.map +1 -1
  36. package/dist/multichain/MultichainRouter.mjs +117 -114
  37. package/dist/multichain/MultichainRouter.mjs.map +1 -1
  38. package/dist/services/AbstractExecutionService.cjs +131 -139
  39. package/dist/services/AbstractExecutionService.cjs.map +1 -1
  40. package/dist/services/AbstractExecutionService.mjs +131 -139
  41. package/dist/services/AbstractExecutionService.mjs.map +1 -1
  42. package/dist/services/ProxyPostMessageStream.cjs +19 -26
  43. package/dist/services/ProxyPostMessageStream.cjs.map +1 -1
  44. package/dist/services/ProxyPostMessageStream.mjs +19 -26
  45. package/dist/services/ProxyPostMessageStream.mjs.map +1 -1
  46. package/dist/services/iframe/IframeExecutionService.cjs +1 -0
  47. package/dist/services/iframe/IframeExecutionService.cjs.map +1 -1
  48. package/dist/services/iframe/IframeExecutionService.mjs +1 -0
  49. package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
  50. package/dist/services/offscreen/OffscreenExecutionService.cjs +3 -16
  51. package/dist/services/offscreen/OffscreenExecutionService.cjs.map +1 -1
  52. package/dist/services/offscreen/OffscreenExecutionService.mjs +3 -16
  53. package/dist/services/offscreen/OffscreenExecutionService.mjs.map +1 -1
  54. package/dist/services/proxy/ProxyExecutionService.cjs +4 -17
  55. package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
  56. package/dist/services/proxy/ProxyExecutionService.mjs +4 -17
  57. package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
  58. package/dist/services/webview/WebViewExecutionService.cjs +6 -19
  59. package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
  60. package/dist/services/webview/WebViewExecutionService.mjs +6 -19
  61. package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
  62. package/dist/services/webview/WebViewMessageStream.cjs +13 -26
  63. package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
  64. package/dist/services/webview/WebViewMessageStream.mjs +13 -26
  65. package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
  66. package/dist/snaps/SnapController.cjs +1432 -1204
  67. package/dist/snaps/SnapController.cjs.map +1 -1
  68. package/dist/snaps/SnapController.d.cts +20 -5
  69. package/dist/snaps/SnapController.d.cts.map +1 -1
  70. package/dist/snaps/SnapController.d.mts +20 -5
  71. package/dist/snaps/SnapController.d.mts.map +1 -1
  72. package/dist/snaps/SnapController.mjs +1432 -1204
  73. package/dist/snaps/SnapController.mjs.map +1 -1
  74. package/dist/snaps/Timer.cjs +4 -0
  75. package/dist/snaps/Timer.cjs.map +1 -1
  76. package/dist/snaps/Timer.mjs +4 -0
  77. package/dist/snaps/Timer.mjs.map +1 -1
  78. package/dist/snaps/constants.cjs +1 -0
  79. package/dist/snaps/constants.cjs.map +1 -1
  80. package/dist/snaps/constants.d.cts.map +1 -1
  81. package/dist/snaps/constants.d.mts.map +1 -1
  82. package/dist/snaps/constants.mjs +1 -0
  83. package/dist/snaps/constants.mjs.map +1 -1
  84. package/dist/snaps/index.cjs +1 -0
  85. package/dist/snaps/index.cjs.map +1 -1
  86. package/dist/snaps/index.d.cts +1 -0
  87. package/dist/snaps/index.d.cts.map +1 -1
  88. package/dist/snaps/index.d.mts +1 -0
  89. package/dist/snaps/index.d.mts.map +1 -1
  90. package/dist/snaps/index.mjs +1 -0
  91. package/dist/snaps/index.mjs.map +1 -1
  92. package/dist/snaps/location/http.cjs +20 -4
  93. package/dist/snaps/location/http.cjs.map +1 -1
  94. package/dist/snaps/location/http.mjs +20 -4
  95. package/dist/snaps/location/http.mjs.map +1 -1
  96. package/dist/snaps/location/local.cjs +4 -17
  97. package/dist/snaps/location/local.cjs.map +1 -1
  98. package/dist/snaps/location/local.mjs +4 -17
  99. package/dist/snaps/location/local.mjs.map +1 -1
  100. package/dist/snaps/location/npm.cjs +28 -48
  101. package/dist/snaps/location/npm.cjs.map +1 -1
  102. package/dist/snaps/location/npm.d.cts.map +1 -1
  103. package/dist/snaps/location/npm.d.mts.map +1 -1
  104. package/dist/snaps/location/npm.mjs +28 -48
  105. package/dist/snaps/location/npm.mjs.map +1 -1
  106. package/dist/snaps/registry/json.cjs +173 -166
  107. package/dist/snaps/registry/json.cjs.map +1 -1
  108. package/dist/snaps/registry/json.mjs +172 -165
  109. package/dist/snaps/registry/json.mjs.map +1 -1
  110. package/dist/utils.d.cts +1 -1
  111. package/dist/utils.d.mts +1 -1
  112. package/dist/websocket/WebSocketService.cjs +194 -0
  113. package/dist/websocket/WebSocketService.cjs.map +1 -0
  114. package/dist/websocket/WebSocketService.d.cts +33 -0
  115. package/dist/websocket/WebSocketService.d.cts.map +1 -0
  116. package/dist/websocket/WebSocketService.d.mts +33 -0
  117. package/dist/websocket/WebSocketService.d.mts.map +1 -0
  118. package/dist/websocket/WebSocketService.mjs +190 -0
  119. package/dist/websocket/WebSocketService.mjs.map +1 -0
  120. package/dist/websocket/index.cjs +18 -0
  121. package/dist/websocket/index.cjs.map +1 -0
  122. package/dist/websocket/index.d.cts +2 -0
  123. package/dist/websocket/index.d.cts.map +1 -0
  124. package/dist/websocket/index.d.mts +2 -0
  125. package/dist/websocket/index.d.mts.map +1 -0
  126. package/dist/websocket/index.mjs +2 -0
  127. package/dist/websocket/index.mjs.map +1 -0
  128. package/package.json +10 -10
@@ -1,16 +1,4 @@
1
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 _MultichainRouter_instances, _MultichainRouter_messenger, _MultichainRouter_withSnapKeyring, _MultichainRouter_resolveRequestAddress, _MultichainRouter_getSnapAccountId, _MultichainRouter_getProtocolSnaps, _MultichainRouter_getSupportedAccountsMetadata;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.MultichainRouter = void 0;
16
4
  const rpc_errors_1 = require("@metamask/rpc-errors");
@@ -21,18 +9,104 @@ const nanoid_1 = require("nanoid");
21
9
  const snaps_1 = require("../snaps/index.cjs");
22
10
  const name = 'MultichainRouter';
23
11
  class MultichainRouter {
12
+ name = name;
13
+ state = null;
14
+ #messenger;
15
+ #withSnapKeyring;
24
16
  constructor({ messenger, withSnapKeyring }) {
25
- _MultichainRouter_instances.add(this);
26
- this.name = name;
27
- this.state = null;
28
- _MultichainRouter_messenger.set(this, void 0);
29
- _MultichainRouter_withSnapKeyring.set(this, void 0);
30
- __classPrivateFieldSet(this, _MultichainRouter_messenger, messenger, "f");
31
- __classPrivateFieldSet(this, _MultichainRouter_withSnapKeyring, withSnapKeyring, "f");
32
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:handleRequest`, async (...args) => this.handleRequest(...args));
33
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:getSupportedMethods`, (...args) => this.getSupportedMethods(...args));
34
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:getSupportedAccounts`, (...args) => this.getSupportedAccounts(...args));
35
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:isSupportedScope`, (...args) => this.isSupportedScope(...args));
17
+ this.#messenger = messenger;
18
+ this.#withSnapKeyring = withSnapKeyring;
19
+ this.#messenger.registerActionHandler(`${name}:handleRequest`, async (...args) => this.handleRequest(...args));
20
+ this.#messenger.registerActionHandler(`${name}:getSupportedMethods`, (...args) => this.getSupportedMethods(...args));
21
+ this.#messenger.registerActionHandler(`${name}:getSupportedAccounts`, (...args) => this.getSupportedAccounts(...args));
22
+ this.#messenger.registerActionHandler(`${name}:isSupportedScope`, (...args) => this.isSupportedScope(...args));
23
+ }
24
+ /**
25
+ * Attempts to resolve the account address to use for a given request by inspecting the request itself.
26
+ *
27
+ * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.
28
+ *
29
+ * @param snapId - The ID of the Snap to send the request to.
30
+ * @param scope - The CAIP-2 scope for the request.
31
+ * @param request - The JSON-RPC request.
32
+ * @returns The resolved address if found, otherwise null.
33
+ * @throws If the invocation of the SnapKeyring fails.
34
+ */
35
+ async #resolveRequestAddress(snapId, scope, request) {
36
+ try {
37
+ const result = await this.#withSnapKeyring(async ({ keyring }) => keyring.resolveAccountAddress(snapId, scope, request));
38
+ const address = result?.address;
39
+ return address ? (0, utils_1.parseCaipAccountId)(address).address : null;
40
+ }
41
+ catch {
42
+ throw rpc_errors_1.rpcErrors.internal();
43
+ }
44
+ }
45
+ /**
46
+ * Get the account ID of the account that should service the RPC request via an account Snap.
47
+ *
48
+ * This function checks whether any accounts exist that can service a given request by
49
+ * using a combination of the resolveAccountAddress functionality and the connected accounts.
50
+ *
51
+ * If an account is expected to service this request but none is found, the function will throw.
52
+ *
53
+ * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.
54
+ * @param scope - The CAIP-2 scope for the request.
55
+ * @param request - The JSON-RPC request.
56
+ * @returns An account ID if found, otherwise null.
57
+ * @throws If no account is found, but the accounts exist that could service the request.
58
+ */
59
+ async #getSnapAccountId(connectedAddresses, scope, request) {
60
+ const accounts = this.#messenger
61
+ .call('AccountsController:listMultichainAccounts', scope)
62
+ .filter((account) => Boolean(account.metadata.snap?.enabled) &&
63
+ account.methods.includes(request.method));
64
+ // If no accounts can service the request, return null.
65
+ if (accounts.length === 0) {
66
+ return null;
67
+ }
68
+ const resolutionSnapId = accounts[0].metadata.snap.id;
69
+ // Attempt to resolve the address that should be used for signing.
70
+ const address = await this.#resolveRequestAddress(resolutionSnapId, scope, request);
71
+ const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => (0, utils_1.parseCaipAccountId)(connectedAddress).address);
72
+ // If we have a resolved address, try to find the selected account based on that
73
+ // otherwise, default to one of the connected accounts.
74
+ // TODO: Eventually let the user choose if we have more than one option for the account.
75
+ const selectedAccount = accounts.find((account) => parsedConnectedAddresses.includes(account.address) &&
76
+ (!address || account.address === address));
77
+ if (!selectedAccount) {
78
+ throw rpc_errors_1.rpcErrors.invalidParams({
79
+ message: 'No available account found for request.',
80
+ });
81
+ }
82
+ return selectedAccount.id;
83
+ }
84
+ /**
85
+ * Get all protocol Snaps that can service a given CAIP-2 scope.
86
+ *
87
+ * Protocol Snaps are deemed fit to service a scope if they are runnable
88
+ * and have the proper permissions set for the scope.
89
+ *
90
+ * @param scope - A CAIP-2 scope.
91
+ * @returns A list of all the protocol Snaps available and their RPC methods.
92
+ */
93
+ #getProtocolSnaps(scope) {
94
+ const allSnaps = this.#messenger.call('SnapController:getAll');
95
+ const filteredSnaps = (0, snaps_1.getRunnableSnaps)(allSnaps);
96
+ return filteredSnaps.reduce((accumulator, snap) => {
97
+ const permissions = this.#messenger.call('PermissionController:getPermissions', snap.id);
98
+ if (permissions && (0, utils_1.hasProperty)(permissions, snaps_rpc_methods_1.SnapEndowments.Protocol)) {
99
+ const permission = permissions[snaps_rpc_methods_1.SnapEndowments.Protocol];
100
+ const scopes = (0, snaps_rpc_methods_1.getProtocolCaveatScopes)(permission);
101
+ if (scopes && (0, utils_1.hasProperty)(scopes, scope)) {
102
+ accumulator.push({
103
+ snapId: snap.id,
104
+ methods: scopes[scope].methods,
105
+ });
106
+ }
107
+ }
108
+ return accumulator;
109
+ }, []);
36
110
  }
37
111
  /**
38
112
  * Handle an incoming JSON-RPC request tied to a specific scope by routing
@@ -62,9 +136,9 @@ class MultichainRouter {
62
136
  };
63
137
  const { method, params } = request;
64
138
  // If the RPC request can be serviced by an account Snap, route it there.
65
- const accountId = await __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSnapAccountId).call(this, connectedAddresses, scope, request);
139
+ const accountId = await this.#getSnapAccountId(connectedAddresses, scope, request);
66
140
  if (accountId) {
67
- return __classPrivateFieldGet(this, _MultichainRouter_withSnapKeyring, "f").call(this, async ({ keyring }) => keyring.submitRequest({
141
+ return this.#withSnapKeyring(async ({ keyring }) => keyring.submitRequest({
68
142
  origin,
69
143
  account: accountId,
70
144
  scope,
@@ -74,10 +148,10 @@ class MultichainRouter {
74
148
  }
75
149
  // If the RPC request cannot be serviced by an account Snap,
76
150
  // but has a protocol Snap available, route it there.
77
- const protocolSnaps = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope);
151
+ const protocolSnaps = this.#getProtocolSnaps(scope);
78
152
  const protocolSnap = protocolSnaps.find((snap) => snap.methods.includes(method));
79
153
  if (protocolSnap) {
80
- return __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('SnapController:handleRequest', {
154
+ return this.#messenger.call('SnapController:handleRequest', {
81
155
  snapId: protocolSnap.snapId,
82
156
  origin,
83
157
  request: {
@@ -93,6 +167,17 @@ class MultichainRouter {
93
167
  // If no compatible account or protocol Snaps were found, throw.
94
168
  throw rpc_errors_1.rpcErrors.methodNotFound();
95
169
  }
170
+ /**
171
+ * Get a list of metadata for supported accounts for a given scope from the client.
172
+ *
173
+ * @param scope - The CAIP-2 scope.
174
+ * @returns A list of metadata for the supported accounts.
175
+ */
176
+ #getSupportedAccountsMetadata(scope) {
177
+ return this.#messenger
178
+ .call('AccountsController:listMultichainAccounts', scope)
179
+ .filter((account) => account.metadata.snap?.enabled);
180
+ }
96
181
  /**
97
182
  * Get a list of supported methods for a given scope.
98
183
  * This combines both protocol and account Snaps supported methods.
@@ -101,8 +186,8 @@ class MultichainRouter {
101
186
  * @returns A list of supported methods.
102
187
  */
103
188
  getSupportedMethods(scope) {
104
- const accountMethods = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSupportedAccountsMetadata).call(this, scope).flatMap((account) => account.methods);
105
- const protocolMethods = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope).flatMap((snap) => snap.methods);
189
+ const accountMethods = this.#getSupportedAccountsMetadata(scope).flatMap((account) => account.methods);
190
+ const protocolMethods = this.#getProtocolSnaps(scope).flatMap((snap) => snap.methods);
106
191
  return Array.from(new Set([...accountMethods, ...protocolMethods]));
107
192
  }
108
193
  /**
@@ -112,7 +197,7 @@ class MultichainRouter {
112
197
  * @returns A list of CAIP-10 addresses.
113
198
  */
114
199
  getSupportedAccounts(scope) {
115
- return __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSupportedAccountsMetadata).call(this, scope).map((account) => `${scope}:${account.address}`);
200
+ return this.#getSupportedAccountsMetadata(scope).map((account) => `${scope}:${account.address}`);
116
201
  }
117
202
  /**
118
203
  * Determine whether a given CAIP-2 scope is supported by the router.
@@ -121,94 +206,12 @@ class MultichainRouter {
121
206
  * @returns True if the router can service the scope, otherwise false.
122
207
  */
123
208
  isSupportedScope(scope) {
124
- const hasAccountSnap = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
209
+ const hasAccountSnap = this.#messenger
125
210
  .call('AccountsController:listMultichainAccounts', scope)
126
211
  .some((account) => account.metadata.snap?.enabled);
127
212
  // We currently assume here that if one Snap exists that service the scope, we can service the scope generally.
128
- return hasAccountSnap || __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope).length > 0;
213
+ return hasAccountSnap || this.#getProtocolSnaps(scope).length > 0;
129
214
  }
130
215
  }
131
216
  exports.MultichainRouter = MultichainRouter;
132
- _MultichainRouter_messenger = new WeakMap(), _MultichainRouter_withSnapKeyring = new WeakMap(), _MultichainRouter_instances = new WeakSet(), _MultichainRouter_resolveRequestAddress =
133
- /**
134
- * Attempts to resolve the account address to use for a given request by inspecting the request itself.
135
- *
136
- * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.
137
- *
138
- * @param snapId - The ID of the Snap to send the request to.
139
- * @param scope - The CAIP-2 scope for the request.
140
- * @param request - The JSON-RPC request.
141
- * @returns The resolved address if found, otherwise null.
142
- * @throws If the invocation of the SnapKeyring fails.
143
- */
144
- async function _MultichainRouter_resolveRequestAddress(snapId, scope, request) {
145
- try {
146
- const result = await __classPrivateFieldGet(this, _MultichainRouter_withSnapKeyring, "f").call(this, async ({ keyring }) => keyring.resolveAccountAddress(snapId, scope, request));
147
- const address = result?.address;
148
- return address ? (0, utils_1.parseCaipAccountId)(address).address : null;
149
- }
150
- catch {
151
- throw rpc_errors_1.rpcErrors.internal();
152
- }
153
- }, _MultichainRouter_getSnapAccountId =
154
- /**
155
- * Get the account ID of the account that should service the RPC request via an account Snap.
156
- *
157
- * This function checks whether any accounts exist that can service a given request by
158
- * using a combination of the resolveAccountAddress functionality and the connected accounts.
159
- *
160
- * If an account is expected to service this request but none is found, the function will throw.
161
- *
162
- * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.
163
- * @param scope - The CAIP-2 scope for the request.
164
- * @param request - The JSON-RPC request.
165
- * @returns An account ID if found, otherwise null.
166
- * @throws If no account is found, but the accounts exist that could service the request.
167
- */
168
- async function _MultichainRouter_getSnapAccountId(connectedAddresses, scope, request) {
169
- const accounts = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
170
- .call('AccountsController:listMultichainAccounts', scope)
171
- .filter((account) => Boolean(account.metadata.snap?.enabled) &&
172
- account.methods.includes(request.method));
173
- // If no accounts can service the request, return null.
174
- if (accounts.length === 0) {
175
- return null;
176
- }
177
- const resolutionSnapId = accounts[0].metadata.snap.id;
178
- // Attempt to resolve the address that should be used for signing.
179
- const address = await __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_resolveRequestAddress).call(this, resolutionSnapId, scope, request);
180
- const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => (0, utils_1.parseCaipAccountId)(connectedAddress).address);
181
- // If we have a resolved address, try to find the selected account based on that
182
- // otherwise, default to one of the connected accounts.
183
- // TODO: Eventually let the user choose if we have more than one option for the account.
184
- const selectedAccount = accounts.find((account) => parsedConnectedAddresses.includes(account.address) &&
185
- (!address || account.address === address));
186
- if (!selectedAccount) {
187
- throw rpc_errors_1.rpcErrors.invalidParams({
188
- message: 'No available account found for request.',
189
- });
190
- }
191
- return selectedAccount.id;
192
- }, _MultichainRouter_getProtocolSnaps = function _MultichainRouter_getProtocolSnaps(scope) {
193
- const allSnaps = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('SnapController:getAll');
194
- const filteredSnaps = (0, snaps_1.getRunnableSnaps)(allSnaps);
195
- return filteredSnaps.reduce((accumulator, snap) => {
196
- const permissions = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('PermissionController:getPermissions', snap.id);
197
- if (permissions && (0, utils_1.hasProperty)(permissions, snaps_rpc_methods_1.SnapEndowments.Protocol)) {
198
- const permission = permissions[snaps_rpc_methods_1.SnapEndowments.Protocol];
199
- const scopes = (0, snaps_rpc_methods_1.getProtocolCaveatScopes)(permission);
200
- if (scopes && (0, utils_1.hasProperty)(scopes, scope)) {
201
- accumulator.push({
202
- snapId: snap.id,
203
- methods: scopes[scope].methods,
204
- });
205
- }
206
- }
207
- return accumulator;
208
- }, []);
209
- }, _MultichainRouter_getSupportedAccountsMetadata = function _MultichainRouter_getSupportedAccountsMetadata(scope) {
210
- return __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
211
- .call('AccountsController:listMultichainAccounts', scope)
212
- .filter((account) => account.metadata.snap?.enabled);
213
- };
214
217
  //# sourceMappingURL=MultichainRouter.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainRouter.cjs","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,qDAAiD;AACjD,m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AM,MAAM,GAAG,IAAA,2CAAuB,EAAC,UAAU,CAAC,CAAC;YACnD,IAAI,MAAM,IAAI,IAAA,mBAAW,EAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC;gBACzC,WAAW,CAAC,IAAI,CAAC;oBACf,MAAM,EAAE,IAAI,CAAC,EAAE;oBACf,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO;iBAC/B,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC,2GA+F6B,KAAkB;IAC9C,OAAO,uBAAA,IAAI,mCAAW;SACnB,IAAI,CAAC,2CAA2C,EAAE,KAAK,CAAC;SACxD,MAAM,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import type { RestrictedMessenger } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n getProtocolCaveatScopes,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipChainId,\n JsonRpcParams,\n} from '@metamask/utils';\nimport {\n assert,\n hasProperty,\n KnownCaipNamespace,\n parseCaipAccountId,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport { getRunnableSnaps } from '../snaps';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\n\nexport type MultichainRouterHandleRequestAction = {\n type: `${typeof name}:handleRequest`;\n handler: MultichainRouter['handleRequest'];\n};\n\nexport type MultichainRouterGetSupportedMethodsAction = {\n type: `${typeof name}:getSupportedMethods`;\n handler: MultichainRouter['getSupportedMethods'];\n};\n\nexport type MultichainRouterGetSupportedAccountsAction = {\n type: `${typeof name}:getSupportedAccounts`;\n handler: MultichainRouter['getSupportedAccounts'];\n};\n\nexport type MultichainRouterIsSupportedScopeAction = {\n type: `${typeof name}:isSupportedScope`;\n handler: MultichainRouter['isSupportedScope'];\n};\n\ntype SnapKeyring = {\n submitRequest: (request: {\n origin: string;\n account: string;\n method: string;\n params?: Json[] | Record<string, Json>;\n scope: CaipChainId;\n }) => Promise<Json>;\n resolveAccountAddress: (\n snapId: SnapId,\n scope: CaipChainId,\n request: Json,\n ) => Promise<{ address: CaipAccountId } | null>;\n};\n\n// Expecting a bound function that calls KeyringController.withKeyring selecting the Snap keyring\ntype WithSnapKeyringFunction = <ReturnType>(\n operation: ({ keyring }: { keyring: SnapKeyring }) => Promise<ReturnType>,\n) => Promise<ReturnType>;\n\nexport type AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type MultichainRouterActions =\n | MultichainRouterHandleRequestAction\n | MultichainRouterGetSupportedMethodsAction\n | MultichainRouterGetSupportedAccountsAction\n | MultichainRouterIsSupportedScopeAction;\n\nexport type MultichainRouterAllowedActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\nexport type MultichainRouterEvents = never;\n\nexport type MultichainRouterMessenger = RestrictedMessenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions,\n never,\n MultichainRouterAllowedActions['type'],\n MultichainRouterEvents['type']\n>;\n\nexport type MultichainRouterArgs = {\n messenger: MultichainRouterMessenger;\n withSnapKeyring: WithSnapKeyringFunction;\n};\n\ntype ProtocolSnap = {\n snapId: SnapId;\n methods: string[];\n};\n\nconst name = 'MultichainRouter';\n\nexport class MultichainRouter {\n name: typeof name = name;\n\n state = null;\n\n readonly #messenger: MultichainRouterMessenger;\n\n readonly #withSnapKeyring: WithSnapKeyringFunction;\n\n constructor({ messenger, withSnapKeyring }: MultichainRouterArgs) {\n this.#messenger = messenger;\n this.#withSnapKeyring = withSnapKeyring;\n\n this.#messenger.registerActionHandler(\n `${name}:handleRequest`,\n async (...args) => this.handleRequest(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:getSupportedMethods`,\n (...args) => this.getSupportedMethods(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:getSupportedAccounts`,\n (...args) => this.getSupportedAccounts(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:isSupportedScope`,\n (...args) => this.isSupportedScope(...args),\n );\n }\n\n /**\n * Attempts to resolve the account address to use for a given request by inspecting the request itself.\n *\n * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.\n *\n * @param snapId - The ID of the Snap to send the request to.\n * @param scope - The CAIP-2 scope for the request.\n * @param request - The JSON-RPC request.\n * @returns The resolved address if found, otherwise null.\n * @throws If the invocation of the SnapKeyring fails.\n */\n async #resolveRequestAddress(\n snapId: SnapId,\n scope: CaipChainId,\n request: JsonRpcRequest,\n ) {\n try {\n const result = await this.#withSnapKeyring(async ({ keyring }) =>\n keyring.resolveAccountAddress(snapId, scope, request),\n );\n const address = result?.address;\n return address ? parseCaipAccountId(address).address : null;\n } catch {\n throw rpcErrors.internal();\n }\n }\n\n /**\n * Get the account ID of the account that should service the RPC request via an account Snap.\n *\n * This function checks whether any accounts exist that can service a given request by\n * using a combination of the resolveAccountAddress functionality and the connected accounts.\n *\n * If an account is expected to service this request but none is found, the function will throw.\n *\n * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.\n * @param scope - The CAIP-2 scope for the request.\n * @param request - The JSON-RPC request.\n * @returns An account ID if found, otherwise null.\n * @throws If no account is found, but the accounts exist that could service the request.\n */\n async #getSnapAccountId(\n connectedAddresses: CaipAccountId[],\n scope: CaipChainId,\n request: JsonRpcRequest,\n ) {\n const accounts = this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .filter(\n (\n account: InternalAccount,\n ): account is InternalAccount & {\n metadata: Required<InternalAccount['metadata']>;\n } =>\n Boolean(account.metadata.snap?.enabled) &&\n account.methods.includes(request.method),\n );\n\n // If no accounts can service the request, return null.\n if (accounts.length === 0) {\n return null;\n }\n\n const resolutionSnapId = accounts[0].metadata.snap.id;\n\n // Attempt to resolve the address that should be used for signing.\n const address = await this.#resolveRequestAddress(\n resolutionSnapId,\n scope,\n request,\n );\n\n const parsedConnectedAddresses = connectedAddresses.map(\n (connectedAddress) => parseCaipAccountId(connectedAddress).address,\n );\n\n // If we have a resolved address, try to find the selected account based on that\n // otherwise, default to one of the connected accounts.\n // TODO: Eventually let the user choose if we have more than one option for the account.\n const selectedAccount = accounts.find(\n (account) =>\n parsedConnectedAddresses.includes(account.address) &&\n (!address || account.address === address),\n );\n\n if (!selectedAccount) {\n throw rpcErrors.invalidParams({\n message: 'No available account found for request.',\n });\n }\n\n return selectedAccount.id;\n }\n\n /**\n * Get all protocol Snaps that can service a given CAIP-2 scope.\n *\n * Protocol Snaps are deemed fit to service a scope if they are runnable\n * and have the proper permissions set for the scope.\n *\n * @param scope - A CAIP-2 scope.\n * @returns A list of all the protocol Snaps available and their RPC methods.\n */\n #getProtocolSnaps(scope: CaipChainId) {\n const allSnaps = this.#messenger.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<ProtocolSnap[]>((accumulator, snap) => {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n if (permissions && hasProperty(permissions, SnapEndowments.Protocol)) {\n const permission = permissions[SnapEndowments.Protocol];\n const scopes = getProtocolCaveatScopes(permission);\n if (scopes && hasProperty(scopes, scope)) {\n accumulator.push({\n snapId: snap.id,\n methods: scopes[scope].methods,\n });\n }\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle an incoming JSON-RPC request tied to a specific scope by routing\n * to either a procotol Snap or an account Snap.\n *\n * Note: Addresses are considered case sensitive by the MultichainRouter as\n * not all non-EVM chains are case insensitive.\n *\n * @param options - An options bag.\n * @param options.connectedAddresses - Addresses currently connected to the origin.\n * @param options.origin - The origin of the RPC request.\n * @param options.request - The JSON-RPC request.\n * @param options.scope - The CAIP-2 scope for the request.\n * @returns The response from the chosen Snap.\n * @throws If no handler was found.\n */\n async handleRequest({\n connectedAddresses,\n origin,\n scope,\n request: rawRequest,\n }: {\n connectedAddresses: CaipAccountId[];\n origin: string;\n scope: CaipChainId;\n request: JsonRpcRequest;\n }): Promise<Json> {\n // Explicitly block EVM scopes, just in case.\n assert(\n !scope.startsWith(KnownCaipNamespace.Eip155) &&\n !scope.startsWith('wallet:eip155'),\n );\n\n // Re-create the request to simplify and remove additional properties that may be present in MM middleware.\n const request = {\n jsonrpc: '2.0' as const,\n id: rawRequest.id ?? nanoid(),\n method: rawRequest.method,\n ...(rawRequest.params ? { params: rawRequest.params } : {}),\n };\n\n const { method, params } = request;\n\n // If the RPC request can be serviced by an account Snap, route it there.\n const accountId = await this.#getSnapAccountId(\n connectedAddresses,\n scope,\n request,\n );\n\n if (accountId) {\n return this.#withSnapKeyring(async ({ keyring }) =>\n keyring.submitRequest({\n origin,\n account: accountId,\n scope,\n method,\n params: params as JsonRpcParams,\n }),\n );\n }\n\n // If the RPC request cannot be serviced by an account Snap,\n // but has a protocol Snap available, route it there.\n const protocolSnaps = this.#getProtocolSnaps(scope);\n const protocolSnap = protocolSnaps.find((snap) =>\n snap.methods.includes(method),\n );\n\n if (protocolSnap) {\n return this.#messenger.call('SnapController:handleRequest', {\n snapId: protocolSnap.snapId,\n origin,\n request: {\n method: '',\n params: {\n request,\n scope,\n },\n },\n handler: HandlerType.OnProtocolRequest,\n }) as Promise<Json>;\n }\n\n // If no compatible account or protocol Snaps were found, throw.\n throw rpcErrors.methodNotFound();\n }\n\n /**\n * Get a list of metadata for supported accounts for a given scope from the client.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of metadata for the supported accounts.\n */\n #getSupportedAccountsMetadata(scope: CaipChainId): InternalAccount[] {\n return this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .filter((account: InternalAccount) => account.metadata.snap?.enabled);\n }\n\n /**\n * Get a list of supported methods for a given scope.\n * This combines both protocol and account Snaps supported methods.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of supported methods.\n */\n getSupportedMethods(scope: CaipChainId): string[] {\n const accountMethods = this.#getSupportedAccountsMetadata(scope).flatMap(\n (account) => account.methods,\n );\n\n const protocolMethods = this.#getProtocolSnaps(scope).flatMap(\n (snap) => snap.methods,\n );\n\n return Array.from(new Set([...accountMethods, ...protocolMethods]));\n }\n\n /**\n * Get a list of supported accounts for a given scope.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of CAIP-10 addresses.\n */\n getSupportedAccounts(scope: CaipChainId): string[] {\n return this.#getSupportedAccountsMetadata(scope).map(\n (account) => `${scope}:${account.address}`,\n );\n }\n\n /**\n * Determine whether a given CAIP-2 scope is supported by the router.\n *\n * @param scope - The CAIP-2 scope.\n * @returns True if the router can service the scope, otherwise false.\n */\n isSupportedScope(scope: CaipChainId): boolean {\n const hasAccountSnap = this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .some((account: InternalAccount) => account.metadata.snap?.enabled);\n // We currently assume here that if one Snap exists that service the scope, we can service the scope generally.\n return hasAccountSnap || this.#getProtocolSnaps(scope).length > 0;\n }\n}\n"]}
1
+ {"version":3,"file":"MultichainRouter.cjs","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AACjD,mEAGqC;AAGrC,uDAAoD;AAMpD,2CAKyB;AACzB,mCAAgC;AAEhC,8CAA4C;AAgF5C,MAAM,IAAI,GAAG,kBAAkB,CAAC;AAEhC,MAAa,gBAAgB;IAC3B,IAAI,GAAgB,IAAI,CAAC;IAEzB,KAAK,GAAG,IAAI,CAAC;IAEJ,UAAU,CAA4B;IAEtC,gBAAgB,CAA0B;IAEnD,YAAY,EAAE,SAAS,EAA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C;aACxD,IAAI,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtE,+GAA+G;QAC/G,OAAO,cAAc,IAAI,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IACpE,CAAC;CACF;AAjTD,4CAiTC","sourcesContent":["import type { RestrictedMessenger } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n getProtocolCaveatScopes,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipChainId,\n JsonRpcParams,\n} from '@metamask/utils';\nimport {\n assert,\n hasProperty,\n KnownCaipNamespace,\n parseCaipAccountId,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport { getRunnableSnaps } from '../snaps';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\n\nexport type MultichainRouterHandleRequestAction = {\n type: `${typeof name}:handleRequest`;\n handler: MultichainRouter['handleRequest'];\n};\n\nexport type MultichainRouterGetSupportedMethodsAction = {\n type: `${typeof name}:getSupportedMethods`;\n handler: MultichainRouter['getSupportedMethods'];\n};\n\nexport type MultichainRouterGetSupportedAccountsAction = {\n type: `${typeof name}:getSupportedAccounts`;\n handler: MultichainRouter['getSupportedAccounts'];\n};\n\nexport type MultichainRouterIsSupportedScopeAction = {\n type: `${typeof name}:isSupportedScope`;\n handler: MultichainRouter['isSupportedScope'];\n};\n\ntype SnapKeyring = {\n submitRequest: (request: {\n origin: string;\n account: string;\n method: string;\n params?: Json[] | Record<string, Json>;\n scope: CaipChainId;\n }) => Promise<Json>;\n resolveAccountAddress: (\n snapId: SnapId,\n scope: CaipChainId,\n request: Json,\n ) => Promise<{ address: CaipAccountId } | null>;\n};\n\n// Expecting a bound function that calls KeyringController.withKeyring selecting the Snap keyring\ntype WithSnapKeyringFunction = <ReturnType>(\n operation: ({ keyring }: { keyring: SnapKeyring }) => Promise<ReturnType>,\n) => Promise<ReturnType>;\n\nexport type AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type MultichainRouterActions =\n | MultichainRouterHandleRequestAction\n | MultichainRouterGetSupportedMethodsAction\n | MultichainRouterGetSupportedAccountsAction\n | MultichainRouterIsSupportedScopeAction;\n\nexport type MultichainRouterAllowedActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\nexport type MultichainRouterEvents = never;\n\nexport type MultichainRouterMessenger = RestrictedMessenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions,\n never,\n MultichainRouterAllowedActions['type'],\n MultichainRouterEvents['type']\n>;\n\nexport type MultichainRouterArgs = {\n messenger: MultichainRouterMessenger;\n withSnapKeyring: WithSnapKeyringFunction;\n};\n\ntype ProtocolSnap = {\n snapId: SnapId;\n methods: string[];\n};\n\nconst name = 'MultichainRouter';\n\nexport class MultichainRouter {\n name: typeof name = name;\n\n state = null;\n\n readonly #messenger: MultichainRouterMessenger;\n\n readonly #withSnapKeyring: WithSnapKeyringFunction;\n\n constructor({ messenger, withSnapKeyring }: MultichainRouterArgs) {\n this.#messenger = messenger;\n this.#withSnapKeyring = withSnapKeyring;\n\n this.#messenger.registerActionHandler(\n `${name}:handleRequest`,\n async (...args) => this.handleRequest(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:getSupportedMethods`,\n (...args) => this.getSupportedMethods(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:getSupportedAccounts`,\n (...args) => this.getSupportedAccounts(...args),\n );\n\n this.#messenger.registerActionHandler(\n `${name}:isSupportedScope`,\n (...args) => this.isSupportedScope(...args),\n );\n }\n\n /**\n * Attempts to resolve the account address to use for a given request by inspecting the request itself.\n *\n * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.\n *\n * @param snapId - The ID of the Snap to send the request to.\n * @param scope - The CAIP-2 scope for the request.\n * @param request - The JSON-RPC request.\n * @returns The resolved address if found, otherwise null.\n * @throws If the invocation of the SnapKeyring fails.\n */\n async #resolveRequestAddress(\n snapId: SnapId,\n scope: CaipChainId,\n request: JsonRpcRequest,\n ) {\n try {\n const result = await this.#withSnapKeyring(async ({ keyring }) =>\n keyring.resolveAccountAddress(snapId, scope, request),\n );\n const address = result?.address;\n return address ? parseCaipAccountId(address).address : null;\n } catch {\n throw rpcErrors.internal();\n }\n }\n\n /**\n * Get the account ID of the account that should service the RPC request via an account Snap.\n *\n * This function checks whether any accounts exist that can service a given request by\n * using a combination of the resolveAccountAddress functionality and the connected accounts.\n *\n * If an account is expected to service this request but none is found, the function will throw.\n *\n * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.\n * @param scope - The CAIP-2 scope for the request.\n * @param request - The JSON-RPC request.\n * @returns An account ID if found, otherwise null.\n * @throws If no account is found, but the accounts exist that could service the request.\n */\n async #getSnapAccountId(\n connectedAddresses: CaipAccountId[],\n scope: CaipChainId,\n request: JsonRpcRequest,\n ) {\n const accounts = this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .filter(\n (\n account: InternalAccount,\n ): account is InternalAccount & {\n metadata: Required<InternalAccount['metadata']>;\n } =>\n Boolean(account.metadata.snap?.enabled) &&\n account.methods.includes(request.method),\n );\n\n // If no accounts can service the request, return null.\n if (accounts.length === 0) {\n return null;\n }\n\n const resolutionSnapId = accounts[0].metadata.snap.id;\n\n // Attempt to resolve the address that should be used for signing.\n const address = await this.#resolveRequestAddress(\n resolutionSnapId,\n scope,\n request,\n );\n\n const parsedConnectedAddresses = connectedAddresses.map(\n (connectedAddress) => parseCaipAccountId(connectedAddress).address,\n );\n\n // If we have a resolved address, try to find the selected account based on that\n // otherwise, default to one of the connected accounts.\n // TODO: Eventually let the user choose if we have more than one option for the account.\n const selectedAccount = accounts.find(\n (account) =>\n parsedConnectedAddresses.includes(account.address) &&\n (!address || account.address === address),\n );\n\n if (!selectedAccount) {\n throw rpcErrors.invalidParams({\n message: 'No available account found for request.',\n });\n }\n\n return selectedAccount.id;\n }\n\n /**\n * Get all protocol Snaps that can service a given CAIP-2 scope.\n *\n * Protocol Snaps are deemed fit to service a scope if they are runnable\n * and have the proper permissions set for the scope.\n *\n * @param scope - A CAIP-2 scope.\n * @returns A list of all the protocol Snaps available and their RPC methods.\n */\n #getProtocolSnaps(scope: CaipChainId) {\n const allSnaps = this.#messenger.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<ProtocolSnap[]>((accumulator, snap) => {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n if (permissions && hasProperty(permissions, SnapEndowments.Protocol)) {\n const permission = permissions[SnapEndowments.Protocol];\n const scopes = getProtocolCaveatScopes(permission);\n if (scopes && hasProperty(scopes, scope)) {\n accumulator.push({\n snapId: snap.id,\n methods: scopes[scope].methods,\n });\n }\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle an incoming JSON-RPC request tied to a specific scope by routing\n * to either a procotol Snap or an account Snap.\n *\n * Note: Addresses are considered case sensitive by the MultichainRouter as\n * not all non-EVM chains are case insensitive.\n *\n * @param options - An options bag.\n * @param options.connectedAddresses - Addresses currently connected to the origin.\n * @param options.origin - The origin of the RPC request.\n * @param options.request - The JSON-RPC request.\n * @param options.scope - The CAIP-2 scope for the request.\n * @returns The response from the chosen Snap.\n * @throws If no handler was found.\n */\n async handleRequest({\n connectedAddresses,\n origin,\n scope,\n request: rawRequest,\n }: {\n connectedAddresses: CaipAccountId[];\n origin: string;\n scope: CaipChainId;\n request: JsonRpcRequest;\n }): Promise<Json> {\n // Explicitly block EVM scopes, just in case.\n assert(\n !scope.startsWith(KnownCaipNamespace.Eip155) &&\n !scope.startsWith('wallet:eip155'),\n );\n\n // Re-create the request to simplify and remove additional properties that may be present in MM middleware.\n const request = {\n jsonrpc: '2.0' as const,\n id: rawRequest.id ?? nanoid(),\n method: rawRequest.method,\n ...(rawRequest.params ? { params: rawRequest.params } : {}),\n };\n\n const { method, params } = request;\n\n // If the RPC request can be serviced by an account Snap, route it there.\n const accountId = await this.#getSnapAccountId(\n connectedAddresses,\n scope,\n request,\n );\n\n if (accountId) {\n return this.#withSnapKeyring(async ({ keyring }) =>\n keyring.submitRequest({\n origin,\n account: accountId,\n scope,\n method,\n params: params as JsonRpcParams,\n }),\n );\n }\n\n // If the RPC request cannot be serviced by an account Snap,\n // but has a protocol Snap available, route it there.\n const protocolSnaps = this.#getProtocolSnaps(scope);\n const protocolSnap = protocolSnaps.find((snap) =>\n snap.methods.includes(method),\n );\n\n if (protocolSnap) {\n return this.#messenger.call('SnapController:handleRequest', {\n snapId: protocolSnap.snapId,\n origin,\n request: {\n method: '',\n params: {\n request,\n scope,\n },\n },\n handler: HandlerType.OnProtocolRequest,\n }) as Promise<Json>;\n }\n\n // If no compatible account or protocol Snaps were found, throw.\n throw rpcErrors.methodNotFound();\n }\n\n /**\n * Get a list of metadata for supported accounts for a given scope from the client.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of metadata for the supported accounts.\n */\n #getSupportedAccountsMetadata(scope: CaipChainId): InternalAccount[] {\n return this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .filter((account: InternalAccount) => account.metadata.snap?.enabled);\n }\n\n /**\n * Get a list of supported methods for a given scope.\n * This combines both protocol and account Snaps supported methods.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of supported methods.\n */\n getSupportedMethods(scope: CaipChainId): string[] {\n const accountMethods = this.#getSupportedAccountsMetadata(scope).flatMap(\n (account) => account.methods,\n );\n\n const protocolMethods = this.#getProtocolSnaps(scope).flatMap(\n (snap) => snap.methods,\n );\n\n return Array.from(new Set([...accountMethods, ...protocolMethods]));\n }\n\n /**\n * Get a list of supported accounts for a given scope.\n *\n * @param scope - The CAIP-2 scope.\n * @returns A list of CAIP-10 addresses.\n */\n getSupportedAccounts(scope: CaipChainId): string[] {\n return this.#getSupportedAccountsMetadata(scope).map(\n (account) => `${scope}:${account.address}`,\n );\n }\n\n /**\n * Determine whether a given CAIP-2 scope is supported by the router.\n *\n * @param scope - The CAIP-2 scope.\n * @returns True if the router can service the scope, otherwise false.\n */\n isSupportedScope(scope: CaipChainId): boolean {\n const hasAccountSnap = this.#messenger\n .call('AccountsController:listMultichainAccounts', scope)\n .some((account: InternalAccount) => account.metadata.snap?.enabled);\n // We currently assume here that if one Snap exists that service the scope, we can service the scope generally.\n return hasAccountSnap || this.#getProtocolSnaps(scope).length > 0;\n }\n}\n"]}