Skip to content

feat: When switching network alert the user and get approval if there are pending requests from origin. #30674

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

Merged
merged 7 commits into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions app/_locales/en_GB/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ async function addEthereumChainHandler(
updatedNetwork.rpcEndpoints[updatedNetwork.defaultRpcEndpointIndex];

return switchChain(res, end, chainId, networkClientId, {
isAddFlow: true,
autoApprove: shouldAddOrUpdateNetwork,
setActiveNetwork,
getCaveat,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const createMockedHandler = () => {
const next = jest.fn();
const end = jest.fn();
const mocks = {
isAddFlow: true,
getCurrentChainIdForDomain: jest.fn().mockReturnValue(NON_INFURA_CHAIN_ID),
setNetworkClientIdForDomain: jest.fn(),
getNetworkConfigurationByChainId: jest.fn(),
Expand Down Expand Up @@ -186,6 +187,7 @@ describe('addEthereumChainHandler', () => {
{
autoApprove: true,
getCaveat: mocks.getCaveat,
isAddFlow: true,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionIncrementalForOrigin:
mocks.requestPermittedChainsPermissionIncrementalForOrigin,
Expand Down Expand Up @@ -252,6 +254,7 @@ describe('addEthereumChainHandler', () => {
{
autoApprove: true,
getCaveat: mocks.getCaveat,
isAddFlow: true,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionIncrementalForOrigin:
mocks.requestPermittedChainsPermissionIncrementalForOrigin,
Expand Down Expand Up @@ -299,6 +302,7 @@ describe('addEthereumChainHandler', () => {
{
autoApprove: false,
getCaveat: mocks.getCaveat,
isAddFlow: true,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionIncrementalForOrigin:
mocks.requestPermittedChainsPermissionIncrementalForOrigin,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ApprovalType } from '@metamask/controller-utils';
import { rpcErrors } from '@metamask/rpc-errors';
import {
Caip25CaveatType,
Expand Down Expand Up @@ -165,12 +166,18 @@ export function validateAddEthereumChainParams(params) {
* @param {string} chainId - The chainId being switched to.
* @param {string} networkClientId - The network client being switched to.
* @param {object} hooks - The hooks object.
* @param {string} hooks.origin - The origin sending this request.
* @param {boolean} hooks.isAddFlow - Variable to check if its add flow.
* @param {boolean} [hooks.autoApprove] - A boolean indicating whether the request should prompt the user or be automatically approved.
* @param {Function} hooks.setActiveNetwork - The callback to change the current network for the origin.
* @param {Function} hooks.getCaveat - The callback to get the CAIP-25 caveat for the origin.
* @param {Function} hooks.requestPermittedChainsPermissionIncrementalForOrigin - The callback to add a new chain to the permittedChains-equivalent CAIP-25 permission.
* @param {Function} hooks.setTokenNetworkFilter - The callback to set the token network filter.
* @param {Function} hooks.rejectApprovalRequestsForOrigin - The callback to reject all pending approval requests for the origin.
* @param {Function} hooks.requestUserApproval - The callback to trigger user approval flow.
* @param {Function} hooks.hasApprovalRequestsForOrigin - Function to check if there are pending approval requests from the origin.
* @param {object} hooks.toNetworkConfiguration - Network configutation of network switching to.
* @param {object} hooks.fromNetworkConfiguration - Network configutation of network switching from.
* @returns a null response on success or an error if user rejects an approval when autoApprove is false or on unexpected errors.
*/
export async function switchChain(
Expand All @@ -179,12 +186,18 @@ export async function switchChain(
chainId,
networkClientId,
{
origin,
isAddFlow,
autoApprove,
setActiveNetwork,
getCaveat,
requestPermittedChainsPermissionIncrementalForOrigin,
setTokenNetworkFilter,
rejectApprovalRequestsForOrigin,
requestUserApproval,
hasApprovalRequestsForOrigin,
toNetworkConfiguration,
fromNetworkConfiguration,
},
) {
try {
Expand All @@ -201,6 +214,15 @@ export async function switchChain(
chainId,
autoApprove,
});
} else if (hasApprovalRequestsForOrigin?.() && !isAddFlow) {
await requestUserApproval({
origin,
type: ApprovalType.SwitchEthereumChain,
requestData: {
toNetworkConfiguration,
fromNetworkConfiguration,
},
});
}
} else {
await requestPermittedChainsPermissionIncrementalForOrigin({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as Multichain from '@metamask/multichain';
import { errorCodes, rpcErrors } from '@metamask/rpc-errors';
import {
Caip25CaveatType,
Expand All @@ -10,12 +11,18 @@ describe('Ethereum Chain Utils', () => {
const createMockedSwitchChain = () => {
const end = jest.fn();
const mocks = {
origin: 'www.test.com',
isAddFlow: false,
autoApprove: false,
setActiveNetwork: jest.fn(),
getCaveat: jest.fn(),
requestPermittedChainsPermissionIncrementalForOrigin: jest.fn(),
setTokenNetworkFilter: jest.fn(),
rejectApprovalRequestsForOrigin: jest.fn(),
requestUserApproval: jest.fn(),
hasApprovalRequestsForOrigin: jest.fn(),
toNetworkConfiguration: {},
fromNetworkConfiguration: {},
};
const response: { result?: true } = {};
const switchChain = (chainId: Hex, networkClientId: string) =>
Expand Down Expand Up @@ -125,6 +132,25 @@ describe('Ethereum Chain Utils', () => {
expect(mocks.setTokenNetworkFilter).toHaveBeenCalledWith('0x1');
});

it('check for user approval is user already has access on the chain', async () => {
jest
.spyOn(Multichain, 'getPermittedEthChainIds')
.mockReturnValue(['0x1']);
const { mocks, switchChain } = createMockedSwitchChain();
mocks.hasApprovalRequestsForOrigin.mockReturnValue(true);
mocks.autoApprove = false;
mocks.getCaveat.mockReturnValue({
value: {
requiredScopes: {},
optionalScopes: {},
isMultichainOrigin: false,
},
});
await switchChain('0x1', 'testnet');

expect(mocks.requestUserApproval).toHaveBeenCalledTimes(1);
});

it('should throw errors if the permittedChains grant fails', async () => {
const { mocks, end, switchChain } = createMockedSwitchChain();
mocks.requestPermittedChainsPermissionIncrementalForOrigin.mockRejectedValueOnce(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { providerErrors } from '@metamask/rpc-errors';

import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
validateSwitchEthereumChainParams,
Expand All @@ -11,10 +12,12 @@ const switchEthereumChain = {
hookNames: {
getNetworkConfigurationByChainId: true,
setActiveNetwork: true,
requestUserApproval: true,
getCaveat: true,
getCurrentChainIdForDomain: true,
requestPermittedChainsPermissionIncrementalForOrigin: true,
setTokenNetworkFilter: true,
hasApprovalRequestsForOrigin: true,
},
};

Expand All @@ -28,10 +31,12 @@ async function switchEthereumChainHandler(
{
getNetworkConfigurationByChainId,
setActiveNetwork,
requestUserApproval,
getCaveat,
getCurrentChainIdForDomain,
requestPermittedChainsPermissionIncrementalForOrigin,
setTokenNetworkFilter,
hasApprovalRequestsForOrigin,
},
) {
let chainId;
Expand Down Expand Up @@ -64,10 +69,21 @@ async function switchEthereumChainHandler(
);
}

const fromNetworkConfiguration = getNetworkConfigurationByChainId(
currentChainIdForOrigin,
);

const toNetworkConfiguration = getNetworkConfigurationByChainId(chainId);

return switchChain(res, end, chainId, networkClientIdToSwitchTo, {
origin,
setActiveNetwork,
getCaveat,
requestPermittedChainsPermissionIncrementalForOrigin,
setTokenNetworkFilter,
requestUserApproval,
hasApprovalRequestsForOrigin,
toNetworkConfiguration,
fromNetworkConfiguration,
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const createMockedHandler = () => {
const next = jest.fn();
const end = jest.fn();
const mocks = {
hasApprovalRequestsForOrigin: () => false,
getNetworkConfigurationByChainId: jest
.fn()
.mockReturnValue(createMockMainnetConfiguration()),
Expand All @@ -47,6 +48,7 @@ const createMockedHandler = () => {
getCurrentChainIdForDomain: jest.fn().mockReturnValue(NON_INFURA_CHAIN_ID),
requestPermittedChainsPermissionIncrementalForOrigin: jest.fn(),
setTokenNetworkFilter: jest.fn(),
requestUserApproval: jest.fn(),
};
const response = {};
const handler = (request) =>
Expand Down Expand Up @@ -167,10 +169,31 @@ describe('switchEthereumChainHandler', () => {
'mainnet',
{
setActiveNetwork: mocks.setActiveNetwork,
fromNetworkConfiguration: {
chainId: '0xe708',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'linea-mainnet',
},
],
},
getCaveat: mocks.getCaveat,
hasApprovalRequestsForOrigin: mocks.hasApprovalRequestsForOrigin,
origin: 'example.com',
requestPermittedChainsPermissionIncrementalForOrigin:
mocks.requestPermittedChainsPermissionIncrementalForOrigin,
requestUserApproval: mocks.requestUserApproval,
setTokenNetworkFilter: mocks.setTokenNetworkFilter,
toNetworkConfiguration: {
chainId: '0x1',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'mainnet',
},
],
},
},
);
});
Expand Down
2 changes: 2 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6197,6 +6197,8 @@ export default class MetamaskController extends EventEmitter {
this.permissionController,
origin,
),
hasApprovalRequestsForOrigin: () =>
this.approvalController.has({ origin }),
rejectApprovalRequestsForOrigin: () =>
this.rejectOriginPendingApprovals(origin),

Expand Down
3 changes: 0 additions & 3 deletions builds.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ buildTypes:
- REJECT_INVALID_SNAPS_PLATFORM_VERSION: true
- IFRAME_EXECUTION_ENVIRONMENT_URL: https://execution.metamask.io/iframe/7.0.0/index.html
- ACCOUNT_SNAPS_DIRECTORY_URL: https://snaps.metamask.io/account-management
- EVM_MULTICHAIN_ENABLED: false
# Modifies how the version is displayed.
# eg. instead of 10.25.0 -> 10.25.0-beta.2
isPrerelease: true
Expand Down Expand Up @@ -90,7 +89,6 @@ buildTypes:
- SEGMENT_WRITE_KEY_REF: SEGMENT_FLASK_WRITE_KEY
- ACCOUNT_SNAPS_DIRECTORY_URL: https://metamask.github.io/snaps-directory-staging/main/account-management
- EIP_4337_ENTRYPOINT: '0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789'
- EVM_MULTICHAIN_ENABLED: false
isPrerelease: true
manifestOverrides: ./app/build-types/flask/manifest/
buildNameOverride: MetaMask Flask
Expand All @@ -113,7 +111,6 @@ buildTypes:
- SUPPORT_LINK: https://support.metamask-institutional.io
- SUPPORT_REQUEST_LINK: https://support.metamask-institutional.io
- SENTRY_DSN: SENTRY_MMI_DSN
- EVM_MULTICHAIN_ENABLED: false
# For some reason, MMI uses this type of versioning
# Leaving it on for backwards compatibility
isPrerelease: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useDispatch } from 'react-redux';
import mockState from '../../../../../test/data/mock-state.json';
import { renderHookWithProvider } from '../../../../../test/lib/render-helpers';
import * as AlertActions from '../../../../ducks/confirm-alerts/confirm-alerts';
import * as AddEthereumChainAlerts from './useAddEthereumChainAlerts';
import * as UpdateEthereumChainAlerts from './useUpdateEthereumChainAlerts';

import { useTemplateConfirmationAlerts } from './useTemplateConfirmationAlerts';

Expand Down Expand Up @@ -34,7 +34,7 @@ describe('updateConfirmationAlerts', () => {
const mockDispatch = jest.fn();
(useDispatch as jest.Mock).mockReturnValue(mockDispatch);
jest
.spyOn(AddEthereumChainAlerts, 'useAddEthereumChainAlerts')
.spyOn(UpdateEthereumChainAlerts, 'useUpdateEthereumChainAlerts')
.mockReturnValue(MOCK_ADD_ETH_CHAIN_ALERT);
const mockUpdateAlerts = jest.spyOn(AlertActions, 'updateAlerts');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import {
clearAlerts,
updateAlerts,
} from '../../../../ducks/confirm-alerts/confirm-alerts';
import { useAddEthereumChainAlerts } from './useAddEthereumChainAlerts';
import { useUpdateEthereumChainAlerts } from './useUpdateEthereumChainAlerts';

export const useTemplateConfirmationAlerts = (
pendingConfirmation: ApprovalRequest<{ id: string }>,
) => {
const dispatch = useDispatch();
const addEthereumChainAlerts = useAddEthereumChainAlerts(pendingConfirmation);
const addEthereumChainAlerts =
useUpdateEthereumChainAlerts(pendingConfirmation);
const alerts: Alert[] = useMemo(
() => addEthereumChainAlerts,
[addEthereumChainAlerts],
Expand Down
Loading
Loading