@metamask-previews/network-controller 12.1.2-preview.c338244 → 12.1.2-preview.f71e42f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -104,10 +104,6 @@ export declare type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClie
|
|
|
104
104
|
export declare type NetworksMetadata = {
|
|
105
105
|
[networkClientId: NetworkClientId]: NetworkMetadata;
|
|
106
106
|
};
|
|
107
|
-
/**
|
|
108
|
-
* The network ID of a network.
|
|
109
|
-
*/
|
|
110
|
-
export declare type NetworkId = `${number}`;
|
|
111
107
|
/**
|
|
112
108
|
* @type NetworkState
|
|
113
109
|
*
|
|
@@ -119,7 +115,6 @@ export declare type NetworkId = `${number}`;
|
|
|
119
115
|
*/
|
|
120
116
|
export declare type NetworkState = {
|
|
121
117
|
selectedNetworkClientId: NetworkClientId;
|
|
122
|
-
networkId: NetworkId | null;
|
|
123
118
|
providerConfig: ProviderConfig;
|
|
124
119
|
networkConfigurations: NetworkConfigurations;
|
|
125
120
|
networksMetadata: NetworksMetadata;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,
|
|
1
|
+
{"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAIL,iBAAiB,EACjB,WAAW,EAEZ,MAAM,4BAA4B,CAAC;AACpC,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAE3C,OAAO,KAAK,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ClB,EAAE;QACD,QAAQ,EAAE,MAAM,CAAC;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,OAAO,CAAC;KACrB,GACA,OAAO,CAAC,MAAM,CAAC;IAuGlB;;;;;;;;;OASG;IACH,0BAA0B,CAAC,sBAAsB,EAAE,MAAM;IAuBzD;;;;OAIG;IACG,0BAA0B;IAUhC;;;;OAIG;IACG,OAAO;IAIb;;;;;OAKG;IACH,UAAU,CAAC,EACT,qBAAqB,GACtB,EAAE;QACD,qBAAqB,EAAE,YAAY,CAAC,uBAAuB,CAAC,CAAC;KAC9D,GAAG,IAAI;IASR;;;;;OAKG;IACH,4BAA4B,CAAC,OAAO,EAAE,GAAG,GAAG,eAAe;CA2P5D"}
|
|
@@ -22,7 +22,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
22
22
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
23
23
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
24
24
|
};
|
|
25
|
-
var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_provider, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_refreshNetwork,
|
|
25
|
+
var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_provider, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_refreshNetwork, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated, _NetworkController_createAutoManagedNetworkClientRegistry, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig, _NetworkController_applyNetworkSelection;
|
|
26
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
27
|
exports.NetworkController = exports.defaultState = exports.knownKeysOf = void 0;
|
|
28
28
|
const base_controller_1 = require("@metamask/base-controller");
|
|
@@ -84,26 +84,6 @@ function pick(object, keys) {
|
|
|
84
84
|
assertOfType(pickedObject, () => keys.every((key) => key in pickedObject), 'The reduce did not produce an object with all of the desired keys.');
|
|
85
85
|
return pickedObject;
|
|
86
86
|
}
|
|
87
|
-
/**
|
|
88
|
-
* Convert the given value into a valid network ID. The ID is accepted
|
|
89
|
-
* as either a number, a decimal string, or a 0x-prefixed hex string.
|
|
90
|
-
*
|
|
91
|
-
* @param value - The network ID to convert, in an unknown format.
|
|
92
|
-
* @returns A valid network ID (as a decimal string)
|
|
93
|
-
* @throws If the given value cannot be safely parsed.
|
|
94
|
-
*/
|
|
95
|
-
function convertNetworkId(value) {
|
|
96
|
-
if (typeof value === 'number' && !Number.isNaN(value)) {
|
|
97
|
-
return `${value}`;
|
|
98
|
-
}
|
|
99
|
-
else if ((0, utils_1.isStrictHexString)(value)) {
|
|
100
|
-
return `${(0, controller_utils_1.convertHexToDecimal)(value)}`;
|
|
101
|
-
}
|
|
102
|
-
else if (typeof value === 'string' && /^\d+$/u.test(value)) {
|
|
103
|
-
return value;
|
|
104
|
-
}
|
|
105
|
-
throw new Error(`Cannot parse as a valid network ID: '${value}'`);
|
|
106
|
-
}
|
|
107
87
|
/**
|
|
108
88
|
* Type guard for determining whether the given value is an error object with a
|
|
109
89
|
* `code` property, such as an instance of Error.
|
|
@@ -210,7 +190,6 @@ function validateCustomProviderConfig(providerConfig) {
|
|
|
210
190
|
const name = 'NetworkController';
|
|
211
191
|
exports.defaultState = {
|
|
212
192
|
selectedNetworkClientId: controller_utils_1.NetworkType.mainnet,
|
|
213
|
-
networkId: null,
|
|
214
193
|
providerConfig: {
|
|
215
194
|
type: controller_utils_1.NetworkType.mainnet,
|
|
216
195
|
chainId: controller_utils_1.ChainId.mainnet,
|
|
@@ -231,10 +210,6 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
231
210
|
persist: true,
|
|
232
211
|
anonymous: false,
|
|
233
212
|
},
|
|
234
|
-
networkId: {
|
|
235
|
-
persist: true,
|
|
236
|
-
anonymous: false,
|
|
237
|
-
},
|
|
238
213
|
networksMetadata: {
|
|
239
214
|
persist: true,
|
|
240
215
|
anonymous: false,
|
|
@@ -349,15 +324,10 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
349
324
|
};
|
|
350
325
|
this.messagingSystem.subscribe('NetworkController:networkDidChange', listener);
|
|
351
326
|
let updatedNetworkStatus;
|
|
352
|
-
let updatedNetworkId = null;
|
|
353
327
|
let updatedIsEIP1559Compatible;
|
|
354
328
|
try {
|
|
355
|
-
const
|
|
356
|
-
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this),
|
|
357
|
-
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this),
|
|
358
|
-
]);
|
|
329
|
+
const isEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this);
|
|
359
330
|
updatedNetworkStatus = constants_1.NetworkStatus.Available;
|
|
360
|
-
updatedNetworkId = networkId;
|
|
361
331
|
updatedIsEIP1559Compatible = isEIP1559Compatible;
|
|
362
332
|
}
|
|
363
333
|
catch (error) {
|
|
@@ -396,7 +366,6 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
396
366
|
}
|
|
397
367
|
this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
|
|
398
368
|
this.update((state) => {
|
|
399
|
-
state.networkId = updatedNetworkId;
|
|
400
369
|
const meta = state.networksMetadata[state.selectedNetworkClientId];
|
|
401
370
|
meta.status = updatedNetworkStatus;
|
|
402
371
|
if (updatedIsEIP1559Compatible === undefined) {
|
|
@@ -683,31 +652,10 @@ exports.NetworkController = NetworkController;
|
|
|
683
652
|
_NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_previousProviderConfig = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_autoManagedNetworkClientRegistry = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
|
|
684
653
|
return __awaiter(this, void 0, void 0, function* () {
|
|
685
654
|
this.messagingSystem.publish('NetworkController:networkWillChange');
|
|
686
|
-
this.update((state) => {
|
|
687
|
-
state.networkId = null;
|
|
688
|
-
});
|
|
689
655
|
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
|
|
690
656
|
this.messagingSystem.publish('NetworkController:networkDidChange');
|
|
691
657
|
yield this.lookupNetwork();
|
|
692
658
|
});
|
|
693
|
-
}, _NetworkController_getNetworkId = function _NetworkController_getNetworkId() {
|
|
694
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
695
|
-
const possibleNetworkId = yield new Promise((resolve, reject) => {
|
|
696
|
-
if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
697
|
-
throw new Error('Provider has not been initialized');
|
|
698
|
-
}
|
|
699
|
-
__classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'net_version' }, (error, result) => {
|
|
700
|
-
if (error) {
|
|
701
|
-
reject(error);
|
|
702
|
-
}
|
|
703
|
-
else {
|
|
704
|
-
// TODO: Validate this type
|
|
705
|
-
resolve(result);
|
|
706
|
-
}
|
|
707
|
-
});
|
|
708
|
-
});
|
|
709
|
-
return convertNetworkId(possibleNetworkId);
|
|
710
|
-
});
|
|
711
659
|
}, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock() {
|
|
712
660
|
return new Promise((resolve, reject) => {
|
|
713
661
|
if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,+DAA6D;AAC7D,iEAQoC;AACpC,oEAA2C;AAC3C,uEAAwE;AAGxE,2CAKyB;AACzB,mCAA0C;AAC1C,mDAA4C;AAE5C,+BAAoC;AAEpC,2CAAgE;AAKhE,6FAAsF;AACtF,qCAA6D;AAC7D,mCAA4C;AAS5C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,mBAAmB,CAAC,CAAC;AAsEnE;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CACzB,MAA+B;IAE/B,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAQ,CAAC;AACpC,CAAC;AAJD,kCAIC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,YAAY,CACnB,KAAc,EACd,QAAqC,EACrC,OAAe;IAEf,eAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,IAAI,CACX,MAAW,EACX,IAAY;IAEZ,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAC9B,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QACnB,uCAAY,WAAW,KAAE,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,IAAG;IAChD,CAAC,EACD,EAAE,CACH,CAAC;IACF,YAAY,CACV,YAAY,EACZ,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,YAAY,CAAC,EAC9C,oEAAoE,CACrE,CAAC;IACF,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;;;;;GAO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,EAAE,YAAY,EAAE,GAAG,wBAAwB,CAAC;IAE5D,IAAI,uBAAA,IAAI,wCAAe,EAAE;QACvB,uBAAA,IAAI,wCAAe,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;KACzC;SAAM;QACL,uBAAA,IAAI,oCAAkB,IAAA,6CAAuB,EAAC,QAAQ,CAAC,MAAA,CAAC;KACzD;IACD,uBAAA,IAAI,+BAAa,QAAQ,MAAA,CAAC;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n convertHexToDecimal,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n isStrictHexString,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { errorCodes } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Convert the given value into a valid network ID. The ID is accepted\n * as either a number, a decimal string, or a 0x-prefixed hex string.\n *\n * @param value - The network ID to convert, in an unknown format.\n * @returns A valid network ID (as a decimal string)\n * @throws If the given value cannot be safely parsed.\n */\nfunction convertNetworkId(value: unknown): NetworkId {\n if (typeof value === 'number' && !Number.isNaN(value)) {\n return `${value}`;\n } else if (isStrictHexString(value)) {\n return `${convertHexToDecimal(value)}`;\n } else if (typeof value === 'string' && /^\\d+$/u.test(value)) {\n return value as NetworkId;\n }\n throw new Error(`Cannot parse as a valid network ID: '${value}'`);\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Returns whether the given argument is a type that our Infura middleware\n * recognizes.\n *\n * @param type - A type to compare.\n * @returns True or false, depending on whether the given type is one that our\n * Infura middleware recognizes.\n */\nfunction isInfuraProviderType(type: string): type is InfuraNetworkType {\n return Object.keys(InfuraNetworkType).includes(type);\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraProviderType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * The network ID of a network.\n */\nexport type NetworkId = `${number}`;\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n networkId: NetworkId | null;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = {\n type: `NetworkController:getState`;\n handler: () => NetworkState;\n};\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n networkId: null,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networkId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraProviderType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish('NetworkController:networkWillChange');\n this.update((state) => {\n state.networkId = null;\n });\n this.#applyNetworkSelection();\n this.messagingSystem.publish('NetworkController:networkDidChange');\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Fetches the network ID for the network, ensuring that it is a hex string.\n *\n * @returns A promise that either resolves to the network ID, or rejects with\n * an error.\n * @throws If the network ID of the network is not a valid hex string.\n */\n async #getNetworkId(): Promise<NetworkId> {\n const possibleNetworkId = await new Promise<string>((resolve, reject) => {\n if (!this.#ethQuery) {\n throw new Error('Provider has not been initialized');\n }\n\n this.#ethQuery.sendAsync(\n { method: 'net_version' },\n (error: unknown, result?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(result as string);\n }\n },\n );\n });\n\n return convertNetworkId(possibleNetworkId);\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork() {\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedNetworkId: NetworkId | null = null;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const [networkId, isEIP1559Compatible] = await Promise.all([\n this.#getNetworkId(),\n this.#determineEIP1559Compatibility(),\n ]);\n updatedNetworkStatus = NetworkStatus.Available;\n updatedNetworkId = networkId;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n state.networkId = updatedNetworkId;\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraProviderType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(): Promise<Block> {\n return new Promise((resolve, reject) => {\n if (!this.#ethQuery) {\n throw new Error('Provider has not been initialized');\n }\n\n this.#ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility() {\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility();\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock();\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,+DAA6D;AAC7D,iEAOoC;AACpC,oEAA2C;AAC3C,uEAAwE;AAGxE,2CAIyB;AACzB,mCAA0C;AAC1C,mDAA4C;AAE5C,+BAAoC;AAEpC,2CAAgE;AAKhE,6FAAsF;AACtF,qCAA6D;AAC7D,mCAA4C;AAS5C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,mBAAmB,CAAC,CAAC;AAsEnE;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CACzB,MAA+B;IAE/B,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAQ,CAAC;AACpC,CAAC;AAJD,kCAIC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,YAAY,CACnB,KAAc,EACd,QAAqC,EACrC,OAAe;IAEf,eAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,IAAI,CACX,MAAW,EACX,IAAY;IAEZ,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAC9B,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QACnB,uCAAY,WAAW,KAAE,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,IAAG;IAChD,CAAC,EACD,EAAE,CACH,CAAC;IACF,YAAY,CACV,YAAY,EACZ,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,YAAY,CAAC,EAC9C,oEAAoE,CACrE,CAAC;IACF,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;;;;;;GAQG;A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C;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { errorCodes } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Returns whether the given argument is a type that our Infura middleware\n * recognizes.\n *\n * @param type - A type to compare.\n * @returns True or false, depending on whether the given type is one that our\n * Infura middleware recognizes.\n */\nfunction isInfuraProviderType(type: string): type is InfuraNetworkType {\n return Object.keys(InfuraNetworkType).includes(type);\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraProviderType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = {\n type: `NetworkController:getState`;\n handler: () => NetworkState;\n};\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraProviderType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish('NetworkController:networkWillChange');\n this.#applyNetworkSelection();\n this.messagingSystem.publish('NetworkController:networkDidChange');\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork() {\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility();\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraProviderType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(): Promise<Block> {\n return new Promise((resolve, reject) => {\n if (!this.#ethQuery) {\n throw new Error('Provider has not been initialized');\n }\n\n this.#ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility() {\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility();\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock();\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
|
|
@@ -96,7 +96,6 @@ function createInfuraNetworkMiddleware({ blockTracker, network, rpcProvider, rpc
|
|
|
96
96
|
function createNetworkAndChainIdMiddleware({ network, }) {
|
|
97
97
|
return (0, json_rpc_engine_1.createScaffoldMiddleware)({
|
|
98
98
|
eth_chainId: controller_utils_1.ChainId[network],
|
|
99
|
-
net_version: controller_utils_1.NetworkId[network],
|
|
100
99
|
});
|
|
101
100
|
}
|
|
102
101
|
const createChainIdMiddleware = (chainId) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-network-client.js","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,
|
|
1
|
+
{"version":3,"file":"create-network-client.js","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAAqD;AACrD,uEAAuE;AACvE,+EAQ2C;AAE3C,2EAGyC;AAEzC,yDAAwD;AACxD,qDAKyB;AAQzB,mCAA4C;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,aAAyC;IAEzC,MAAM,gBAAgB,GACpB,aAAa,CAAC,IAAI,KAAK,yBAAiB,CAAC,MAAM;QAC7C,CAAC,CAAC,IAAA,4CAAsB,EAAC;YACrB,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,eAAe;YACxC,WAAW,EAAE,CAAC;YACd,MAAM,EAAE,UAAU;SACnB,CAAC;QACJ,CAAC,CAAC,IAAA,+CAAqB,EAAC;YACpB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,MAAM,EAAE,aAAa,CAAC,MAAM;SAC7B,CAAC,CAAC;IAET,MAAM,WAAW,GAAG,IAAA,8CAAsB,EAAC,gBAAgB,CAAC,CAAC;IAE7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AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,IAAA,uCAAqB,EAAC,CAAO,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;SACjE;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { InfuraNetworkType } from '@metamask/controller-utils';\nimport { ChainId } from '@metamask/controller-utils';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport type { Hex } from '@metamask/utils';\nimport { PollingBlockTracker } from 'eth-block-tracker';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from 'json-rpc-engine';\nimport type { JsonRpcMiddleware } from 'json-rpc-engine';\n\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param networkConfig - The network configuration.\n * @returns The network client.\n */\nexport function createNetworkClient(\n networkConfig: NetworkClientConfiguration,\n): NetworkClient {\n const rpcApiMiddleware =\n networkConfig.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n network: networkConfig.network,\n projectId: networkConfig.infuraProjectId,\n maxAttempts: 5,\n source: 'metamask',\n })\n : createFetchMiddleware({\n btoa: global.btoa,\n fetch: global.fetch,\n rpcUrl: networkConfig.rpcUrl,\n });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTrackerOpts =\n // eslint-disable-next-line n/no-process-env\n process.env.IN_TEST && networkConfig.type === 'custom'\n ? { pollingInterval: SECOND }\n : {};\n const blockTracker = new PollingBlockTracker({\n ...blockTrackerOpts,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n networkConfig.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: networkConfig.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: networkConfig.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider = providerFromEngine(engine);\n\n const destroy = () => {\n blockTracker.destroy();\n };\n\n return { configuration: networkConfig, provider, blockTracker, destroy };\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: SafeEventEmitterProvider;\n rpcApiMiddleware: JsonRpcMiddleware<unknown, unknown>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements eth_chainId & net_version methods.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<unknown, unknown> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: any;\n}) {\n // eslint-disable-next-line n/no-process-env\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/network-controller",
|
|
3
|
-
"version": "12.1.2-preview.
|
|
3
|
+
"version": "12.1.2-preview.f71e42f",
|
|
4
4
|
"description": "Provides an interface to the currently selected network via a MetaMask-compatible provider object",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|