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..da9116130a --- /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/compare/@metamask/multichain-provider-example-snap@HEAD 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..6fae95b0d2 --- /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.8.1" + }, + "devDependencies": { + "@jest/globals": "^29.5.0", + "@lavamoat/allow-scripts": "^3.4.0", + "@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..f07977b4b4 --- /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": "RyR1kz1QopXlnxzsiEeZ701kfshofBBz30eYJu7MOdQ=", + "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.1.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..8e64d9b6eb --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/index.test.ts @@ -0,0 +1,95 @@ +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('getChainId', () => { + const MOCK_CHAIN_ID = '0x01'; // Ethereum Mainnet + + it('returns the current network version', async () => { + const { request } = await installSnap(); + + const response = await request({ + method: 'getChainId', + }); + + expect(response).toRespondWith(MOCK_CHAIN_ID); + }); + }); + + describe('getAccounts', () => { + it('returns the addresses granted access to by the user', async () => { + const { request } = await installSnap(); + + const response = await request({ + method: 'getAccounts', + }); + + // Currently, snaps-jest will always return this account. + expect(response).toRespondWith([ + '0xc6d5a3c98ec9073b54fa0969957bd582e8d874bf', + ]); + }); + }); + + describe('signMessage', () => { + const MOCK_SIGNATURE = + '0x16f672a12220dc4d9e27671ef580cfc1397a9a4d5ee19eadea46c0f350b2f72a4922be7c1f16ed9b03ef1d3351eac469e33accf5a36194b1d88923701c2b163f1b'; + + it('returns a signature', async () => { + const { request, mockJsonRpc } = await installSnap(); + + // 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: { message: 'foo' }, + }); + + expect(response).toRespondWith(MOCK_SIGNATURE); + }); + }); + + describe('signTypedData', () => { + const MOCK_SIGNATURE = + '0x01b37713300d99fecf0274bcb0dfb586a23d56c4bf2ed700c5ecf4ada7a2a14825e7b1212b1cc49c9440c375337561f2b7a6e639ba25be6a6f5a16f60e6931d31c'; + + it('returns a signature', async () => { + const { request, mockJsonRpc } = await installSnap(); + + // 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: { message: 'foo' }, + }); + + expect(response).toRespondWith(MOCK_SIGNATURE); + }); + }); +}); 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..7334a8b11c --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/index.ts @@ -0,0 +1,108 @@ +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'; + +// TODO: Consider letting the permission create the "session" +async function createSession() { + const optionalScopes = { + 'eip155:1': { + methods: ['personal_sign', 'eth_signTypedData_v4'], + notifications: [], + accounts: [], + }, + 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': { + methods: ['signMessage'], + notifications: [], + accounts: [], + }, + }; + // TODO: Fix snap.request types + return await (snap as any).request({ + method: 'wallet_createSession', + params: { + optionalScopes, + }, + }); +} + +async function getAccounts(scope: CaipChainId) { + const session = await await (snap as any).request({ + method: 'wallet_getSession', + }); + + return session.sessionScopes[scope]?.accounts ?? []; +} + +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: + * + * - `getChainId`: Get the current Ethereum chain ID as a string. + * - `getAccounts`: Get the Ethereum accounts that the snap has access to. + * - `personalSign`: Sign a message using an Ethereum account. + * - `signTypedData` Sign a struct using an Ethereum account. + * + * @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.signMessage(accounts[0], params.message); + } + + 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..38c2c989bc --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/base.ts @@ -0,0 +1,37 @@ +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; +} + +export async function invokeMethod( + scope: CaipChainId, + request: Omit, +): Promise { + // TODO: Fix snap.request types + return (await (snap as any).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..12d365ab6e --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/evm.ts @@ -0,0 +1,101 @@ +import type { CaipAccountId, Hex } from '@metamask/utils'; +import { + 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, + }, + }, + ], + }); + } +} 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..2c78cb4762 --- /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'; \ No newline at end of file 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..5d164e98d7 --- /dev/null +++ b/packages/examples/packages/multichain-provider/src/modules/sol.ts @@ -0,0 +1,31 @@ +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(); + } +} 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/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/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-simulation/src/methods/specifications.test.ts b/packages/snaps-simulation/src/methods/specifications.test.ts index 8881eab17a..1c66594739 100644 --- a/packages/snaps-simulation/src/methods/specifications.test.ts +++ b/packages/snaps-simulation/src/methods/specifications.test.ts @@ -104,6 +104,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", diff --git a/packages/snaps-simulation/src/middleware/engine.ts b/packages/snaps-simulation/src/middleware/engine.ts index ab3639d747..be00938201 100644 --- a/packages/snaps-simulation/src/middleware/engine.ts +++ b/packages/snaps-simulation/src/middleware/engine.ts @@ -13,6 +13,7 @@ import type { RestrictedMiddlewareHooks, } from '../simulation'; import type { Store } from '../store'; +import { createMultichainMiddleware } from './multichain'; export type CreateJsonRpcEngineOptions = { store: Store; @@ -20,6 +21,7 @@ export type CreateJsonRpcEngineOptions = { permittedHooks: PermittedMiddlewareHooks; permissionMiddleware: JsonRpcMiddleware; endpoint?: string; + isMultichain: boolean; }; /** @@ -42,10 +44,13 @@ export function createJsonRpcEngine({ permittedHooks, permissionMiddleware, endpoint = DEFAULT_JSON_RPC_ENDPOINT, + isMultichain, }: CreateJsonRpcEngineOptions) { const engine = new JsonRpcEngine(); engine.push(createMockMiddleware(store)); + engine.push(createMultichainMiddleware(isMultichain)); + // The hooks here do not match the hooks used by the clients, so this // middleware should not be used outside of the simulation environment. engine.push(createInternalMethodsMiddleware(restrictedHooks)); diff --git a/packages/snaps-simulation/src/middleware/internal-methods/middleware.ts b/packages/snaps-simulation/src/middleware/internal-methods/middleware.ts index 6465e2a048..ecd167a436 100644 --- a/packages/snaps-simulation/src/middleware/internal-methods/middleware.ts +++ b/packages/snaps-simulation/src/middleware/internal-methods/middleware.ts @@ -7,6 +7,7 @@ import { getChainIdHandler } from './chain-id'; import { getNetworkVersionHandler } from './net-version'; import { getProviderStateHandler } from './provider-state'; import { getSwitchEthereumChainHandler } from './switch-ethereum-chain'; +import { getSessionHandler } from './multichain'; export type InternalMethodsMiddlewareHooks = { /** @@ -25,6 +26,7 @@ const methodHandlers = { eth_chainId: getChainIdHandler, net_version: getNetworkVersionHandler, wallet_switchEthereumChain: getSwitchEthereumChainHandler, + wallet_getSession: getSessionHandler, /* eslint-enable @typescript-eslint/naming-convention */ }; @@ -50,7 +52,7 @@ export function createInternalMethodsMiddleware( if (handler) { try { // Implementations may or may not be async, so we must await them. - return await handler(request, response, next, end, hooks); + return await handler(request as any, response as any, next, end, hooks as any); } catch (error: any) { logError(error); return end(error); diff --git a/packages/snaps-simulation/src/middleware/internal-methods/multichain/get-session.ts b/packages/snaps-simulation/src/middleware/internal-methods/multichain/get-session.ts new file mode 100644 index 0000000000..9ce3fe051d --- /dev/null +++ b/packages/snaps-simulation/src/middleware/internal-methods/multichain/get-session.ts @@ -0,0 +1,22 @@ +import type { + JsonRpcEngineEndCallback, + JsonRpcEngineNextCallback, +} from '@metamask/json-rpc-engine'; +import { Caveat } from '@metamask/permission-controller'; +import type { Json, JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils'; + +export type GetSessionHandlerHooks = { + getCaveat: (permission: string, caveatType: string) => Caveat; +}; + +export async function getSessionHandler( + _request: JsonRpcRequest, + response: PendingJsonRpcResponse, + _next: JsonRpcEngineNextCallback, + end: JsonRpcEngineEndCallback, + hooks: GetSessionHandlerHooks, +) { + + response.result = hooks.getCaveat('endowment:caip25', "authorizedScopes"); + return end(); +} diff --git a/packages/snaps-simulation/src/middleware/internal-methods/multichain/index.ts b/packages/snaps-simulation/src/middleware/internal-methods/multichain/index.ts new file mode 100644 index 0000000000..107f4cc3b1 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/internal-methods/multichain/index.ts @@ -0,0 +1 @@ +export * from './get-session'; diff --git a/packages/snaps-simulation/src/middleware/multichain.ts b/packages/snaps-simulation/src/middleware/multichain.ts new file mode 100644 index 0000000000..c842a63aa7 --- /dev/null +++ b/packages/snaps-simulation/src/middleware/multichain.ts @@ -0,0 +1,24 @@ +import { createAsyncMiddleware, JsonRpcMiddleware } from "@metamask/json-rpc-engine"; +import { Json, JsonRpcParams } from "@metamask/utils"; +import { rpcErrors } from '@metamask/rpc-errors'; + +export function createMultichainMiddleware(isMultichain: boolean): JsonRpcMiddleware { + return createAsyncMiddleware(async (request, response, next) => { + const isMultichainRequest = [ + 'wallet_createSession', + 'wallet_invokeMethod', + 'wallet_getSession', + 'wallet_revokeSession', +].includes(request.method); + +if (!isMultichain && isMultichainRequest) { + throw rpcErrors.methodNotFound(); +} + +if (isMultichain && !isMultichainRequest) { + throw rpcErrors.methodNotFound(); +} + + await next(); + }); +} \ No newline at end of file diff --git a/packages/snaps-simulation/src/simulation.ts b/packages/snaps-simulation/src/simulation.ts index 7cdec6dba3..1554d48f70 100644 --- a/packages/snaps-simulation/src/simulation.ts +++ b/packages/snaps-simulation/src/simulation.ts @@ -62,6 +62,7 @@ import { getOptions } from './options'; import type { Interface, RunSagaFunction, Store } from './store'; import { createStore, getCurrentInterface } from './store'; import { addSnapMetadataToAccount } from './utils/account'; +import { Caveat } from '@metamask/permission-controller'; /** * Options for the execution service, without the options that are shared @@ -93,16 +94,16 @@ export type InstallSnapOptions< ) => InstanceType>, > = ExecutionServiceOptions extends Record - ? { - executionService: Service; - executionServiceOptions?: ExecutionServiceOptions; - options?: SimulationUserOptions; - } - : { - executionService: Service; - executionServiceOptions: ExecutionServiceOptions; - options?: SimulationUserOptions; - }; + ? { + executionService: Service; + executionServiceOptions?: ExecutionServiceOptions; + options?: SimulationUserOptions; + } + : { + executionService: Service; + executionServiceOptions: ExecutionServiceOptions; + options?: SimulationUserOptions; + }; export type InstalledSnap = { snapId: SnapId; @@ -155,6 +156,8 @@ export type RestrictedMiddlewareHooks = { * @returns The metadata for the given Snap. */ getSnap: (snapId: string) => Snap; + + getCaveat: (permission: string, caveatType: string) => Caveat; }; export type PermittedMiddlewareHooks = { @@ -373,7 +376,7 @@ export async function installSnap< registerActions(controllerMessenger, runSaga, options, snapId); // Set up controllers and JSON-RPC stack. - const restrictedHooks = getRestrictedHooks(options); + const restrictedHooks = getRestrictedHooks(snapId, options, controllerMessenger); const permittedHooks = getPermittedHooks( snapId, snapFiles, @@ -388,13 +391,24 @@ export async function installSnap< options, }); + const permissionMiddleware = permissionController.createPermissionMiddleware({ + origin: snapId, + }); + const engine = createJsonRpcEngine({ store, restrictedHooks, permittedHooks, - permissionMiddleware: permissionController.createPermissionMiddleware({ - origin: snapId, - }), + permissionMiddleware, + isMultichain: false, + }); + + const multichainEngine = createJsonRpcEngine({ + store, + restrictedHooks, + permittedHooks, + permissionMiddleware, + isMultichain: true, }); // Create execution service. @@ -417,6 +431,16 @@ 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); + } + }); }, }); @@ -460,7 +484,9 @@ export async function installSnap< * @returns The hooks for the simulation. */ export function getRestrictedHooks( + snapId: SnapId, options: SimulationOptions, + controllerMessenger: RootControllerMessenger, ): RestrictedMiddlewareHooks { return { getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase), @@ -470,6 +496,7 @@ export function getRestrictedHooks( getIsLocked: () => false, getClientCryptography: () => ({}), getSnap: getGetSnapImplementation(true), + getCaveat: (permission: string, caveatType: string) => controllerMessenger.call('PermissionController:getCaveat', snapId, permission, caveatType), }; } diff --git a/packages/test-snaps/package.json b/packages/test-snaps/package.json index c01e0c8769..91a457d30f 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..273f6a5c11 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/MultichainProvider.tsx @@ -0,0 +1,89 @@ +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'); + + return ( + + + + + + {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..59a4dd9fa4 --- /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 ( + <> +

Personal Sign

+
+ 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..c135b618b9 --- /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..08b5e219f2 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/multichain-provider/components/SwitchChain.tsx @@ -0,0 +1,30 @@ +import { 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 d9442ce3da..7234692941 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3817,6 +3817,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.0" + "@metamask/auto-changelog": "npm:^5.0.2" + "@metamask/snaps-cli": "workspace:^" + "@metamask/snaps-jest": "workspace:^" + "@metamask/snaps-sdk": "workspace:^" + "@metamask/utils": "npm:^11.8.1" + "@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" @@ -4713,6 +4738,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:^"