Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unblock wallet_switchEthereumChain #2634

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/snaps.git"
},
"source": {
"shasum": "pAw1i97eZQAkVu1vghgoOKBdA5EImKc8HuC3rQyLo7k=",
"shasum": "u/BaDj7fzOZvB+bPRLbkBie65a5oxunLABteu1+qWns=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
17 changes: 16 additions & 1 deletion packages/examples/packages/ethereum-provider/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,19 @@ import {
import type { Hex } from '@metamask/utils';
import { assert, stringToBytes, bytesToHex } from '@metamask/utils';

import type { PersonalSignParams } from './types';
import type { BaseParams, PersonalSignParams } from './types';

/**
* Set the active Ethereum chain for the Snap.
*
* @param chainId - The chain ID to switch to.
*/
async function switchChain(chainId: Hex) {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId }],
});
}

/**
* Get the current gas price using the `ethereum` global. This is essentially
Expand Down Expand Up @@ -106,6 +118,9 @@ async function personalSign(message: string, from: string) {
* @see https://docs.metamask.io/snaps/reference/rpc-api/#wallet_invokesnap
*/
export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => {
const { chainId = '0x1' } = (request.params as BaseParams) ?? {};
await switchChain(chainId);

switch (request.method) {
case 'getGasPrice':
return await getGasPrice();
Expand Down
8 changes: 7 additions & 1 deletion packages/examples/packages/ethereum-provider/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export type PersonalSignParams = {
import type { Hex } from '@metamask/utils';

export type BaseParams = {
chainId?: Hex;
};

export type PersonalSignParams = BaseParams & {
message: string;
};
6 changes: 3 additions & 3 deletions packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"branches": 92.54,
"branches": 92.56,
"functions": 96.91,
"lines": 98.01,
"statements": 97.71
"lines": 98.02,
"statements": 97.72
}
2 changes: 2 additions & 0 deletions packages/snaps-controllers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,13 @@
"@metamask/base-controller": "^6.0.2",
"@metamask/json-rpc-engine": "^9.0.2",
"@metamask/json-rpc-middleware-stream": "^8.0.2",
"@metamask/network-controller": "^20.1.0",
"@metamask/object-multiplex": "^2.0.0",
"@metamask/permission-controller": "^11.0.0",
"@metamask/phishing-controller": "^10.1.1",
"@metamask/post-message-stream": "^8.1.0",
"@metamask/rpc-errors": "^6.3.1",
"@metamask/selected-network-controller": "^17.0.0",
"@metamask/snaps-registry": "^3.2.1",
"@metamask/snaps-rpc-methods": "workspace:^",
"@metamask/snaps-sdk": "workspace:^",
Expand Down
220 changes: 219 additions & 1 deletion packages/snaps-controllers/src/snaps/SnapController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@
sleep,
} from '../test-utils';
import { delay } from '../utils';
import { LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS } from './constants';
import {
LEGACY_ENCRYPTION_KEY_DERIVATION_OPTIONS,
PERMITTED_CHAINS_ENDOWMENT,
} from './constants';
import { SnapsRegistryStatus } from './registry';
import type { SnapControllerState } from './SnapController';
import {
Expand Down Expand Up @@ -1848,7 +1851,7 @@
});

// This isn't stable in CI unfortunately
it.skip('throws if the Snap is terminated while executing', async () => {

Check warning on line 1854 in packages/snaps-controllers/src/snaps/SnapController.test.tsx

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (@metamask/snaps-controllers)

Disabled test
const { manifest, sourceCode, svgIcon } =
await getMockSnapFilesWithUpdatedChecksum({
sourceCode: `
Expand Down Expand Up @@ -4628,6 +4631,221 @@
snapController.destroy();
});

it('grants the `endowment:permitted-chains` permission to a Snap with `endowment:ethereum-provider`', async () => {
const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);

rootMessenger.registerActionHandler(
'PermissionController:getPermissions',
() => ({}),
);

rootMessenger.registerActionHandler(
'SelectedNetworkController:getNetworkClientIdForDomain',
() => 'mainnet',
);

rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() => ({
// @ts-expect-error - Partial network client.
configuration: {
chainId: '0x1',
},
}),
);

const { manifest } = await getMockSnapFilesWithUpdatedChecksum({
manifest: getSnapManifest({
initialPermissions: {
'endowment:page-home': {},
'endowment:ethereum-provider': {},
},
}),
});

const snapController = getSnapController(
getSnapControllerOptions({
messenger,
detectSnapLocation: loopbackDetect({ manifest }),
}),
);

await snapController.installSnaps(MOCK_ORIGIN, {
[MOCK_SNAP_ID]: {},
});

const approvedPermissions = {
'endowment:page-home': {
caveats: null,
},
'endowment:ethereum-provider': {},
[PERMITTED_CHAINS_ENDOWMENT]: {
caveats: [
{
type: 'restrictNetworkSwitching',
value: ['0x1'],
},
],
invoker: MOCK_SNAP_ID,
parentCapability: PERMITTED_CHAINS_ENDOWMENT,
},
};

expect(messenger.call).toHaveBeenCalledWith(
'PermissionController:grantPermissions',
{
approvedPermissions,
subject: { origin: MOCK_SNAP_ID },
requestData: expect.any(Object),
},
);

snapController.destroy();
});

it('overrides the `endowment:permitted-chains` permission if the Snap specifies it in its manifest', async () => {
const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);

rootMessenger.registerActionHandler(
'PermissionController:getPermissions',
() => ({}),
);

rootMessenger.registerActionHandler(
'SelectedNetworkController:getNetworkClientIdForDomain',
() => 'mainnet',
);

rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() => ({
// @ts-expect-error - Partial network client.
configuration: {
chainId: '0x1',
},
}),
);

const { manifest } = await getMockSnapFilesWithUpdatedChecksum({
manifest: getSnapManifest({
initialPermissions: {
'endowment:page-home': {},
'endowment:ethereum-provider': {},
// @ts-expect-error - There is no type definition for this.
'endowment:permitted-chains': {
caveats: [
{
type: 'restrictNetworkSwitching',
value: ['0x5'],
},
],
},
},
}),
});

const snapController = getSnapController(
getSnapControllerOptions({
messenger,
detectSnapLocation: loopbackDetect({ manifest }),
}),
);

await snapController.installSnaps(MOCK_ORIGIN, {
[MOCK_SNAP_ID]: {},
});

const approvedPermissions = {
'endowment:page-home': {
caveats: null,
},
'endowment:ethereum-provider': {},
[PERMITTED_CHAINS_ENDOWMENT]: {
caveats: [
{
type: 'restrictNetworkSwitching',
value: ['0x1'],
},
],
invoker: MOCK_SNAP_ID,
parentCapability: PERMITTED_CHAINS_ENDOWMENT,
},
};

expect(messenger.call).toHaveBeenCalledWith(
'PermissionController:grantPermissions',
{
approvedPermissions,
subject: { origin: MOCK_SNAP_ID },
requestData: expect.any(Object),
},
);

snapController.destroy();
});

it('does not grant the `endowment:permitted-chains` permission if the Snap does not have the `endowment:ethereum-provider` permission', async () => {
const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);

rootMessenger.registerActionHandler(
'PermissionController:getPermissions',
() => ({}),
);

rootMessenger.registerActionHandler(
'SelectedNetworkController:getNetworkClientIdForDomain',
() => {
throw new Error('This should not be called.');
},
);

rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() => {
throw new Error('This should not be called.');
},
);

const { manifest } = await getMockSnapFilesWithUpdatedChecksum({
manifest: getSnapManifest({
initialPermissions: {
'endowment:page-home': {},
},
}),
});

const snapController = getSnapController(
getSnapControllerOptions({
messenger,
detectSnapLocation: loopbackDetect({ manifest }),
}),
);

await snapController.installSnaps(MOCK_ORIGIN, {
[MOCK_SNAP_ID]: {},
});

const approvedPermissions = {
'endowment:page-home': {
caveats: null,
},
};

expect(messenger.call).toHaveBeenCalledWith(
'PermissionController:grantPermissions',
{
approvedPermissions,
subject: { origin: MOCK_SNAP_ID },
requestData: expect.any(Object),
},
);

snapController.destroy();
});

it('supports preinstalled snaps', async () => {
const rootMessenger = getControllerMessenger();
jest.spyOn(rootMessenger, 'call');
Expand Down
Loading
Loading