@metamask/snaps-controllers 17.2.1 → 18.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.
- package/CHANGELOG.md +23 -1
- package/dist/multichain/MultichainRouter.cjs +33 -10
- package/dist/multichain/MultichainRouter.cjs.map +1 -1
- package/dist/multichain/MultichainRouter.d.cts +5 -7
- package/dist/multichain/MultichainRouter.d.cts.map +1 -1
- package/dist/multichain/MultichainRouter.d.mts +5 -7
- package/dist/multichain/MultichainRouter.d.mts.map +1 -1
- package/dist/multichain/MultichainRouter.mjs +34 -11
- package/dist/multichain/MultichainRouter.mjs.map +1 -1
- package/dist/services/AbstractExecutionService.cjs +1 -2
- package/dist/services/AbstractExecutionService.cjs.map +1 -1
- package/dist/services/AbstractExecutionService.d.cts.map +1 -1
- package/dist/services/AbstractExecutionService.d.mts.map +1 -1
- package/dist/services/AbstractExecutionService.mjs +1 -2
- package/dist/services/AbstractExecutionService.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +111 -26
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts +10 -17
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts +10 -17
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +111 -26
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/utils.d.cts +1 -0
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +1 -0
- package/dist/utils.d.mts.map +1 -1
- package/package.json +9 -8
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [18.0.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **BREAKING:** Use `StorageService` to store source code ([#3777](https://github.com/MetaMask/snaps/pull/3777))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- **BREAKING:** Remove `closeAllConnections` constructor argument ([#3814](https://github.com/MetaMask/snaps/pull/3814))
|
|
19
|
+
- Pass executor parameters by object ([#3803](https://github.com/MetaMask/snaps/pull/3803))
|
|
20
|
+
- Bump `lodash` from `4.17.21` to `4.17.23` ([#3821](https://github.com/MetaMask/snaps/pull/3821))
|
|
21
|
+
- Bump `tar` from `7.0.0` to `7.1.0` ([#3821](https://github.com/MetaMask/snaps/pull/3821))
|
|
22
|
+
- Bump `@metamask/json-rpc-engine` from `10.2.0` to `10.2.1` ([#3804](https://github.com/MetaMask/snaps/pull/3804))
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Disallow using unconnected accounts in `MultichainRouter` ([#3837](https://github.com/MetaMask/snaps/pull/3837))
|
|
27
|
+
- Update `SnapController` state when `SnapsRegistry` changes ([#3828](https://github.com/MetaMask/snaps/pull/3828))
|
|
28
|
+
- Update documentation for `MultichainRouter` ([#3827](https://github.com/MetaMask/snaps/pull/3827))
|
|
29
|
+
- Manually construct `keyring_resolveAccountAddress` request ([#3822](https://github.com/MetaMask/snaps/pull/3822))
|
|
30
|
+
|
|
10
31
|
## [17.2.1]
|
|
11
32
|
|
|
12
33
|
### Changed
|
|
@@ -1018,7 +1039,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
1018
1039
|
- The version of the package no longer needs to match the version of all other
|
|
1019
1040
|
MetaMask Snaps packages.
|
|
1020
1041
|
|
|
1021
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@
|
|
1042
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@18.0.0...HEAD
|
|
1043
|
+
[18.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@17.2.1...@metamask/snaps-controllers@18.0.0
|
|
1022
1044
|
[17.2.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@17.2.0...@metamask/snaps-controllers@17.2.1
|
|
1023
1045
|
[17.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@17.1.2...@metamask/snaps-controllers@17.2.0
|
|
1024
1046
|
[17.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@17.1.1...@metamask/snaps-controllers@17.1.2
|
|
@@ -24,7 +24,9 @@ class MultichainRouter {
|
|
|
24
24
|
/**
|
|
25
25
|
* Attempts to resolve the account address to use for a given request by inspecting the request itself.
|
|
26
26
|
*
|
|
27
|
-
* The request is sent to
|
|
27
|
+
* The request is sent to an account Snap that will attempt this resolution.
|
|
28
|
+
*
|
|
29
|
+
* We manually construct the request instead of using the SnapKeyring, as the keyring may not be available.
|
|
28
30
|
*
|
|
29
31
|
* @param snapId - The ID of the Snap to send the request to.
|
|
30
32
|
* @param scope - The CAIP-2 scope for the request.
|
|
@@ -34,7 +36,19 @@ class MultichainRouter {
|
|
|
34
36
|
*/
|
|
35
37
|
async #resolveRequestAddress(snapId, scope, request) {
|
|
36
38
|
try {
|
|
37
|
-
const result = await this.#
|
|
39
|
+
const result = await this.#messenger.call('SnapController:handleRequest', {
|
|
40
|
+
snapId,
|
|
41
|
+
origin: 'metamask',
|
|
42
|
+
request: {
|
|
43
|
+
method: 'keyring_resolveAccountAddress',
|
|
44
|
+
params: {
|
|
45
|
+
request,
|
|
46
|
+
scope,
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
handler: snaps_utils_1.HandlerType.OnKeyringRequest,
|
|
50
|
+
});
|
|
51
|
+
(0, utils_1.assert)(result === null || (0, utils_1.isObject)(result));
|
|
38
52
|
const address = result?.address;
|
|
39
53
|
return address ? (0, utils_1.parseCaipAccountId)(address).address : null;
|
|
40
54
|
}
|
|
@@ -50,7 +64,8 @@ class MultichainRouter {
|
|
|
50
64
|
*
|
|
51
65
|
* If an account is expected to service this request but none is found, the function will throw.
|
|
52
66
|
*
|
|
53
|
-
* @param connectedAddresses - The CAIP-10 addresses connected to the
|
|
67
|
+
* @param connectedAddresses - The CAIP-10 addresses connected to the
|
|
68
|
+
* requesting origin for the requested scope.
|
|
54
69
|
* @param scope - The CAIP-2 scope for the request.
|
|
55
70
|
* @param request - The JSON-RPC request.
|
|
56
71
|
* @returns An account ID if found, otherwise null.
|
|
@@ -65,15 +80,22 @@ class MultichainRouter {
|
|
|
65
80
|
if (accounts.length === 0) {
|
|
66
81
|
return null;
|
|
67
82
|
}
|
|
68
|
-
const
|
|
83
|
+
const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => (0, utils_1.parseCaipAccountId)(connectedAddress).address);
|
|
84
|
+
const connectedAccounts = accounts.filter((account) => parsedConnectedAddresses.includes(account.address));
|
|
85
|
+
if (connectedAccounts.length === 0) {
|
|
86
|
+
throw rpc_errors_1.rpcErrors.invalidParams({
|
|
87
|
+
message: 'No available account found for request.',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
const resolutionSnapId = connectedAccounts[0].metadata.snap.id;
|
|
69
91
|
// Attempt to resolve the address that should be used for signing.
|
|
70
92
|
const address = await this.#resolveRequestAddress(resolutionSnapId, scope, request);
|
|
71
|
-
const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => (0, utils_1.parseCaipAccountId)(connectedAddress).address);
|
|
72
93
|
// If we have a resolved address, try to find the selected account based on that
|
|
73
94
|
// otherwise, default to one of the connected accounts.
|
|
74
95
|
// TODO: Eventually let the user choose if we have more than one option for the account.
|
|
75
|
-
const selectedAccount =
|
|
76
|
-
(
|
|
96
|
+
const selectedAccount = address
|
|
97
|
+
? connectedAccounts.find((account) => account.address === address)
|
|
98
|
+
: connectedAccounts[0];
|
|
77
99
|
if (!selectedAccount) {
|
|
78
100
|
throw rpc_errors_1.rpcErrors.invalidParams({
|
|
79
101
|
message: 'No available account found for request.',
|
|
@@ -112,11 +134,12 @@ class MultichainRouter {
|
|
|
112
134
|
* Handle an incoming JSON-RPC request tied to a specific scope by routing
|
|
113
135
|
* to either a protocol Snap or an account Snap.
|
|
114
136
|
*
|
|
115
|
-
* Note: Addresses are considered case
|
|
116
|
-
* not all non-EVM chains are case
|
|
137
|
+
* Note: Addresses are considered case-sensitive by the MultichainRouter as
|
|
138
|
+
* not all non-EVM chains are case-insensitive.
|
|
117
139
|
*
|
|
118
140
|
* @param options - An options bag.
|
|
119
|
-
* @param options.connectedAddresses - Addresses currently connected to the
|
|
141
|
+
* @param options.connectedAddresses - Addresses currently connected to the
|
|
142
|
+
* origin for the requested scope.
|
|
120
143
|
* @param options.origin - The origin of the RPC request.
|
|
121
144
|
* @param options.request - The JSON-RPC request.
|
|
122
145
|
* @param options.scope - The CAIP-2 scope for the request.
|
|
@@ -1 +1 @@
|
|
|
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;AA6E5C,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,EAAE,eAAe,EAAwB;QAC9D,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;QAExC,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,gBAAgB,EACvB,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,CAC/C,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,sBAAsB,EAC7B,CAAC,GAAG,IAAI,EAA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E,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC1E,CAAC;IAED;;;;;;OAMG;IACH,mBAAmB,CAAC,KAAkB;QACpC,MAAM,cAAc,GAAG,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC,CAAC,OAAO,CACtE,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAC7B,CAAC;QAEF,MAAM,eAAe,GAAG,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,OAAO,CAC3D,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CACvB,CAAC;QAEF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,cAAc,EAAE,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;IACtE,CAAC;IAED;;;;;OAKG;IACH,oBAAoB,CAAC,KAAkB;QACrC,OAAO,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC,CAAC,GAAG,CAClD,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAC3C,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,gBAAgB,CAAC,KAAkB;QACjC,MAAM,cAAc,GAAG,IAAI,CAAC,UAAU;aACnC,IAAI,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;AAjTD,4CAiTC","sourcesContent":["import type { Messenger } from '@metamask/messenger';\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\nexport type 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 = Messenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions\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 protocol 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,2CAMyB;AACzB,mCAAgC;AAEhC,8CAA4C;AAwE5C,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,EAAE,eAAe,EAAwB;QAC9D,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;QAExC,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,gBAAgB,EACvB,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,CAC/C,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,sBAAsB,EAC7B,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,IAAI,CAAC,CAC/C,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,uBAAuB,EAC9B,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,IAAI,CAAC,CAChD,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI,mBAAmB,EAC1B,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,IAAI,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ask/messenger';\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 isObject,\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};\n\n// Expecting a bound function that calls KeyringController.withKeyring selecting the Snap keyring\nexport type 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 = Messenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions\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 an account Snap that will attempt this resolution.\n *\n * We manually construct the request instead of using the SnapKeyring, as the keyring may not be available.\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.#messenger.call(\n 'SnapController:handleRequest',\n {\n snapId,\n origin: 'metamask',\n request: {\n method: 'keyring_resolveAccountAddress',\n params: {\n request,\n scope,\n },\n },\n handler: HandlerType.OnKeyringRequest,\n },\n );\n\n assert(result === null || isObject(result));\n\n const address = result?.address as CaipAccountId;\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\n * requesting origin for the requested scope.\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 parsedConnectedAddresses = connectedAddresses.map(\n (connectedAddress) => parseCaipAccountId(connectedAddress).address,\n );\n\n const connectedAccounts = accounts.filter((account) =>\n parsedConnectedAddresses.includes(account.address),\n );\n\n if (connectedAccounts.length === 0) {\n throw rpcErrors.invalidParams({\n message: 'No available account found for request.',\n });\n }\n\n const resolutionSnapId = connectedAccounts[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 // 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 = address\n ? connectedAccounts.find((account) => account.address === address)\n : connectedAccounts[0];\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 protocol 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\n * origin for the requested scope.\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,6 +1,6 @@
|
|
|
1
1
|
import type { Messenger } from "@metamask/messenger";
|
|
2
2
|
import type { GetPermissions } from "@metamask/permission-controller";
|
|
3
|
-
import type { Json, JsonRpcRequest
|
|
3
|
+
import type { Json, JsonRpcRequest } from "@metamask/snaps-sdk";
|
|
4
4
|
import type { InternalAccount } from "@metamask/snaps-utils";
|
|
5
5
|
import type { CaipAccountId, CaipChainId } from "@metamask/utils";
|
|
6
6
|
import type { GetAllSnaps, HandleSnapRequest } from "../snaps/index.cjs";
|
|
@@ -28,9 +28,6 @@ type SnapKeyring = {
|
|
|
28
28
|
params?: Json[] | Record<string, Json>;
|
|
29
29
|
scope: CaipChainId;
|
|
30
30
|
}) => Promise<Json>;
|
|
31
|
-
resolveAccountAddress: (snapId: SnapId, scope: CaipChainId, request: Json) => Promise<{
|
|
32
|
-
address: CaipAccountId;
|
|
33
|
-
} | null>;
|
|
34
31
|
};
|
|
35
32
|
export type WithSnapKeyringFunction = <ReturnType>(operation: ({ keyring }: {
|
|
36
33
|
keyring: SnapKeyring;
|
|
@@ -57,11 +54,12 @@ export declare class MultichainRouter {
|
|
|
57
54
|
* Handle an incoming JSON-RPC request tied to a specific scope by routing
|
|
58
55
|
* to either a protocol Snap or an account Snap.
|
|
59
56
|
*
|
|
60
|
-
* Note: Addresses are considered case
|
|
61
|
-
* not all non-EVM chains are case
|
|
57
|
+
* Note: Addresses are considered case-sensitive by the MultichainRouter as
|
|
58
|
+
* not all non-EVM chains are case-insensitive.
|
|
62
59
|
*
|
|
63
60
|
* @param options - An options bag.
|
|
64
|
-
* @param options.connectedAddresses - Addresses currently connected to the
|
|
61
|
+
* @param options.connectedAddresses - Addresses currently connected to the
|
|
62
|
+
* origin for the requested scope.
|
|
65
63
|
* @param options.origin - The origin of the RPC request.
|
|
66
64
|
* @param options.request - The JSON-RPC request.
|
|
67
65
|
* @param options.scope - The CAIP-2 scope for the request.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainRouter.d.cts","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,wCAAwC;AAMtE,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,
|
|
1
|
+
{"version":3,"file":"MultichainRouter.d.cts","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,wCAAwC;AAMtE,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAU,4BAA4B;AACxE,OAAO,KAAK,EAAE,eAAe,EAAE,8BAA8B;AAE7D,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EAEZ,wBAAwB;AAWzB,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,2BAAiB;AAE/D,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,GAAG,OAAO,IAAI,gBAAgB,CAAC;IACrC,OAAO,EAAE,gBAAgB,CAAC,eAAe,CAAC,CAAC;CAC5C,CAAC;AAEF,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,GAAG,OAAO,IAAI,sBAAsB,CAAC;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,GAAG,KAAK,CAAC;AAE3C,MAAM,MAAM,yBAAyB,GAAG,SAAS,CAC/C,OAAO,IAAI,EACX,uBAAuB,GAAG,8BAA8B,CACzD,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,SAAS,EAAE,yBAAyB,CAAC;IACrC,eAAe,EAAE,uBAAuB,CAAC;CAC1C,CAAC;AAOF,QAAA,MAAM,IAAI,qBAAqB,CAAC;AAEhC,qBAAa,gBAAgB;;IAC3B,IAAI,EAAE,OAAO,IAAI,CAAQ;IAEzB,KAAK,OAAQ;gBAMD,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,oBAAoB;IAmLhE;;;;;;;;;;;;;;;OAeG;IACG,aAAa,CAAC,EAClB,kBAAkB,EAClB,MAAM,EACN,KAAK,EACL,OAAO,EAAE,UAAU,GACpB,EAAE;QACD,kBAAkB,EAAE,aAAa,EAAE,CAAC;QACpC,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,WAAW,CAAC;QACnB,OAAO,EAAE,cAAc,CAAC;KACzB,GAAG,OAAO,CAAC,IAAI,CAAC;IA0EjB;;;;;;OAMG;IACH,mBAAmB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,EAAE;IAYjD;;;;;OAKG;IACH,oBAAoB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,EAAE;IAMlD;;;;;OAKG;IACH,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO;CAO9C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Messenger } from "@metamask/messenger";
|
|
2
2
|
import type { GetPermissions } from "@metamask/permission-controller";
|
|
3
|
-
import type { Json, JsonRpcRequest
|
|
3
|
+
import type { Json, JsonRpcRequest } from "@metamask/snaps-sdk";
|
|
4
4
|
import type { InternalAccount } from "@metamask/snaps-utils";
|
|
5
5
|
import type { CaipAccountId, CaipChainId } from "@metamask/utils";
|
|
6
6
|
import type { GetAllSnaps, HandleSnapRequest } from "../snaps/index.mjs";
|
|
@@ -28,9 +28,6 @@ type SnapKeyring = {
|
|
|
28
28
|
params?: Json[] | Record<string, Json>;
|
|
29
29
|
scope: CaipChainId;
|
|
30
30
|
}) => Promise<Json>;
|
|
31
|
-
resolveAccountAddress: (snapId: SnapId, scope: CaipChainId, request: Json) => Promise<{
|
|
32
|
-
address: CaipAccountId;
|
|
33
|
-
} | null>;
|
|
34
31
|
};
|
|
35
32
|
export type WithSnapKeyringFunction = <ReturnType>(operation: ({ keyring }: {
|
|
36
33
|
keyring: SnapKeyring;
|
|
@@ -57,11 +54,12 @@ export declare class MultichainRouter {
|
|
|
57
54
|
* Handle an incoming JSON-RPC request tied to a specific scope by routing
|
|
58
55
|
* to either a protocol Snap or an account Snap.
|
|
59
56
|
*
|
|
60
|
-
* Note: Addresses are considered case
|
|
61
|
-
* not all non-EVM chains are case
|
|
57
|
+
* Note: Addresses are considered case-sensitive by the MultichainRouter as
|
|
58
|
+
* not all non-EVM chains are case-insensitive.
|
|
62
59
|
*
|
|
63
60
|
* @param options - An options bag.
|
|
64
|
-
* @param options.connectedAddresses - Addresses currently connected to the
|
|
61
|
+
* @param options.connectedAddresses - Addresses currently connected to the
|
|
62
|
+
* origin for the requested scope.
|
|
65
63
|
* @param options.origin - The origin of the RPC request.
|
|
66
64
|
* @param options.request - The JSON-RPC request.
|
|
67
65
|
* @param options.scope - The CAIP-2 scope for the request.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainRouter.d.mts","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,wCAAwC;AAMtE,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,
|
|
1
|
+
{"version":3,"file":"MultichainRouter.d.mts","sourceRoot":"","sources":["../../src/multichain/MultichainRouter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SA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AAC,KAAK,EAAE,WAAW,GAAG,MAAM,EAAE;IAYjD;;;;;OAKG;IACH,oBAAoB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,EAAE;IAMlD;;;;;OAKG;IACH,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO;CAO9C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { rpcErrors } from "@metamask/rpc-errors";
|
|
2
2
|
import { getProtocolCaveatScopes, SnapEndowments } from "@metamask/snaps-rpc-methods";
|
|
3
3
|
import { HandlerType } from "@metamask/snaps-utils";
|
|
4
|
-
import { assert, hasProperty, KnownCaipNamespace, parseCaipAccountId } from "@metamask/utils";
|
|
4
|
+
import { assert, hasProperty, isObject, KnownCaipNamespace, parseCaipAccountId } from "@metamask/utils";
|
|
5
5
|
import { nanoid } from "nanoid";
|
|
6
6
|
import { getRunnableSnaps } from "../snaps/index.mjs";
|
|
7
7
|
const name = 'MultichainRouter';
|
|
@@ -21,7 +21,9 @@ export class MultichainRouter {
|
|
|
21
21
|
/**
|
|
22
22
|
* Attempts to resolve the account address to use for a given request by inspecting the request itself.
|
|
23
23
|
*
|
|
24
|
-
* The request is sent to
|
|
24
|
+
* The request is sent to an account Snap that will attempt this resolution.
|
|
25
|
+
*
|
|
26
|
+
* We manually construct the request instead of using the SnapKeyring, as the keyring may not be available.
|
|
25
27
|
*
|
|
26
28
|
* @param snapId - The ID of the Snap to send the request to.
|
|
27
29
|
* @param scope - The CAIP-2 scope for the request.
|
|
@@ -31,7 +33,19 @@ export class MultichainRouter {
|
|
|
31
33
|
*/
|
|
32
34
|
async #resolveRequestAddress(snapId, scope, request) {
|
|
33
35
|
try {
|
|
34
|
-
const result = await this.#
|
|
36
|
+
const result = await this.#messenger.call('SnapController:handleRequest', {
|
|
37
|
+
snapId,
|
|
38
|
+
origin: 'metamask',
|
|
39
|
+
request: {
|
|
40
|
+
method: 'keyring_resolveAccountAddress',
|
|
41
|
+
params: {
|
|
42
|
+
request,
|
|
43
|
+
scope,
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
handler: HandlerType.OnKeyringRequest,
|
|
47
|
+
});
|
|
48
|
+
assert(result === null || isObject(result));
|
|
35
49
|
const address = result?.address;
|
|
36
50
|
return address ? parseCaipAccountId(address).address : null;
|
|
37
51
|
}
|
|
@@ -47,7 +61,8 @@ export class MultichainRouter {
|
|
|
47
61
|
*
|
|
48
62
|
* If an account is expected to service this request but none is found, the function will throw.
|
|
49
63
|
*
|
|
50
|
-
* @param connectedAddresses - The CAIP-10 addresses connected to the
|
|
64
|
+
* @param connectedAddresses - The CAIP-10 addresses connected to the
|
|
65
|
+
* requesting origin for the requested scope.
|
|
51
66
|
* @param scope - The CAIP-2 scope for the request.
|
|
52
67
|
* @param request - The JSON-RPC request.
|
|
53
68
|
* @returns An account ID if found, otherwise null.
|
|
@@ -62,15 +77,22 @@ export class MultichainRouter {
|
|
|
62
77
|
if (accounts.length === 0) {
|
|
63
78
|
return null;
|
|
64
79
|
}
|
|
65
|
-
const
|
|
80
|
+
const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => parseCaipAccountId(connectedAddress).address);
|
|
81
|
+
const connectedAccounts = accounts.filter((account) => parsedConnectedAddresses.includes(account.address));
|
|
82
|
+
if (connectedAccounts.length === 0) {
|
|
83
|
+
throw rpcErrors.invalidParams({
|
|
84
|
+
message: 'No available account found for request.',
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const resolutionSnapId = connectedAccounts[0].metadata.snap.id;
|
|
66
88
|
// Attempt to resolve the address that should be used for signing.
|
|
67
89
|
const address = await this.#resolveRequestAddress(resolutionSnapId, scope, request);
|
|
68
|
-
const parsedConnectedAddresses = connectedAddresses.map((connectedAddress) => parseCaipAccountId(connectedAddress).address);
|
|
69
90
|
// If we have a resolved address, try to find the selected account based on that
|
|
70
91
|
// otherwise, default to one of the connected accounts.
|
|
71
92
|
// TODO: Eventually let the user choose if we have more than one option for the account.
|
|
72
|
-
const selectedAccount =
|
|
73
|
-
(
|
|
93
|
+
const selectedAccount = address
|
|
94
|
+
? connectedAccounts.find((account) => account.address === address)
|
|
95
|
+
: connectedAccounts[0];
|
|
74
96
|
if (!selectedAccount) {
|
|
75
97
|
throw rpcErrors.invalidParams({
|
|
76
98
|
message: 'No available account found for request.',
|
|
@@ -109,11 +131,12 @@ export class MultichainRouter {
|
|
|
109
131
|
* Handle an incoming JSON-RPC request tied to a specific scope by routing
|
|
110
132
|
* to either a protocol Snap or an account Snap.
|
|
111
133
|
*
|
|
112
|
-
* Note: Addresses are considered case
|
|
113
|
-
* not all non-EVM chains are case
|
|
134
|
+
* Note: Addresses are considered case-sensitive by the MultichainRouter as
|
|
135
|
+
* not all non-EVM chains are case-insensitive.
|
|
114
136
|
*
|
|
115
137
|
* @param options - An options bag.
|
|
116
|
-
* @param options.connectedAddresses - Addresses currently connected to the
|
|
138
|
+
* @param options.connectedAddresses - Addresses currently connected to the
|
|
139
|
+
* origin for the requested scope.
|
|
117
140
|
* @param options.origin - The origin of the RPC request.
|
|
118
141
|
* @param options.request - The JSON-RPC request.
|
|
119
142
|
* @param options.scope - The CAIP-2 scope for the request.
|
|
@@ -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,EAAE,gBAAgB,EAAE,2BAAiB;AA6E5C,MAAM,IAAI,GAAG,kBAAkB,CAAC;AAEhC,MAAM,OAAO,gBAAgB;IAC3B,IAAI,GAAgB,IAAI,CAAC;IAEzB,KAAK,GA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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 { Messenger } from '@metamask/messenger';\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\nexport type 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 = Messenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions\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 protocol 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,QAAQ,EACR,kBAAkB,EAClB,kBAAkB,EACnB,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAwE5C,MAAM,IAAI,GAAG,kBAAkB,CAAC;AAEhC,MAAM,OAAO,gBAAgB;IAC3B,IAAI,GAAgB,IAAI,CAAC;IAEzB,KAAK,GAAG,IAAI,CAAC;IAEJ,UAAU,CAA4B;IAEtC,gBAAgB,CAA0B;IAEnD,YAAY,EAAE,SAAS,EAAE,eAAe,EAAwB;QAC9D,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;QAExC,IAAI,CAAC,UAAU,CAAC,qBAAqB,CACnC,GAAG,IAAI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C,CAAC,GAAG,CAClD,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAC3C,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,gBAAgB,CAAC,KAAkB;QACjC,MAAM,cAAc,GAAG,IAAI,CAAC,UAAU;aACnC,IAAI,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 { Messenger } from '@metamask/messenger';\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 isObject,\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};\n\n// Expecting a bound function that calls KeyringController.withKeyring selecting the Snap keyring\nexport type 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 = Messenger<\n typeof name,\n MultichainRouterActions | MultichainRouterAllowedActions\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 an account Snap that will attempt this resolution.\n *\n * We manually construct the request instead of using the SnapKeyring, as the keyring may not be available.\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.#messenger.call(\n 'SnapController:handleRequest',\n {\n snapId,\n origin: 'metamask',\n request: {\n method: 'keyring_resolveAccountAddress',\n params: {\n request,\n scope,\n },\n },\n handler: HandlerType.OnKeyringRequest,\n },\n );\n\n assert(result === null || isObject(result));\n\n const address = result?.address as CaipAccountId;\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\n * requesting origin for the requested scope.\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 parsedConnectedAddresses = connectedAddresses.map(\n (connectedAddress) => parseCaipAccountId(connectedAddress).address,\n );\n\n const connectedAccounts = accounts.filter((account) =>\n parsedConnectedAddresses.includes(account.address),\n );\n\n if (connectedAccounts.length === 0) {\n throw rpcErrors.invalidParams({\n message: 'No available account found for request.',\n });\n }\n\n const resolutionSnapId = connectedAccounts[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 // 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 = address\n ? connectedAccounts.find((account) => account.address === address)\n : connectedAccounts[0];\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 protocol 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\n * origin for the requested scope.\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"]}
|
|
@@ -65,7 +65,6 @@ class AbstractExecutionService {
|
|
|
65
65
|
const result = await (0, utils_2.withTimeout)(this.#command(snapId, {
|
|
66
66
|
jsonrpc: '2.0',
|
|
67
67
|
method: 'terminate',
|
|
68
|
-
params: [],
|
|
69
68
|
id: (0, nanoid_1.nanoid)(),
|
|
70
69
|
}), this.#terminationTimeout);
|
|
71
70
|
if (result === utils_2.hasTimedOut || result !== 'OK') {
|
|
@@ -282,10 +281,10 @@ class AbstractExecutionService {
|
|
|
282
281
|
jsonrpc: '2.0',
|
|
283
282
|
method: 'snapRpc',
|
|
284
283
|
params: {
|
|
284
|
+
snapId,
|
|
285
285
|
origin,
|
|
286
286
|
handler,
|
|
287
287
|
request: request,
|
|
288
|
-
target: snapId,
|
|
289
288
|
},
|
|
290
289
|
});
|
|
291
290
|
}
|