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

Remove networkId from NetworkController #1633

Merged
merged 40 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
2719a27
remove network id
jiexi Aug 23, 2023
b035596
ENS
jiexi Aug 23, 2023
d5825fb
Merge branch 'main' into jl/remove-network-id
jiexi Aug 23, 2023
1174d12
DRY shared-tests. Lint
jiexi Aug 24, 2023
26747ce
network controller spec
jiexi Aug 24, 2023
2d9cbcd
Merge branch 'main' into jl/remove-network-id
jiexi Aug 24, 2023
6598c91
Remove uneeded hextodec
jiexi Aug 24, 2023
66a422e
fix spec
jiexi Aug 24, 2023
5be731a
fix spec coverage ens controller
jiexi Aug 24, 2023
f8c301e
Update tx controller coverage thresholds
jiexi Aug 24, 2023
c91fe91
Merge remote-tracking branch 'origin/jl/remove-network-id' into jl/re…
jiexi Aug 24, 2023
c6d1dc5
Update assets controller code coverage
jiexi Aug 25, 2023
43f7cab
Merge branch 'main' into jl/remove-network-id
jiexi Aug 25, 2023
3dbf14f
Revert assets controller code coverage. Fix failed spec
jiexi Aug 25, 2023
3700f96
Merge branch 'main' into jl/remove-network-id
jiexi Sep 5, 2023
aaa8db3
Make chainId required in tx types. Remove networkId from ethjs common…
jiexi Sep 5, 2023
cc5c02e
Make TransactionMeta.chainId required
jiexi Sep 5, 2023
986225b
Add NON_MATCHING_NETWORK_ID_TO_CHAIN_IDS and deprecatedNetworkIdMatch…
jiexi Sep 6, 2023
258047d
Add back TransactionMeta.networkID as deprecated readonly
jiexi Sep 6, 2023
1603ef1
Add transactionMatchesChainId to utils
jiexi Sep 6, 2023
c840766
Cleanup
jiexi Sep 6, 2023
a8d97a1
Merge branch 'main' into jl/remove-network-id
jiexi Sep 6, 2023
f71e42f
Add NON_MATCHING_CHAIN_ID_TO_NETWORK_ID and deprecatedConvertChainIdT…
jiexi Sep 7, 2023
4fe8354
fix transactionMatchesChainId undefined check
jiexi Sep 7, 2023
3c9bba5
Merge branch 'main' into jl/remove-network-id
jiexi Sep 7, 2023
5c5f996
Merge branch 'main' into jl/remove-network-id
jiexi Sep 11, 2023
e5d271e
Cleanup tests
jiexi Sep 11, 2023
da5016d
Loosen transaction jest coverage
jiexi Sep 11, 2023
98ff807
transaction match only on chainId
jiexi Sep 13, 2023
156f386
Remove networkId <=> chainId helpers
jiexi Sep 13, 2023
9c9148f
Merge branch 'main' into jl/remove-network-id
jiexi Sep 13, 2023
3ce5824
Merge branch 'main' into jl/remove-network-id
jiexi Sep 13, 2023
86b0c3d
use chainId only for nonce key
jiexi Sep 13, 2023
b8e954a
Merge branch 'main' into jl/remove-network-id
jiexi Sep 18, 2023
7458d1a
remove net_version references
jiexi Sep 18, 2023
0d52dda
check only txMeta.chainId
jiexi Sep 20, 2023
76bc0ab
Merge branch 'main' into jl/remove-network-id
jiexi Sep 20, 2023
3d15203
Merge branch 'main' into jl/remove-network-id
jiexi Sep 21, 2023
8ba585a
Merge branch 'main' into jl/remove-network-id
jiexi Sep 22, 2023
0c8f0b5
Merge branch 'main' into jl/remove-network-id
jiexi Sep 25, 2023
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 @@ -519,7 +519,6 @@ function buildNetworkControllerStateWithProviderConfig(
return {
selectedNetworkClientId,
providerConfig,
networkId: '1',
networksMetadata: {
[selectedNetworkClientId]: {
EIPS: {},
Expand Down
24 changes: 15 additions & 9 deletions packages/controller-utils/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { NetworkType, NetworksTicker, ChainId, NetworkId } from './types';
import {
NetworkType,
NetworksTicker,
ChainId,
BuiltInNetworkName,
} from './types';

export const RPC = 'rpc';
export const FALL_BACK_VS_CURRENCY = 'ETH';
Expand Down Expand Up @@ -125,13 +130,14 @@ export enum ApprovalType {
WatchAsset = 'wallet_watchAsset',
}

export const NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP: Record<
NetworkId,
NetworkType
export const CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP: Record<
ChainId,
BuiltInNetworkName
> = {
[NetworkId.goerli]: NetworkType.goerli,
[NetworkId.sepolia]: NetworkType.sepolia,
[NetworkId.mainnet]: NetworkType.mainnet,
[NetworkId['linea-goerli']]: NetworkType['linea-goerli'],
[NetworkId['linea-mainnet']]: NetworkType['linea-mainnet'],
[ChainId.goerli]: BuiltInNetworkName.Goerli,
[ChainId.sepolia]: BuiltInNetworkName.Sepolia,
[ChainId.mainnet]: BuiltInNetworkName.Mainnet,
[ChainId['linea-goerli']]: BuiltInNetworkName.LineaGoerli,
[ChainId['linea-mainnet']]: BuiltInNetworkName.LineaMainnet,
[ChainId.aurora]: BuiltInNetworkName.Aurora,
};
12 changes: 0 additions & 12 deletions packages/controller-utils/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,6 @@ export const ChainId = {
} as const;
export type ChainId = (typeof ChainId)[keyof typeof ChainId];

/**
* Decimal string network IDs of built-in Infura networks, by name.
*/
export const NetworkId = {
[InfuraNetworkType.mainnet]: '1',
[InfuraNetworkType.goerli]: '5',
[InfuraNetworkType.sepolia]: '11155111',
[InfuraNetworkType['linea-goerli']]: '59140',
[InfuraNetworkType['linea-mainnet']]: '59144',
} as const;
export type NetworkId = (typeof NetworkId)[keyof typeof NetworkId];

export enum NetworksTicker {
mainnet = 'ETH',
goerli = 'GoerliETH',
Expand Down
12 changes: 1 addition & 11 deletions packages/ens-controller/src/EnsController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand Down Expand Up @@ -445,7 +444,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: null,
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -464,9 +462,8 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1544',
providerConfig: {
chainId: toHex(1),
chainId: toHex(0),
adonesky1 marked this conversation as resolved.
Show resolved Hide resolved
type: NetworkType.mainnet,
ticker: NetworksTicker.mainnet,
},
Expand All @@ -490,7 +487,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -514,7 +510,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -537,7 +532,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -563,7 +557,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -589,7 +582,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand Down Expand Up @@ -617,7 +609,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand All @@ -644,7 +635,6 @@ describe('EnsController', () => {
provider: getProvider(),
onNetworkStateChange: (listener) => {
listener({
networkId: '1',
providerConfig: {
chainId: toHex(1),
type: NetworkType.mainnet,
Expand Down
49 changes: 16 additions & 33 deletions packages/ens-controller/src/EnsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,22 @@ import type {
import { Web3Provider } from '@ethersproject/providers';
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
import { BaseControllerV2 } from '@metamask/base-controller';
import type { ChainId } from '@metamask/controller-utils';
import {
normalizeEnsName,
isValidHexAddress,
toChecksumHexAddress,
NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP,
CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,
convertHexToDecimal,
} from '@metamask/controller-utils';
import type { NetworkState } from '@metamask/network-controller';
import type { Hex } from '@metamask/utils';
import { createProjectLogger, hasProperty } from '@metamask/utils';
import { createProjectLogger } from '@metamask/utils';
import ensNetworkMap from 'ethereum-ens-network-map';
import { toASCII } from 'punycode/';

const log = createProjectLogger('ens-controller');

/**
* Checks whether the given string is a known network ID.
*
* @param networkId - Network id.
* @returns Boolean indicating if the network ID is recognized.
*/
function isKnownNetworkId(
networkId: string | null,
): networkId is keyof typeof NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP {
return (
networkId !== null &&
hasProperty(NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP, networkId)
);
}

const name = 'EnsController';

/**
Expand Down Expand Up @@ -118,9 +104,7 @@ export class EnsController extends BaseControllerV2<
state?: Partial<EnsControllerState>;
provider?: ExternalProvider | JsonRpcFetchFunc;
onNetworkStateChange?: (
listener: (
networkState: Pick<NetworkState, 'networkId' | 'providerConfig'>,
) => void,
listener: (networkState: Pick<NetworkState, 'providerConfig'>) => void,
) => void;
}) {
super({
Expand All @@ -136,15 +120,14 @@ export class EnsController extends BaseControllerV2<
if (provider && onNetworkStateChange) {
onNetworkStateChange((networkState) => {
this.resetState();
const currentNetwork = networkState.networkId;
if (
isKnownNetworkId(currentNetwork) &&
this.#getNetworkEnsSupport(currentNetwork)
) {
const currentChainId = networkState.providerConfig.chainId;
if (this.#getChainEnsSupport(currentChainId)) {
this.#ethProvider = new Web3Provider(provider, {
chainId: convertHexToDecimal(networkState.providerConfig.chainId),
name: NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP[currentNetwork],
ensAddress: ensNetworkMap[currentNetwork],
chainId: convertHexToDecimal(currentChainId),
name: CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP[
currentChainId as ChainId
],
ensAddress: ensNetworkMap[parseInt(currentChainId, 16)],
});
} else {
this.#ethProvider = null;
Expand Down Expand Up @@ -269,13 +252,13 @@ export class EnsController extends BaseControllerV2<
}

/**
* Check if network supports ENS.
* Check if the chain supports ENS.
*
* @param networkId - Network id.
* @returns Boolean indicating if the network supports ENS.
* @param chainId - chain id.
* @returns Boolean indicating if the chain supports ENS.
*/
#getNetworkEnsSupport(networkId: string) {
return Boolean(ensNetworkMap[networkId]);
#getChainEnsSupport(chainId: string) {
return Boolean(ensNetworkMap[parseInt(chainId, 16)]);
jiexi marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
72 changes: 1 addition & 71 deletions packages/network-controller/src/NetworkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { RestrictedControllerMessenger } from '@metamask/base-controller';
import { BaseControllerV2 } from '@metamask/base-controller';
import {
BUILT_IN_NETWORKS,
convertHexToDecimal,
NetworksTicker,
ChainId,
InfuraNetworkType,
Expand All @@ -17,7 +16,6 @@ import {
assertIsStrictHexString,
hasProperty,
isPlainObject,
isStrictHexString,
} from '@metamask/utils';
import { strict as assert } from 'assert';
import { errorCodes } from 'eth-rpc-errors';
Expand Down Expand Up @@ -174,25 +172,6 @@ function pick<Obj extends Record<any, any>, Keys extends keyof Obj>(
return pickedObject;
}

/**
* Convert the given value into a valid network ID. The ID is accepted
* as either a number, a decimal string, or a 0x-prefixed hex string.
*
* @param value - The network ID to convert, in an unknown format.
* @returns A valid network ID (as a decimal string)
* @throws If the given value cannot be safely parsed.
*/
function convertNetworkId(value: unknown): NetworkId {
if (typeof value === 'number' && !Number.isNaN(value)) {
return `${value}`;
} else if (isStrictHexString(value)) {
return `${convertHexToDecimal(value)}`;
} else if (typeof value === 'string' && /^\d+$/u.test(value)) {
return value as NetworkId;
}
throw new Error(`Cannot parse as a valid network ID: '${value}'`);
}

/**
* Type guard for determining whether the given value is an error object with a
* `code` property, such as an instance of Error.
Expand Down Expand Up @@ -343,11 +322,6 @@ export type NetworksMetadata = {
[networkClientId: NetworkClientId]: NetworkMetadata;
};

/**
* The network ID of a network.
*/
export type NetworkId = `${number}`;

/**
* @type NetworkState
*
Expand All @@ -359,7 +333,6 @@ export type NetworkId = `${number}`;
*/
export type NetworkState = {
selectedNetworkClientId: NetworkClientId;
networkId: NetworkId | null;
providerConfig: ProviderConfig;
networkConfigurations: NetworkConfigurations;
networksMetadata: NetworksMetadata;
Expand Down Expand Up @@ -475,7 +448,6 @@ export type NetworkControllerOptions = {

export const defaultState: NetworkState = {
selectedNetworkClientId: NetworkType.mainnet,
networkId: null,
providerConfig: {
type: NetworkType.mainnet,
chainId: ChainId.mainnet,
Expand Down Expand Up @@ -562,10 +534,6 @@ export class NetworkController extends BaseControllerV2<
persist: true,
anonymous: false,
},
networkId: {
persist: true,
anonymous: false,
},
networksMetadata: {
persist: true,
anonymous: false,
Expand Down Expand Up @@ -708,9 +676,6 @@ export class NetworkController extends BaseControllerV2<
*/
async #refreshNetwork() {
this.messagingSystem.publish('NetworkController:networkWillChange');
this.update((state) => {
state.networkId = null;
});
this.#applyNetworkSelection();
this.messagingSystem.publish('NetworkController:networkDidChange');
await this.lookupNetwork();
Expand All @@ -727,35 +692,6 @@ export class NetworkController extends BaseControllerV2<
await this.lookupNetwork();
}

/**
* Fetches the network ID for the network, ensuring that it is a hex string.
*
* @returns A promise that either resolves to the network ID, or rejects with
* an error.
* @throws If the network ID of the network is not a valid hex string.
*/
async #getNetworkId(): Promise<NetworkId> {
const possibleNetworkId = await new Promise<string>((resolve, reject) => {
if (!this.#ethQuery) {
throw new Error('Provider has not been initialized');
}

this.#ethQuery.sendAsync(
{ method: 'net_version' },
(error: unknown, result?: unknown) => {
if (error) {
reject(error);
} else {
// TODO: Validate this type
resolve(result as string);
}
},
);
});

return convertNetworkId(possibleNetworkId);
}

/**
* Performs side effects after switching to a network. If the network is
* available, updates the network state with the network ID of the network and
Expand Down Expand Up @@ -788,16 +724,11 @@ export class NetworkController extends BaseControllerV2<
);

let updatedNetworkStatus: NetworkStatus;
let updatedNetworkId: NetworkId | null = null;
let updatedIsEIP1559Compatible: boolean | undefined;

try {
const [networkId, isEIP1559Compatible] = await Promise.all([
this.#getNetworkId(),
this.#determineEIP1559Compatibility(),
]);
const isEIP1559Compatible = await this.#determineEIP1559Compatibility();
updatedNetworkStatus = NetworkStatus.Available;
updatedNetworkId = networkId;
updatedIsEIP1559Compatible = isEIP1559Compatible;
} catch (error) {
if (isErrorWithCode(error)) {
Expand Down Expand Up @@ -841,7 +772,6 @@ export class NetworkController extends BaseControllerV2<
);

this.update((state) => {
state.networkId = updatedNetworkId;
const meta = state.networksMetadata[state.selectedNetworkClientId];
meta.status = updatedNetworkStatus;
if (updatedIsEIP1559Compatible === undefined) {
Expand Down
Loading
Loading