Skip to content

Commit

Permalink
fix: set default selectedNetworkClientId to 'mainnet' if no matching …
Browse files Browse the repository at this point in the history
…with entry on network list (#12227)

<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**
This PR implements a fix for Migration 60 to handle cases where
selectedNetworkClientId does not match any entry within
networkConfigurationsByChainId. If no corresponding networkClientId is
found, the migration will now set selectedNetworkClientId to 'mainnet'
by default.

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

## **Related issues**

Fixes:
[#11657](#11657)

## **Manual testing steps**

1. Go to this page...
2.
3.

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [ ] I’ve followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.
  • Loading branch information
salimtb authored Dec 19, 2024
1 parent d2b2b1a commit dd81987
Show file tree
Hide file tree
Showing 3 changed files with 342 additions and 0 deletions.
173 changes: 173 additions & 0 deletions app/store/migrations/064.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import migration from './064';
import { merge } from 'lodash';
import initialRootState from '../../util/test/initial-root-state';
import { captureException } from '@sentry/react-native';
import { RootState } from '../../reducers';

const oldState = {
engine: {
backgroundState: {
NetworkController: {
selectedNetworkClientId: 'unknown-client-id',
networkConfigurationsByChainId: {
'0x1': {
rpcEndpoints: [{ networkClientId: 'mainnet' }],
},
'0x5': {
rpcEndpoints: [{ networkClientId: 'goerli' }],
},
},
},
},
},
};

const expectedNewState = {
engine: {
backgroundState: {
NetworkController: {
selectedNetworkClientId: 'mainnet',
networkConfigurationsByChainId: {
'0x1': {
rpcEndpoints: [{ networkClientId: 'mainnet' }],
},
'0x5': {
rpcEndpoints: [{ networkClientId: 'goerli' }],
},
},
},
},
},
};

jest.mock('@sentry/react-native', () => ({
captureException: jest.fn(),
}));
const mockedCaptureException = jest.mocked(captureException);

describe('Migration #64', () => {
beforeEach(() => {
jest.restoreAllMocks();
jest.resetAllMocks();
});

const invalidStates = [
{
state: merge({}, initialRootState, {
engine: {
backgroundState: {
NetworkController: null,
},
},
}),
errorMessage:
"Migration 64: Invalid or missing 'NetworkController' in backgroundState: 'object'",
scenario: 'NetworkController state is invalid',
},
{
state: merge({}, initialRootState, {
engine: {
backgroundState: {
NetworkController: { networkConfigurationsByChainId: null },
},
},
}),
errorMessage:
"Migration 64: Missing or invalid 'networkConfigurationsByChainId' in NetworkController",
scenario: 'networkConfigurationsByChainId is invalid',
},
];

for (const { errorMessage, scenario, state } of invalidStates) {
it(`should capture exception if ${scenario}`, async () => {
const newState = await migration(state);

expect(newState).toStrictEqual(state);
expect(mockedCaptureException).toHaveBeenCalledWith(expect.any(Error));
expect(mockedCaptureException.mock.calls[0][0].message).toBe(
errorMessage,
);
});
}

it('should set selectedNetworkClientId to "mainnet" if it does not exist in networkConfigurationsByChainId', async () => {
const newState = await migration(oldState);
expect(newState).toStrictEqual(expectedNewState);
});

it('should keep selectedNetworkClientId unchanged if it exists in networkConfigurationsByChainId', async () => {
const validState = merge({}, oldState, {
engine: {
backgroundState: {
NetworkController: {
selectedNetworkClientId: 'mainnet',
},
},
},
});
const newState = await migration(validState);

expect(newState).toStrictEqual(validState);
});

it('should set selectedNetworkClientId to the default mainnet client ID if mainnet configuration exists but selectedNetworkClientId is invalid', async () => {
const invalidClientState = merge({}, oldState, {
engine: {
backgroundState: {
NetworkController: {
selectedNetworkClientId: 'invalid-client-id',
},
},
},
});

const newState = await migration(invalidClientState);
expect(
(newState as RootState).engine.backgroundState.NetworkController
.selectedNetworkClientId,
).toBe('mainnet');
});

it('should handle the absence of mainnet configuration gracefully', async () => {
const noMainnetState = merge({}, oldState, {
engine: {
backgroundState: {
NetworkController: {
networkConfigurationsByChainId: {
'0x1': {
chainId: '0x1',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [{ networkClientId: 'another-mainnet' }],
},
'0x5': {
rpcEndpoints: [{ networkClientId: 'goerli' }],
},
},
selectedNetworkClientId: 'unknown-client-id',
},
},
},
});

const newState = await migration(noMainnetState);
expect(
(newState as RootState).engine.backgroundState.NetworkController
.selectedNetworkClientId,
).toBe('another-mainnet');
});

it('should not modify the state if it is already valid', async () => {
const validState = merge({}, oldState, {
engine: {
backgroundState: {
NetworkController: {
selectedNetworkClientId: 'mainnet',
},
},
},
});

const newState = await migration(validState);
expect(newState).toStrictEqual(validState);
});
});
167 changes: 167 additions & 0 deletions app/store/migrations/064.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { captureException } from '@sentry/react-native';
import { isObject, hasProperty, Hex } from '@metamask/utils';
import { CHAIN_IDS } from '@metamask/transaction-controller';
import {
NetworkClientId,
NetworkConfiguration,
NetworkState,
} from '@metamask/network-controller';
import { ensureValidState } from './util';
import { RootState } from '../../reducers';

/**
* This migration checks if `selectedNetworkClientId` exists in any entry within `networkConfigurationsByChainId`.
* If it does not, or if `selectedNetworkClientId` is undefined or invalid, it sets `selectedNetworkClientId` to `'mainnet'`.
* @param {unknown} stateAsync - Redux state.
* @returns Migrated Redux state.
*/
export default async function migrate(stateAsync: unknown) {
const migrationVersion = 64;
const mainnetChainId = CHAIN_IDS.MAINNET;

const state = await stateAsync;

if (!ensureValidState(state, migrationVersion)) {
return state;
}

const networkControllerState = state.engine.backgroundState
.NetworkController as NetworkState;

if (
!isValidNetworkControllerState(
networkControllerState,
state as RootState,
migrationVersion,
)
) {
return state;
}

const { networkConfigurationsByChainId, selectedNetworkClientId } =
networkControllerState;

const networkClientIdExists = doesNetworkClientIdExist(
selectedNetworkClientId,
networkConfigurationsByChainId,
migrationVersion,
);

const isMainnetRpcExists = isMainnetRpcConfigured(
networkConfigurationsByChainId,
);

ensureSelectedNetworkClientId(
networkControllerState,
networkClientIdExists,
isMainnetRpcExists,
networkConfigurationsByChainId,
mainnetChainId,
);

return state;
}

function isValidNetworkControllerState(
networkControllerState: NetworkState,
state: RootState,
migrationVersion: number,
) {
if (
!isObject(networkControllerState) ||
!hasProperty(state.engine.backgroundState, 'NetworkController')
) {
captureException(
new Error(
`Migration ${migrationVersion}: Invalid or missing 'NetworkController' in backgroundState: '${typeof networkControllerState}'`,
),
);
return false;
}

if (
!hasProperty(networkControllerState, 'networkConfigurationsByChainId') ||
!isObject(networkControllerState.networkConfigurationsByChainId)
) {
captureException(
new Error(
`Migration ${migrationVersion}: Missing or invalid 'networkConfigurationsByChainId' in NetworkController`,
),
);
return false;
}

return true;
}

function doesNetworkClientIdExist(
selectedNetworkClientId: NetworkClientId,
networkConfigurationsByChainId: Record<Hex, NetworkConfiguration>,
migrationVersion: number,
) {
for (const chainId in networkConfigurationsByChainId) {
const networkConfig = networkConfigurationsByChainId[chainId as Hex];

if (
isObject(networkConfig) &&
hasProperty(networkConfig, 'rpcEndpoints') &&
Array.isArray(networkConfig.rpcEndpoints)
) {
if (
networkConfig.rpcEndpoints.some(
(endpoint) =>
isObject(endpoint) &&
hasProperty(endpoint, 'networkClientId') &&
endpoint.networkClientId === selectedNetworkClientId,
)
) {
return true;
}
} else {
captureException(
new Error(
`Migration ${migrationVersion}: Invalid network configuration or missing 'rpcEndpoints' for chainId: '${chainId}'`,
),
);
}
}

return false;
}

function isMainnetRpcConfigured(
networkConfigurationsByChainId: Record<Hex, NetworkConfiguration>,
) {
return Object.values(networkConfigurationsByChainId).some((networkConfig) =>
networkConfig.rpcEndpoints.some(
(endpoint) => endpoint.networkClientId === 'mainnet',
),
);
}

function ensureSelectedNetworkClientId(
networkControllerState: NetworkState,
networkClientIdExists: boolean,
isMainnetRpcExists: boolean,
networkConfigurationsByChainId: Record<Hex, NetworkConfiguration>,
mainnetChainId: Hex,
) {
const setDefaultMainnetClientId = () => {
networkControllerState.selectedNetworkClientId = isMainnetRpcExists
? 'mainnet'
: networkConfigurationsByChainId[mainnetChainId].rpcEndpoints[
networkConfigurationsByChainId[mainnetChainId].defaultRpcEndpointIndex
].networkClientId;
};

if (
!hasProperty(networkControllerState, 'selectedNetworkClientId') ||
typeof networkControllerState.selectedNetworkClientId !== 'string'
) {
setDefaultMainnetClientId();
}

if (!networkClientIdExists) {
setDefaultMainnetClientId();
}
}
2 changes: 2 additions & 0 deletions app/store/migrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import migration60 from './060';
import migration61 from './061';
import migration62 from './062';
import migration63 from './063';
import migration64 from './064';

type MigrationFunction = (state: unknown) => unknown;
type AsyncMigrationFunction = (state: unknown) => Promise<unknown>;
Expand Down Expand Up @@ -140,6 +141,7 @@ export const migrationList: MigrationsList = {
61: migration61,
62: migration62,
63: migration63,
64: migration64,
};

// Enable both synchronous and asynchronous migrations
Expand Down

0 comments on commit dd81987

Please sign in to comment.