Skip to content

Commit

Permalink
fix: fix network verification chainID and name verification for popul…
Browse files Browse the repository at this point in the history
…ar network (#8953)

## **Description**

the chainId must be displayed in decimal instead of hexadecimal in the
network verification modal.
the name warning must not be displayed in the case of a popular network.

## **Related issues**

Fixes: #8950 , #8951 

## **Manual testing steps**

1. Go to settings then network
2. click on optimism network add button
3. a network verification modal will be displayed , check the value of
the chainID
4. a warning name will be displayed

## **Screenshots/Recordings**

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

### **Before**

![Bug](https://github.com/MetaMask/metamask-mobile/assets/26223211/d0f2a81e-0bbe-4485-804c-de24878e8f74)

### **After**
![Screenshot 2024-03-15 at 12 12
44](https://github.com/MetaMask/metamask-mobile/assets/26223211/5af45c9e-ae83-433d-8a03-f542e41e220e)



## **Pre-merge author checklist**

- [x] I’ve followed [MetaMask Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've clearly explained what problem this PR is solving and how it
is solved.
- [x] I've linked related issues
- [x] I've included manual testing steps
- [x] I've included screenshots/recordings if applicable
- [x] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] 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.
- [x] I’ve properly set the pull request status:
  - [ ] In case it's not yet "ready for review", I've set it to "draft".
- [x] In case it's "ready for review", I've changed it from "draft" to
"non-draft".

## **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.

Co-authored-by: Cal Leung <cleun007@gmail.com>
  • Loading branch information
salimtb and Cal-L authored Mar 18, 2024
1 parent 28e2325 commit 521ef63
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useSelector } from 'react-redux';

const mockNetworkInfo = {
chainName: 'Test Chain',
chainId: '1',
chainId: '0xa',
rpcUrl: 'http://test.com',
ticker: 'TEST',
blockExplorerUrl: 'http://explorer.test.com',
Expand Down Expand Up @@ -68,4 +68,13 @@ describe('NetworkVerificationInfo', () => {
getByText(strings('add_custom_network.unrecognized_chain_name')),
).toThrow('Unable to find an element with text');
});

it('should render chainId on decimal', () => {
(useSelector as jest.Mock).mockReturnValue(true);
const { getByText } = render(
<NetworkVerificationInfo customNetworkInformation={mockNetworkInfo} />,
);

expect(getByText('10')).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
} from '../../../util/networks';
import { NetworkApprovalModalSelectorsIDs } from '../../../../e2e/selectors/Modals/NetworkApprovalModal.selectors';
import hideKeyFromUrl from '../../../util/hideKeyFromUrl';
import { convertHexToDecimal } from '@metamask/controller-utils';

interface Alert {
alertError: string;
Expand Down Expand Up @@ -106,7 +107,9 @@ const NetworkVerificationInfo = ({
<Text variant={TextVariant.BodyMDBold}>
{strings('add_custom_network.chain_id')}
</Text>
<Text style={styles.textSection}>{customNetworkInformation.chainId}</Text>
<Text style={styles.textSection}>
{convertHexToDecimal(customNetworkInformation.chainId)}
</Text>

<Text variant={TextVariant.BodyMDBold}>
{strings('add_custom_network.network_url')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,32 +93,33 @@ exports[`NetworkVerificationInfo renders correctly 1`] = `
<View
style={
Object {
"alignItems": "center",
"backgroundColor": "#F2F4F6",
"backgroundColor": "#FFFFFF",
"borderRadius": 8,
"borderWidth": 1,
"height": 16,
"justifyContent": "center",
"overflow": "hidden",
"width": 16,
}
}
>
<Text
accessibilityRole="text"
<Image
onError={[Function]}
resizeMode="contain"
source={
Object {
"default": Object {
"uri": "MockImage",
},
}
}
style={
Object {
"color": "#24272A",
"fontFamily": "Euclid Circular B",
"fontSize": 10,
"fontWeight": "400",
"letterSpacing": 0,
"lineHeight": undefined,
"flex": 1,
"height": undefined,
"width": undefined,
}
}
>
T
</Text>
testID="network-avatar-image"
/>
</View>
<Text
accessibilityRole="text"
Expand Down Expand Up @@ -353,7 +354,7 @@ exports[`NetworkVerificationInfo renders correctly 1`] = `
}
}
>
1
10
</Text>
<Text
accessibilityRole="text"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jest.mock('react-redux', () => ({
useSelector: jest.fn(),
}));

describe('useNativeTokenFiatAmount', () => {
describe('useIsOriginalNativeTokenSymbol', () => {
afterEach(() => {
jest.clearAllMocks();
});
Expand Down
64 changes: 64 additions & 0 deletions app/core/RPCMethods/networkChecker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,68 @@ describe('checkSafeNetwork', () => {
);
expect(alerts).toEqual([]);
});

it('should not return warning name/symbol if it match with popular network', async () => {
mockedAxios.get.mockImplementation(() =>
Promise.resolve({
data: [
{
chainId: '10',
rpc: ['https://optimism-mainnet.infura.io/v3/1234'],
name: 'Optimism',
nativeCurrency: {
symbol: 'ETH',
decimals: 18,
},
},
],
}),
);

const alerts = await checkSafeNetwork(
'10',
'https://optimism-mainnet.infura.io/v3/1234',
'Optimism',
'ETH',
);
expect(alerts).toEqual([]);
});
it('should return warning name/symbol if it doesnt match with popular network and third part provider', async () => {
mockedAxios.get.mockImplementation(() =>
Promise.resolve({
data: [
{
chainId: '10',
rpc: ['https://optimism-mainnet.infura.io/v3/1234'],
name: 'Optimism',
nativeCurrency: {
symbol: 'ETH',
decimals: 18,
},
},
],
}),
);

const alerts = await checkSafeNetwork(
'10',
'https://optimism-mainnet.infura.io/v3/1234',
'Optimism test',
'OP',
);
expect(alerts).toEqual([
{
alertError:
"It looks like this network's display name doesn't match its chain ID.",
alertSeverity: BannerAlertSeverity.Warning,
alertOrigin: 'chain_name',
},
{
alertError:
"It looks like this network's symbol doesn't match this chain ID.",
alertSeverity: BannerAlertSeverity.Warning,
alertOrigin: 'chain_ticker',
},
]);
});
});
29 changes: 24 additions & 5 deletions app/core/RPCMethods/networkChecker.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@ import axios from 'axios';
import { BannerAlertSeverity } from '../../component-library/components/Banners/Banner';
import { strings } from '../../../locales/i18n';
import PopularList from '../../util/networks/customNetworks';
import { toHex } from '@metamask/controller-utils';

const findPopularNetwork = (rpcUrl: string) =>
const findPopularNetwork = (rpcUrl: string, chainId: string) =>
PopularList.some((network) => {
const { origin } = new URL(network.rpcUrl);
return origin === rpcUrl;
return origin === rpcUrl && network.chainId === chainId;
});

const findPopularNetworkName = (name: string, chainId: string) =>
PopularList.some(
(network) =>
network.nickname.toLowerCase() === name.toLowerCase() &&
network.chainId === chainId,
);

const findPopularNetworkSymbol = (symbol: string, chainId: string) =>
PopularList.some(
(network) => network.ticker === symbol && network.chainId === chainId,
);

const checkSafeNetwork = async (
chainIdDecimal: string,
rpcUrl: string,
Expand All @@ -31,7 +44,7 @@ const checkSafeNetwork = async (
!matchedChain.rpc
?.map((rpc: string) => new URL(rpc).origin)
.includes(origin) &&
!findPopularNetwork(origin)
!findPopularNetwork(origin, toHex(chainIdDecimal))
) {
alerts.push({
alertError: strings('add_custom_network.invalid_rpc_url'),
Expand All @@ -46,14 +59,20 @@ const checkSafeNetwork = async (
alertOrigin: 'decimals',
});
}
if (matchedChain.name?.toLowerCase() !== nickname?.toLowerCase()) {
if (
matchedChain.name?.toLowerCase() !== nickname?.toLowerCase() &&
!findPopularNetworkName(nickname, toHex(chainIdDecimal))
) {
alerts.push({
alertError: strings('add_custom_network.unrecognized_chain_name'),
alertSeverity: BannerAlertSeverity.Warning,
alertOrigin: 'chain_name',
});
}
if (matchedChain.nativeCurrency?.symbol !== ticker) {
if (
matchedChain.nativeCurrency?.symbol !== ticker &&
!findPopularNetworkSymbol(ticker, toHex(chainIdDecimal))
) {
alerts.push({
alertError: strings('add_custom_network.unrecognized_chain_ticker'),
alertSeverity: BannerAlertSeverity.Warning,
Expand Down

0 comments on commit 521ef63

Please sign in to comment.