From 9d0084bcd69dbb46c933c9e527dd755263a7795f Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 27 Nov 2024 14:11:35 +0100 Subject: [PATCH 01/14] Add `onSettingsPage` export --- .../src/snaps/SnapController.test.tsx | 170 ++++++++++++++++++ .../src/snaps/SnapController.ts | 13 +- .../coverage.json | 2 +- .../common/BaseSnapExecutor.test.browser.ts | 33 ++++ .../src/common/commands.ts | 2 + .../snaps-rpc-methods/src/endowments/enum.ts | 1 + .../snaps-rpc-methods/src/endowments/index.ts | 3 + .../src/endowments/settings-page.test.ts | 19 ++ .../src/endowments/settings-page.ts | 45 +++++ .../snaps-sdk/src/types/handlers/index.ts | 1 + .../src/types/handlers/settings-page.ts | 24 +++ packages/snaps-utils/src/handler-types.ts | 1 + packages/snaps-utils/src/handlers.ts | 21 +++ 13 files changed, 333 insertions(+), 2 deletions(-) create mode 100644 packages/snaps-rpc-methods/src/endowments/settings-page.test.ts create mode 100644 packages/snaps-rpc-methods/src/endowments/settings-page.ts create mode 100644 packages/snaps-sdk/src/types/handlers/settings-page.ts diff --git a/packages/snaps-controllers/src/snaps/SnapController.test.tsx b/packages/snaps-controllers/src/snaps/SnapController.test.tsx index 4c69531223..4317077341 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.test.tsx +++ b/packages/snaps-controllers/src/snaps/SnapController.test.tsx @@ -3514,6 +3514,176 @@ describe('SnapController', () => { snapController.destroy(); }); + it('throws if onSettingsPage handler returns a phishing link', async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.HomePage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => + Promise.resolve({ + content: text('[Foo bar](https://foo.bar)'), + }), + ); + + rootMessenger.registerActionHandler( + 'SnapInterfaceController:createInterface', + () => { + throw new Error('Invalid URL: The specified URL is not allowed.'); + }, + ); + + await expect( + snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }), + ).rejects.toThrow(`Invalid URL: The specified URL is not allowed.`); + + snapController.destroy(); + }); + + it('throws if onSettingsPage return value is an invalid id', async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + const handlerResponse = { id: 'bar' }; + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.HomePage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => Promise.resolve(handlerResponse), + ); + + await expect( + snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }), + ).rejects.toThrow("Interface with id 'bar' not found."); + + snapController.destroy(); + }); + + it("doesn't throw if onSettingsPage return value is valid", async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + const handlerResponse = { content: text('[foobar](https://foo.bar)') }; + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.HomePage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => Promise.resolve(handlerResponse), + ); + + const result = await snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }); + + expect(result).toStrictEqual({ id: MOCK_INTERFACE_ID }); + + snapController.destroy(); + }); + it('throws if onNameLookup returns an invalid value', async () => { const rootMessenger = getControllerMessenger(); const messenger = getSnapControllerMessenger(rootMessenger); diff --git a/packages/snaps-controllers/src/snaps/SnapController.ts b/packages/snaps-controllers/src/snaps/SnapController.ts index 7b655839d0..173e8ba0d1 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.ts +++ b/packages/snaps-controllers/src/snaps/SnapController.ts @@ -90,6 +90,7 @@ import { OnNameLookupResponseStruct, getLocalizedSnapManifest, MAX_FILE_SIZE, + OnSettingsPageResponseStruct, } from '@metamask/snaps-utils'; import type { Json, NonEmptyArray, SemVerRange } from '@metamask/utils'; import { @@ -3463,7 +3464,8 @@ export class SnapController extends BaseController< switch (handlerType) { case HandlerType.OnTransaction: case HandlerType.OnSignature: - case HandlerType.OnHomePage: { + case HandlerType.OnHomePage: + case HandlerType.OnSettingsPage: { // Since this type has been asserted earlier we can cast const castResult = result as Record | null; @@ -3524,6 +3526,15 @@ export class SnapController extends BaseController< break; } + case HandlerType.OnSettingsPage: { + assertStruct(result, OnSettingsPageResponseStruct); + + if (result && hasProperty(result, 'id')) { + this.#assertInterfaceExists(snapId, result.id as string); + } + + break; + } case HandlerType.OnNameLookup: assertStruct(result, OnNameLookupResponseStruct); break; diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index f958e510ae..ffc40218c8 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,5 +1,5 @@ { - "branches": 80.55, + "branches": 80, "functions": 89.26, "lines": 90.67, "statements": 90.06 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 88208997cb..332b50097d 100644 --- a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts +++ b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts @@ -1441,6 +1441,39 @@ describe('BaseSnapExecutor', () => { }); }); + it('supports onSettingsPage export', async () => { + const CODE = ` + module.exports.onSettingsPage = () => ({ content: { type: 'panel', children: [] }}); + `; + + 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.OnSettingsPage, + MOCK_ORIGIN, + { jsonrpc: '2.0', method: '' }, + ], + }); + + expect(await executor.readCommand()).toStrictEqual({ + id: 2, + jsonrpc: '2.0', + result: { content: { type: 'panel', children: [] } }, + }); + }); + it('supports onSignature export', async () => { const CODE = ` module.exports.onSignature = ({ signature, signatureOrigin }) => diff --git a/packages/snaps-execution-environments/src/common/commands.ts b/packages/snaps-execution-environments/src/common/commands.ts index 32d073f71f..273d4ff51b 100644 --- a/packages/snaps-execution-environments/src/common/commands.ts +++ b/packages/snaps-execution-environments/src/common/commands.ts @@ -87,6 +87,8 @@ export function getHandlerArguments( case HandlerType.OnHomePage: return {}; + case HandlerType.OnSettingsPage: + return {}; case HandlerType.OnUserInput: { assertIsOnUserInputRequestArguments(request.params); diff --git a/packages/snaps-rpc-methods/src/endowments/enum.ts b/packages/snaps-rpc-methods/src/endowments/enum.ts index f0d1577c6f..cdd13a6746 100644 --- a/packages/snaps-rpc-methods/src/endowments/enum.ts +++ b/packages/snaps-rpc-methods/src/endowments/enum.ts @@ -10,4 +10,5 @@ export enum SnapEndowments { LifecycleHooks = 'endowment:lifecycle-hooks', Keyring = 'endowment:keyring', HomePage = 'endowment:page-home', + SettingsPage = 'endowment:page-settings', } diff --git a/packages/snaps-rpc-methods/src/endowments/index.ts b/packages/snaps-rpc-methods/src/endowments/index.ts index faa0c8fe06..4d0b691a15 100644 --- a/packages/snaps-rpc-methods/src/endowments/index.ts +++ b/packages/snaps-rpc-methods/src/endowments/index.ts @@ -31,6 +31,7 @@ import { rpcCaveatSpecifications, rpcEndowmentBuilder, } from './rpc'; +import { settingsPageEndowmentBuilder } from './settings-page'; import { getSignatureInsightCaveatMapper, signatureInsightCaveatSpecifications, @@ -93,6 +94,7 @@ export const endowmentCaveatMappers: Record< ), [lifecycleHooksEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, [homePageEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, + [settingsPageEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, }; // We allow null because a permitted handler does not have an endowment @@ -105,6 +107,7 @@ export const handlerEndowments: Record = { [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName, [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName, [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName, + [HandlerType.OnSettingsPage]: settingsPageEndowmentBuilder.targetName, [HandlerType.OnSignature]: signatureInsightEndowmentBuilder.targetName, [HandlerType.OnUserInput]: null, }; diff --git a/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts b/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts new file mode 100644 index 0000000000..957b315211 --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts @@ -0,0 +1,19 @@ +import { PermissionType, SubjectType } from '@metamask/permission-controller'; + +import { SnapEndowments } from './enum'; +import { settingsPageEndowmentBuilder } from './settings-page'; + +describe('endowment:page-settings', () => { + it('builds the expected permission specification', () => { + const specification = settingsPageEndowmentBuilder.specificationBuilder({}); + expect(specification).toStrictEqual({ + permissionType: PermissionType.Endowment, + targetName: SnapEndowments.SettingsPage, + endowmentGetter: expect.any(Function), + allowedCaveats: null, + subjectTypes: [SubjectType.Snap], + }); + + expect(specification.endowmentGetter()).toBeNull(); + }); +}); diff --git a/packages/snaps-rpc-methods/src/endowments/settings-page.ts b/packages/snaps-rpc-methods/src/endowments/settings-page.ts new file mode 100644 index 0000000000..dc4dd8c42b --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/settings-page.ts @@ -0,0 +1,45 @@ +import type { + PermissionSpecificationBuilder, + EndowmentGetterParams, + ValidPermissionSpecification, +} from '@metamask/permission-controller'; +import { PermissionType, SubjectType } from '@metamask/permission-controller'; +import type { NonEmptyArray } from '@metamask/utils'; + +import { SnapEndowments } from './enum'; + +const permissionName = SnapEndowments.SettingsPage; + +type HomePageEndowmentSpecification = ValidPermissionSpecification<{ + permissionType: PermissionType.Endowment; + targetName: typeof permissionName; + endowmentGetter: (_options?: EndowmentGetterParams) => null; + allowedCaveats: Readonly> | null; +}>; + +/** + * `endowment:settings-page` returns nothing; it is intended to be used as a + * flag by the snap controller to detect whether the snap has the capability to + * use the snap settings page feature. + * + * @param _builderOptions - Optional specification builder options. + * @returns The specification for the `settings-page` endowment. + */ +const specificationBuilder: PermissionSpecificationBuilder< + PermissionType.Endowment, + any, + HomePageEndowmentSpecification +> = (_builderOptions?: unknown) => { + return { + permissionType: PermissionType.Endowment, + targetName: permissionName, + allowedCaveats: null, + endowmentGetter: (_getterOptions?: EndowmentGetterParams) => null, + subjectTypes: [SubjectType.Snap], + }; +}; + +export const settingsPageEndowmentBuilder = Object.freeze({ + targetName: permissionName, + specificationBuilder, +} as const); diff --git a/packages/snaps-sdk/src/types/handlers/index.ts b/packages/snaps-sdk/src/types/handlers/index.ts index 1e4fc63634..ab6a86d833 100644 --- a/packages/snaps-sdk/src/types/handlers/index.ts +++ b/packages/snaps-sdk/src/types/handlers/index.ts @@ -7,3 +7,4 @@ export * from './rpc-request'; export * from './transaction'; export * from './signature'; export * from './user-input'; +export * from './settings-page'; diff --git a/packages/snaps-sdk/src/types/handlers/settings-page.ts b/packages/snaps-sdk/src/types/handlers/settings-page.ts new file mode 100644 index 0000000000..0dd746f96b --- /dev/null +++ b/packages/snaps-sdk/src/types/handlers/settings-page.ts @@ -0,0 +1,24 @@ +import type { ComponentOrElement } from '..'; + +/** + * The `onSettingsPage` handler. This is called when the user navigates to the + * Snap's settings page in the MetaMask UI. + * + * This function does not receive any arguments. + * + * @returns The content to display on the settings page. See + * {@link OnSettingsPageResponse}. + */ +export type OnSettingsPageHandler = () => Promise; + +/** + * The content to display on the settings page. + * + * @property content - A custom UI component, that will be shown in MetaMask. + * @property id - A custom UI interface ID, that will be shown in MetaMask. + */ +export type OnSettingsPageResponse = + | { + content: ComponentOrElement; + } + | { id: string }; diff --git a/packages/snaps-utils/src/handler-types.ts b/packages/snaps-utils/src/handler-types.ts index 642c201fec..230486a95e 100644 --- a/packages/snaps-utils/src/handler-types.ts +++ b/packages/snaps-utils/src/handler-types.ts @@ -8,6 +8,7 @@ export enum HandlerType { OnNameLookup = 'onNameLookup', OnKeyringRequest = 'onKeyringRequest', OnHomePage = 'onHomePage', + OnSettingsPage = 'onSettingsPage', OnUserInput = 'onUserInput', } diff --git a/packages/snaps-utils/src/handlers.ts b/packages/snaps-utils/src/handlers.ts index 6c4e37a9e6..265a2c98d8 100644 --- a/packages/snaps-utils/src/handlers.ts +++ b/packages/snaps-utils/src/handlers.ts @@ -5,6 +5,7 @@ import type { OnKeyringRequestHandler, OnNameLookupHandler, OnRpcRequestHandler, + OnSettingsPageHandler, OnSignatureHandler, OnTransactionHandler, OnUpdateHandler, @@ -89,6 +90,13 @@ export const SNAP_EXPORTS = { return typeof snapExport === 'function'; }, }, + [HandlerType.OnSettingsPage]: { + type: HandlerType.OnSettingsPage, + required: true, + validator: (snapExport: unknown): snapExport is OnSettingsPageHandler => { + return typeof snapExport === 'function'; + }, + }, [HandlerType.OnSignature]: { type: HandlerType.OnSignature, required: true, @@ -145,6 +153,19 @@ export const OnHomePageResponseStruct = union([ OnHomePageResponseWithIdStruct, ]); +export const OnSettingsPageResponseWithContentStruct = object({ + content: ComponentOrElementStruct, +}); + +export const OnSettingsPageResponseWithIdStruct = object({ + id: string(), +}); + +export const OnSettingsPageResponseStruct = union([ + OnSettingsPageResponseWithContentStruct, + OnSettingsPageResponseWithIdStruct, +]); + export const AddressResolutionStruct = object({ protocol: string(), resolvedDomain: string(), From e998a46dc6cb4a108ed042b2f67249541998d2c5 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 27 Nov 2024 14:15:20 +0100 Subject: [PATCH 02/14] fix tests --- .../snaps-controllers/src/snaps/SnapController.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/snaps-controllers/src/snaps/SnapController.test.tsx b/packages/snaps-controllers/src/snaps/SnapController.test.tsx index 4317077341..339258f968 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.test.tsx +++ b/packages/snaps-controllers/src/snaps/SnapController.test.tsx @@ -3529,7 +3529,7 @@ describe('SnapController', () => { rootMessenger.registerActionHandler( 'PermissionController:getPermissions', () => ({ - [SnapEndowments.HomePage]: { + [SnapEndowments.SettingsPage]: { caveats: null, date: 1664187844588, id: 'izn0WGUO8cvq_jqvLQuQP', @@ -3593,7 +3593,7 @@ describe('SnapController', () => { rootMessenger.registerActionHandler( 'PermissionController:getPermissions', () => ({ - [SnapEndowments.HomePage]: { + [SnapEndowments.SettingsPage]: { caveats: null, date: 1664187844588, id: 'izn0WGUO8cvq_jqvLQuQP', @@ -3647,7 +3647,7 @@ describe('SnapController', () => { rootMessenger.registerActionHandler( 'PermissionController:getPermissions', () => ({ - [SnapEndowments.HomePage]: { + [SnapEndowments.SettingsPage]: { caveats: null, date: 1664187844588, id: 'izn0WGUO8cvq_jqvLQuQP', From 1af9d826ed14775d5d6eaadee9aa9bf49aba1643 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 27 Nov 2024 14:29:38 +0100 Subject: [PATCH 03/14] fix tests and coverage --- packages/snaps-controllers/src/snaps/SnapController.test.tsx | 2 +- packages/snaps-utils/coverage.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/snaps-controllers/src/snaps/SnapController.test.tsx b/packages/snaps-controllers/src/snaps/SnapController.test.tsx index 339258f968..b60903fed1 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.test.tsx +++ b/packages/snaps-controllers/src/snaps/SnapController.test.tsx @@ -5612,7 +5612,7 @@ describe('SnapController', () => { [MOCK_SNAP_ID]: {}, }), ).rejects.toThrow( - 'A snap must request at least one of the following permissions: endowment:rpc, endowment:transaction-insight, endowment:cronjob, endowment:name-lookup, endowment:lifecycle-hooks, endowment:keyring, endowment:page-home, endowment:signature-insight.', + 'A snap must request at least one of the following permissions: endowment:rpc, endowment:transaction-insight, endowment:cronjob, endowment:name-lookup, endowment:lifecycle-hooks, endowment:keyring, endowment:page-home, endowment:page-settings, endowment:signature-insight.', ); controller.destroy(); diff --git a/packages/snaps-utils/coverage.json b/packages/snaps-utils/coverage.json index 102bd1c6df..14174b4b43 100644 --- a/packages/snaps-utils/coverage.json +++ b/packages/snaps-utils/coverage.json @@ -2,5 +2,5 @@ "branches": 99.74, "functions": 98.93, "lines": 99.46, - "statements": 96.37 + "statements": 96.18 } From c04288d872c358ae5459d1a380a98357679c8211 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 27 Nov 2024 15:10:13 +0100 Subject: [PATCH 04/14] fix coverage --- packages/snaps-controllers/coverage.json | 4 ++-- packages/snaps-execution-environments/coverage.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/snaps-controllers/coverage.json b/packages/snaps-controllers/coverage.json index 28873f6536..74c70ee306 100644 --- a/packages/snaps-controllers/coverage.json +++ b/packages/snaps-controllers/coverage.json @@ -1,6 +1,6 @@ { - "branches": 92.89, + "branches": 92.96, "functions": 96.71, - "lines": 98, + "lines": 98.01, "statements": 97.71 } diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index ffc40218c8..1a3193285c 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,5 +1,5 @@ { - "branches": 80, + "branches": 80.68, "functions": 89.26, "lines": 90.67, "statements": 90.06 From fccfebeab51b5ed25465f6f6aba497b81a233733 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 4 Dec 2024 10:24:10 +0100 Subject: [PATCH 05/14] fix bugs and add example snap --- packages/examples/README.md | 3 + .../packages/settings-page/.depcheckrc.json | 18 ++ .../packages/settings-page/.eslintrc.js | 7 + .../packages/settings-page/CHANGELOG.md | 47 ++++ .../packages/settings-page/LICENSE.APACHE2 | 201 ++++++++++++++++++ .../packages/settings-page/LICENSE.MIT0 | 16 ++ .../examples/packages/settings-page/README.md | 22 ++ .../packages/settings-page/jest.config.js | 36 ++++ .../packages/settings-page/package.json | 86 ++++++++ .../packages/settings-page/snap.config.ts | 17 ++ .../packages/settings-page/snap.manifest.json | 23 ++ .../packages/settings-page/src/index.test.tsx | 23 ++ .../packages/settings-page/src/index.tsx | 64 ++++++ .../packages/settings-page/tsconfig.json | 8 + .../snaps-rpc-methods/src/endowments/index.ts | 1 + packages/snaps-sdk/src/types/permissions.ts | 3 + .../test-snaps/src/features/snaps/index.ts | 1 + .../snaps/settings-page/SettingsPage.tsx | 20 ++ .../features/snaps/settings-page/constants.ts | 5 + .../src/features/snaps/settings-page/index.ts | 1 + yarn.lock | 37 ++++ 21 files changed, 639 insertions(+) create mode 100644 packages/examples/packages/settings-page/.depcheckrc.json create mode 100644 packages/examples/packages/settings-page/.eslintrc.js create mode 100644 packages/examples/packages/settings-page/CHANGELOG.md create mode 100644 packages/examples/packages/settings-page/LICENSE.APACHE2 create mode 100644 packages/examples/packages/settings-page/LICENSE.MIT0 create mode 100644 packages/examples/packages/settings-page/README.md create mode 100644 packages/examples/packages/settings-page/jest.config.js create mode 100644 packages/examples/packages/settings-page/package.json create mode 100644 packages/examples/packages/settings-page/snap.config.ts create mode 100644 packages/examples/packages/settings-page/snap.manifest.json create mode 100644 packages/examples/packages/settings-page/src/index.test.tsx create mode 100644 packages/examples/packages/settings-page/src/index.tsx create mode 100644 packages/examples/packages/settings-page/tsconfig.json create mode 100644 packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx create mode 100644 packages/test-snaps/src/features/snaps/settings-page/constants.ts create mode 100644 packages/test-snaps/src/features/snaps/settings-page/index.ts diff --git a/packages/examples/README.md b/packages/examples/README.md index d2c0dfa004..cee01f973d 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -66,6 +66,9 @@ The following is a list of the snaps in this directory. - [**`packages/notifications`**](./packages/notifications): This snap demonstrates how to use the `snap_notify` method to display notifications to the user, either as a MetaMask notification or as a desktop notification. +- [**`packages/settings-page`**](./packages/settings-page): + This snap demonstrates how to use `endowment:page-settings` permission, + showing a settings page to the user. - [**`packages/transaction-insights`**](./packages/transaction-insights): This snap demonstrates how to use `endowment:transaction-insights` permission, and provide transaction insights to the user. diff --git a/packages/examples/packages/settings-page/.depcheckrc.json b/packages/examples/packages/settings-page/.depcheckrc.json new file mode 100644 index 0000000000..c437c59cd2 --- /dev/null +++ b/packages/examples/packages/settings-page/.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/settings-page/.eslintrc.js b/packages/examples/packages/settings-page/.eslintrc.js new file mode 100644 index 0000000000..a47fd0b65d --- /dev/null +++ b/packages/examples/packages/settings-page/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + extends: ['../../.eslintrc.js'], + + parserOptions: { + tsconfigRootDir: __dirname, + }, +}; diff --git a/packages/examples/packages/settings-page/CHANGELOG.md b/packages/examples/packages/settings-page/CHANGELOG.md new file mode 100644 index 0000000000..78434e6f40 --- /dev/null +++ b/packages/examples/packages/settings-page/CHANGELOG.md @@ -0,0 +1,47 @@ +# 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] + +## [1.1.3] + +### Fixed + +- Bump MetaMask dependencies + +## [1.1.2] + +### Changed + +- Use error wrappers ([#2178](https://github.com/MetaMask/snaps/pull/2178)) + +## [1.1.1] + +### Changed + +- Remove snap icon ([#2189](https://github.com/MetaMask/snaps/pull/2189)) + +## [1.1.0] + +### Changed + +- Use `@metamask/snaps-sdk` package ([#1946](https://github.com/MetaMask/snaps/pull/1946), [#1954](https://github.com/MetaMask/snaps/pull/1954)) + - This package replaces the `@metamask/snaps-types` and + - `@metamask/snaps-ui` packages, and is much more lightweight. + +## [1.0.0] + +### Added + +- Initial release ([#1918](https://github.com/MetaMask/snaps/pull/1918)) + +[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.3...HEAD +[1.1.3]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.2...@metamask/home-page-example-snap@1.1.3 +[1.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.1...@metamask/home-page-example-snap@1.1.2 +[1.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.0...@metamask/home-page-example-snap@1.1.1 +[1.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.0.0...@metamask/home-page-example-snap@1.1.0 +[1.0.0]: https://github.com/MetaMask/snaps/releases/tag/@metamask/home-page-example-snap@1.0.0 diff --git a/packages/examples/packages/settings-page/LICENSE.APACHE2 b/packages/examples/packages/settings-page/LICENSE.APACHE2 new file mode 100644 index 0000000000..bf37d0e612 --- /dev/null +++ b/packages/examples/packages/settings-page/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/settings-page/LICENSE.MIT0 b/packages/examples/packages/settings-page/LICENSE.MIT0 new file mode 100644 index 0000000000..3a4d3cb295 --- /dev/null +++ b/packages/examples/packages/settings-page/LICENSE.MIT0 @@ -0,0 +1,16 @@ +MIT No Attribution + +Copyright 2024 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/settings-page/README.md b/packages/examples/packages/settings-page/README.md new file mode 100644 index 0000000000..efa3c024e0 --- /dev/null +++ b/packages/examples/packages/settings-page/README.md @@ -0,0 +1,22 @@ +# `@metamask/settings-page-example-snap` + +This snap demonstrates how to use `endowment:page-settings` permission to show +a settings page that leverages custom UI components. + +## Snap manifest + +The manifest of this snap includes the `endowment:page-settings` permission: + +```json +{ + "initialPermissions": { + "endowment:page-settings": {} + } +} +``` + +This permission does not require any additional configuration. + +## Snap usage + +This snap exposes an `onSettingsPage` handler, which returns the UI to be shown. diff --git a/packages/examples/packages/settings-page/jest.config.js b/packages/examples/packages/settings-page/jest.config.js new file mode 100644 index 0000000000..f473a91b83 --- /dev/null +++ b/packages/examples/packages/settings-page/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/settings-page/package.json b/packages/examples/packages/settings-page/package.json new file mode 100644 index 0000000000..f7ec55e4b4 --- /dev/null +++ b/packages/examples/packages/settings-page/package.json @@ -0,0 +1,86 @@ +{ + "name": "@metamask/settings-page-example-snap", + "version": "1.1.3", + "description": "MetaMask example snap demonstrating the use of settings pages", + "keywords": [ + "MetaMask", + "Snaps", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/snaps/tree/main/packages/examples/packages/settings-page#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/home-page-example-snap", + "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/home-page-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 --ext js,ts,jsx,tsx", + "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", + "lint:misc": "prettier --no-error-on-unmatched-pattern --loglevel 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:^" + }, + "devDependencies": { + "@jest/globals": "^29.5.0", + "@lavamoat/allow-scripts": "^3.0.4", + "@metamask/auto-changelog": "^3.4.4", + "@metamask/eslint-config": "^12.1.0", + "@metamask/eslint-config-jest": "^12.1.0", + "@metamask/eslint-config-nodejs": "^12.1.0", + "@metamask/eslint-config-typescript": "^12.1.0", + "@metamask/snaps-cli": "workspace:^", + "@metamask/snaps-jest": "workspace:^", + "@swc/core": "1.3.78", + "@swc/jest": "^0.2.26", + "@typescript-eslint/eslint-plugin": "^5.42.1", + "@typescript-eslint/parser": "^6.21.0", + "deepmerge": "^4.2.2", + "depcheck": "^1.4.7", + "eslint": "^8.27.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jest": "^27.1.5", + "eslint-plugin-jsdoc": "^41.1.2", + "eslint-plugin-n": "^15.7.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", + "jest": "^29.0.2", + "jest-silent-reporter": "^0.6.0", + "prettier": "^2.8.8", + "prettier-plugin-packagejson": "^2.5.2", + "ts-node": "^10.9.1", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.16 || >=20" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/examples/packages/settings-page/snap.config.ts b/packages/examples/packages/settings-page/snap.config.ts new file mode 100644 index 0000000000..577ddbdd7b --- /dev/null +++ b/packages/examples/packages/settings-page/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.tsx'), + server: { + port: 8071, + }, + typescript: { + enabled: true, + }, + stats: { + buffer: false, + }, +}; + +export default config; diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json new file mode 100644 index 0000000000..c8a0a6d894 --- /dev/null +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -0,0 +1,23 @@ +{ + "version": "1.1.3", + "description": "MetaMask example snap demonstrating the use of settings pages.", + "proposedName": "Settings Page Example Snap", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "source": { + "shasum": "1EtjSOu6ZrLaiCRMQo03YWHnXKsjDV0bIyS0mhiImpw=", + "location": { + "npm": { + "filePath": "dist/bundle.js", + "packageName": "@metamask/settings-page-example-snap", + "registry": "https://registry.npmjs.org" + } + } + }, + "initialPermissions": { + "endowment:page-settings": {} + }, + "manifestVersion": "0.1" +} diff --git a/packages/examples/packages/settings-page/src/index.test.tsx b/packages/examples/packages/settings-page/src/index.test.tsx new file mode 100644 index 0000000000..b33376d1c5 --- /dev/null +++ b/packages/examples/packages/settings-page/src/index.test.tsx @@ -0,0 +1,23 @@ +import { describe, it } from '@jest/globals'; +import { installSnap } from '@metamask/snaps-jest'; +import { Box, Text } from '@metamask/snaps-sdk/jsx'; + +describe('onHomePage', () => { + it('returns custom UI', async () => { + const { onHomePage } = await installSnap(); + + const response = await onHomePage(); + + const screen = response.getInterface(); + + await screen.clickElement('footer_button'); + + const newUi = response.getInterface(); + + expect(newUi).toRender( + + Footer button was pressed + , + ); + }); +}); diff --git a/packages/examples/packages/settings-page/src/index.tsx b/packages/examples/packages/settings-page/src/index.tsx new file mode 100644 index 0000000000..5206feb893 --- /dev/null +++ b/packages/examples/packages/settings-page/src/index.tsx @@ -0,0 +1,64 @@ +import type { OnSettingsPageHandler } from '@metamask/snaps-sdk'; +import { + assert, + UserInputEventType, + type OnUserInputHandler, +} from '@metamask/snaps-sdk'; +import { + Box, + Container, + Footer, + Heading, + Text, + Button, +} from '@metamask/snaps-sdk/jsx'; + +/** + * Handle incoming settings page requests from the MetaMask clients. + * + * @returns A static panel rendered with custom UI. + * @see https://docs.metamask.io/snaps/reference/exports/#onsettingspage + */ +export const onSettingsPage: OnSettingsPageHandler = async () => { + return { + content: ( + + + Hello world! + Welcome to my Snap settings page! + +
+ +
+
+ ), + }; +}; + +/** + * Handle incoming user events coming from the Snap interface. + * + * @param params - The event parameters. + * @param params.id - The Snap interface ID where the event was fired. + * @param params.event - The event object containing the event type, name and + * value. + * @see https://docs.metamask.io/snaps/reference/exports/#onuserinput + */ +export const onUserInput: OnUserInputHandler = async ({ event, id }) => { + // Since this Snap only has one event, we can assert the event type and name + // directly. + assert(event.type === UserInputEventType.ButtonClickEvent); + assert(event.name === 'footer_button'); + + await snap.request({ + method: 'snap_updateInterface', + params: { + id, + ui: ( + + Footer button was pressed + + ), + }, + }); +}; diff --git a/packages/examples/packages/settings-page/tsconfig.json b/packages/examples/packages/settings-page/tsconfig.json new file mode 100644 index 0000000000..17a40a6a74 --- /dev/null +++ b/packages/examples/packages/settings-page/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": false, + "baseUrl": "./" + }, + "include": ["src", "snap.config.ts"] +} diff --git a/packages/snaps-rpc-methods/src/endowments/index.ts b/packages/snaps-rpc-methods/src/endowments/index.ts index 4d0b691a15..7d82ac72d3 100644 --- a/packages/snaps-rpc-methods/src/endowments/index.ts +++ b/packages/snaps-rpc-methods/src/endowments/index.ts @@ -56,6 +56,7 @@ export const endowmentPermissionBuilders = { [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder, [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder, [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder, + [settingsPageEndowmentBuilder.targetName]: settingsPageEndowmentBuilder, [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder, [signatureInsightEndowmentBuilder.targetName]: signatureInsightEndowmentBuilder, diff --git a/packages/snaps-sdk/src/types/permissions.ts b/packages/snaps-sdk/src/types/permissions.ts index 7caed09815..76fc232dcd 100644 --- a/packages/snaps-sdk/src/types/permissions.ts +++ b/packages/snaps-sdk/src/types/permissions.ts @@ -57,6 +57,9 @@ export type InitialPermissions = Partial<{ 'endowment:page-home'?: { maxRequestTime?: number; }; + 'endowment:page-settings'?: { + maxRequestTime?: number; + }; 'endowment:rpc': { dapps?: boolean; snaps?: boolean; diff --git a/packages/test-snaps/src/features/snaps/index.ts b/packages/test-snaps/src/features/snaps/index.ts index c80978a40d..91ba2991f4 100644 --- a/packages/test-snaps/src/features/snaps/index.ts +++ b/packages/test-snaps/src/features/snaps/index.ts @@ -27,3 +27,4 @@ export * from './signature-insights'; export * from './updates'; export * from './wasm'; export * from './send-flow'; +export * from './settings-page'; diff --git a/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx new file mode 100644 index 0000000000..399bb17fb9 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx @@ -0,0 +1,20 @@ +import type { FunctionComponent } from 'react'; + +import { Snap } from '../../../components'; +import { + SETTINGS_PAGE_SNAP_ID, + SETTINGS_PAGE_SNAP_PORT, + SETTINGS_PAGE_VERSION, +} from './constants'; + +export const SettingsPage: FunctionComponent = () => { + return ( + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/settings-page/constants.ts b/packages/test-snaps/src/features/snaps/settings-page/constants.ts new file mode 100644 index 0000000000..36e2a59d81 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/constants.ts @@ -0,0 +1,5 @@ +import packageJson from '@metamask/home-page-example-snap/package.json'; + +export const SETTINGS_PAGE_SNAP_ID = 'npm:@metamask/settings-page-example-snap'; +export const SETTINGS_PAGE_SNAP_PORT = 8071; +export const SETTINGS_PAGE_VERSION = packageJson.version; diff --git a/packages/test-snaps/src/features/snaps/settings-page/index.ts b/packages/test-snaps/src/features/snaps/settings-page/index.ts new file mode 100644 index 0000000000..f533f5abe0 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/index.ts @@ -0,0 +1 @@ +export * from './SettingsPage'; diff --git a/yarn.lock b/yarn.lock index 7041b9ad4e..cfdc6a6fb2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5517,6 +5517,43 @@ __metadata: languageName: unknown linkType: soft +"@metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page": + version: 0.0.0-use.local + resolution: "@metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page" + dependencies: + "@jest/globals": "npm:^29.5.0" + "@lavamoat/allow-scripts": "npm:^3.0.4" + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/eslint-config": "npm:^12.1.0" + "@metamask/eslint-config-jest": "npm:^12.1.0" + "@metamask/eslint-config-nodejs": "npm:^12.1.0" + "@metamask/eslint-config-typescript": "npm:^12.1.0" + "@metamask/snaps-cli": "workspace:^" + "@metamask/snaps-jest": "workspace:^" + "@metamask/snaps-sdk": "workspace:^" + "@swc/core": "npm:1.3.78" + "@swc/jest": "npm:^0.2.26" + "@typescript-eslint/eslint-plugin": "npm:^5.42.1" + "@typescript-eslint/parser": "npm:^6.21.0" + deepmerge: "npm:^4.2.2" + depcheck: "npm:^1.4.7" + eslint: "npm:^8.27.0" + eslint-config-prettier: "npm:^8.5.0" + eslint-plugin-import: "npm:^2.26.0" + eslint-plugin-jest: "npm:^27.1.5" + eslint-plugin-jsdoc: "npm:^41.1.2" + eslint-plugin-n: "npm:^15.7.0" + eslint-plugin-prettier: "npm:^4.2.1" + eslint-plugin-promise: "npm:^6.1.1" + jest: "npm:^29.0.2" + jest-silent-reporter: "npm:^0.6.0" + prettier: "npm:^2.8.8" + prettier-plugin-packagejson: "npm:^2.5.2" + ts-node: "npm:^10.9.1" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/signature-insights-example-snap@workspace:^, @metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights": version: 0.0.0-use.local resolution: "@metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights" From 96e865b60da0edcb9e1eb1d1ef4d0faaadf28530 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Fri, 6 Dec 2024 10:46:08 +0100 Subject: [PATCH 06/14] address comments --- .../src/common/commands.ts | 1 - .../src/endowments/settings-page.ts | 4 ++-- packages/snaps-utils/src/handlers.ts | 23 ++++++------------- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/packages/snaps-execution-environments/src/common/commands.ts b/packages/snaps-execution-environments/src/common/commands.ts index 273d4ff51b..b03a32d23d 100644 --- a/packages/snaps-execution-environments/src/common/commands.ts +++ b/packages/snaps-execution-environments/src/common/commands.ts @@ -86,7 +86,6 @@ export function getHandlerArguments( return { origin }; case HandlerType.OnHomePage: - return {}; case HandlerType.OnSettingsPage: return {}; case HandlerType.OnUserInput: { diff --git a/packages/snaps-rpc-methods/src/endowments/settings-page.ts b/packages/snaps-rpc-methods/src/endowments/settings-page.ts index dc4dd8c42b..ec6a1de592 100644 --- a/packages/snaps-rpc-methods/src/endowments/settings-page.ts +++ b/packages/snaps-rpc-methods/src/endowments/settings-page.ts @@ -10,7 +10,7 @@ import { SnapEndowments } from './enum'; const permissionName = SnapEndowments.SettingsPage; -type HomePageEndowmentSpecification = ValidPermissionSpecification<{ +type SettingsPageEndowmentSpecification = ValidPermissionSpecification<{ permissionType: PermissionType.Endowment; targetName: typeof permissionName; endowmentGetter: (_options?: EndowmentGetterParams) => null; @@ -28,7 +28,7 @@ type HomePageEndowmentSpecification = ValidPermissionSpecification<{ const specificationBuilder: PermissionSpecificationBuilder< PermissionType.Endowment, any, - HomePageEndowmentSpecification + SettingsPageEndowmentSpecification > = (_builderOptions?: unknown) => { return { permissionType: PermissionType.Endowment, diff --git a/packages/snaps-utils/src/handlers.ts b/packages/snaps-utils/src/handlers.ts index 265a2c98d8..3d329f33d4 100644 --- a/packages/snaps-utils/src/handlers.ts +++ b/packages/snaps-utils/src/handlers.ts @@ -140,31 +140,22 @@ export const OnTransactionResponseStruct = nullable( export const OnSignatureResponseStruct = OnTransactionResponseStruct; -export const OnHomePageResponseWithContentStruct = object({ +export const OnPageResponseWithContentStruct = object({ content: ComponentOrElementStruct, }); -export const OnHomePageResponseWithIdStruct = object({ +export const OnPageResponseWithIdStruct = object({ id: string(), }); -export const OnHomePageResponseStruct = union([ - OnHomePageResponseWithContentStruct, - OnHomePageResponseWithIdStruct, +export const OnPageResponseStruct = union([ + OnPageResponseWithContentStruct, + OnPageResponseWithIdStruct, ]); -export const OnSettingsPageResponseWithContentStruct = object({ - content: ComponentOrElementStruct, -}); - -export const OnSettingsPageResponseWithIdStruct = object({ - id: string(), -}); +export const OnHomePageResponseStruct = OnPageResponseStruct; -export const OnSettingsPageResponseStruct = union([ - OnSettingsPageResponseWithContentStruct, - OnSettingsPageResponseWithIdStruct, -]); +export const OnSettingsPageResponseStruct = OnPageResponseStruct; export const AddressResolutionStruct = object({ protocol: string(), From ad40bf172673ba8ecf4fd4323507743ba59b801d Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Fri, 6 Dec 2024 10:53:20 +0100 Subject: [PATCH 07/14] update after rebase --- packages/snaps-rpc-methods/jest.config.js | 6 +++--- packages/snaps-rpc-methods/src/permissions.test.ts | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/snaps-rpc-methods/jest.config.js b/packages/snaps-rpc-methods/jest.config.js index 077ed1c65d..f3813d88c0 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: 92.94, - functions: 97.26, - lines: 97.87, - statements: 97.39, + functions: 97.29, + lines: 97.88, + statements: 97.41, }, }, }); diff --git a/packages/snaps-rpc-methods/src/permissions.test.ts b/packages/snaps-rpc-methods/src/permissions.test.ts index 50f911b100..7725f2cd0e 100644 --- a/packages/snaps-rpc-methods/src/permissions.test.ts +++ b/packages/snaps-rpc-methods/src/permissions.test.ts @@ -82,6 +82,15 @@ describe('buildSnapEndowmentSpecifications', () => { ], "targetName": "endowment:page-home", }, + "endowment:page-settings": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:page-settings", + }, "endowment:rpc": { "allowedCaveats": [ "rpcOrigin", From 3ac9f89fa37d4a0ac05eea2aa540e27bc2029b4d Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Tue, 10 Dec 2024 12:06:25 +0100 Subject: [PATCH 08/14] address comments --- .../packages/settings-page/CHANGELOG.md | 39 +------------------ .../examples/packages/settings-page/README.md | 2 + .../packages/settings-page/package.json | 6 +-- .../packages/settings-page/snap.manifest.json | 4 +- .../coverage.json | 4 +- packages/snaps-utils/coverage.json | 2 +- packages/snaps-utils/src/handlers.ts | 14 +++---- packages/test-snaps/package.json | 1 + .../snaps/settings-page/SettingsPage.tsx | 2 +- .../features/snaps/settings-page/constants.ts | 2 +- yarn.lock | 3 +- 11 files changed, 22 insertions(+), 57 deletions(-) diff --git a/packages/examples/packages/settings-page/CHANGELOG.md b/packages/examples/packages/settings-page/CHANGELOG.md index 78434e6f40..720e00537e 100644 --- a/packages/examples/packages/settings-page/CHANGELOG.md +++ b/packages/examples/packages/settings-page/CHANGELOG.md @@ -7,41 +7,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [1.1.3] - -### Fixed - -- Bump MetaMask dependencies - -## [1.1.2] - -### Changed - -- Use error wrappers ([#2178](https://github.com/MetaMask/snaps/pull/2178)) - -## [1.1.1] - -### Changed - -- Remove snap icon ([#2189](https://github.com/MetaMask/snaps/pull/2189)) - -## [1.1.0] - -### Changed - -- Use `@metamask/snaps-sdk` package ([#1946](https://github.com/MetaMask/snaps/pull/1946), [#1954](https://github.com/MetaMask/snaps/pull/1954)) - - This package replaces the `@metamask/snaps-types` and - - `@metamask/snaps-ui` packages, and is much more lightweight. - -## [1.0.0] - -### Added - -- Initial release ([#1918](https://github.com/MetaMask/snaps/pull/1918)) - -[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.3...HEAD -[1.1.3]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.2...@metamask/home-page-example-snap@1.1.3 -[1.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.1...@metamask/home-page-example-snap@1.1.2 -[1.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.1.0...@metamask/home-page-example-snap@1.1.1 -[1.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/home-page-example-snap@1.0.0...@metamask/home-page-example-snap@1.1.0 -[1.0.0]: https://github.com/MetaMask/snaps/releases/tag/@metamask/home-page-example-snap@1.0.0 +[Unreleased]: https://github.com/MetaMask/snaps/ diff --git a/packages/examples/packages/settings-page/README.md b/packages/examples/packages/settings-page/README.md index efa3c024e0..faa5015009 100644 --- a/packages/examples/packages/settings-page/README.md +++ b/packages/examples/packages/settings-page/README.md @@ -3,6 +3,8 @@ This snap demonstrates how to use `endowment:page-settings` permission to show a settings page that leverages custom UI components. +This endowment is initially restricted to preinstalled snaps only. + ## Snap manifest The manifest of this snap includes the `endowment:page-settings` permission: diff --git a/packages/examples/packages/settings-page/package.json b/packages/examples/packages/settings-page/package.json index f7ec55e4b4..900c03737f 100644 --- a/packages/examples/packages/settings-page/package.json +++ b/packages/examples/packages/settings-page/package.json @@ -1,6 +1,6 @@ { "name": "@metamask/settings-page-example-snap", - "version": "1.1.3", + "version": "0.0.0", "description": "MetaMask example snap demonstrating the use of settings pages", "keywords": [ "MetaMask", @@ -25,8 +25,8 @@ "scripts": { "build": "mm-snap build", "build:clean": "yarn clean && yarn build", - "changelog:update": "../../../../scripts/update-changelog.sh @metamask/home-page-example-snap", - "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/home-page-example-snap", + "changelog:update": "../../../../scripts/update-changelog.sh @metamask/settings-page-example-snap", + "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/settings-page-example-snap", "clean": "rimraf \"dist\"", "lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies", "lint:ci": "yarn lint", diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json index c8a0a6d894..df8810766d 100644 --- a/packages/examples/packages/settings-page/snap.manifest.json +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -1,5 +1,5 @@ { - "version": "1.1.3", + "version": "0.0.0", "description": "MetaMask example snap demonstrating the use of settings pages.", "proposedName": "Settings Page Example Snap", "repository": { @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "1EtjSOu6ZrLaiCRMQo03YWHnXKsjDV0bIyS0mhiImpw=", + "shasum": "yWcDv7XuV/FGRxKdOMkelR4qB0Ivel7oP9fEuNz0EE8=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index 1a3193285c..b6bfc2ac6f 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,6 +1,6 @@ { "branches": 80.68, "functions": 89.26, - "lines": 90.67, - "statements": 90.06 + "lines": 90.66, + "statements": 90.05 } diff --git a/packages/snaps-utils/coverage.json b/packages/snaps-utils/coverage.json index 14174b4b43..b7d146113b 100644 --- a/packages/snaps-utils/coverage.json +++ b/packages/snaps-utils/coverage.json @@ -2,5 +2,5 @@ "branches": 99.74, "functions": 98.93, "lines": 99.46, - "statements": 96.18 + "statements": 96.25 } diff --git a/packages/snaps-utils/src/handlers.ts b/packages/snaps-utils/src/handlers.ts index 3d329f33d4..a20a48b842 100644 --- a/packages/snaps-utils/src/handlers.ts +++ b/packages/snaps-utils/src/handlers.ts @@ -140,22 +140,20 @@ export const OnTransactionResponseStruct = nullable( export const OnSignatureResponseStruct = OnTransactionResponseStruct; -export const OnPageResponseWithContentStruct = object({ +export const OnHomePageResponseWithContentStruct = object({ content: ComponentOrElementStruct, }); -export const OnPageResponseWithIdStruct = object({ +export const OnHomePageResponseWithIdStruct = object({ id: string(), }); -export const OnPageResponseStruct = union([ - OnPageResponseWithContentStruct, - OnPageResponseWithIdStruct, +export const OnHomePageResponseStruct = union([ + OnHomePageResponseWithContentStruct, + OnHomePageResponseWithIdStruct, ]); -export const OnHomePageResponseStruct = OnPageResponseStruct; - -export const OnSettingsPageResponseStruct = OnPageResponseStruct; +export const OnSettingsPageResponseStruct = OnHomePageResponseStruct; export const AddressResolutionStruct = object({ protocol: string(), diff --git a/packages/test-snaps/package.json b/packages/test-snaps/package.json index 1077a1ba86..47b175528a 100644 --- a/packages/test-snaps/package.json +++ b/packages/test-snaps/package.json @@ -66,6 +66,7 @@ "@metamask/notification-example-snap": "workspace:^", "@metamask/preinstalled-example-snap": "workspace:^", "@metamask/send-flow-example-snap": "workspace:^", + "@metamask/settings-page-example-snap": "workspace:^", "@metamask/signature-insights-example-snap": "workspace:^", "@metamask/snaps-utils": "workspace:^", "@metamask/utils": "^10.0.0", diff --git a/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx index 399bb17fb9..d5c6f1a78f 100644 --- a/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx +++ b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx @@ -14,7 +14,7 @@ export const SettingsPage: FunctionComponent = () => { snapId={SETTINGS_PAGE_SNAP_ID} port={SETTINGS_PAGE_SNAP_PORT} version={SETTINGS_PAGE_VERSION} - testId="homepage" + testId="settingspage" /> ); }; diff --git a/packages/test-snaps/src/features/snaps/settings-page/constants.ts b/packages/test-snaps/src/features/snaps/settings-page/constants.ts index 36e2a59d81..0b2b4ef5da 100644 --- a/packages/test-snaps/src/features/snaps/settings-page/constants.ts +++ b/packages/test-snaps/src/features/snaps/settings-page/constants.ts @@ -1,4 +1,4 @@ -import packageJson from '@metamask/home-page-example-snap/package.json'; +import packageJson from '@metamask/settings-page-example-snap/package.json'; export const SETTINGS_PAGE_SNAP_ID = 'npm:@metamask/settings-page-example-snap'; export const SETTINGS_PAGE_SNAP_PORT = 8071; diff --git a/yarn.lock b/yarn.lock index cfdc6a6fb2..5eb2d26aed 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5517,7 +5517,7 @@ __metadata: languageName: unknown linkType: soft -"@metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page": +"@metamask/settings-page-example-snap@workspace:^, @metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page": version: 0.0.0-use.local resolution: "@metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page" dependencies: @@ -6443,6 +6443,7 @@ __metadata: "@metamask/preinstalled-example-snap": "workspace:^" "@metamask/providers": "npm:^18.1.1" "@metamask/send-flow-example-snap": "workspace:^" + "@metamask/settings-page-example-snap": "workspace:^" "@metamask/signature-insights-example-snap": "workspace:^" "@metamask/snaps-utils": "workspace:^" "@metamask/utils": "npm:^10.0.0" From c11bc8d93631b91b146c446dd63377bea7af36cf Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Tue, 10 Dec 2024 12:16:49 +0100 Subject: [PATCH 09/14] update coverage --- packages/snaps-execution-environments/coverage.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index b6bfc2ac6f..1a3193285c 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,6 +1,6 @@ { "branches": 80.68, "functions": 89.26, - "lines": 90.66, - "statements": 90.05 + "lines": 90.67, + "statements": 90.06 } From 154e93965780184756313f1e4f1a8af864502a2e Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Tue, 10 Dec 2024 12:17:36 +0100 Subject: [PATCH 10/14] update coverage again --- packages/snaps-utils/coverage.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/snaps-utils/coverage.json b/packages/snaps-utils/coverage.json index b7d146113b..a9248b7438 100644 --- a/packages/snaps-utils/coverage.json +++ b/packages/snaps-utils/coverage.json @@ -2,5 +2,5 @@ "branches": 99.74, "functions": 98.93, "lines": 99.46, - "statements": 96.25 + "statements": 96.31 } From 94fd0aa62480518a0a88a9f3f663ea82c0b9dc89 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Tue, 10 Dec 2024 12:31:15 +0100 Subject: [PATCH 11/14] add support for `onSettingsPage` in `snaps-simulation` and `snaps-jest` --- .../packages/settings-page/snap.manifest.json | 2 +- .../packages/settings-page/src/index.test.tsx | 17 +++--- .../packages/settings-page/src/index.tsx | 55 ++----------------- packages/snaps-jest/src/helpers.test.tsx | 26 +++++++++ packages/snaps-jest/src/helpers.ts | 2 + .../snaps-simulation/src/helpers.test.tsx | 26 +++++++++ packages/snaps-simulation/src/helpers.ts | 27 +++++++++ .../src/methods/specifications.test.ts | 9 +++ packages/snaps-simulation/src/types.ts | 7 +++ 9 files changed, 110 insertions(+), 61 deletions(-) diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json index df8810766d..23091f669d 100644 --- a/packages/examples/packages/settings-page/snap.manifest.json +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "yWcDv7XuV/FGRxKdOMkelR4qB0Ivel7oP9fEuNz0EE8=", + "shasum": "Ha9z5pHnxqQOH7GQoWBcj99quZy5eqRMzjxOKCEIIQI=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/examples/packages/settings-page/src/index.test.tsx b/packages/examples/packages/settings-page/src/index.test.tsx index b33376d1c5..47954a2623 100644 --- a/packages/examples/packages/settings-page/src/index.test.tsx +++ b/packages/examples/packages/settings-page/src/index.test.tsx @@ -1,22 +1,19 @@ import { describe, it } from '@jest/globals'; import { installSnap } from '@metamask/snaps-jest'; -import { Box, Text } from '@metamask/snaps-sdk/jsx'; +import { Box, Heading, Text } from '@metamask/snaps-sdk/jsx'; -describe('onHomePage', () => { +describe('onSettingsPage', () => { it('returns custom UI', async () => { - const { onHomePage } = await installSnap(); + const { onSettingsPage } = await installSnap(); - const response = await onHomePage(); + const response = await onSettingsPage(); const screen = response.getInterface(); - await screen.clickElement('footer_button'); - - const newUi = response.getInterface(); - - expect(newUi).toRender( + expect(screen).toRender( - Footer button was pressed + Hello world! + Welcome to my Snap settings page! , ); }); diff --git a/packages/examples/packages/settings-page/src/index.tsx b/packages/examples/packages/settings-page/src/index.tsx index 5206feb893..33a6270842 100644 --- a/packages/examples/packages/settings-page/src/index.tsx +++ b/packages/examples/packages/settings-page/src/index.tsx @@ -1,17 +1,5 @@ import type { OnSettingsPageHandler } from '@metamask/snaps-sdk'; -import { - assert, - UserInputEventType, - type OnUserInputHandler, -} from '@metamask/snaps-sdk'; -import { - Box, - Container, - Footer, - Heading, - Text, - Button, -} from '@metamask/snaps-sdk/jsx'; +import { Box, Heading, Text } from '@metamask/snaps-sdk/jsx'; /** * Handle incoming settings page requests from the MetaMask clients. @@ -22,43 +10,10 @@ import { export const onSettingsPage: OnSettingsPageHandler = async () => { return { content: ( - - - Hello world! - Welcome to my Snap settings page! - -
- -
-
+ + Hello world! + Welcome to my Snap settings page! + ), }; }; - -/** - * Handle incoming user events coming from the Snap interface. - * - * @param params - The event parameters. - * @param params.id - The Snap interface ID where the event was fired. - * @param params.event - The event object containing the event type, name and - * value. - * @see https://docs.metamask.io/snaps/reference/exports/#onuserinput - */ -export const onUserInput: OnUserInputHandler = async ({ event, id }) => { - // Since this Snap only has one event, we can assert the event type and name - // directly. - assert(event.type === UserInputEventType.ButtonClickEvent); - assert(event.name === 'footer_button'); - - await snap.request({ - method: 'snap_updateInterface', - params: { - id, - ui: ( - - Footer button was pressed - - ), - }, - }); -}; diff --git a/packages/snaps-jest/src/helpers.test.tsx b/packages/snaps-jest/src/helpers.test.tsx index 684490c54a..6f7ccf69ba 100644 --- a/packages/snaps-jest/src/helpers.test.tsx +++ b/packages/snaps-jest/src/helpers.test.tsx @@ -774,6 +774,32 @@ describe('installSnap', () => { }); }); + describe('getSettingsPage', () => { + it('sends a OnSettingsPage request and returns the result', async () => { + jest.spyOn(console, 'log').mockImplementation(); + + const { snapId, close: closeServer } = await getMockServer({ + sourceCode: ` + module.exports.onSettingsPage = async () => { + return { content: { type: 'text', value: 'Hello, world!' } }; + }; + `, + }); + + const { onSettingsPage, close } = await installSnap(snapId); + const response = await onSettingsPage(); + + expect(response).toStrictEqual( + expect.objectContaining({ + getInterface: expect.any(Function), + }), + ); + + await close(); + await closeServer(); + }); + }); + describe('onKeyringRequest', () => { it('sends a keyring request and returns the result', async () => { jest.spyOn(console, 'log').mockImplementation(); diff --git a/packages/snaps-jest/src/helpers.ts b/packages/snaps-jest/src/helpers.ts index a4d3d38d33..0688084cd6 100644 --- a/packages/snaps-jest/src/helpers.ts +++ b/packages/snaps-jest/src/helpers.ts @@ -178,6 +178,7 @@ export async function installSnap< onCronjob, runCronjob, onHomePage, + onSettingsPage, onKeyringRequest, onInstall, onUpdate, @@ -194,6 +195,7 @@ export async function installSnap< onCronjob, runCronjob, onHomePage, + onSettingsPage, onKeyringRequest, onInstall, onUpdate, diff --git a/packages/snaps-simulation/src/helpers.test.tsx b/packages/snaps-simulation/src/helpers.test.tsx index e8f83c4646..53368ef92a 100644 --- a/packages/snaps-simulation/src/helpers.test.tsx +++ b/packages/snaps-simulation/src/helpers.test.tsx @@ -548,6 +548,32 @@ describe('helpers', () => { }); }); + describe('getSettingsPage', () => { + it('sends a OnSettingsPage request and returns the result', async () => { + jest.spyOn(console, 'log').mockImplementation(); + + const { snapId, close: closeServer } = await getMockServer({ + sourceCode: ` + module.exports.onSettingsPage = async () => { + return { content: { type: 'text', value: 'Hello, world!' } }; + }; + `, + }); + + const { onSettingsPage, close } = await installSnap(snapId); + const response = await onSettingsPage(); + + expect(response).toStrictEqual( + expect.objectContaining({ + getInterface: expect.any(Function), + }), + ); + + await close(); + await closeServer(); + }); + }); + describe('onKeyringRequest', () => { it('sends a keyring request and returns the result', async () => { jest.spyOn(console, 'log').mockImplementation(); diff --git a/packages/snaps-simulation/src/helpers.ts b/packages/snaps-simulation/src/helpers.ts index 639b119a77..8ec77c2513 100644 --- a/packages/snaps-simulation/src/helpers.ts +++ b/packages/snaps-simulation/src/helpers.ts @@ -118,6 +118,13 @@ export type SnapHelpers = { */ onHomePage(): Promise; + /** + * Get the response from the snap's `onSettingsPage` method. + * + * @returns The response. + */ + onSettingsPage(): Promise; + /** * Send a keyring request to the Snap. * @@ -402,6 +409,26 @@ export function getHelpers({ return response; }, + onSettingsPage: async (): Promise => { + log('Rendering settings page.'); + + const response = await handleRequest({ + snapId, + store, + executionService, + controllerMessenger, + runSaga, + handler: HandlerType.OnSettingsPage, + request: { + method: '', + }, + }); + + assertIsResponseWithInterface(response); + + return response; + }, + mockJsonRpc(mock: JsonRpcMockOptions) { log('Mocking JSON-RPC request %o.', mock); diff --git a/packages/snaps-simulation/src/methods/specifications.test.ts b/packages/snaps-simulation/src/methods/specifications.test.ts index 487eda7235..2c556403e4 100644 --- a/packages/snaps-simulation/src/methods/specifications.test.ts +++ b/packages/snaps-simulation/src/methods/specifications.test.ts @@ -123,6 +123,15 @@ describe('getPermissionSpecifications', () => { ], "targetName": "endowment:page-home", }, + "endowment:page-settings": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:page-settings", + }, "endowment:rpc": { "allowedCaveats": [ "rpcOrigin", diff --git a/packages/snaps-simulation/src/types.ts b/packages/snaps-simulation/src/types.ts index 21bc37c7ea..5bb52f557c 100644 --- a/packages/snaps-simulation/src/types.ts +++ b/packages/snaps-simulation/src/types.ts @@ -420,6 +420,13 @@ export type Snap = { */ onHomePage(): Promise; + /** + * Get the response from the snap's `onSettingsPage` method. + * + * @returns The response. + */ + onSettingsPage(): Promise; + /** * Send a keyring to the Snap. * From ea4b4e48be98597a9d01ecf4862998e3d83a95a9 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Tue, 10 Dec 2024 12:52:32 +0100 Subject: [PATCH 12/14] update manifests --- packages/examples/packages/settings-page/snap.manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json index 23091f669d..77f377ec7c 100644 --- a/packages/examples/packages/settings-page/snap.manifest.json +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "Ha9z5pHnxqQOH7GQoWBcj99quZy5eqRMzjxOKCEIIQI=", + "shasum": "3ALmFgSTATWDBMOVlvPbwPWdtkp98ewtZGFvRQysJB4=", "location": { "npm": { "filePath": "dist/bundle.js", From 21dac9d6f3ed7e591f78a10dfe4aa2bcb797cdd4 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Wed, 11 Dec 2024 12:05:05 +0100 Subject: [PATCH 13/14] add `SettingCell` component --- .../src/jsx/components/SettingCell.test.tsx | 28 +++++++++++ .../src/jsx/components/SettingCell.ts | 44 +++++++++++++++++ .../snaps-sdk/src/jsx/components/index.ts | 5 +- .../snaps-sdk/src/jsx/validation.test.tsx | 47 +++++++++++++++++++ packages/snaps-sdk/src/jsx/validation.ts | 15 ++++++ 5 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 packages/snaps-sdk/src/jsx/components/SettingCell.test.tsx create mode 100644 packages/snaps-sdk/src/jsx/components/SettingCell.ts diff --git a/packages/snaps-sdk/src/jsx/components/SettingCell.test.tsx b/packages/snaps-sdk/src/jsx/components/SettingCell.test.tsx new file mode 100644 index 0000000000..2312e059b7 --- /dev/null +++ b/packages/snaps-sdk/src/jsx/components/SettingCell.test.tsx @@ -0,0 +1,28 @@ +import { Input } from './form'; +import { SettingCell } from './SettingCell'; + +describe('SettingCell', () => { + it('renders a setting cell', () => { + const result = ( + + + + ); + + expect(result).toStrictEqual({ + type: 'SettingCell', + key: null, + props: { + title: 'Title', + description: 'Description', + children: { + type: 'Input', + key: null, + props: { + name: 'setting1', + }, + }, + }, + }); + }); +}); diff --git a/packages/snaps-sdk/src/jsx/components/SettingCell.ts b/packages/snaps-sdk/src/jsx/components/SettingCell.ts new file mode 100644 index 0000000000..53c2f74960 --- /dev/null +++ b/packages/snaps-sdk/src/jsx/components/SettingCell.ts @@ -0,0 +1,44 @@ +import { + createSnapComponent, + type GenericSnapElement, + type SnapsChildren, +} from '../component'; + +/** + * The props of the {@link SettingCell} component. + * + * @property title - The title. + * @property description - The description. + * @property children - The children to show within the cell. + */ +export type SettingCellProps = { + title: string; + description: string; + children: SnapsChildren; +}; + +const TYPE = 'SettingCell'; + +/** + * A setting cell component which can be used to display a setting control. + * + * @param props - The props of the component. + * @param props.title - The title. + * @param props.description - The description. + * @param props.children - The children to show within the cell. + * @returns A setting cell element. + * @example + * + * + * + */ +export const SettingCell = createSnapComponent( + TYPE, +); + +/** + * A setting cell element. + * + * @see SettingCell + */ +export type SettingCellElement = ReturnType; diff --git a/packages/snaps-sdk/src/jsx/components/index.ts b/packages/snaps-sdk/src/jsx/components/index.ts index bc64836bb2..1a6051b110 100644 --- a/packages/snaps-sdk/src/jsx/components/index.ts +++ b/packages/snaps-sdk/src/jsx/components/index.ts @@ -14,6 +14,7 @@ import type { ImageElement } from './Image'; import type { LinkElement } from './Link'; import type { RowElement } from './Row'; import type { SectionElement } from './Section'; +import type { SettingCellElement } from './SettingCell'; import type { SpinnerElement } from './Spinner'; import type { TextElement } from './Text'; import type { TooltipElement } from './Tooltip'; @@ -39,6 +40,7 @@ export * from './Tooltip'; export * from './Footer'; export * from './Container'; export * from './Section'; +export * from './SettingCell'; /** * A built-in JSX element, which can be used in a Snap user interface. @@ -63,4 +65,5 @@ export type JSXElement = | SectionElement | SpinnerElement | TextElement - | TooltipElement; + | TooltipElement + | SettingCellElement; diff --git a/packages/snaps-sdk/src/jsx/validation.test.tsx b/packages/snaps-sdk/src/jsx/validation.test.tsx index f755a75d70..7fdbf97d31 100644 --- a/packages/snaps-sdk/src/jsx/validation.test.tsx +++ b/packages/snaps-sdk/src/jsx/validation.test.tsx @@ -33,6 +33,7 @@ import { SelectorOption, Section, Avatar, + SettingCell, } from './components'; import { AddressStruct, @@ -70,6 +71,7 @@ import { SelectorStruct, SectionStruct, AvatarStruct, + SettingCellStruct, } from './validation'; describe('KeyStruct', () => { @@ -1414,6 +1416,51 @@ describe('SectionStruct', () => { }); }); +describe('SettingCellStruct', () => { + it.each([ + + + , + + + + + , + +
+ +
+
, + ])('validates a setting cell element', (value) => { + expect(is(value, SettingCellStruct)).toBe(true); + }); + + it.each([ + 'foo', + 42, + null, + undefined, + {}, + [], + // @ts-expect-error - Invalid props. + , + // @ts-expect-error - Invalid props. + + + , + + + , + + alt + , + // @ts-expect-error - Invalid props. + , + ])('does not validate "%p"', (value) => { + expect(is(value, SettingCellStruct)).toBe(false); + }); +}); + describe('isJSXElement', () => { it.each([ foo, diff --git a/packages/snaps-sdk/src/jsx/validation.ts b/packages/snaps-sdk/src/jsx/validation.ts index be3702912b..77f0e7e633 100644 --- a/packages/snaps-sdk/src/jsx/validation.ts +++ b/packages/snaps-sdk/src/jsx/validation.ts @@ -84,6 +84,7 @@ import { type SelectorOptionElement, IconName, } from './components'; +import type { SettingCellElement } from './components/SettingCell'; /** * A struct for the {@link Key} type. @@ -633,6 +634,18 @@ export const SectionStruct: Describe = element('Section', { ), }); +/** + * A struct for the {@link SettingCellElement} type. + */ +export const SettingCellStruct: Describe = element( + 'SettingCell', + { + children: BoxChildrenStruct, + title: string(), + description: string(), + }, +); + /** * A subset of JSX elements that are allowed as children of the Footer component. * This set should include a single button or a tuple of two buttons. @@ -821,6 +834,7 @@ export const BoxChildStruct = typedUnion([ SelectorStruct, SectionStruct, AvatarStruct, + SettingCellStruct, ]); /** @@ -886,6 +900,7 @@ export const JSXElementStruct: Describe = typedUnion([ SelectorOptionStruct, SectionStruct, AvatarStruct, + SettingCellStruct, ]); /** From b78c61cd48370ce6c2a29818e9d071462bee7eef Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Fri, 13 Dec 2024 10:54:36 +0100 Subject: [PATCH 14/14] update manifests after rebase --- .../examples/packages/browserify-plugin/snap.manifest.json | 2 +- packages/examples/packages/browserify/snap.manifest.json | 2 +- packages/examples/packages/settings-page/snap.manifest.json | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/examples/packages/browserify-plugin/snap.manifest.json b/packages/examples/packages/browserify-plugin/snap.manifest.json index e9c820531b..f68f25de57 100644 --- a/packages/examples/packages/browserify-plugin/snap.manifest.json +++ b/packages/examples/packages/browserify-plugin/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "eug1Oxfxo/X97epSDNuF3elpxJUBNGgPgfvvmVxShxo=", + "shasum": "35HQhxL4gofSuKHVUys68L7FJfbI+6gaNrVPOBl20Mo=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/examples/packages/browserify/snap.manifest.json b/packages/examples/packages/browserify/snap.manifest.json index ef628744cf..48488e7653 100644 --- a/packages/examples/packages/browserify/snap.manifest.json +++ b/packages/examples/packages/browserify/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "Jh7Kcnzc5flRZM4SL8yQnMBj99YrmU91iLLaIxH2o/k=", + "shasum": "M/1ovz7O+iaOD9387jISV8LlmXbTxLO3AlWbnv2pEOc=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json index 77f377ec7c..da1bbf29cb 100644 --- a/packages/examples/packages/settings-page/snap.manifest.json +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "3ALmFgSTATWDBMOVlvPbwPWdtkp98ewtZGFvRQysJB4=", + "shasum": "9xTn79sMhMLJJgSKn/6kfI+VTEKv9J1acTVlM2Le2ac=", "location": { "npm": { "filePath": "dist/bundle.js", @@ -19,5 +19,6 @@ "initialPermissions": { "endowment:page-settings": {} }, + "platformVersion": "6.13.0", "manifestVersion": "0.1" }