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

poc: dynamic switch network confirmation #29723

Draft
wants to merge 3 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
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -487,10 +487,11 @@ module.exports = {
'getNfts',
'getProviderConfig',
'getRpcPrefsForCurrentProvider',
'getSelectedNetworkClientId',
'getUSDConversionRate',
'isCurrentProviderCustom',
]
.map((method) => `(${method})`)
.map((method) => `^${method}$`)
.join('|')}/]`,
message: 'Avoid using global network selectors in confirmations',
},
Expand Down
17 changes: 15 additions & 2 deletions app/_locales/en/messages.json

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

5 changes: 0 additions & 5 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -1071,11 +1071,6 @@ export function setupController(
updateBadge,
);

controller.controllerMessenger.subscribe(
METAMASK_CONTROLLER_EVENTS.QUEUED_REQUEST_STATE_CHANGE,
updateBadge,
);

controller.controllerMessenger.subscribe(
METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_LIST_UPDATED,
updateBadge,
Expand Down
112 changes: 78 additions & 34 deletions app/scripts/lib/approval/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { ApprovalController } from '@metamask/approval-controller';
import {
ApprovalController,
ApprovalRequest,
} from '@metamask/approval-controller';
import { ApprovalType } from '@metamask/controller-utils';
import { DIALOG_APPROVAL_TYPES } from '@metamask/snaps-rpc-methods';
import { providerErrors } from '@metamask/rpc-errors';
import { createProjectLogger } from '@metamask/utils';
import { createProjectLogger, Json } from '@metamask/utils';
///: BEGIN:ONLY_INCLUDE_IF(keyring-snaps)
import { SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES } from '../../../../shared/constants/app';
///: END:ONLY_INCLUDE_IF
Expand All @@ -20,37 +23,78 @@ export function rejectAllApprovals({
const approvalRequests = Object.values(approvalRequestsById);

for (const approvalRequest of approvalRequests) {
const { id, type } = approvalRequest;
const interfaceId = approvalRequest.requestData?.id as string;

switch (type) {
case ApprovalType.SnapDialogAlert:
case ApprovalType.SnapDialogPrompt:
case DIALOG_APPROVAL_TYPES.default:
log('Rejecting snap dialog', { id, interfaceId });
approvalController.accept(id, null);
deleteInterface?.(interfaceId);
break;

case ApprovalType.SnapDialogConfirmation:
log('Rejecting snap confirmation', { id, interfaceId });
approvalController.accept(id, false);
deleteInterface?.(interfaceId);
break;

///: BEGIN:ONLY_INCLUDE_IF(keyring-snaps)
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.confirmAccountCreation:
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.confirmAccountRemoval:
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.showSnapAccountRedirect:
log('Rejecting snap account confirmation', { id });
approvalController.accept(id, false);
break;
///: END:ONLY_INCLUDE_IF

default:
log('Rejecting pending approval', { id });
approvalController.reject(id, providerErrors.userRejectedRequest());
break;
}
rejectApproval({
approvalController,
approvalRequest,
deleteInterface,
});
}
}

export function rejectOriginApprovals({
approvalController,
deleteInterface,
origin,
}: {
approvalController: ApprovalController;
deleteInterface?: (id: string) => void;
origin: string;
}) {
const approvalRequestsById = approvalController.state.pendingApprovals;
const approvalRequests = Object.values(approvalRequestsById);

const originApprovalRequests = approvalRequests.filter(
(approvalRequest) => approvalRequest.origin === origin,
);

for (const approvalRequest of originApprovalRequests) {
rejectApproval({
approvalController,
approvalRequest,
deleteInterface,
});
}
}

function rejectApproval({
approvalController,
approvalRequest,
deleteInterface,
}: {
approvalController: ApprovalController;
approvalRequest: ApprovalRequest<Record<string, Json>>;
deleteInterface?: (id: string) => void;
}) {
const { id, type, origin } = approvalRequest;
const interfaceId = approvalRequest.requestData?.id as string;

switch (type) {
case ApprovalType.SnapDialogAlert:
case ApprovalType.SnapDialogPrompt:
case DIALOG_APPROVAL_TYPES.default:
log('Rejecting snap dialog', { id, interfaceId, origin, type });
approvalController.accept(id, null);
deleteInterface?.(interfaceId);
break;

case ApprovalType.SnapDialogConfirmation:
log('Rejecting snap confirmation', { id, interfaceId, origin, type });
approvalController.accept(id, false);
deleteInterface?.(interfaceId);
break;

///: BEGIN:ONLY_INCLUDE_IF(keyring-snaps)
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.confirmAccountCreation:
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.confirmAccountRemoval:
case SNAP_MANAGE_ACCOUNTS_CONFIRMATION_TYPES.showSnapAccountRedirect:
log('Rejecting snap account confirmation', { id, origin, type });
approvalController.accept(id, false);
break;
///: END:ONLY_INCLUDE_IF

default:
log('Rejecting pending approval', { id, origin, type });
approvalController.reject(id, providerErrors.userRejectedRequest());
break;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const addEthereumChain = {
getCaveat: true,
requestPermittedChainsPermission: true,
grantPermittedChainsPermissionIncremental: true,
hasApprovalRequestsForOrigin: true,
rejectApprovalRequestsForOrigin: true,
},
};

Expand All @@ -46,6 +48,8 @@ async function addEthereumChainHandler(
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
hasApprovalRequestsForOrigin,
rejectApprovalRequestsForOrigin,
},
) {
let validParams;
Expand Down Expand Up @@ -193,13 +197,32 @@ async function addEthereumChainHandler(
const { networkClientId } =
updatedNetwork.rpcEndpoints[updatedNetwork.defaultRpcEndpointIndex];

return switchChain(res, end, chainId, networkClientId, approvalFlowId, {
isAddFlow: true,
setActiveNetwork,
endApprovalFlow,
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
const fromNetworkConfiguration = getNetworkConfigurationByChainId(
currentChainIdForDomain,
);

const toNetworkConfiguration = getNetworkConfigurationByChainId(chainId);

return switchChain({
res,
end,
chainId,
networkClientId,
approvalFlowId,
fromNetworkConfiguration,
toNetworkConfiguration,
origin,
hooks: {
isAddFlow: true,
setActiveNetwork,
endApprovalFlow,
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
requestUserApproval,
hasApprovalRequestsForOrigin,
rejectApprovalRequestsForOrigin,
},
});
} else if (approvalFlowId) {
endApprovalFlow({ id: approvalFlowId });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { errorCodes, rpcErrors } from '@metamask/rpc-errors';
import { ApprovalType } from '@metamask/controller-utils';
import {
isPrefixedFormattedHexString,
isSafeChainId,
Expand Down Expand Up @@ -152,21 +153,27 @@ export function validateAddEthereumChainParams(params) {
};
}

export async function switchChain(
export async function switchChain({
res,
end,
chainId,
networkClientId,
approvalFlowId,
{
origin,
fromNetworkConfiguration,
toNetworkConfiguration,
hooks: {
isAddFlow,
setActiveNetwork,
endApprovalFlow,
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
requestUserApproval,
hasApprovalRequestsForOrigin,
rejectApprovalRequestsForOrigin,
},
) {
}) {
try {
const { value: permissionedChainIds } =
getCaveat({
Expand All @@ -183,8 +190,19 @@ export async function switchChain(
} else {
await requestPermittedChainsPermission([chainId]);
}
} else if (hasApprovalRequestsForOrigin() && !isAddFlow) {
await requestUserApproval({
origin,
type: ApprovalType.SwitchEthereumChain,
requestData: {
toNetworkConfiguration,
fromNetworkConfiguration,
},
});
}

rejectApprovalRequestsForOrigin();

await setActiveNetwork(networkClientId);
res.result = null;
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ const switchEthereumChain = {
requestPermittedChainsPermission: true,
getCurrentChainIdForDomain: true,
grantPermittedChainsPermissionIncremental: true,
requestUserApproval: true,
hasApprovalRequestsForOrigin: true,
rejectApprovalRequestsForOrigin: true,
},
};

Expand All @@ -32,6 +35,9 @@ async function switchEthereumChainHandler(
getCaveat,
getCurrentChainIdForDomain,
grantPermittedChainsPermissionIncremental,
requestUserApproval,
hasApprovalRequestsForOrigin,
rejectApprovalRequestsForOrigin,
},
) {
let chainId;
Expand All @@ -48,11 +54,15 @@ async function switchEthereumChainHandler(
return end();
}

const networkConfigurationForRequestedChainId =
getNetworkConfigurationByChainId(chainId);
const fromNetworkConfiguration = getNetworkConfigurationByChainId(
currentChainIdForOrigin,
);

const toNetworkConfiguration = getNetworkConfigurationByChainId(chainId);

const networkClientIdToSwitchTo =
networkConfigurationForRequestedChainId?.rpcEndpoints[
networkConfigurationForRequestedChainId.defaultRpcEndpointIndex
toNetworkConfiguration?.rpcEndpoints[
toNetworkConfiguration.defaultRpcEndpointIndex
].networkClientId;

if (!networkClientIdToSwitchTo) {
Expand All @@ -64,10 +74,22 @@ async function switchEthereumChainHandler(
);
}

return switchChain(res, end, chainId, networkClientIdToSwitchTo, null, {
setActiveNetwork,
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
return switchChain({
res,
end,
chainId,
networkClientId: networkClientIdToSwitchTo,
fromNetworkConfiguration,
toNetworkConfiguration,
origin,
hooks: {
setActiveNetwork,
getCaveat,
requestPermittedChainsPermission,
grantPermittedChainsPermissionIncremental,
requestUserApproval,
hasApprovalRequestsForOrigin,
rejectApprovalRequestsForOrigin,
},
});
}
Loading
Loading