diff --git a/packages/examples/packages/multichain-provider/.depcheckrc.json b/packages/examples/packages/multichain-provider/.depcheckrc.json new file mode 100644 index 0000000000..c437c59cd2 --- /dev/null +++ b/packages/examples/packages/multichain-provider/.depcheckrc.json @@ -0,0 +1,18 @@ +{ + "ignore-patterns": ["dist", "coverage"], + "ignores": [ + "@lavamoat/allow-scripts", + "@lavamoat/preinstall-always-fail", + "@metamask/auto-changelog", + "@metamask/eslint-*", + "@types/*", + "@typescript-eslint/*", + "eslint-config-*", + "eslint-plugin-*", + "jest-silent-reporter", + "prettier-plugin-packagejson", + "ts-node", + "typedoc", + "typescript" + ] +} diff --git a/packages/examples/packages/multichain-provider/CHANGELOG.md b/packages/examples/packages/multichain-provider/CHANGELOG.md new file mode 100644 index 0000000000..720e00537e --- /dev/null +++ b/packages/examples/packages/multichain-provider/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +[Unreleased]: https://github.com/MetaMask/snaps/ diff --git a/packages/examples/packages/multichain-provider/LICENSE.APACHE2 b/packages/examples/packages/multichain-provider/LICENSE.APACHE2 new file mode 100644 index 0000000000..bf37d0e612 --- /dev/null +++ b/packages/examples/packages/multichain-provider/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 ConsenSys Software Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/examples/packages/multichain-provider/LICENSE.MIT0 b/packages/examples/packages/multichain-provider/LICENSE.MIT0 new file mode 100644 index 0000000000..913c577462 --- /dev/null +++ b/packages/examples/packages/multichain-provider/LICENSE.MIT0 @@ -0,0 +1,16 @@ +MIT No Attribution + +Copyright 2023 ConsenSys Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/examples/packages/multichain-provider/README.md b/packages/examples/packages/multichain-provider/README.md new file mode 100644 index 0000000000..1e8220acf2 --- /dev/null +++ b/packages/examples/packages/multichain-provider/README.md @@ -0,0 +1,40 @@ +# `@metamask/ethereum-provider-example-snap` + +This snap demonstrates the use of the `endowment:ethereum-provider` permission +and the corresponding `ethereum` global. This is similar to the +`window.ethereum` API, but it does not have access to all methods. + +## Snap manifest + +> **Note**: Using `ethereum` requires the `endowment:ethereum-provider` +> permissions. Refer to [the documentation](https://docs.metamask.io/snaps/reference/permissions/#endowmentethereum-provider) +> for more information. + +Along with other permissions, the manifest of this snap includes the +`endowment:ethereum-provider` permission: + +```json +{ + "initialPermissions": { + "endowment:ethereum-provider": {} + } +} +``` + +This permission does not require any additional configuration. + +## Snap usage + +This snap exposes an `onRpcRequest` handler, which supports the following +JSON-RPC methods: + +- `getGasPrice`: Get the current recommended gas price from an Ethereum + provider. +- `getVersion`: Get the Ethereum network version from an Ethereum provider. +- `getAccounts`: Get the Ethereum accounts made available to the snap from an + Ethereum provider. +- `personalSign`: Sign a message using an Ethereum account made available to the Snap. +- `signTypedData`: Sign a struct using an Ethereum account made available to the Snap. + +For more information, you can refer to +[the end-to-end tests](./src/index.test.ts). diff --git a/packages/examples/packages/multichain-provider/jest.config.js b/packages/examples/packages/multichain-provider/jest.config.js new file mode 100644 index 0000000000..f473a91b83 --- /dev/null +++ b/packages/examples/packages/multichain-provider/jest.config.js @@ -0,0 +1,36 @@ +const deepmerge = require('deepmerge'); + +const baseConfig = require('../../../../jest.config.base'); + +module.exports = deepmerge(baseConfig, { + preset: '@metamask/snaps-jest', + + // Since `@metamask/snaps-jest` runs in the browser, we can't collect + // coverage information. + collectCoverage: false, + + // This is required for the tests to run inside the `MetaMask/snaps` + // repository. You don't need this in your own project. + moduleNameMapper: { + '^@metamask/(.+)/production/jsx-runtime': [ + '/../../../$1/src/jsx/production/jsx-runtime', + '/../../../../node_modules/@metamask/$1/jsx/production/jsx-runtime', + '/node_modules/@metamask/$1/jsx/production/jsx-runtime', + ], + '^@metamask/(.+)/jsx': [ + '/../../../$1/src/jsx', + '/../../../../node_modules/@metamask/$1/jsx', + '/node_modules/@metamask/$1/jsx', + ], + '^@metamask/(.+)/node$': [ + '/../../../$1/src/node', + '/../../../../node_modules/@metamask/$1/node', + '/node_modules/@metamask/$1/node', + ], + '^@metamask/(.+)$': [ + '/../../../$1/src', + '/../../../../node_modules/@metamask/$1', + '/node_modules/@metamask/$1', + ], + }, +}); diff --git a/packages/examples/packages/multichain-provider/package.json b/packages/examples/packages/multichain-provider/package.json new file mode 100644 index 0000000000..55fe69d296 --- /dev/null +++ b/packages/examples/packages/multichain-provider/package.json @@ -0,0 +1,74 @@ +{ + "name": "@metamask/multichain-provider-example-snap", + "version": "0.0.0", + "description": "MetaMask example snap demonstrating the use of the Multichain Provider API and `endowment:multichain-provider` permission", + "keywords": [ + "MetaMask", + "Snaps", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/snaps/tree/main/packages/examples/packages/multichain-provider#readme", + "bugs": { + "url": "https://github.com/MetaMask/snaps/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "license": "(MIT-0 OR Apache-2.0)", + "sideEffects": false, + "main": "./dist/bundle.js", + "files": [ + "dist", + "snap.manifest.json" + ], + "scripts": { + "build": "mm-snap build", + "build:clean": "yarn clean && yarn build", + "changelog:update": "../../../../scripts/update-changelog.sh @metamask/multichain-provider-example-snap", + "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/multichain-provider-example-snap", + "clean": "rimraf \"dist\"", + "lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies", + "lint:ci": "yarn lint", + "lint:dependencies": "depcheck", + "lint:eslint": "eslint . --cache", + "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", + "lint:misc": "prettier --no-error-on-unmatched-pattern --log-level warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" \"!snap.manifest.json\" --ignore-path ../../../../.gitignore", + "publish:preview": "yarn npm publish --tag preview", + "since-latest-release": "../../../../scripts/since-latest-release.sh", + "start": "mm-snap watch", + "test": "jest --reporters=jest-silent-reporter", + "test:clean": "jest --clearCache", + "test:verbose": "jest --verbose", + "test:watch": "jest --watch" + }, + "dependencies": { + "@metamask/snaps-sdk": "workspace:^", + "@metamask/utils": "^11.9.0" + }, + "devDependencies": { + "@jest/globals": "^29.5.0", + "@lavamoat/allow-scripts": "^3.4.1", + "@metamask/auto-changelog": "^5.0.2", + "@metamask/snaps-cli": "workspace:^", + "@metamask/snaps-jest": "workspace:^", + "@swc/core": "1.11.31", + "@swc/jest": "^0.2.38", + "@types/node": "18.14.2", + "deepmerge": "^4.2.2", + "depcheck": "^1.4.7", + "eslint": "^9.11.0", + "jest": "^29.0.2", + "jest-silent-reporter": "^0.6.0", + "prettier": "^3.3.3", + "ts-node": "^10.9.1", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^20 || >=22" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/examples/packages/multichain-provider/snap.config.ts b/packages/examples/packages/multichain-provider/snap.config.ts new file mode 100644 index 0000000000..9310eec961 --- /dev/null +++ b/packages/examples/packages/multichain-provider/snap.config.ts @@ -0,0 +1,17 @@ +import type { SnapConfig } from '@metamask/snaps-cli'; +import { resolve } from 'path'; + +const config: SnapConfig = { + input: resolve(__dirname, 'src/index.ts'), + server: { + port: 8036, + }, + typescript: { + enabled: true, + }, + stats: { + buffer: false, + }, +}; + +export default config; diff --git a/packages/examples/packages/multichain-provider/snap.manifest.json b/packages/examples/packages/multichain-provider/snap.manifest.json new file mode 100644 index 0000000000..aab6c63188 --- /dev/null +++ b/packages/examples/packages/multichain-provider/snap.manifest.json @@ -0,0 +1,27 @@ +{ + "version": "0.0.0", + "description": "MetaMask example snap demonstrating the use of the Multichain Provider API and `endowment:multichain-provider` permission.", + "proposedName": "Multichain Provider Example Snap", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "source": { + "shasum": "/71hyHus4xSBCPLrzCzc7sYLZgRXAddpGoPT8Kw1PsM=", + "location": { + "npm": { + "filePath": "dist/bundle.js", + "packageName": "@metamask/multichain-provider-example-snap", + "registry": "https://registry.npmjs.org/" + } + } + }, + "initialPermissions": { + "endowment:rpc": { + "dapps": true + }, + "endowment:multichain-provider": {} + }, + "platformVersion": "10.3.0", + "manifestVersion": "0.1" +} diff --git a/packages/examples/packages/multichain-provider/src/index.test.ts b/packages/examples/packages/multichain-provider/src/index.test.ts new file mode 100644 index 0000000000..d3d9e52641 --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/index.test.ts @@ -0,0 +1,183 @@ +import { expect } from '@jest/globals'; +import { installSnap } from '@metamask/snaps-jest'; + +describe('onRpcRequest', () => { + it('throws an error if the requested method does not exist', async () => { + const { request } = await installSnap(); + + const response = await request({ + method: 'foo', + }); + + expect(response).toRespondWithError({ + code: -32601, + message: 'The method does not exist / is not available.', + stack: expect.any(String), + data: { + method: 'foo', + cause: null, + }, + }); + }); + + describe('createSession', () => { + it('returns the established session', async () => { + const { request } = await installSnap(); + + const response = await request({ + method: 'createSession', + }); + + expect(response).toRespondWith({ + sessionScopes: { + 'eip155:1': { + accounts: ['eip155:1:0xc6d5a3c98ec9073b54fa0969957bd582e8d874bf'], + methods: expect.arrayContaining(['personal_sign']), + notifications: expect.arrayContaining(['eth_subscription']), + }, + 'eip155:11155111': { + accounts: [ + 'eip155:11155111:0xc6d5a3c98ec9073b54fa0969957bd582e8d874bf', + ], + methods: expect.arrayContaining(['personal_sign']), + notifications: expect.arrayContaining(['eth_subscription']), + }, + 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': { + accounts: [], + methods: expect.arrayContaining(['signMessage']), + notifications: [], + }, + }, + }); + }); + }); + + describe('getChainId', () => { + const ETHEREUM_CHAIN_ID = '0x1'; + const SEPOLIA_CHAIN_ID = '0xaa36a7'; + + it('returns the Ethereum Mainnet chain ID', async () => { + const { request } = await installSnap(); + + await request({ method: 'createSession' }); + + const response = await request({ + method: 'getChainId', + }); + + expect(response).toRespondWith(ETHEREUM_CHAIN_ID); + }); + + it('returns the Sepolia chain ID', async () => { + const { request } = await installSnap(); + + await request({ method: 'createSession' }); + + const response = await request({ + method: 'getChainId', + params: { + scope: 'eip155:11155111', + }, + }); + + expect(response).toRespondWith(SEPOLIA_CHAIN_ID); + }); + }); + + describe('getAccounts', () => { + it('returns the addresses granted access to by the user', async () => { + const { request } = await installSnap(); + + await request({ method: 'createSession' }); + + const response = await request({ + method: 'getAccounts', + }); + + expect(response).toRespondWith([ + 'eip155:1:0xc6d5a3c98ec9073b54fa0969957bd582e8d874bf', + ]); + }); + }); + + describe('signMessage', () => { + const MOCK_SIGNATURE = + '0x16f672a12220dc4d9e27671ef580cfc1397a9a4d5ee19eadea46c0f350b2f72a4922be7c1f16ed9b03ef1d3351eac469e33accf5a36194b1d88923701c2b163f1b'; + + it('returns a signature for Ethereum', async () => { + const { request, mockJsonRpc } = await installSnap(); + + await request({ method: 'createSession' }); + + // We can mock the signature request with the response we want. + mockJsonRpc({ + method: 'personal_sign', + result: MOCK_SIGNATURE, + }); + + const response = await request({ + method: 'signMessage', + params: { scope: 'eip155:1', message: 'foo' }, + }); + + expect(response).toRespondWith(MOCK_SIGNATURE); + }); + }); + + describe('signTypedData', () => { + const MOCK_SIGNATURE = + '0x01b37713300d99fecf0274bcb0dfb586a23d56c4bf2ed700c5ecf4ada7a2a14825e7b1212b1cc49c9440c375337561f2b7a6e639ba25be6a6f5a16f60e6931d31c'; + + it('returns a signature for Ethereum', async () => { + const { request, mockJsonRpc } = await installSnap(); + + await request({ method: 'createSession' }); + + // We can mock the signature request with the response we want. + mockJsonRpc({ + method: 'eth_signTypedData_v4', + result: MOCK_SIGNATURE, + }); + + const response = await request({ + method: 'signTypedData', + params: { scope: 'eip155:1', message: 'foo' }, + }); + + expect(response).toRespondWith(MOCK_SIGNATURE); + }); + }); + + describe('getGenesisHash', () => { + it('returns the Ethereum Mainnet hash', async () => { + const { request } = await installSnap(); + + await request({ method: 'createSession' }); + + const response = await request({ + method: 'getGenesisHash', + params: { scope: 'eip155:1' }, + }); + + expect(response).toRespondWith( + '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3', + ); + }); + + it('returns the Solana Mainnet hash', async () => { + const SOLANA_GENESIS_HASH = 'abc'; + const { request, mockJsonRpc } = await installSnap(); + + await request({ method: 'createSession' }); + + mockJsonRpc({ method: 'getGenesisHash', result: SOLANA_GENESIS_HASH }); + + const response = await request({ + method: 'getGenesisHash', + params: { scope: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' }, + }); + + expect(response).toRespondWith(SOLANA_GENESIS_HASH); + }); + }); +}); diff --git a/packages/examples/packages/multichain-provider/src/index.ts b/packages/examples/packages/multichain-provider/src/index.ts new file mode 100644 index 0000000000..761fbb2ea7 --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/index.ts @@ -0,0 +1,133 @@ +import { + MethodNotFoundError, + type OnRpcRequestHandler, +} from '@metamask/snaps-sdk'; +import type { CaipChainId } from '@metamask/utils'; +import { parseCaipChainId } from '@metamask/utils'; + +import { invokeMethod, Evm, Solana } from './modules'; +import type { + BaseParams, + SignMessageParams, + SignTypedDataParams, +} from './types'; + +/** + * Create the multichain API session. + * + * @returns The session. + */ +async function createSession() { + const optionalScopes = { + 'eip155:1': { + methods: ['personal_sign', 'eth_signTypedData_v4'], + notifications: [], + accounts: [], + }, + 'eip155:11155111': { + methods: ['personal_sign', 'eth_signTypedData_v4'], + notifications: [], + accounts: [], + }, + 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': { + methods: ['signMessage', 'getGenesisHash'], + notifications: [], + accounts: [], + }, + }; + return await snap.request({ + method: 'wallet_createSession', + params: { + optionalScopes, + }, + }); +} + +/** + * Retrieve the currently permissioned accounts in the active session for a given scope. + * + * @param scope - The CAIP-2 scope. + * @returns A list of CAIP-10 addresses. + */ +async function getAccounts(scope: CaipChainId) { + const session = await snap.request({ + method: 'wallet_getSession', + }); + + return session.sessionScopes[scope]?.accounts ?? []; +} + +/** + * Get the Snap sub-module for the given scope. + * + * @param scope - The CAIP-2 scope. + * @returns The module. + */ +function getModule(scope: CaipChainId) { + const { namespace } = parseCaipChainId(scope); + + switch (namespace) { + case 'eip155': + return new Evm(scope); + + case 'solana': + return new Solana(scope); + + default: + throw new Error(`${namespace} not supported.`); + } +} + +/** + * Handle incoming JSON-RPC requests from the dapp, sent through the + * `wallet_invokeSnap` method. This handler handles six methods: + * + * - `createSession`: Create the multichain API session. + * - `getChainId`: Get the current Ethereum chain ID as a string. + * - `getAccounts`: Get the accounts for the selected scope. + * - `signMessage`: Sign a message using an Ethereum or Solana account. + * - `signTypedData`: Sign a struct using an Ethereum account. + * - `getGenesisHash`: Get the genesis hash for the selected scope. + * + * @param params - The request parameters. + * @param params.request - The JSON-RPC request object. + * @returns The JSON-RPC response. + * @see https://docs.metamask.io/snaps/reference/exports/#onrpcrequest + * @see https://docs.metamask.io/snaps/reference/rpc-api/#wallet_invokesnap + */ +export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => { + const { scope = 'eip155:1' } = (request.params as BaseParams) ?? {}; + + const scopeModule = getModule(scope); + + switch (request.method) { + case 'createSession': + return await createSession(); + + case 'getChainId': + return await invokeMethod(scope, { + method: 'eth_chainId', + }); + + case 'getAccounts': + return await getAccounts(scope); + + case 'signMessage': { + const params = request.params as SignMessageParams; + const accounts = await getAccounts(scope); + return await scopeModule.signMessage(accounts[0], params.message); + } + + case 'signTypedData': { + const params = request.params as SignTypedDataParams; + const accounts = await getAccounts(scope); + return await scopeModule.signTypedData(accounts[0], params.message); + } + + case 'getGenesisHash': + return await scopeModule.getGenesisHash(); + + default: + throw new MethodNotFoundError({ method: request.method }); + } +}; diff --git a/packages/examples/packages/multichain-provider/src/modules/base.ts b/packages/examples/packages/multichain-provider/src/modules/base.ts new file mode 100644 index 0000000000..3a3d6d2d8f --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/base.ts @@ -0,0 +1,45 @@ +import type { + CaipAccountId, + CaipChainId, + JsonRpcRequest, +} from '@metamask/utils'; + +export abstract class Module { + scope: CaipChainId; + + constructor(scope: CaipChainId) { + this.scope = scope; + } + + abstract signMessage( + account: CaipAccountId, + message: string, + ): Promise; + + abstract signTypedData( + account: CaipAccountId, + message: string, + ): Promise; + + abstract getGenesisHash(): Promise; +} + +/** + * Invoke a RPC method for a given scope. + * + * @param scope - The CAIP-2 scope. + * @param request - The JSON-RPC request. + * @returns The JSON-RPC response. + */ +export async function invokeMethod( + scope: CaipChainId, + request: Omit, +): Promise { + return (await snap.request({ + method: 'wallet_invokeMethod', + params: { + scope, + request, + }, + })) as ReturnType; +} diff --git a/packages/examples/packages/multichain-provider/src/modules/evm.ts b/packages/examples/packages/multichain-provider/src/modules/evm.ts new file mode 100644 index 0000000000..44a5dce517 --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/evm.ts @@ -0,0 +1,113 @@ +import type { CaipAccountId, Hex } from '@metamask/utils'; +import { + assert, + bytesToHex, + hexToNumber, + parseCaipAccountId, + stringToBytes, +} from '@metamask/utils'; + +import { invokeMethod, Module } from './base'; + +export class Evm extends Module { + async signMessage(account: CaipAccountId, message: string): Promise { + const { address } = parseCaipAccountId(account); + + return await invokeMethod(this.scope, { + method: 'personal_sign', + params: [bytesToHex(stringToBytes(message)), address], + }); + } + + async signTypedData( + account: CaipAccountId, + message: string, + ): Promise { + const { + chain: { reference }, + address, + } = parseCaipAccountId(account); + + return await invokeMethod(this.scope, { + method: 'eth_signTypedData_v4', + params: [ + address, + { + types: { + EIP712Domain: [ + { + name: 'name', + type: 'string', + }, + { + name: 'version', + type: 'string', + }, + { + name: 'chainId', + type: 'uint256', + }, + { + name: 'verifyingContract', + type: 'address', + }, + ], + Person: [ + { + name: 'name', + type: 'string', + }, + { + name: 'wallet', + type: 'address', + }, + ], + Mail: [ + { + name: 'from', + type: 'Person', + }, + { + name: 'to', + type: 'Person', + }, + { + name: 'contents', + type: 'string', + }, + ], + }, + primaryType: 'Mail', + domain: { + name: 'Ether Mail', + version: '1', + chainId: hexToNumber(reference), + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, + message: { + from: { + name: 'Snap', + wallet: address, + }, + to: { + name: 'Bob', + wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', + }, + contents: message, + }, + }, + ], + }); + } + + async getGenesisHash(): Promise { + const block = await invokeMethod<{ hash: string }>(this.scope, { + method: 'eth_getBlockByNumber', + params: ['0x0', false], + }); + + assert(block, 'Multichain API did not return a valid block.'); + + return block.hash; + } +} diff --git a/packages/examples/packages/multichain-provider/src/modules/index.ts b/packages/examples/packages/multichain-provider/src/modules/index.ts new file mode 100644 index 0000000000..f69a8a3ddc --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/index.ts @@ -0,0 +1,3 @@ +export * from './base'; +export * from './evm'; +export * from './sol'; diff --git a/packages/examples/packages/multichain-provider/src/modules/sol.ts b/packages/examples/packages/multichain-provider/src/modules/sol.ts new file mode 100644 index 0000000000..9888e36adc --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/sol.ts @@ -0,0 +1,35 @@ +import { MethodNotSupportedError } from '@metamask/snaps-sdk'; +import type { CaipAccountId } from '@metamask/utils'; +import { + bytesToBase64, + parseCaipAccountId, + stringToBytes, +} from '@metamask/utils'; + +import { invokeMethod, Module } from './base'; + +export class Solana extends Module { + async signMessage(account: CaipAccountId, message: string): Promise { + const { address } = parseCaipAccountId(account); + + const bytes = stringToBytes(message); + + const result = await invokeMethod<{ signature: string }>(this.scope, { + method: 'signMessage', + params: { account: { address }, message: bytesToBase64(bytes) }, + }); + + return result.signature; + } + + async signTypedData( + _account: CaipAccountId, + _message: string, + ): Promise { + throw new MethodNotSupportedError(); + } + + async getGenesisHash(): Promise { + return await invokeMethod(this.scope, { method: 'getGenesisHash' }); + } +} diff --git a/packages/examples/packages/multichain-provider/src/types.ts b/packages/examples/packages/multichain-provider/src/types.ts new file mode 100644 index 0000000000..219052a709 --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/types.ts @@ -0,0 +1,13 @@ +import type { CaipChainId } from '@metamask/utils'; + +export type BaseParams = { + scope: CaipChainId; +}; + +export type SignMessageParams = BaseParams & { + message: string; +}; + +export type SignTypedDataParams = { + message: string; +}; diff --git a/packages/examples/packages/multichain-provider/tsconfig.json b/packages/examples/packages/multichain-provider/tsconfig.json new file mode 100644 index 0000000000..17a40a6a74 --- /dev/null +++ b/packages/examples/packages/multichain-provider/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": false, + "baseUrl": "./" + }, + "include": ["src", "snap.config.ts"] +} diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index 4a327b8cc6..e10e897f53 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,6 +1,6 @@ { - "branches": 90.09, - "functions": 94.73, - "lines": 90.24, - "statements": 89.37 + "branches": 90.19, + "functions": 94.02, + "lines": 90.26, + "statements": 89.32 } diff --git a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts index a0b358791b..ce7982380b 100644 --- a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts +++ b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts @@ -612,6 +612,65 @@ describe('BaseSnapExecutor', () => { }); }); + it('supports the multichain API using the snap global', async () => { + const CODE = ` + module.exports.onRpcRequest = () => snap.request({ method: 'wallet_invokeMethod', params: { scope: 'eip155:1', request: { method: 'eth_chainId' } } }); + `; + + const executor = new TestSnapExecutor(); + await executor.executeSnap(1, MOCK_SNAP_ID, CODE, []); + + expect(await executor.readCommand()).toStrictEqual({ + jsonrpc: '2.0', + id: 1, + result: 'OK', + }); + + await executor.writeCommand({ + jsonrpc: '2.0', + id: 2, + method: 'snapRpc', + params: [ + MOCK_SNAP_ID, + HandlerType.OnRpcRequest, + MOCK_ORIGIN, + { jsonrpc: '2.0', method: '', params: [] }, + ], + }); + + const multichainRequest = await executor.readRpc(); + expect(multichainRequest).toStrictEqual({ + name: 'metamask-multichain-provider', + data: { + id: expect.any(Number), + jsonrpc: '2.0', + method: 'wallet_invokeMethod', + params: { + scope: 'eip155:1', + request: { + method: 'eth_chainId', + }, + }, + }, + }); + + await executor.writeRpc({ + name: 'metamask-multichain-provider', + data: { + jsonrpc: '2.0', + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + id: multichainRequest.data.id!, + result: '0x1', + }, + }); + + expect(await executor.readCommand()).toStrictEqual({ + id: 2, + jsonrpc: '2.0', + result: '0x1', + }); + }); + it('sanitizes JSON before checking for blocked methods using snap global', async () => { const CODE = ` const badToJSON = () => { diff --git a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.ts b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.ts index 3818439f46..288480b113 100644 --- a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.ts +++ b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.ts @@ -48,6 +48,7 @@ import { sanitizeRequestArguments, withTeardown, isValidResponse, + isMultichainRequest, } from './utils'; import { ExecuteSnapRequestArgumentsStruct, @@ -417,7 +418,16 @@ export class BaseSnapExecutor { provider.initializeSync(); - const snap = this.createSnapGlobal(provider); + const multichainProvider = new SnapProvider( + multiplex.createStream('metamask-multichain-provider'), + { + rpcMiddleware: [createIdRemapMiddleware()], + }, + ); + + multichainProvider.initializeSync(); + + const snap = this.createSnapGlobal(provider, multichainProvider); const ethereum = this.createEIP1193Provider(provider); // We specifically use any type because the Snap can modify the object any way they want const snapModule: any = { exports: {} }; @@ -516,19 +526,33 @@ export class BaseSnapExecutor { /** * Instantiates a snap API object (i.e. `globalThis.snap`). * - * @param provider - A StreamProvider connected to MetaMask. + * @param provider - A StreamProvider connected to the EIP-1193 client stream. + * @param multichainProvider - A StreamProvider connected to the CAIP-27 client stream. * @returns The snap provider object. */ // TODO: Either fix this lint violation or explain why it's necessary to // ignore. // eslint-disable-next-line no-restricted-syntax - private createSnapGlobal(provider: StreamProvider): SnapsProvider { + private createSnapGlobal( + provider: StreamProvider, + multichainProvider: StreamProvider, + ): SnapsProvider { const originalRequest = provider.request.bind(provider); + const originalMultichainRequest = + multichainProvider.request.bind(multichainProvider); const request = async (args: RequestArguments) => { // As part of the sanitization, we validate that the args are valid JSON. const sanitizedArgs = sanitizeRequestArguments(args); assertSnapOutboundRequest(sanitizedArgs); + + if (isMultichainRequest(sanitizedArgs)) { + return await withTeardown( + originalMultichainRequest(sanitizedArgs), + this as any, + ); + } + return await withTeardown(originalRequest(sanitizedArgs), this as any); }; diff --git a/packages/snaps-execution-environments/src/common/utils.ts b/packages/snaps-execution-environments/src/common/utils.ts index 72e5ff343d..a0041fca3e 100644 --- a/packages/snaps-execution-environments/src/common/utils.ts +++ b/packages/snaps-execution-environments/src/common/utils.ts @@ -62,6 +62,23 @@ export const BLOCKED_RPC_METHODS = Object.freeze([ 'wallet_scanQRCode', ]); +export const MULTICHAIN_API_METHODS = Object.freeze([ + 'wallet_createSession', + 'wallet_invokeMethod', + 'wallet_getSession', + 'wallet_revokeSession', +]); + +/** + * Check whether a validated request should be routed to the multichain API. + * + * @param args - The request arguments. + * @returns True if the request is a multichain request, otherwise false. + */ +export function isMultichainRequest(args: RequestArguments) { + return MULTICHAIN_API_METHODS.includes(args.method); +} + /** * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API. * diff --git a/packages/snaps-rpc-methods/jest.config.js b/packages/snaps-rpc-methods/jest.config.js index f4af002854..bf861e0833 100644 --- a/packages/snaps-rpc-methods/jest.config.js +++ b/packages/snaps-rpc-methods/jest.config.js @@ -11,9 +11,9 @@ module.exports = deepmerge(baseConfig, { coverageThreshold: { global: { branches: 95.7, - functions: 98.76, - lines: 98.99, - statements: 98.7, + functions: 98.77, + lines: 99, + statements: 98.71, }, }, }); diff --git a/packages/snaps-rpc-methods/src/endowments/enum.ts b/packages/snaps-rpc-methods/src/endowments/enum.ts index e3f24b4de5..fa8c695d6e 100644 --- a/packages/snaps-rpc-methods/src/endowments/enum.ts +++ b/packages/snaps-rpc-methods/src/endowments/enum.ts @@ -4,6 +4,7 @@ export enum SnapEndowments { TransactionInsight = 'endowment:transaction-insight', Cronjob = 'endowment:cronjob', EthereumProvider = 'endowment:ethereum-provider', + MultichainProvider = 'endowment:multichain-provider', Rpc = 'endowment:rpc', WebAssemblyAccess = 'endowment:webassembly', NameLookup = 'endowment:name-lookup', diff --git a/packages/snaps-rpc-methods/src/endowments/index.ts b/packages/snaps-rpc-methods/src/endowments/index.ts index 91bc010ce3..f170b96bfb 100644 --- a/packages/snaps-rpc-methods/src/endowments/index.ts +++ b/packages/snaps-rpc-methods/src/endowments/index.ts @@ -21,6 +21,7 @@ import { keyringEndowmentBuilder, } from './keyring'; import { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks'; +import { multichainProviderEndowmentBuilder } from './multichain-provider'; import { getNameLookupCaveatMapper, nameLookupCaveatSpecifications, @@ -57,6 +58,8 @@ export const endowmentPermissionBuilders = { [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder, [ethereumProviderEndowmentBuilder.targetName]: ethereumProviderEndowmentBuilder, + [multichainProviderEndowmentBuilder.targetName]: + multichainProviderEndowmentBuilder, [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder, [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder, [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder, diff --git a/packages/snaps-rpc-methods/src/endowments/multichain-provider.test.ts b/packages/snaps-rpc-methods/src/endowments/multichain-provider.test.ts new file mode 100644 index 0000000000..a0fb610401 --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/multichain-provider.test.ts @@ -0,0 +1,20 @@ +import { PermissionType, SubjectType } from '@metamask/permission-controller'; + +import { SnapEndowments } from './enum'; +import { multichainProviderEndowmentBuilder } from './multichain-provider'; + +describe('endowment:multichain-provider', () => { + it('builds the expected permission specification', () => { + const specification = + multichainProviderEndowmentBuilder.specificationBuilder({}); + expect(specification).toStrictEqual({ + permissionType: PermissionType.Endowment, + targetName: SnapEndowments.MultichainProvider, + endowmentGetter: expect.any(Function), + allowedCaveats: null, + subjectTypes: [SubjectType.Snap], + }); + + expect(specification.endowmentGetter()).toBeNull(); + }); +}); diff --git a/packages/snaps-rpc-methods/src/endowments/multichain-provider.ts b/packages/snaps-rpc-methods/src/endowments/multichain-provider.ts new file mode 100644 index 0000000000..924777d2c5 --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/multichain-provider.ts @@ -0,0 +1,44 @@ +import type { + EndowmentGetterParams, + PermissionSpecificationBuilder, + ValidPermissionSpecification, +} from '@metamask/permission-controller'; +import { PermissionType, SubjectType } from '@metamask/permission-controller'; + +import { SnapEndowments } from './enum'; + +const permissionName = SnapEndowments.MultichainProvider; + +type MultichainProviderEndowmentSpecification = ValidPermissionSpecification<{ + permissionType: PermissionType.Endowment; + targetName: typeof permissionName; + endowmentGetter: (_options?: EndowmentGetterParams) => null; + allowedCaveats: null; +}>; + +/** + * `endowment:multichain-provider` returns nothing; it is intended to be used as a + * flag by the Snaps Platform to detect whether a Snap has the capability to + * use the multichain API. + * + * @param _builderOptions - Optional specification builder options. + * @returns The specification for the network endowment. + */ +const specificationBuilder: PermissionSpecificationBuilder< + PermissionType.Endowment, + any, + MultichainProviderEndowmentSpecification +> = (_builderOptions?: any) => { + return { + permissionType: PermissionType.Endowment, + targetName: permissionName, + allowedCaveats: null, + endowmentGetter: (_getterOptions?: EndowmentGetterParams) => null, + subjectTypes: [SubjectType.Snap], + }; +}; + +export const multichainProviderEndowmentBuilder = Object.freeze({ + targetName: permissionName, + specificationBuilder, +} as const); diff --git a/packages/snaps-rpc-methods/src/permissions.test.ts b/packages/snaps-rpc-methods/src/permissions.test.ts index ba39525e4d..4064e3ffdf 100644 --- a/packages/snaps-rpc-methods/src/permissions.test.ts +++ b/packages/snaps-rpc-methods/src/permissions.test.ts @@ -63,6 +63,15 @@ describe('buildSnapEndowmentSpecifications', () => { ], "targetName": "endowment:lifecycle-hooks", }, + "endowment:multichain-provider": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:multichain-provider", + }, "endowment:name-lookup": { "allowedCaveats": [ "chainIds", diff --git a/packages/snaps-sdk/src/types/methods/index.ts b/packages/snaps-sdk/src/types/methods/index.ts index 72da8be705..abcc53a41a 100644 --- a/packages/snaps-sdk/src/types/methods/index.ts +++ b/packages/snaps-sdk/src/types/methods/index.ts @@ -21,6 +21,7 @@ export type * from './list-entropy-sources'; export type * from './manage-accounts'; export * from './manage-state'; export type * from './methods'; +export type * from './multichain'; export * from './notify'; export type * from './provider-request'; export type * from './request-snaps'; diff --git a/packages/snaps-sdk/src/types/methods/methods.ts b/packages/snaps-sdk/src/types/methods/methods.ts index 0668c1700a..7313a7677f 100644 --- a/packages/snaps-sdk/src/types/methods/methods.ts +++ b/packages/snaps-sdk/src/types/methods/methods.ts @@ -72,6 +72,13 @@ import type { ManageAccountsResult, } from './manage-accounts'; import type { ManageStateParams, ManageStateResult } from './manage-state'; +import type { + CreateSessionParams, + CreateSessionResult, + GetSessionParams, + GetSessionResult, + InvokeMethodParams, +} from './multichain'; import type { NotifyParams, NotifyResult } from './notify'; import type { OpenWebSocketParams, @@ -154,8 +161,11 @@ export type SnapMethods = { SendWebSocketMessageParams, SendWebSocketMessageResult, ]; + wallet_createSession: [CreateSessionParams, CreateSessionResult]; + wallet_getSession: [GetSessionParams, GetSessionResult]; wallet_getSnaps: [GetSnapsParams, GetSnapsResult]; wallet_invokeKeyring: [InvokeKeyringParams, InvokeKeyringResult]; + wallet_invokeMethod: [InvokeMethodParams, InvokeKeyringResult]; wallet_invokeSnap: [InvokeSnapParams, InvokeSnapResult]; wallet_snap: [InvokeSnapParams, InvokeSnapResult]; wallet_requestSnaps: [RequestSnapsParams, RequestSnapsResult]; diff --git a/packages/snaps-sdk/src/types/methods/multichain/create-session.ts b/packages/snaps-sdk/src/types/methods/multichain/create-session.ts new file mode 100644 index 0000000000..c30f281d3c --- /dev/null +++ b/packages/snaps-sdk/src/types/methods/multichain/create-session.ts @@ -0,0 +1,27 @@ +import type { CaipAccountId, CaipChainId } from '@metamask/utils'; + +export type SessionScopes = Record< + CaipChainId, + { + methods: string[]; + notifications: string[]; + accounts: CaipAccountId[]; + } +>; + +/** + * The request parameters for the `wallet_createSession` method. + * + * @property id - The id of the background event to cancel. + */ +export type CreateSessionParams = { + requiredScopes?: SessionScopes; + optionalScopes?: SessionScopes; +}; + +/** + * The result returned for the `wallet_createSession` method. + * + * @property sessionScopes - The scopes granted for the session. + */ +export type CreateSessionResult = { sessionScopes: SessionScopes }; diff --git a/packages/snaps-sdk/src/types/methods/multichain/get-session.ts b/packages/snaps-sdk/src/types/methods/multichain/get-session.ts new file mode 100644 index 0000000000..b5e8ca38b5 --- /dev/null +++ b/packages/snaps-sdk/src/types/methods/multichain/get-session.ts @@ -0,0 +1,15 @@ +import type { CreateSessionResult } from './create-session'; + +/** + * The request parameters for the `wallet_getSession` method. + * + * This method does not accept any parameters. + */ +export type GetSessionParams = never; + +/** + * The result returned for the `wallet_getSession` method. + * + * @property sessionScopes - The scopes granted for the session. + */ +export type GetSessionResult = CreateSessionResult; diff --git a/packages/snaps-sdk/src/types/methods/multichain/index.ts b/packages/snaps-sdk/src/types/methods/multichain/index.ts new file mode 100644 index 0000000000..552052da65 --- /dev/null +++ b/packages/snaps-sdk/src/types/methods/multichain/index.ts @@ -0,0 +1,3 @@ +export type * from './create-session'; +export type * from './get-session'; +export type * from './invoke-method'; diff --git a/packages/snaps-sdk/src/types/methods/multichain/invoke-method.ts b/packages/snaps-sdk/src/types/methods/multichain/invoke-method.ts new file mode 100644 index 0000000000..e916c5e99f --- /dev/null +++ b/packages/snaps-sdk/src/types/methods/multichain/invoke-method.ts @@ -0,0 +1,19 @@ +import type { CaipChainId, Json, JsonRpcRequest } from '@metamask/utils'; + +/** + * The request parameters for the `wallet_invokeMethod` method. + * + * @property scope - The scope on which to invoke the method. + * @property request - The request to send. + */ +export type InvokeMethodParams = { + scope: CaipChainId; + request: Pick; +}; + +/** + * The result returned for the `wallet_invokeMethod` method. + * + * This method returns the response of the wrapped request. + */ +export type InvokeMethodResult = Json; diff --git a/packages/snaps-simulation/package.json b/packages/snaps-simulation/package.json index 7c759c8421..9acbf2f3a3 100644 --- a/packages/snaps-simulation/package.json +++ b/packages/snaps-simulation/package.json @@ -55,6 +55,7 @@ "test:watch": "jest --watch" }, "dependencies": { + "@metamask/chain-agnostic-permission": "^1.4.0", "@metamask/json-rpc-engine": "^10.1.0", "@metamask/json-rpc-middleware-stream": "^8.0.8", "@metamask/key-tree": "^10.1.1", diff --git a/packages/snaps-simulation/src/controllers.test.ts b/packages/snaps-simulation/src/controllers.test.ts index 431baf15cf..89bf4ee11a 100644 --- a/packages/snaps-simulation/src/controllers.test.ts +++ b/packages/snaps-simulation/src/controllers.test.ts @@ -1,31 +1,36 @@ +import { mnemonicPhraseToBytes } from '@metamask/key-tree'; import { Messenger } from '@metamask/messenger'; import { PermissionController, SubjectMetadataController, } from '@metamask/permission-controller'; +import { DEFAULT_SRP } from './constants'; import { getControllers } from './controllers'; import type { RestrictedMiddlewareHooks } from './simulation'; import { getMockOptions } from './test-utils'; -const MOCK_HOOKS: RestrictedMiddlewareHooks = { - getIsLocked: jest.fn(), - getMnemonic: jest.fn(), - getSnapFile: jest.fn(), - createInterface: jest.fn(), - updateInterface: jest.fn(), - getInterfaceState: jest.fn(), - resolveInterface: jest.fn(), -}; - describe('getControllers', () => { - it('returns the controllers', () => { - const { permissionController, subjectMetadataController } = getControllers({ - controllerMessenger: new Messenger({ namespace: 'Root' }), - hooks: MOCK_HOOKS, - runSaga: jest.fn(), - options: getMockOptions(), - }); + it('returns the controllers', async () => { + const MOCK_HOOKS: RestrictedMiddlewareHooks = { + getIsLocked: jest.fn(), + getMnemonic: jest + .fn() + .mockResolvedValue(mnemonicPhraseToBytes(DEFAULT_SRP)), + getSnapFile: jest.fn(), + createInterface: jest.fn(), + updateInterface: jest.fn(), + getInterfaceState: jest.fn(), + resolveInterface: jest.fn(), + }; + + const { permissionController, subjectMetadataController } = + await getControllers({ + controllerMessenger: new Messenger({ namespace: 'Root' }), + hooks: MOCK_HOOKS, + runSaga: jest.fn(), + options: getMockOptions(), + }); expect(permissionController).toBeInstanceOf(PermissionController); expect(subjectMetadataController).toBeInstanceOf(SubjectMetadataController); diff --git a/packages/snaps-simulation/src/controllers.ts b/packages/snaps-simulation/src/controllers.ts index 020416bf85..f9c10c8982 100644 --- a/packages/snaps-simulation/src/controllers.ts +++ b/packages/snaps-simulation/src/controllers.ts @@ -1,3 +1,7 @@ +import { + caip25CaveatBuilder, + Caip25CaveatType, +} from '@metamask/chain-agnostic-permission'; import { Messenger } from '@metamask/messenger'; import type { CaveatSpecificationConstraint, @@ -28,6 +32,7 @@ import { getSafeJson } from '@metamask/utils'; import { getPermissionSpecifications } from './methods'; import { UNRESTRICTED_METHODS } from './methods/constants'; +import { getSimulationAccount } from './middleware/internal-methods/accounts'; import type { SimulationOptions } from './options'; import type { RestrictedMiddlewareHooks } from './simulation'; import type { RunSagaFunction } from './store'; @@ -70,7 +75,9 @@ export type Controllers = { * @param options - The options. * @returns The controllers for the Snap. */ -export function getControllers(options: GetControllersOptions): Controllers { +export async function getControllers( + options: GetControllersOptions, +): Promise { const { controllerMessenger } = options; const subjectMetadataController = new SubjectMetadataController({ messenger: new Messenger({ @@ -104,7 +111,7 @@ export function getControllers(options: GetControllersOptions): Controllers { messenger: interfaceControllerMessenger, }); - const permissionController = getPermissionController(options); + const permissionController = await getPermissionController(options); return { permissionController, @@ -121,7 +128,7 @@ export function getControllers(options: GetControllersOptions): Controllers { * @param options.options - Miscellaneous options. * @returns The permission controller for the Snap. */ -function getPermissionController(options: GetControllersOptions) { +async function getPermissionController(options: GetControllersOptions) { const { controllerMessenger } = options; const permissionSpecifications = getPermissionSpecifications(options); const messenger = new Messenger({ @@ -142,9 +149,18 @@ function getPermissionController(options: GetControllersOptions) { ], }); + const mnemonic = await options.hooks.getMnemonic(); + const defaultAddress = await getSimulationAccount(mnemonic); + return new PermissionController({ messenger, caveatSpecifications: { + [Caip25CaveatType]: caip25CaveatBuilder({ + findNetworkClientIdByChainId: (chainId) => chainId, + isNonEvmScopeSupported: (_scope) => true, + getNonEvmAccountAddresses: () => [], + listAccounts: () => [{ type: 'eip155:eoa', address: defaultAddress }], + }), ...snapsCaveatsSpecifications, ...snapsEndowmentCaveatSpecifications, }, diff --git a/packages/snaps-simulation/src/methods/specifications.test.ts b/packages/snaps-simulation/src/methods/specifications.test.ts index 8881eab17a..510b9e2782 100644 --- a/packages/snaps-simulation/src/methods/specifications.test.ts +++ b/packages/snaps-simulation/src/methods/specifications.test.ts @@ -1,3 +1,4 @@ +import { mnemonicPhraseToBytes } from '@metamask/key-tree'; import type { MockAnyNamespace } from '@metamask/messenger'; import { MOCK_ANY_NAMESPACE, Messenger } from '@metamask/messenger'; import { @@ -11,11 +12,11 @@ import { getPermissionSpecifications, resolve, } from './specifications'; +import { DEFAULT_SRP } from '../constants'; import { getControllers, registerSnap } from '../controllers'; -import type { RestrictedMiddlewareHooks } from '../simulation'; import { getMockOptions } from '../test-utils/options'; -const MOCK_HOOKS: RestrictedMiddlewareHooks = { +const MOCK_HOOKS = { getClientCryptography: jest.fn(), getMnemonic: jest.fn(), getMnemonicSeed: jest.fn(), @@ -61,6 +62,15 @@ describe('getPermissionSpecifications', () => { "targetName": "endowment:assets", "validator": [Function], }, + "endowment:caip25": { + "allowedCaveats": [ + "authorizedScopes", + ], + "endowmentGetter": [Function], + "permissionType": "Endowment", + "targetName": "endowment:caip25", + "validator": [Function], + }, "endowment:cronjob": { "allowedCaveats": [ "snapCronjob", @@ -104,6 +114,15 @@ describe('getPermissionSpecifications', () => { ], "targetName": "endowment:lifecycle-hooks", }, + "endowment:multichain-provider": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:multichain-provider", + }, "endowment:name-lookup": { "allowedCaveats": [ "chainIds", @@ -323,7 +342,11 @@ describe('getPermissionSpecifications', () => { describe('getEndowments', () => { it('returns the endowments', async () => { - const controllers = getControllers({ + MOCK_HOOKS.getMnemonic.mockResolvedValue( + mnemonicPhraseToBytes(DEFAULT_SRP), + ); + + const controllers = await getControllers({ controllerMessenger: new Messenger({ namespace: MOCK_ANY_NAMESPACE, }), diff --git a/packages/snaps-simulation/src/methods/specifications.ts b/packages/snaps-simulation/src/methods/specifications.ts index 38c6346779..55a247f5dc 100644 --- a/packages/snaps-simulation/src/methods/specifications.ts +++ b/packages/snaps-simulation/src/methods/specifications.ts @@ -1,3 +1,4 @@ +import { caip25EndowmentBuilder } from '@metamask/chain-agnostic-permission'; import type { GenericPermissionController } from '@metamask/permission-controller'; import { endowmentPermissionBuilders, @@ -81,6 +82,8 @@ export function getPermissionSpecifications({ options, }: GetPermissionSpecificationsOptions) { return { + [caip25EndowmentBuilder.targetName]: + caip25EndowmentBuilder.specificationBuilder({}), ...buildSnapEndowmentSpecifications(EXCLUDED_SNAP_ENDOWMENTS), ...buildSnapRestrictedMethodSpecifications(EXCLUDED_SNAP_PERMISSIONS, { // Shared hooks. diff --git a/packages/snaps-simulation/src/middleware/engine.ts b/packages/snaps-simulation/src/middleware/engine.ts index 1ccfcfb1c9..fd3df1fe9d 100644 --- a/packages/snaps-simulation/src/middleware/engine.ts +++ b/packages/snaps-simulation/src/middleware/engine.ts @@ -6,8 +6,10 @@ import type { Json } from '@metamask/utils'; import { createInternalMethodsMiddleware } from './internal-methods'; import { createMockMiddleware } from './mock'; +import { createMultichainMiddleware } from './multichain'; import { createProviderMiddleware } from './provider'; import type { + MultichainMiddlewareHooks, PermittedMiddlewareHooks, RestrictedMiddlewareHooks, } from '../simulation'; @@ -17,8 +19,10 @@ export type CreateJsonRpcEngineOptions = { store: Store; restrictedHooks: RestrictedMiddlewareHooks; permittedHooks: PermittedMiddlewareHooks; + multichainHooks: MultichainMiddlewareHooks; permissionMiddleware: JsonRpcMiddleware; endpoint?: string; + isMultichain: boolean; }; /** @@ -32,6 +36,8 @@ export type CreateJsonRpcEngineOptions = { * @param options.restrictedHooks - Any hooks used by the middleware handlers. * @param options.permittedHooks - Any hooks used by the middleware handlers. * @param options.permissionMiddleware - The permission middleware to use. + * @param options.multichainHooks - Hooks used by the multichain middleware. + * @param options.isMultichain - Whether the engine is used for multichain. * @returns A JSON-RPC engine. */ export function createJsonRpcEngine({ @@ -39,8 +45,13 @@ export function createJsonRpcEngine({ restrictedHooks, permittedHooks, permissionMiddleware, + multichainHooks, + isMultichain, }: CreateJsonRpcEngineOptions) { const engine = new JsonRpcEngine(); + + engine.push(createMultichainMiddleware(isMultichain, multichainHooks)); + engine.push(createMockMiddleware(store)); // The hooks here do not match the hooks used by the clients, so this diff --git a/packages/snaps-simulation/src/middleware/internal-methods/accounts.ts b/packages/snaps-simulation/src/middleware/internal-methods/accounts.ts index d2f2ab5dbd..f93ed34035 100644 --- a/packages/snaps-simulation/src/middleware/internal-methods/accounts.ts +++ b/packages/snaps-simulation/src/middleware/internal-methods/accounts.ts @@ -3,12 +3,37 @@ import type { JsonRpcEngineNextCallback, } from '@metamask/json-rpc-engine'; import { BIP44Node } from '@metamask/key-tree'; -import type { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils'; +import type { + Hex, + JsonRpcRequest, + PendingJsonRpcResponse, +} from '@metamask/utils'; export type GetAccountsHandlerHooks = { getMnemonic: () => Promise; }; +/** + * Derive the account returned by the Snaps simulation. + * + * @param mnemonic - The mnemonic. + * @returns An account address. + */ +export async function getSimulationAccount(mnemonic: Uint8Array): Promise { + const { address } = await BIP44Node.fromDerivationPath({ + derivationPath: [ + mnemonic, + `bip32:44'`, + `bip32:60'`, + `bip32:0'`, + `bip32:0`, + `bip32:0`, + ], + }); + + return address as Hex; +} + /** * A mock handler for account related methods that always returns the first * address for the selected secret recovery phrase. @@ -31,17 +56,9 @@ export async function getAccountsHandler( ) { const { getMnemonic } = hooks; - const node = await BIP44Node.fromDerivationPath({ - derivationPath: [ - await getMnemonic(), - `bip32:44'`, - `bip32:60'`, - `bip32:0'`, - `bip32:0`, - `bip32:0`, - ], - }); + const mnemonic = await getMnemonic(); + const address = await getSimulationAccount(mnemonic); - response.result = [node.address]; + response.result = [address]; return end(); } diff --git a/packages/snaps-simulation/src/middleware/internal-methods/chain-id.ts b/packages/snaps-simulation/src/middleware/internal-methods/chain-id.ts index ae62d4d104..80d4b84077 100644 --- a/packages/snaps-simulation/src/middleware/internal-methods/chain-id.ts +++ b/packages/snaps-simulation/src/middleware/internal-methods/chain-id.ts @@ -2,7 +2,13 @@ import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback, } from '@metamask/json-rpc-engine'; -import type { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils'; +import { + bigIntToHex, + parseCaipChainId, + type CaipChainId, + type JsonRpcRequest, + type PendingJsonRpcResponse, +} from '@metamask/utils'; import type { InternalMethodsMiddlewareHooks } from './middleware'; @@ -10,8 +16,7 @@ import type { InternalMethodsMiddlewareHooks } from './middleware'; * A mock handler for eth_chainId that always returns a specific * hardcoded result. * - * @param _request - Incoming JSON-RPC request. Ignored for this specific - * handler. + * @param request - Incoming JSON-RPC request. * @param response - The outgoing JSON-RPC response, modified to return the * result. * @param _next - The `json-rpc-engine` middleware next handler. @@ -20,13 +25,16 @@ import type { InternalMethodsMiddlewareHooks } from './middleware'; * @returns The JSON-RPC response. */ export async function getChainIdHandler( - _request: JsonRpcRequest, + request: JsonRpcRequest & { scope?: CaipChainId }, response: PendingJsonRpcResponse, _next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback, hooks: Pick, ) { - response.result = hooks.getSimulationState().chain.chainId; + const requestScope = request.scope && parseCaipChainId(request.scope); + response.result = requestScope + ? bigIntToHex(BigInt(requestScope.reference)) + : hooks.getSimulationState().chain.chainId; return end(); } diff --git a/packages/snaps-simulation/src/middleware/internal-methods/net-version.ts b/packages/snaps-simulation/src/middleware/internal-methods/net-version.ts index 94b706e550..63c1143974 100644 --- a/packages/snaps-simulation/src/middleware/internal-methods/net-version.ts +++ b/packages/snaps-simulation/src/middleware/internal-methods/net-version.ts @@ -2,8 +2,12 @@ import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback, } from '@metamask/json-rpc-engine'; -import { hexToBigInt } from '@metamask/utils'; -import type { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils'; +import { hexToBigInt, parseCaipChainId } from '@metamask/utils'; +import type { + CaipChainId, + JsonRpcRequest, + PendingJsonRpcResponse, +} from '@metamask/utils'; import type { InternalMethodsMiddlewareHooks } from './middleware'; @@ -11,8 +15,7 @@ import type { InternalMethodsMiddlewareHooks } from './middleware'; * A mock handler for net_version that always returns a specific * hardcoded result. * - * @param _request - Incoming JSON-RPC request. Ignored for this specific - * handler. + * @param request - Incoming JSON-RPC request. * @param response - The outgoing JSON-RPC response, modified to return the * result. * @param _next - The `json-rpc-engine` middleware next handler. @@ -21,14 +24,16 @@ import type { InternalMethodsMiddlewareHooks } from './middleware'; * @returns The JSON-RPC response. */ export async function getNetworkVersionHandler( - _request: JsonRpcRequest, + request: JsonRpcRequest & { scope?: CaipChainId }, response: PendingJsonRpcResponse, _next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback, hooks: Pick, ) { - const hexChainId = hooks.getSimulationState().chain.chainId; - response.result = hexToBigInt(hexChainId).toString(10); + const requestScope = request.scope && parseCaipChainId(request.scope); + response.result = requestScope + ? BigInt(requestScope.reference).toString(10) + : hexToBigInt(hooks.getSimulationState().chain.chainId).toString(10); return end(); } diff --git a/packages/snaps-simulation/src/middleware/multichain/create-session.ts b/packages/snaps-simulation/src/middleware/multichain/create-session.ts new file mode 100644 index 0000000000..d7748107f3 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/create-session.ts @@ -0,0 +1,58 @@ +import type { Caip25CaveatValue } from '@metamask/chain-agnostic-permission'; +import { setEthAccounts } from '@metamask/chain-agnostic-permission'; +import type { RequestedPermissions } from '@metamask/permission-controller'; +import { rpcErrors } from '@metamask/rpc-errors'; +import { isObject, type JsonRpcRequest } from '@metamask/utils'; + +import { getSessionScopes } from './utils'; +import { getSimulationAccount } from '../internal-methods/accounts'; + +export type CreateSessionHandlerHooks = { + grantPermissions: (permissions: RequestedPermissions) => void; + getMnemonic: () => Promise; +}; + +/** + * A handler that implements a simplified version of `wallet_createSession`. + * + * @param request - Incoming JSON-RPC request. + * @param hooks - The method hooks. + * @returns The JSON-RPC response. + */ +export async function createSessionHandler( + request: JsonRpcRequest, + hooks: CreateSessionHandlerHooks, +) { + if (!isObject(request.params)) { + throw rpcErrors.invalidParams({ data: { request } }); + } + + const caveat = { + requiredScopes: request.params.requiredScopes ?? {}, + optionalScopes: request.params.optionalScopes ?? {}, + sessionProperties: {}, + isMultichainOrigin: true, + } as Caip25CaveatValue; + + const mnemonic = await hooks.getMnemonic(); + const ethereumAccounts = [await getSimulationAccount(mnemonic)]; + + const caveatWithAccounts = setEthAccounts(caveat, ethereumAccounts); + + const permissions = { + 'endowment:caip25': { + caveats: [ + { + type: 'authorizedScopes', + value: caveatWithAccounts, + }, + ], + }, + } as RequestedPermissions; + + hooks.grantPermissions(permissions); + + const sessionScopes = getSessionScopes(caveatWithAccounts); + + return { sessionScopes }; +} diff --git a/packages/snaps-simulation/src/middleware/multichain/get-session.ts b/packages/snaps-simulation/src/middleware/multichain/get-session.ts new file mode 100644 index 0000000000..bf0880873d --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/get-session.ts @@ -0,0 +1,38 @@ +import type { Caip25CaveatValue } from '@metamask/chain-agnostic-permission'; +import { + Caip25CaveatType, + Caip25EndowmentPermissionName, +} from '@metamask/chain-agnostic-permission'; +import type { Caveat } from '@metamask/permission-controller'; +import type { Json, JsonRpcRequest } from '@metamask/utils'; + +import { getSessionScopes } from './utils'; + +export type GetSessionHandlerHooks = { + getCaveat: ( + permission: string, + caveatType: string, + ) => Caveat | undefined; +}; + +/** + * A handler that implements a simplified version of `wallet_getSession`. + * + * @param _request - Incoming JSON-RPC request. Ignored for this specific + * handler. + * @param hooks - The method hooks. + * @returns The JSON-RPC response. + */ +export function getSessionHandler( + _request: JsonRpcRequest, + hooks: GetSessionHandlerHooks, +) { + const caveat = hooks.getCaveat( + Caip25EndowmentPermissionName, + Caip25CaveatType, + ) as Caveat; + + const sessionScopes = caveat ? getSessionScopes(caveat.value) : {}; + + return { sessionScopes }; +} diff --git a/packages/snaps-simulation/src/middleware/multichain/index.ts b/packages/snaps-simulation/src/middleware/multichain/index.ts new file mode 100644 index 0000000000..911fc1f568 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/index.ts @@ -0,0 +1,4 @@ +export * from './create-session'; +export * from './get-session'; +export * from './invoke-method'; +export * from './middleware'; diff --git a/packages/snaps-simulation/src/middleware/multichain/invoke-method.ts b/packages/snaps-simulation/src/middleware/multichain/invoke-method.ts new file mode 100644 index 0000000000..2950962857 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/invoke-method.ts @@ -0,0 +1,56 @@ +import type { Caip25CaveatValue } from '@metamask/chain-agnostic-permission'; +import { + Caip25CaveatType, + Caip25EndowmentPermissionName, +} from '@metamask/chain-agnostic-permission'; +import type { Caveat } from '@metamask/permission-controller'; +import { providerErrors, rpcErrors } from '@metamask/rpc-errors'; +import { + type CaipChainId, + isObject, + type Json, + type JsonRpcRequest, +} from '@metamask/utils'; + +import { getSessionScopes } from './utils'; + +export type InvokeMethodHandlerHooks = { + getCaveat: ( + permission: string, + caveatType: string, + ) => Caveat | undefined; +}; + +/** + * A handler that implements a simplified version of `wallet_invokeMethod`. + * + * @param request - Incoming JSON-RPC request. + * @param hooks - The method hooks. + * @returns Nothing. + */ +export async function invokeMethodHandler( + request: JsonRpcRequest & { scope?: CaipChainId }, + hooks: InvokeMethodHandlerHooks, +) { + if (!isObject(request.params)) { + throw rpcErrors.invalidParams({ data: { request } }); + } + + // TODO: Struct? + const { request: wrappedRequest, scope } = request.params as any; + + const caveat = hooks.getCaveat( + Caip25EndowmentPermissionName, + Caip25CaveatType, + ) as Caveat; + + const sessionScopes = getSessionScopes(caveat.value); + + if (!sessionScopes[scope]?.methods.includes(wrappedRequest.method)) { + throw providerErrors.unauthorized(); + } + + request.method = wrappedRequest.method; + request.params = wrappedRequest.params; + request.scope = scope; +} diff --git a/packages/snaps-simulation/src/middleware/multichain/middleware.test.ts b/packages/snaps-simulation/src/middleware/multichain/middleware.test.ts new file mode 100644 index 0000000000..98a976670f --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/middleware.test.ts @@ -0,0 +1,98 @@ +import { JsonRpcEngine } from '@metamask/json-rpc-engine'; +import { mnemonicPhraseToBytes } from '@metamask/key-tree'; + +import { createMultichainMiddleware } from './middleware'; +import { DEFAULT_SRP } from '../../constants'; + +/** + * Sets up the JSON-RPC engine and middleware for testing. + * + * @param isMultichain - Whether to enable the multichain API or not. + * @returns The JSON-RPC engine. + */ +function createMiddleware(isMultichain: boolean = true) { + const hooks = { + getMnemonic: jest + .fn() + .mockResolvedValue(mnemonicPhraseToBytes(DEFAULT_SRP)), + getCaveat: jest.fn(), + grantPermissions: jest.fn(), + }; + const middleware = createMultichainMiddleware(isMultichain, hooks); + const engine = new JsonRpcEngine(); + engine.push(middleware); + return { engine, hooks }; +} + +describe('Multichain Middleware', () => { + it('routes requests to multichain handlers', async () => { + const { engine } = createMiddleware(); + const result = await engine.handle({ + jsonrpc: '2.0', + id: 1, + method: 'wallet_getSession', + }); + + expect(result).toStrictEqual( + expect.objectContaining({ result: { sessionScopes: {} } }), + ); + }); + + it('throws when receiving non-multichain requests', async () => { + const { engine } = createMiddleware(); + const result = await engine.handle({ + jsonrpc: '2.0', + id: 1, + method: 'eth_call', + }); + + expect(result).toStrictEqual( + expect.objectContaining({ + error: { + code: -32601, + message: 'The method does not exist / is not available.', + stack: expect.any(String), + }, + }), + ); + }); + + it('throws when receiving multichain requests while multichain is disabled', async () => { + const { engine } = createMiddleware(false); + const result = await engine.handle({ + jsonrpc: '2.0', + id: 1, + method: 'wallet_getSession', + }); + + expect(result).toStrictEqual( + expect.objectContaining({ + error: { + code: -32601, + message: 'The method does not exist / is not available.', + stack: expect.any(String), + }, + }), + ); + }); + + it('passes non-multichain requests to the next middleware', async () => { + const { engine } = createMiddleware(false); + const result = await engine.handle({ + jsonrpc: '2.0', + id: 1, + method: 'eth_call', + }); + + expect(result).toStrictEqual( + expect.objectContaining({ + error: expect.objectContaining({ + message: expect.stringContaining( + 'JsonRpcEngine: Response has no error or result for request:', + ), + stack: expect.any(String), + }), + }), + ); + }); +}); diff --git a/packages/snaps-simulation/src/middleware/multichain/middleware.ts b/packages/snaps-simulation/src/middleware/multichain/middleware.ts new file mode 100644 index 0000000000..8a5d1f1704 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/middleware.ts @@ -0,0 +1,73 @@ +import type { + AsyncJsonRpcEngineNextCallback, + JsonRpcMiddleware, +} from '@metamask/json-rpc-engine'; +import { createAsyncMiddleware } from '@metamask/json-rpc-engine'; +import { rpcErrors } from '@metamask/rpc-errors'; +import type { + Json, + JsonRpcParams, + JsonRpcRequest, + PendingJsonRpcResponse, +} from '@metamask/utils'; + +import { createSessionHandler } from './create-session'; +import { getSessionHandler } from './get-session'; +import { invokeMethodHandler } from './invoke-method'; +import type { MultichainMiddlewareHooks } from '../../simulation'; + +const multichainHandlers = { + /* eslint-disable @typescript-eslint/naming-convention */ + wallet_createSession: createSessionHandler, + wallet_invokeMethod: invokeMethodHandler, + wallet_getSession: getSessionHandler, + /* eslint-enable @typescript-eslint/naming-convention */ +}; + +/** + * Create a middleware that handles requests to the multichain API. + * + * @param isMultichain - Whether the JSON-RPC pipeline has multichain enabled. + * @param hooks - Hooks required to execute the middleware RPC methods. + * @returns The middleware. + */ +export function createMultichainMiddleware( + isMultichain: boolean, + hooks: MultichainMiddlewareHooks, +): JsonRpcMiddleware { + return createAsyncMiddleware( + async ( + request: JsonRpcRequest, + response: PendingJsonRpcResponse, + next: AsyncJsonRpcEngineNextCallback, + ) => { + const handler = + multichainHandlers[request.method as keyof typeof multichainHandlers]; + + const isMultichainRequest = handler !== undefined; + + if (!isMultichain && isMultichainRequest) { + throw rpcErrors.methodNotFound(); + } + + // If disabled, this middleware functions as a passthrough. + if (!isMultichain && !isMultichainRequest) { + await next(); + return; + } + + if (isMultichain && !isMultichainRequest) { + throw rpcErrors.methodNotFound(); + } + + const result = await handler(request, hooks); + + if (result) { + response.result = result; + return; + } + + await next(); + }, + ); +} diff --git a/packages/snaps-simulation/src/middleware/multichain/utils.ts b/packages/snaps-simulation/src/middleware/multichain/utils.ts new file mode 100644 index 0000000000..1ca2fd1c38 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain/utils.ts @@ -0,0 +1,34 @@ +import type { + Caip25CaveatValue, + InternalScopeObject, +} from '@metamask/chain-agnostic-permission'; +import { getSessionScopes as getMergedSessionScopes } from '@metamask/chain-agnostic-permission'; +import type { CaipChainId } from '@metamask/utils'; + +/** + * Get a session scopes value that can be used for simulation, by injecting non-EVM methods into the returned session scopes + * directly from the caveat. + * + * @param value The caveat value. + * @returns The session scopes. + */ +export function getSessionScopes(value: Caip25CaveatValue) { + const mergedScopes = { + ...value.requiredScopes, + ...value.optionalScopes, + } as Record; + + const nonEvmMethods = Object.keys(mergedScopes).reduce< + Record + >((accumulator, scope) => { + const castScope = scope as CaipChainId | 'wallet'; + if (!castScope.startsWith('eip155') && castScope !== 'wallet') { + accumulator[castScope] = mergedScopes[castScope].methods; + } + return accumulator; + }, {}); + + return getMergedSessionScopes(value, { + getNonEvmSupportedMethods: (scope) => nonEvmMethods[scope] ?? [], + }); +} diff --git a/packages/snaps-simulation/src/middleware/provider.ts b/packages/snaps-simulation/src/middleware/provider.ts index f457037873..26114d9b19 100644 --- a/packages/snaps-simulation/src/middleware/provider.ts +++ b/packages/snaps-simulation/src/middleware/provider.ts @@ -1,8 +1,13 @@ import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine'; import { createAsyncMiddleware } from '@metamask/json-rpc-engine'; import { rpcErrors, serializeCause } from '@metamask/rpc-errors'; -import type { Json, JsonRpcParams } from '@metamask/utils'; -import { hasProperty, hexToBigInt } from '@metamask/utils'; +import type { + CaipChainId, + Json, + JsonRpcParams, + JsonRpcRequest, +} from '@metamask/utils'; +import { hasProperty, hexToBigInt, parseCaipChainId } from '@metamask/utils'; import { InfuraProvider } from 'ethers'; import type { Store } from '../store'; @@ -17,25 +22,45 @@ import { getChainId } from '../store'; export function createProviderMiddleware( store: Store, ): JsonRpcMiddleware { - return createAsyncMiddleware(async (request, response) => { - try { - const chainId = getChainId(store.getState()); - const provider = new InfuraProvider(hexToBigInt(chainId)); + return createAsyncMiddleware( + async ( + request: JsonRpcRequest & { scope?: CaipChainId }, + response, + next, + ) => { + const requestScope = request.scope && parseCaipChainId(request.scope); + const isEvm = requestScope ? requestScope.namespace === 'eip155' : true; - const result = await provider.send(request.method, request.params ?? []); - response.result = result; - } catch (error) { - if (hasProperty(error, 'info') && hasProperty(error.info, 'error')) { - response.error = error.info.error; + if (!isEvm) { + await next(); return; } - if (hasProperty(error, 'error')) { - response.error = error.error; - return; + + const chainId = requestScope + ? BigInt(requestScope.reference) + : hexToBigInt(getChainId(store.getState())); + + try { + const provider = new InfuraProvider(chainId); + + const result = await provider.send( + request.method, + request.params ?? [], + ); + response.result = result; + } catch (error) { + if (hasProperty(error, 'info') && hasProperty(error.info, 'error')) { + response.error = error.info.error; + return; + } + if (hasProperty(error, 'error')) { + response.error = error.error; + return; + } + response.error = rpcErrors.internal({ + data: { cause: serializeCause(error) }, + }); } - response.error = rpcErrors.internal({ - data: { cause: serializeCause(error) }, - }); - } - }); + }, + ); } diff --git a/packages/snaps-simulation/src/simulation.ts b/packages/snaps-simulation/src/simulation.ts index 5a95ec994f..7bd1099ba8 100644 --- a/packages/snaps-simulation/src/simulation.ts +++ b/packages/snaps-simulation/src/simulation.ts @@ -7,6 +7,11 @@ import type { NamespacedName, } from '@metamask/messenger'; import { MOCK_ANY_NAMESPACE, Messenger } from '@metamask/messenger'; +import { + PermissionDoesNotExistError, + type Caveat, + type RequestedPermissions, +} from '@metamask/permission-controller'; import { PhishingDetectorResultType } from '@metamask/phishing-controller'; import type { AbstractExecutionService } from '@metamask/snaps-controllers'; import { @@ -347,6 +352,33 @@ export type PermittedMiddlewareHooks = { endTrace(request: EndTraceRequest): void; }; +export type MultichainMiddlewareHooks = { + /** + * A hook that returns the user's secret recovery phrase. + * + * @returns The user's secret recovery phrase. + */ + getMnemonic: () => Promise; + /** + * A hook that retrieves a caveat for a given permission. + * + * @param permission - The permission name. + * @param caveatType - The caveat type. + * @returns The caveat, if it exists. + */ + getCaveat: ( + permission: string, + caveatType: string, + ) => Caveat | undefined; + + /** + * A hook that grants permissions to the origin. + * + * @param permissions - The permissions. + */ + grantPermissions: (permissions: RequestedPermissions) => void; +}; + /** * Install a Snap in a simulated environment. This will fetch the Snap files, * create a Redux store, set up the controllers and JSON-RPC stack, register the @@ -394,6 +426,7 @@ export async function installSnap< // Set up controllers and JSON-RPC stack. const restrictedHooks = getRestrictedHooks(options, store, runSaga); + const permittedHooks = getPermittedHooks( snapId, snapFiles, @@ -401,20 +434,40 @@ export async function installSnap< runSaga, ); - const { subjectMetadataController, permissionController } = getControllers({ - controllerMessenger, - hooks: restrictedHooks, - runSaga, + const multichainHooks = getMultichainHooks( + snapId, options, + controllerMessenger, + ); + + const { subjectMetadataController, permissionController } = + await getControllers({ + controllerMessenger, + hooks: restrictedHooks, + runSaga, + options, + }); + + const permissionMiddleware = permissionController.createPermissionMiddleware({ + origin: snapId, }); const engine = createJsonRpcEngine({ store, restrictedHooks, permittedHooks, - permissionMiddleware: permissionController.createPermissionMiddleware({ - origin: snapId, - }), + permissionMiddleware, + multichainHooks, + isMultichain: false, + }); + + const multichainEngine = createJsonRpcEngine({ + store, + restrictedHooks, + permittedHooks, + permissionMiddleware, + multichainHooks, + isMultichain: true, }); // Create execution service. @@ -437,6 +490,23 @@ export async function installSnap< logError(`Provider stream failure.`, error); } }); + + const multichainStream = mux.createStream('metamask-multichain-provider'); + const multichainProviderStream = createEngineStream({ + engine: multichainEngine, + }); + + /* istanbul ignore next 2 */ + pipeline( + multichainStream, + multichainProviderStream, + multichainStream, + (error) => { + if (error && !error.message?.match('Premature close')) { + logError(`Provider stream failure.`, error); + } + }, + ); }, }); @@ -568,6 +638,45 @@ export function getPermittedHooks( }; } +/** + * Get the hooks for the multichain middleware simulation. + * + * @param snapId - The Snap ID. + * @param options - The simulation options. + * @param controllerMessenger - The controller messenger. + * @returns The hooks for the middleware. + */ +export function getMultichainHooks( + snapId: SnapId, + options: SimulationOptions, + controllerMessenger: RootControllerMessenger, +): MultichainMiddlewareHooks { + return { + getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase), + getCaveat: (permission: string, caveatType: string) => { + try { + return controllerMessenger.call( + 'PermissionController:getCaveat', + snapId, + permission, + caveatType, + ); + } catch (error) { + if (error instanceof PermissionDoesNotExistError) { + return undefined; + } + throw error; + } + }, + grantPermissions: (approvedPermissions: RequestedPermissions) => { + controllerMessenger.call('PermissionController:grantPermissions', { + subject: { origin: snapId }, + approvedPermissions, + }); + }, + }; +} + /** * Register mocked action handlers. * diff --git a/packages/test-snaps/package.json b/packages/test-snaps/package.json index c141cc294e..bb9cb0745c 100644 --- a/packages/test-snaps/package.json +++ b/packages/test-snaps/package.json @@ -66,6 +66,7 @@ "@metamask/lifecycle-hooks-example-snap": "workspace:^", "@metamask/localization-example-snap": "workspace:^", "@metamask/manage-state-example-snap": "workspace:^", + "@metamask/multichain-provider-example-snap": "workspace:^", "@metamask/name-lookup-example-snap": "workspace:^", "@metamask/network-example-snap": "workspace:^", "@metamask/notification-example-snap": "workspace:^", diff --git a/packages/test-snaps/src/features/snaps/index.ts b/packages/test-snaps/src/features/snaps/index.ts index 601569b976..dac2b82224 100644 --- a/packages/test-snaps/src/features/snaps/index.ts +++ b/packages/test-snaps/src/features/snaps/index.ts @@ -19,6 +19,7 @@ export * from './jsx'; export * from './lifecycle-hooks'; export * from './legacy-state'; export * from './multi-install'; +export * from './multichain-provider'; export * from './name-lookup'; export * from './network-access'; export * from './notifications'; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/MultichainProvider.tsx b/packages/test-snaps/src/features/snaps/multichain-provider/MultichainProvider.tsx new file mode 100644 index 0000000000..4c6e6819a2 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/MultichainProvider.tsx @@ -0,0 +1,96 @@ +import { logError } from '@metamask/snaps-utils'; +import type { CaipChainId } from '@metamask/utils'; +import type { FunctionComponent } from 'react'; +import { useState } from 'react'; +import { Button, ButtonGroup } from 'react-bootstrap'; + +import { SignMessage, SignTypedData, SwitchChain } from './components'; +import { + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, + MULTICHAIN_PROVIDER_VERSION, +} from './constants'; +import { useInvokeMutation } from '../../../api'; +import { Result, Snap } from '../../../components'; +import { getSnapId } from '../../../utils'; + +export const MultichainProvider: FunctionComponent = () => { + const [invokeSnap, { isLoading, data, error }] = useInvokeMutation(); + const [scope, setScope] = useState('eip155:1'); + + const handleSubmit = (method: string) => { + invokeSnap({ + snapId: getSnapId( + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, + ), + method, + params: { + scope, + }, + }).catch(logError); + }; + + const handleCreateSession = () => handleSubmit('createSession'); + const handleGetChainId = () => handleSubmit('getChainId'); + const handleGetAccounts = () => handleSubmit('getAccounts'); + const handleGetGenesisHash = () => handleSubmit('getGenesisHash'); + + return ( + + + + + {scope.startsWith('eip155') && ( + + )} + + + + + + {JSON.stringify(data, null, 2)} + {JSON.stringify(error, null, 2)} + + + + {scope.startsWith('eip155') && } + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/components/SignMessage.tsx b/packages/test-snaps/src/features/snaps/multichain-provider/components/SignMessage.tsx new file mode 100644 index 0000000000..3fdf36e0e2 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/components/SignMessage.tsx @@ -0,0 +1,73 @@ +import { logError } from '@metamask/snaps-utils'; +import type { CaipChainId } from '@metamask/utils'; +import type { ChangeEvent, FormEvent, FunctionComponent } from 'react'; +import { useState } from 'react'; +import { Button, Form } from 'react-bootstrap'; + +import { useInvokeMutation } from '../../../../api'; +import { Result } from '../../../../components'; +import { getSnapId } from '../../../../utils'; +import { + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, +} from '../constants'; + +export type SignMessageProps = { + scope: CaipChainId; +}; + +export const SignMessage: FunctionComponent = ({ scope }) => { + const [message, setMessage] = useState(''); + const [invokeSnap, { isLoading, data, error }] = useInvokeMutation(); + + const handleChange = (event: ChangeEvent) => { + setMessage(event.target.value); + }; + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + + invokeSnap({ + snapId: getSnapId( + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, + ), + method: 'signMessage', + params: { + message, + scope, + }, + }).catch(logError); + }; + + return ( + <> +

Message Signing

+
+ Message + + + + + + + {JSON.stringify(data, null, 2)} + {JSON.stringify(error, null, 2)} + + + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/components/SignTypedData.tsx b/packages/test-snaps/src/features/snaps/multichain-provider/components/SignTypedData.tsx new file mode 100644 index 0000000000..70698808c7 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/components/SignTypedData.tsx @@ -0,0 +1,75 @@ +import { logError } from '@metamask/snaps-utils'; +import type { CaipChainId } from '@metamask/utils'; +import type { ChangeEvent, FormEvent, FunctionComponent } from 'react'; +import { useState } from 'react'; +import { Button, Form } from 'react-bootstrap'; + +import { useInvokeMutation } from '../../../../api'; +import { Result } from '../../../../components'; +import { getSnapId } from '../../../../utils'; +import { + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, +} from '../constants'; + +export type SignTypedDataProps = { + scope: CaipChainId; +}; + +export const SignTypedData: FunctionComponent = ({ + scope, +}) => { + const [message, setMessage] = useState(''); + const [invokeSnap, { isLoading, data, error }] = useInvokeMutation(); + + const handleChange = (event: ChangeEvent) => { + setMessage(event.target.value); + }; + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + + invokeSnap({ + snapId: getSnapId( + MULTICHAIN_PROVIDER_SNAP_ID, + MULTICHAIN_PROVIDER_SNAP_PORT, + ), + method: 'signTypedData', + params: { + message, + scope, + }, + }).catch(logError); + }; + + return ( + <> +

Sign Typed Data

+
+ Message + + + + + + + {JSON.stringify(data, null, 2)} + {JSON.stringify(error, null, 2)} + + + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/components/SwitchChain.tsx b/packages/test-snaps/src/features/snaps/multichain-provider/components/SwitchChain.tsx new file mode 100644 index 0000000000..323c61a5c6 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/components/SwitchChain.tsx @@ -0,0 +1,29 @@ +import type { CaipChainId } from '@metamask/utils'; +import type { ChangeEvent, FunctionComponent } from 'react'; + +export type SwitchChainProps = { + onChange: (chainId: CaipChainId) => void; +}; + +export const SwitchChain: FunctionComponent = ({ + onChange, +}) => { + const handleChange = (event: ChangeEvent) => { + onChange(event.target.value as CaipChainId); + }; + + return ( + <> +

Select chain

+ + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/components/index.ts b/packages/test-snaps/src/features/snaps/multichain-provider/components/index.ts new file mode 100644 index 0000000000..5f58fe7608 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/components/index.ts @@ -0,0 +1,3 @@ +export * from './SignMessage'; +export * from './SignTypedData'; +export * from './SwitchChain'; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/constants.ts b/packages/test-snaps/src/features/snaps/multichain-provider/constants.ts new file mode 100644 index 0000000000..9da3800a38 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/constants.ts @@ -0,0 +1,6 @@ +import packageJson from '@metamask/multichain-provider-example-snap/package.json'; + +export const MULTICHAIN_PROVIDER_SNAP_ID = + 'npm:@metamask/multichain-provider-example-snap'; +export const MULTICHAIN_PROVIDER_SNAP_PORT = 8036; +export const MULTICHAIN_PROVIDER_VERSION = packageJson.version; diff --git a/packages/test-snaps/src/features/snaps/multichain-provider/index.ts b/packages/test-snaps/src/features/snaps/multichain-provider/index.ts new file mode 100644 index 0000000000..f337f07f51 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/index.ts @@ -0,0 +1 @@ +export * from './MultichainProvider'; diff --git a/yarn.lock b/yarn.lock index 126f205818..b64481892d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2830,6 +2830,13 @@ __metadata: languageName: node linkType: hard +"@metamask/api-specs@npm:^0.14.0": + version: 0.14.0 + resolution: "@metamask/api-specs@npm:0.14.0" + checksum: 10/6caad5e233c12b87f25313fe1e0fb35af6ad9f0ef49e105b36a1826bd8b611a9335642920ddb6c556343375db4b02138a32598b7185392e50050ae7f390e0e7d + languageName: node + linkType: hard + "@metamask/approval-controller@npm:^8.0.0": version: 8.0.0 resolution: "@metamask/approval-controller@npm:8.0.0" @@ -2976,6 +2983,20 @@ __metadata: languageName: node linkType: hard +"@metamask/chain-agnostic-permission@npm:^1.4.0": + version: 1.4.0 + resolution: "@metamask/chain-agnostic-permission@npm:1.4.0" + dependencies: + "@metamask/api-specs": "npm:^0.14.0" + "@metamask/controller-utils": "npm:^11.17.0" + "@metamask/permission-controller": "npm:^12.2.0" + "@metamask/rpc-errors": "npm:^7.0.2" + "@metamask/utils": "npm:^11.9.0" + lodash: "npm:^4.17.21" + checksum: 10/fecd0ead0423b283519d8e2a4c783621a4323c961e7ff33653ef0c7fe4a0b3b039918b082c76267a1beb3c11178283a0c1b7e0dc18b3030e5e2019e7cbd10080 + languageName: node + linkType: hard + "@metamask/client-status-example-snap@workspace:^, @metamask/client-status-example-snap@workspace:packages/examples/packages/client-status": version: 0.0.0-use.local resolution: "@metamask/client-status-example-snap@workspace:packages/examples/packages/client-status" @@ -3758,6 +3779,31 @@ __metadata: languageName: node linkType: hard +"@metamask/multichain-provider-example-snap@workspace:^, @metamask/multichain-provider-example-snap@workspace:packages/examples/packages/multichain-provider": + version: 0.0.0-use.local + resolution: "@metamask/multichain-provider-example-snap@workspace:packages/examples/packages/multichain-provider" + dependencies: + "@jest/globals": "npm:^29.5.0" + "@lavamoat/allow-scripts": "npm:^3.4.1" + "@metamask/auto-changelog": "npm:^5.0.2" + "@metamask/snaps-cli": "workspace:^" + "@metamask/snaps-jest": "workspace:^" + "@metamask/snaps-sdk": "workspace:^" + "@metamask/utils": "npm:^11.9.0" + "@swc/core": "npm:1.11.31" + "@swc/jest": "npm:^0.2.38" + "@types/node": "npm:18.14.2" + deepmerge: "npm:^4.2.2" + depcheck: "npm:^1.4.7" + eslint: "npm:^9.11.0" + jest: "npm:^29.0.2" + jest-silent-reporter: "npm:^0.6.0" + prettier: "npm:^3.3.3" + ts-node: "npm:^10.9.1" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/name-lookup-example-snap@workspace:^, @metamask/name-lookup-example-snap@workspace:packages/examples/packages/name-lookup": version: 0.0.0-use.local resolution: "@metamask/name-lookup-example-snap@workspace:packages/examples/packages/name-lookup" @@ -4494,6 +4540,7 @@ __metadata: dependencies: "@lavamoat/allow-scripts": "npm:^3.4.1" "@metamask/auto-changelog": "npm:^5.0.2" + "@metamask/chain-agnostic-permission": "npm:^1.4.0" "@metamask/json-rpc-engine": "npm:^10.1.0" "@metamask/json-rpc-middleware-stream": "npm:^8.0.8" "@metamask/key-tree": "npm:^10.1.1" @@ -4656,6 +4703,7 @@ __metadata: "@metamask/lifecycle-hooks-example-snap": "workspace:^" "@metamask/localization-example-snap": "workspace:^" "@metamask/manage-state-example-snap": "workspace:^" + "@metamask/multichain-provider-example-snap": "workspace:^" "@metamask/name-lookup-example-snap": "workspace:^" "@metamask/network-example-snap": "workspace:^" "@metamask/notification-example-snap": "workspace:^"