Skip to content

fix: fix granted permissions when adding an existing network via wallet_addEthereumChain #29837

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 29 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
b7bf2ac
remove approvalFlowId. replace isAddFlow with autoApprove
jiexi Jan 21, 2025
65a837b
WIP wallet_addEthereumChain specs
jiexi Jan 21, 2025
15248fb
replace withPermissionControllerConnectedToTestDappWithChain with wit…
jiexi Jan 21, 2025
0d44554
add wallet_addEthereumChain spec
jiexi Jan 21, 2025
493e644
lint
jiexi Jan 21, 2025
9097ee2
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 21, 2025
d21a6bc
remove withPermissionControllerConnectedToTestDappWithTwoChains
jiexi Jan 22, 2025
fcc79fc
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 22, 2025
11f009f
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 22, 2025
2e5ea92
Update test/e2e/json-rpc/wallet_addEthereumChain.spec.ts
jiexi Jan 22, 2025
0d3c7f9
Update test/e2e/json-rpc/wallet_addEthereumChain.spec.ts
jiexi Jan 22, 2025
9d67497
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 22, 2025
1cffddb
Merge remote-tracking branch 'origin/jl/mmp-3814/fix-grant-permission…
jiexi Jan 22, 2025
d37a303
Merge remote-tracking branch 'origin/jl/mmp-3814/fix-grant-permission…
jiexi Jan 22, 2025
d9b397b
assert the approval is for a switch
jiexi Jan 22, 2025
6b5c973
jsdoc
jiexi Jan 22, 2025
06f8e6a
always call switchChain to ensure correct permittedChain permissions …
jiexi Jan 22, 2025
e5f13fb
update hooks.autoApprove jsdoc
jiexi Jan 22, 2025
81ea328
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 22, 2025
7921445
lint
jiexi Jan 23, 2025
3fb039a
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 23, 2025
b1b2f8e
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
adonesky1 Jan 23, 2025
a686e2b
add test case (#29885)
adonesky1 Jan 23, 2025
8b5cedd
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 28, 2025
21ee113
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
adonesky1 Jan 28, 2025
b5905f7
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
jiexi Jan 29, 2025
d924efc
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
adonesky1 Jan 29, 2025
4579d6a
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
adonesky1 Jan 29, 2025
060a6cd
Merge branch 'main' into jl/mmp-3814/fix-grant-permissions-add-ethere…
adonesky1 Jan 30, 2025
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 @@ -88,12 +88,14 @@ async function addEthereumChainHandler(
: undefined;

// If there's something to add or update
if (

const shouldAddOrUpdateNetwork =
!existingNetwork ||
rpcIndex !== existingNetwork.defaultRpcEndpointIndex ||
(firstValidBlockExplorerUrl &&
blockExplorerIndex !== existingNetwork.defaultBlockExplorerUrlIndex)
) {
blockExplorerIndex !== existingNetwork.defaultBlockExplorerUrlIndex);

if (shouldAddOrUpdateNetwork) {
try {
await requestUserApproval({
origin,
Expand Down Expand Up @@ -180,20 +182,14 @@ async function addEthereumChainHandler(
}
}

// If the added or updated network is not the current chain, prompt the user to switch
if (chainId !== currentChainIdForDomain) {
const { networkClientId } =
updatedNetwork.rpcEndpoints[updatedNetwork.defaultRpcEndpointIndex];

return switchChain(res, end, chainId, networkClientId, {
isAddFlow: true,
setActiveNetwork,
getCaveat,
requestPermittedChainsPermissionForOrigin,
requestPermittedChainsPermissionIncrementalForOrigin,
});
}
const { networkClientId } =
updatedNetwork.rpcEndpoints[updatedNetwork.defaultRpcEndpointIndex];

res.result = null;
return end();
return switchChain(res, end, chainId, networkClientId, {
autoApprove: shouldAddOrUpdateNetwork,
setActiveNetwork,
getCaveat,
requestPermittedChainsPermissionForOrigin,
requestPermittedChainsPermissionIncrementalForOrigin,
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ describe('addEthereumChainHandler', () => {
NON_INFURA_CHAIN_ID,
123,
{
isAddFlow: true,
autoApprove: true,
getCaveat: mocks.getCaveat,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionForOrigin:
Expand Down Expand Up @@ -251,7 +251,7 @@ describe('addEthereumChainHandler', () => {
'0x1',
123,
{
isAddFlow: true,
autoApprove: true,
getCaveat: mocks.getCaveat,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionForOrigin:
Expand All @@ -264,7 +264,7 @@ describe('addEthereumChainHandler', () => {
});

describe('if the proposed networkConfiguration does not have a different rpcUrl from the one already in state', () => {
it('should only switch to the existing networkConfiguration if one already exists for the given chain id', async () => {
it('should only switch to the existing networkConfiguration if one already exists for the given chain id without auto approving the chain permission', async () => {
const { mocks, end, handler } = createMockedHandler();
mocks.getCurrentChainIdForDomain.mockReturnValue(CHAIN_IDS.MAINNET);
mocks.getNetworkConfigurationByChainId.mockReturnValue(
Expand Down Expand Up @@ -298,7 +298,7 @@ describe('addEthereumChainHandler', () => {
'0xa',
createMockOptimismConfiguration().rpcEndpoints[0].networkClientId,
{
isAddFlow: true,
autoApprove: false,
getCaveat: mocks.getCaveat,
setActiveNetwork: mocks.setActiveNetwork,
requestPermittedChainsPermissionForOrigin:
Expand Down Expand Up @@ -338,30 +338,4 @@ describe('addEthereumChainHandler', () => {
}),
);
});

it('should add result set to null to response object if the requested rpcUrl (and chainId) is currently selected', async () => {
const CURRENT_RPC_CONFIG = createMockNonInfuraConfiguration();

const { mocks, response, handler } = createMockedHandler();
mocks.getCurrentChainIdForDomain.mockReturnValue(
CURRENT_RPC_CONFIG.chainId,
);
mocks.getNetworkConfigurationByChainId.mockReturnValue(CURRENT_RPC_CONFIG);
await handler({
origin: 'example.com',
params: [
{
chainId: CURRENT_RPC_CONFIG.chainId,
chainName: 'Custom Network',
rpcUrls: [CURRENT_RPC_CONFIG.rpcEndpoints[0].url],
nativeCurrency: {
symbol: CURRENT_RPC_CONFIG.nativeCurrency,
decimals: 18,
},
blockExplorerUrls: ['https://custom.blockexplorer'],
},
],
});
expect(response.result).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -165,20 +165,20 @@ 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 {boolean} hooks.isAddFlow - The boolean determining if this call originates from wallet_addEthereumChain.
* @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.requestPermittedChainsPermissionForOrigin - The callback to request a new permittedChains-equivalent CAIP-25 permission.
* @param {Function} hooks.requestPermittedChainsPermissionIncrementalForOrigin - The callback to add a new chain to the permittedChains-equivalent CAIP-25 permission.
* @returns a null response on success or an error if user rejects an approval when isAddFlow is false or on unexpected errors.
* @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(
response,
end,
chainId,
networkClientId,
{
isAddFlow,
autoApprove,
setActiveNetwork,
getCaveat,
requestPermittedChainsPermissionForOrigin,
Expand All @@ -197,13 +197,13 @@ export async function switchChain(
if (!ethChainIds.includes(chainId)) {
await requestPermittedChainsPermissionIncrementalForOrigin({
chainId,
autoApprove: isAddFlow,
autoApprove,
});
}
} else {
await requestPermittedChainsPermissionForOrigin({
chainId,
autoApprove: isAddFlow,
autoApprove,
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { rpcErrors } from '@metamask/rpc-errors';
import { errorCodes, rpcErrors } from '@metamask/rpc-errors';
import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
Expand All @@ -10,7 +10,7 @@ describe('Ethereum Chain Utils', () => {
const createMockedSwitchChain = () => {
const end = jest.fn();
const mocks = {
isAddFlow: false,
autoApprove: false,
setActiveNetwork: jest.fn(),
getCaveat: jest.fn(),
requestPermittedChainsPermissionForOrigin: jest.fn(),
Expand Down Expand Up @@ -39,21 +39,10 @@ describe('Ethereum Chain Utils', () => {
});
});

it('passes through unexpected errors', async () => {
const { mocks, end, switchChain } = createMockedSwitchChain();
mocks.requestPermittedChainsPermissionForOrigin.mockRejectedValueOnce(
new Error('unexpected error'),
);

await switchChain('0x1', 'mainnet');

expect(end).toHaveBeenCalledWith(new Error('unexpected error'));
});

describe('with no existing CAIP-25 permission', () => {
it('requests a switch chain approval without autoApprove if isAddFlow: false', async () => {
it('requests a switch chain approval without autoApprove if autoApprove: false', async () => {
const { mocks, switchChain } = createMockedSwitchChain();
mocks.isAddFlow = false;
mocks.autoApprove = false;
await switchChain('0x1', 'mainnet');

expect(
Expand All @@ -68,28 +57,28 @@ describe('Ethereum Chain Utils', () => {
expect(mocks.setActiveNetwork).toHaveBeenCalledWith('mainnet');
});

it('should handle errors if the switch chain grant fails', async () => {
it('should throw an error if the switch chain approval is rejected', async () => {
const { mocks, end, switchChain } = createMockedSwitchChain();
mocks.requestPermittedChainsPermissionForOrigin.mockRejectedValueOnce(
new Error('failed to grant permittedChains'),
);
mocks.requestPermittedChainsPermissionForOrigin.mockRejectedValueOnce({
code: errorCodes.provider.userRejectedRequest,
});

await switchChain('0x1', 'mainnet');

expect(
mocks.requestPermittedChainsPermissionForOrigin,
).toHaveBeenCalled();
expect(mocks.setActiveNetwork).not.toHaveBeenCalled();
expect(end).toHaveBeenCalledWith(
new Error('failed to grant permittedChains'),
);
expect(end).toHaveBeenCalledWith({
code: errorCodes.provider.userRejectedRequest,
});
});
});

describe('with an existing CAIP-25 permission granted from the legacy flow (isMultichainOrigin: false) and the chainId is not already permissioned', () => {
it('requests a switch chain approval with autoApprove and switches to it if isAddFlow: true', async () => {
it('requests a switch chain approval with autoApprove and switches to it if autoApprove: true', async () => {
const { mocks, switchChain } = createMockedSwitchChain();
mocks.isAddFlow = true;
mocks.autoApprove = true;
mocks.getCaveat.mockReturnValue({
value: {
requiredScopes: {},
Expand All @@ -105,9 +94,9 @@ describe('Ethereum Chain Utils', () => {
expect(mocks.setActiveNetwork).toHaveBeenCalledWith('mainnet');
});

it('requests permittedChains approval without autoApprove then switches to it if isAddFlow: false', async () => {
it('requests permittedChains approval without autoApprove then switches to it if autoApprove: false', async () => {
const { mocks, switchChain } = createMockedSwitchChain();
mocks.isAddFlow = false;
mocks.autoApprove = false;
mocks.getCaveat.mockReturnValue({
value: {
requiredScopes: {},
Expand All @@ -123,10 +112,10 @@ describe('Ethereum Chain Utils', () => {
expect(mocks.setActiveNetwork).toHaveBeenCalledWith('mainnet');
});

it('should handle errors if the permittedChains grant fails', async () => {
it('should throw errors if the permittedChains grant fails', async () => {
const { mocks, end, switchChain } = createMockedSwitchChain();
mocks.requestPermittedChainsPermissionIncrementalForOrigin.mockRejectedValueOnce(
new Error('failed to grant permittedChains'),
new Error('failed to auto grant permittedChains'),
);
mocks.getCaveat.mockReturnValue({
value: {
Expand All @@ -142,7 +131,7 @@ describe('Ethereum Chain Utils', () => {
).toHaveBeenCalled();
expect(mocks.setActiveNetwork).not.toHaveBeenCalled();
expect(end).toHaveBeenCalledWith(
new Error('failed to grant permittedChains'),
new Error('failed to auto grant permittedChains'),
);
});
});
Expand Down
Loading
Loading