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

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
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": "Vm44DmG3HizDFI1VHohwXafP+dnv3evvlhgFmB8DX98=",
"shasum": "FvNPBDpxgcjSkTlVJ73Xi15wnD1MvkaJyIJqFK6eW3I=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
21 changes: 20 additions & 1 deletion packages/examples/packages/ethereum-provider/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,23 @@ import {
hexToNumber,
} from '@metamask/utils';

import type { PersonalSignParams, SignTypedDataParams } from './types';
import type {
BaseParams,
PersonalSignParams,
SignTypedDataParams,
} 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 @@ -207,6 +223,9 @@ async function signTypedData(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);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably not a problem, but i think always using mainnet makes it possible in the extension e2e tests that use this snap to try to hit the mainnet infura endpoint, but I think that's probably only the case if something triggers getGasPrice and i'm not certain there is an extension e2e test that does that. Just pointing this out in case I am wrong


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,4 +1,10 @@
export type PersonalSignParams = {
import type { Hex } from '@metamask/utils';

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

export type PersonalSignParams = BaseParams & {
message: string;
};

Expand Down
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": 93.31,
"branches": 93.34,
"functions": 96.8,
"lines": 98.15,
"statements": 97.88
"lines": 98.16,
"statements": 97.89
}
210 changes: 210 additions & 0 deletions packages/snaps-controllers/src/snaps/SnapController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1842,7 +1842,7 @@
});

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

Check warning on line 1845 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 @@ -5330,6 +5330,216 @@
snapController.destroy();
});

it('grants the `endowment:caip25` permission to a Snap with `endowment:ethereum-provider` if the `useCaip25Permission` feature flag is enabled', async () => {
Copy link
Member

@FrederikBolding FrederikBolding Feb 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add some tests for updating a Snap? That it also grants the permission and maybe revokes the permission as well? I can't recall what happens to eth_accounts normally actually

const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);

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

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

rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() => ({
configuration: {
chainId: '0x1',
},
}),
);

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

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

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

const approvedPermissions = {
'endowment:page-home': {
caveats: null,
},
'endowment:ethereum-provider': {},
'endowment:caip25': {
caveats: [
{
type: 'authorizedScopes',
value: {
requiredScopes: {},
optionalScopes: {
'eip155:1': {
accounts: [],
},
},
sessionProperties: {},
isMultichainOrigin: false,
},
},
],
},
};

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

snapController.destroy();
});

it('does not grant the `endowment:caip25` permission to a Snap with `endowment:ethereum-provider` if the `useCaip25Permission` feature flag is disabled', async () => {
const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);

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

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

rootMessenger.registerActionHandler(
'NetworkController:getNetworkClientById',
() => ({
configuration: {
chainId: '0x1',
},
}),
);

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

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

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

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

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

snapController.destroy();
});

it('does not grant the `endowment:caip25` 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 }),
featureFlags: {
useCaip25Permission: true,
},
}),
);

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