@metamask/snaps-controllers 12.3.0 → 13.0.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 (88) hide show
  1. package/CHANGELOG.md +32 -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/insights/SnapInsightsController.cjs +199 -149
  19. package/dist/insights/SnapInsightsController.cjs.map +1 -1
  20. package/dist/insights/SnapInsightsController.mjs +198 -148
  21. package/dist/insights/SnapInsightsController.mjs.map +1 -1
  22. package/dist/interface/SnapInterfaceController.cjs +160 -101
  23. package/dist/interface/SnapInterfaceController.cjs.map +1 -1
  24. package/dist/interface/SnapInterfaceController.mjs +160 -101
  25. package/dist/interface/SnapInterfaceController.mjs.map +1 -1
  26. package/dist/multichain/MultichainRouter.cjs +117 -114
  27. package/dist/multichain/MultichainRouter.cjs.map +1 -1
  28. package/dist/multichain/MultichainRouter.mjs +117 -114
  29. package/dist/multichain/MultichainRouter.mjs.map +1 -1
  30. package/dist/services/AbstractExecutionService.cjs +131 -139
  31. package/dist/services/AbstractExecutionService.cjs.map +1 -1
  32. package/dist/services/AbstractExecutionService.mjs +131 -139
  33. package/dist/services/AbstractExecutionService.mjs.map +1 -1
  34. package/dist/services/ProxyPostMessageStream.cjs +19 -26
  35. package/dist/services/ProxyPostMessageStream.cjs.map +1 -1
  36. package/dist/services/ProxyPostMessageStream.mjs +19 -26
  37. package/dist/services/ProxyPostMessageStream.mjs.map +1 -1
  38. package/dist/services/iframe/IframeExecutionService.cjs +1 -0
  39. package/dist/services/iframe/IframeExecutionService.cjs.map +1 -1
  40. package/dist/services/iframe/IframeExecutionService.mjs +1 -0
  41. package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
  42. package/dist/services/offscreen/OffscreenExecutionService.cjs +3 -16
  43. package/dist/services/offscreen/OffscreenExecutionService.cjs.map +1 -1
  44. package/dist/services/offscreen/OffscreenExecutionService.mjs +3 -16
  45. package/dist/services/offscreen/OffscreenExecutionService.mjs.map +1 -1
  46. package/dist/services/proxy/ProxyExecutionService.cjs +4 -17
  47. package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
  48. package/dist/services/proxy/ProxyExecutionService.mjs +4 -17
  49. package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
  50. package/dist/services/webview/WebViewExecutionService.cjs +6 -19
  51. package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
  52. package/dist/services/webview/WebViewExecutionService.mjs +6 -19
  53. package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
  54. package/dist/services/webview/WebViewMessageStream.cjs +13 -26
  55. package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
  56. package/dist/services/webview/WebViewMessageStream.mjs +13 -26
  57. package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
  58. package/dist/snaps/SnapController.cjs +1370 -1161
  59. package/dist/snaps/SnapController.cjs.map +1 -1
  60. package/dist/snaps/SnapController.d.cts +4 -4
  61. package/dist/snaps/SnapController.d.cts.map +1 -1
  62. package/dist/snaps/SnapController.d.mts +4 -4
  63. package/dist/snaps/SnapController.d.mts.map +1 -1
  64. package/dist/snaps/SnapController.mjs +1370 -1161
  65. package/dist/snaps/SnapController.mjs.map +1 -1
  66. package/dist/snaps/Timer.cjs +4 -0
  67. package/dist/snaps/Timer.cjs.map +1 -1
  68. package/dist/snaps/Timer.mjs +4 -0
  69. package/dist/snaps/Timer.mjs.map +1 -1
  70. package/dist/snaps/location/http.cjs +20 -4
  71. package/dist/snaps/location/http.cjs.map +1 -1
  72. package/dist/snaps/location/http.mjs +20 -4
  73. package/dist/snaps/location/http.mjs.map +1 -1
  74. package/dist/snaps/location/local.cjs +4 -17
  75. package/dist/snaps/location/local.cjs.map +1 -1
  76. package/dist/snaps/location/local.mjs +4 -17
  77. package/dist/snaps/location/local.mjs.map +1 -1
  78. package/dist/snaps/location/npm.cjs +28 -48
  79. package/dist/snaps/location/npm.cjs.map +1 -1
  80. package/dist/snaps/location/npm.d.cts.map +1 -1
  81. package/dist/snaps/location/npm.d.mts.map +1 -1
  82. package/dist/snaps/location/npm.mjs +28 -48
  83. package/dist/snaps/location/npm.mjs.map +1 -1
  84. package/dist/snaps/registry/json.cjs +173 -166
  85. package/dist/snaps/registry/json.cjs.map +1 -1
  86. package/dist/snaps/registry/json.mjs +172 -165
  87. package/dist/snaps/registry/json.mjs.map +1 -1
  88. package/package.json +9 -9
@@ -1,15 +1,3 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- 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");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- 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");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _MultichainRouter_instances, _MultichainRouter_messenger, _MultichainRouter_withSnapKeyring, _MultichainRouter_resolveRequestAddress, _MultichainRouter_getSnapAccountId, _MultichainRouter_getProtocolSnaps, _MultichainRouter_getSupportedAccountsMetadata;
13
1
  import { rpcErrors } from "@metamask/rpc-errors";
14
2
  import { getProtocolCaveatScopes, SnapEndowments } from "@metamask/snaps-rpc-methods";
15
3
  import { HandlerType } from "@metamask/snaps-utils";
@@ -18,18 +6,104 @@ import { nanoid } from "nanoid";
18
6
  import { getRunnableSnaps } from "../snaps/index.mjs";
19
7
  const name = 'MultichainRouter';
20
8
  export class MultichainRouter {
9
+ name = name;
10
+ state = null;
11
+ #messenger;
12
+ #withSnapKeyring;
21
13
  constructor({ messenger, withSnapKeyring }) {
22
- _MultichainRouter_instances.add(this);
23
- this.name = name;
24
- this.state = null;
25
- _MultichainRouter_messenger.set(this, void 0);
26
- _MultichainRouter_withSnapKeyring.set(this, void 0);
27
- __classPrivateFieldSet(this, _MultichainRouter_messenger, messenger, "f");
28
- __classPrivateFieldSet(this, _MultichainRouter_withSnapKeyring, withSnapKeyring, "f");
29
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:handleRequest`, async (...args) => this.handleRequest(...args));
30
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:getSupportedMethods`, (...args) => this.getSupportedMethods(...args));
31
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:getSupportedAccounts`, (...args) => this.getSupportedAccounts(...args));
32
- __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").registerActionHandler(`${name}:isSupportedScope`, (...args) => this.isSupportedScope(...args));
14
+ this.#messenger = messenger;
15
+ this.#withSnapKeyring = withSnapKeyring;
16
+ this.#messenger.registerActionHandler(`${name}:handleRequest`, async (...args) => this.handleRequest(...args));
17
+ this.#messenger.registerActionHandler(`${name}:getSupportedMethods`, (...args) => this.getSupportedMethods(...args));
18
+ this.#messenger.registerActionHandler(`${name}:getSupportedAccounts`, (...args) => this.getSupportedAccounts(...args));
19
+ this.#messenger.registerActionHandler(`${name}:isSupportedScope`, (...args) => this.isSupportedScope(...args));
20
+ }
21
+ /**
22
+ * Attempts to resolve the account address to use for a given request by inspecting the request itself.
23
+ *
24
+ * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.
25
+ *
26
+ * @param snapId - The ID of the Snap to send the request to.
27
+ * @param scope - The CAIP-2 scope for the request.
28
+ * @param request - The JSON-RPC request.
29
+ * @returns The resolved address if found, otherwise null.
30
+ * @throws If the invocation of the SnapKeyring fails.
31
+ */
32
+ async #resolveRequestAddress(snapId, scope, request) {
33
+ try {
34
+ const result = await this.#withSnapKeyring(async ({ keyring }) => keyring.resolveAccountAddress(snapId, scope, request));
35
+ const address = result?.address;
36
+ return address ? parseCaipAccountId(address).address : null;
37
+ }
38
+ catch {
39
+ throw rpcErrors.internal();
40
+ }
41
+ }
42
+ /**
43
+ * Get the account ID of the account that should service the RPC request via an account Snap.
44
+ *
45
+ * This function checks whether any accounts exist that can service a given request by
46
+ * using a combination of the resolveAccountAddress functionality and the connected accounts.
47
+ *
48
+ * If an account is expected to service this request but none is found, the function will throw.
49
+ *
50
+ * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.
51
+ * @param scope - The CAIP-2 scope for the request.
52
+ * @param request - The JSON-RPC request.
53
+ * @returns An account ID if found, otherwise null.
54
+ * @throws If no account is found, but the accounts exist that could service the request.
55
+ */
56
+ async #getSnapAccountId(connectedAddresses, scope, request) {
57
+ const accounts = this.#messenger
58
+ .call('AccountsController:listMultichainAccounts', scope)
59
+ .filter((account) => Boolean(account.metadata.snap?.enabled) &&
60
+ account.methods.includes(request.method));
61
+ // If no accounts can service the request, return null.
62
+ if (accounts.length === 0) {
63
+ return null;
64
+ }
65
+ const resolutionSnapId = accounts[0].metadata.snap.id;
66
+ // Attempt to resolve the address that should be used for signing.
67
+ const address = await this.#resolveRequestAddress(resolutionSnapId, scope, request);
68
+ const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => parseCaipAccountId(connectedAddress).address);
69
+ // If we have a resolved address, try to find the selected account based on that
70
+ // otherwise, default to one of the connected accounts.
71
+ // TODO: Eventually let the user choose if we have more than one option for the account.
72
+ const selectedAccount = accounts.find((account) => parsedConnectedAddresses.includes(account.address) &&
73
+ (!address || account.address === address));
74
+ if (!selectedAccount) {
75
+ throw rpcErrors.invalidParams({
76
+ message: 'No available account found for request.',
77
+ });
78
+ }
79
+ return selectedAccount.id;
80
+ }
81
+ /**
82
+ * Get all protocol Snaps that can service a given CAIP-2 scope.
83
+ *
84
+ * Protocol Snaps are deemed fit to service a scope if they are runnable
85
+ * and have the proper permissions set for the scope.
86
+ *
87
+ * @param scope - A CAIP-2 scope.
88
+ * @returns A list of all the protocol Snaps available and their RPC methods.
89
+ */
90
+ #getProtocolSnaps(scope) {
91
+ const allSnaps = this.#messenger.call('SnapController:getAll');
92
+ const filteredSnaps = getRunnableSnaps(allSnaps);
93
+ return filteredSnaps.reduce((accumulator, snap) => {
94
+ const permissions = this.#messenger.call('PermissionController:getPermissions', snap.id);
95
+ if (permissions && hasProperty(permissions, SnapEndowments.Protocol)) {
96
+ const permission = permissions[SnapEndowments.Protocol];
97
+ const scopes = getProtocolCaveatScopes(permission);
98
+ if (scopes && hasProperty(scopes, scope)) {
99
+ accumulator.push({
100
+ snapId: snap.id,
101
+ methods: scopes[scope].methods,
102
+ });
103
+ }
104
+ }
105
+ return accumulator;
106
+ }, []);
33
107
  }
34
108
  /**
35
109
  * Handle an incoming JSON-RPC request tied to a specific scope by routing
@@ -59,9 +133,9 @@ export class MultichainRouter {
59
133
  };
60
134
  const { method, params } = request;
61
135
  // If the RPC request can be serviced by an account Snap, route it there.
62
- const accountId = await __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSnapAccountId).call(this, connectedAddresses, scope, request);
136
+ const accountId = await this.#getSnapAccountId(connectedAddresses, scope, request);
63
137
  if (accountId) {
64
- return __classPrivateFieldGet(this, _MultichainRouter_withSnapKeyring, "f").call(this, async ({ keyring }) => keyring.submitRequest({
138
+ return this.#withSnapKeyring(async ({ keyring }) => keyring.submitRequest({
65
139
  origin,
66
140
  account: accountId,
67
141
  scope,
@@ -71,10 +145,10 @@ export class MultichainRouter {
71
145
  }
72
146
  // If the RPC request cannot be serviced by an account Snap,
73
147
  // but has a protocol Snap available, route it there.
74
- const protocolSnaps = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope);
148
+ const protocolSnaps = this.#getProtocolSnaps(scope);
75
149
  const protocolSnap = protocolSnaps.find((snap) => snap.methods.includes(method));
76
150
  if (protocolSnap) {
77
- return __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('SnapController:handleRequest', {
151
+ return this.#messenger.call('SnapController:handleRequest', {
78
152
  snapId: protocolSnap.snapId,
79
153
  origin,
80
154
  request: {
@@ -90,6 +164,17 @@ export class MultichainRouter {
90
164
  // If no compatible account or protocol Snaps were found, throw.
91
165
  throw rpcErrors.methodNotFound();
92
166
  }
167
+ /**
168
+ * Get a list of metadata for supported accounts for a given scope from the client.
169
+ *
170
+ * @param scope - The CAIP-2 scope.
171
+ * @returns A list of metadata for the supported accounts.
172
+ */
173
+ #getSupportedAccountsMetadata(scope) {
174
+ return this.#messenger
175
+ .call('AccountsController:listMultichainAccounts', scope)
176
+ .filter((account) => account.metadata.snap?.enabled);
177
+ }
93
178
  /**
94
179
  * Get a list of supported methods for a given scope.
95
180
  * This combines both protocol and account Snaps supported methods.
@@ -98,8 +183,8 @@ export class MultichainRouter {
98
183
  * @returns A list of supported methods.
99
184
  */
100
185
  getSupportedMethods(scope) {
101
- const accountMethods = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSupportedAccountsMetadata).call(this, scope).flatMap((account) => account.methods);
102
- const protocolMethods = __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope).flatMap((snap) => snap.methods);
186
+ const accountMethods = this.#getSupportedAccountsMetadata(scope).flatMap((account) => account.methods);
187
+ const protocolMethods = this.#getProtocolSnaps(scope).flatMap((snap) => snap.methods);
103
188
  return Array.from(new Set([...accountMethods, ...protocolMethods]));
104
189
  }
105
190
  /**
@@ -109,7 +194,7 @@ export class MultichainRouter {
109
194
  * @returns A list of CAIP-10 addresses.
110
195
  */
111
196
  getSupportedAccounts(scope) {
112
- return __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getSupportedAccountsMetadata).call(this, scope).map((account) => `${scope}:${account.address}`);
197
+ return this.#getSupportedAccountsMetadata(scope).map((account) => `${scope}:${account.address}`);
113
198
  }
114
199
  /**
115
200
  * Determine whether a given CAIP-2 scope is supported by the router.
@@ -118,93 +203,11 @@ export class MultichainRouter {
118
203
  * @returns True if the router can service the scope, otherwise false.
119
204
  */
120
205
  isSupportedScope(scope) {
121
- const hasAccountSnap = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
206
+ const hasAccountSnap = this.#messenger
122
207
  .call('AccountsController:listMultichainAccounts', scope)
123
208
  .some((account) => account.metadata.snap?.enabled);
124
209
  // We currently assume here that if one Snap exists that service the scope, we can service the scope generally.
125
- return hasAccountSnap || __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_getProtocolSnaps).call(this, scope).length > 0;
210
+ return hasAccountSnap || this.#getProtocolSnaps(scope).length > 0;
126
211
  }
127
212
  }
128
- _MultichainRouter_messenger = new WeakMap(), _MultichainRouter_withSnapKeyring = new WeakMap(), _MultichainRouter_instances = new WeakSet(), _MultichainRouter_resolveRequestAddress =
129
- /**
130
- * Attempts to resolve the account address to use for a given request by inspecting the request itself.
131
- *
132
- * The request is sent to to an account Snap via the SnapKeyring that will attempt this resolution.
133
- *
134
- * @param snapId - The ID of the Snap to send the request to.
135
- * @param scope - The CAIP-2 scope for the request.
136
- * @param request - The JSON-RPC request.
137
- * @returns The resolved address if found, otherwise null.
138
- * @throws If the invocation of the SnapKeyring fails.
139
- */
140
- async function _MultichainRouter_resolveRequestAddress(snapId, scope, request) {
141
- try {
142
- const result = await __classPrivateFieldGet(this, _MultichainRouter_withSnapKeyring, "f").call(this, async ({ keyring }) => keyring.resolveAccountAddress(snapId, scope, request));
143
- const address = result?.address;
144
- return address ? parseCaipAccountId(address).address : null;
145
- }
146
- catch {
147
- throw rpcErrors.internal();
148
- }
149
- }, _MultichainRouter_getSnapAccountId =
150
- /**
151
- * Get the account ID of the account that should service the RPC request via an account Snap.
152
- *
153
- * This function checks whether any accounts exist that can service a given request by
154
- * using a combination of the resolveAccountAddress functionality and the connected accounts.
155
- *
156
- * If an account is expected to service this request but none is found, the function will throw.
157
- *
158
- * @param connectedAddresses - The CAIP-10 addresses connected to the requesting origin.
159
- * @param scope - The CAIP-2 scope for the request.
160
- * @param request - The JSON-RPC request.
161
- * @returns An account ID if found, otherwise null.
162
- * @throws If no account is found, but the accounts exist that could service the request.
163
- */
164
- async function _MultichainRouter_getSnapAccountId(connectedAddresses, scope, request) {
165
- const accounts = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
166
- .call('AccountsController:listMultichainAccounts', scope)
167
- .filter((account) => Boolean(account.metadata.snap?.enabled) &&
168
- account.methods.includes(request.method));
169
- // If no accounts can service the request, return null.
170
- if (accounts.length === 0) {
171
- return null;
172
- }
173
- const resolutionSnapId = accounts[0].metadata.snap.id;
174
- // Attempt to resolve the address that should be used for signing.
175
- const address = await __classPrivateFieldGet(this, _MultichainRouter_instances, "m", _MultichainRouter_resolveRequestAddress).call(this, resolutionSnapId, scope, request);
176
- const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => parseCaipAccountId(connectedAddress).address);
177
- // If we have a resolved address, try to find the selected account based on that
178
- // otherwise, default to one of the connected accounts.
179
- // TODO: Eventually let the user choose if we have more than one option for the account.
180
- const selectedAccount = accounts.find((account) => parsedConnectedAddresses.includes(account.address) &&
181
- (!address || account.address === address));
182
- if (!selectedAccount) {
183
- throw rpcErrors.invalidParams({
184
- message: 'No available account found for request.',
185
- });
186
- }
187
- return selectedAccount.id;
188
- }, _MultichainRouter_getProtocolSnaps = function _MultichainRouter_getProtocolSnaps(scope) {
189
- const allSnaps = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('SnapController:getAll');
190
- const filteredSnaps = getRunnableSnaps(allSnaps);
191
- return filteredSnaps.reduce((accumulator, snap) => {
192
- const permissions = __classPrivateFieldGet(this, _MultichainRouter_messenger, "f").call('PermissionController:getPermissions', snap.id);
193
- if (permissions && hasProperty(permissions, SnapEndowments.Protocol)) {
194
- const permission = permissions[SnapEndowments.Protocol];
195
- const scopes = getProtocolCaveatScopes(permission);
196
- if (scopes && hasProperty(scopes, scope)) {
197
- accumulator.push({
198
- snapId: snap.id,
199
- methods: scopes[scope].methods,
200
- });
201
- }
202
- }
203
- return accumulator;
204
- }, []);
205
- }, _MultichainRouter_getSupportedAccountsMetadata = function _MultichainRouter_getSupportedAccountsMetadata(scope) {
206
- return __classPrivateFieldGet(this, _MultichainRouter_messenger, "f")
207
- .call('AccountsController:listMultichainAccounts', scope)
208
- .filter((account) => account.metadata.snap?.enabled);
209
- };
210
213
  //# sourceMappingURL=MultichainRouter.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainRouter.mjs","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACf,oCAAoC;AAGrC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAMpD,OAAO,EACL,MAAM,EACN,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EACnB,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,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E,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.mjs","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACf,oCAAoC;AAGrC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAMpD,OAAO,EACL,MAAM,EACN,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EACnB,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAgF5C,MAAM,IAAI,GAAG,kBAAkB,CAAC;AAEhC,MAAM,OAAO,gBAAgB;IAC3B,IAAI,GAAgB,IAAI,CAAC;IAEzB,KAAK,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I,CAAC,2CAA2C,EAAE,KAAK,CAAC;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","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"]}