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

Replace network state with networkId and networkStatus #1196

Merged
merged 4 commits into from
Apr 18, 2023
Merged
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
1 change: 1 addition & 0 deletions packages/network-controller/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"babel-runtime": "^6.26.0",
"eth-json-rpc-infura": "^5.1.0",
"eth-query": "^2.1.2",
"eth-rpc-errors": "^4.0.0",
"immer": "^9.0.6",
"uuid": "^8.3.2",
"web3-provider-engine": "^16.0.3"
Expand Down
72 changes: 60 additions & 12 deletions packages/network-controller/src/NetworkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { SwappableProxy } from '@metamask/swappable-obj-proxy';
import { Mutex } from 'async-mutex';
import { v4 as random } from 'uuid';
import type { Patch } from 'immer';
import { errorCodes } from 'eth-rpc-errors';
import {
BaseControllerV2,
RestrictedControllerMessenger,
Expand All @@ -19,9 +20,10 @@ import {
isNetworkType,
BUILT_IN_NETWORKS,
} from '@metamask/controller-utils';

import { assertIsStrictHexString } from '@metamask/utils';

import { NetworkStatus } from './constants';

/**
* @type ProviderConfig
*
Expand Down Expand Up @@ -70,6 +72,36 @@ export type NetworkConfiguration = {
};
};

/**
* Asserts that the given value is a network ID, i.e., that it is a decimal
* number represented as a string.
*
* @param value - The value to check.
*/
function assertNetworkId(value: string): asserts value is NetworkId {
if (!/^\d+$/u.test(value) || Number.isNaN(Number(value))) {
throw new Error('value is not a number');
}
}

/**
* Type guard for determining whether the given value is an error object with a
* `code` property, such as an instance of Error.
*
* TODO: Move this to @metamask/utils.
*
* @param error - The object to check.
* @returns True if `error` has a `code`, false otherwise.
*/
function isErrorWithCode(error: unknown): error is { code: string | number } {
return typeof error === 'object' && error !== null && 'code' in error;
}

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

/**
* @type NetworkState
*
Expand All @@ -81,7 +113,8 @@ export type NetworkConfiguration = {
* @property networkConfigurations - the full list of configured networks either preloaded or added by the user.
*/
export type NetworkState = {
network: string;
networkId: NetworkId | null;
networkStatus: NetworkStatus;
isCustomNetwork: boolean;
providerConfig: ProviderConfig;
networkDetails: NetworkDetails;
Expand Down Expand Up @@ -147,7 +180,8 @@ export type NetworkControllerOptions = {
};

export const defaultState: NetworkState = {
network: 'loading',
networkId: null,
networkStatus: NetworkStatus.Unknown,
isCustomNetwork: false,
providerConfig: {
type: NetworkType.mainnet,
Expand Down Expand Up @@ -205,7 +239,11 @@ export class NetworkController extends BaseControllerV2<
super({
name,
metadata: {
network: {
networkId: {
persist: true,
anonymous: false,
},
networkStatus: {
persist: true,
anonymous: false,
},
Expand Down Expand Up @@ -290,7 +328,8 @@ export class NetworkController extends BaseControllerV2<

async #refreshNetwork() {
this.update((state) => {
state.network = 'loading';
state.networkId = null;
state.networkStatus = NetworkStatus.Unknown;
state.networkDetails = {};
});
const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;
Expand Down Expand Up @@ -364,7 +403,7 @@ export class NetworkController extends BaseControllerV2<
}

async #verifyNetwork() {
if (this.state.network === 'loading') {
if (this.state.networkStatus !== NetworkStatus.Available) {
await this.lookupNetwork();
}
}
Expand All @@ -383,8 +422,8 @@ export class NetworkController extends BaseControllerV2<
await this.lookupNetwork();
}

async #getNetworkId(): Promise<string> {
return await new Promise((resolve, reject) => {
async #getNetworkId(): Promise<NetworkId> {
const possibleNetworkId = await new Promise<string>((resolve, reject) => {
this.#ethQuery.sendAsync(
{ method: 'net_version' },
(error: Error, result: string) => {
Expand All @@ -396,6 +435,9 @@ export class NetworkController extends BaseControllerV2<
},
);
});

assertNetworkId(possibleNetworkId);
return possibleNetworkId;
}

/**
Expand All @@ -410,16 +452,22 @@ export class NetworkController extends BaseControllerV2<
try {
try {
const networkId = await this.#getNetworkId();
if (this.state.network === networkId) {
if (this.state.networkId === networkId) {
return;
}

this.update((state) => {
state.network = networkId;
state.networkId = networkId;
state.networkStatus = NetworkStatus.Available;
});
} catch (_error) {
} catch (error) {
const networkStatus =
isErrorWithCode(error) && error.code !== errorCodes.rpc.internal
? NetworkStatus.Unavailable
: NetworkStatus.Unknown;
this.update((state) => {
state.network = 'loading';
state.networkId = null;
state.networkStatus = networkStatus;
});
}

Expand Down
20 changes: 20 additions & 0 deletions packages/network-controller/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Represents the availability state of the currently selected network.
*/
export enum NetworkStatus {
/**
* The network may or may not be able to receive requests, but either no
* attempt has been made to determine this, or an attempt was made but was
* unsuccessful.
*/
Unknown = 'unknown',
/**
* The network is able to receive and respond to requests.
*/
Available = 'available',
/**
* The network was unable to receive and respond to requests for unknown
* reasons.
*/
Unavailable = 'unavailable',
}
1 change: 1 addition & 0 deletions packages/network-controller/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './NetworkController';
export * from './constants';
Loading