@metamask-previews/network-controller 19.0.0-preview-ca4ed28f → 19.0.0-preview-ece76bc

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkWBGETWDRjs = require('./chunk-WBGETWDR.js');
5
+ var _chunkWT5ZBF4Xjs = require('./chunk-WT5ZBF4X.js');
6
6
  require('./chunk-ZKNI7MD3.js');
7
7
  require('./chunk-LLMZDA4Q.js');
8
8
  require('./chunk-E4V6XEBR.js');
@@ -13,5 +13,5 @@ require('./chunk-Z4BLTVTB.js');
13
13
 
14
14
 
15
15
 
16
- exports.NetworkController = _chunkWBGETWDRjs.NetworkController; exports.defaultState = _chunkWBGETWDRjs.defaultState; exports.knownKeysOf = _chunkWBGETWDRjs.knownKeysOf;
16
+ exports.NetworkController = _chunkWT5ZBF4Xjs.NetworkController; exports.defaultState = _chunkWT5ZBF4Xjs.defaultState; exports.knownKeysOf = _chunkWT5ZBF4Xjs.knownKeysOf;
17
17
  //# sourceMappingURL=NetworkController.js.map
@@ -2,7 +2,7 @@ import {
2
2
  NetworkController,
3
3
  defaultState,
4
4
  knownKeysOf
5
- } from "./chunk-MTNLTXYW.mjs";
5
+ } from "./chunk-6PT34M4U.mjs";
6
6
  import "./chunk-2QJYHWIP.mjs";
7
7
  import "./chunk-TZA3CBEI.mjs";
8
8
  import "./chunk-U43RY4MY.mjs";
@@ -34,7 +34,7 @@ import {
34
34
  } from "@metamask/utils";
35
35
  import { strict as assert } from "assert";
36
36
  import { v4 as random } from "uuid";
37
- var log = createModuleLogger(projectLogger, "NetworkController");
37
+ var debugLog = createModuleLogger(projectLogger, "NetworkController");
38
38
  function knownKeysOf(object) {
39
39
  return Object.keys(object);
40
40
  }
@@ -64,13 +64,14 @@ var defaultState = {
64
64
  networksMetadata: {},
65
65
  networkConfigurations: {}
66
66
  };
67
- var _ethQuery, _infuraProjectId, _trackMetaMetricsEvent, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn, _applyNetworkSelection, applyNetworkSelection_fn;
67
+ var _ethQuery, _infuraProjectId, _trackMetaMetricsEvent, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _log, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn, _applyNetworkSelection, applyNetworkSelection_fn;
68
68
  var NetworkController = class extends BaseController {
69
69
  constructor({
70
70
  messenger,
71
71
  state,
72
72
  infuraProjectId,
73
- trackMetaMetricsEvent
73
+ trackMetaMetricsEvent,
74
+ log
74
75
  }) {
75
76
  super({
76
77
  name,
@@ -182,6 +183,7 @@ var NetworkController = class extends BaseController {
182
183
  __privateAdd(this, _blockTrackerProxy, void 0);
183
184
  __privateAdd(this, _autoManagedNetworkClientRegistry, void 0);
184
185
  __privateAdd(this, _autoManagedNetworkClient, void 0);
186
+ __privateAdd(this, _log, void 0);
185
187
  if (!infuraProjectId || typeof infuraProjectId !== "string") {
186
188
  throw new Error("Invalid Infura project ID");
187
189
  }
@@ -238,6 +240,7 @@ var NetworkController = class extends BaseController {
238
240
  this.getSelectedNetworkClient.bind(this)
239
241
  );
240
242
  __privateSet(this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
243
+ __privateSet(this, _log, log);
241
244
  }
242
245
  /**
243
246
  * Accesses the provider and block tracker for the currently selected network.
@@ -328,28 +331,45 @@ var NetworkController = class extends BaseController {
328
331
  updatedIsEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, networkClientId);
329
332
  updatedNetworkStatus = "available" /* Available */;
330
333
  } catch (error) {
334
+ debugLog("NetworkController: lookupNetworkByClientId: ", error);
331
335
  if (isErrorWithCode(error)) {
332
336
  let responseBody;
333
337
  if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
334
338
  try {
335
339
  responseBody = JSON.parse(error.message);
336
340
  } catch {
341
+ __privateGet(this, _log)?.warn(
342
+ "NetworkController: lookupNetworkByClientId: json parse error: ",
343
+ error
344
+ );
337
345
  }
338
346
  }
339
347
  if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
340
348
  updatedNetworkStatus = "blocked" /* Blocked */;
341
349
  } else if (error.code === errorCodes.rpc.internal) {
342
350
  updatedNetworkStatus = "unknown" /* Unknown */;
351
+ __privateGet(this, _log)?.warn(
352
+ "NetworkController: lookupNetworkByClientId: rpc internal error: ",
353
+ error
354
+ );
343
355
  } else {
344
356
  updatedNetworkStatus = "unavailable" /* Unavailable */;
357
+ __privateGet(this, _log)?.warn(
358
+ "NetworkController: lookupNetworkByClientId: ",
359
+ error
360
+ );
345
361
  }
346
362
  } else if (typeof Error !== "undefined" && hasProperty(error, "message") && typeof error.message === "string" && error.message.includes(
347
363
  "No custom network client was found with the ID"
348
364
  )) {
349
365
  throw error;
350
366
  } else {
351
- log("NetworkController - could not determine network status", error);
367
+ debugLog(
368
+ "NetworkController - could not determine network status",
369
+ error
370
+ );
352
371
  updatedNetworkStatus = "unknown" /* Unknown */;
372
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetworkByClientId: ", error);
353
373
  }
354
374
  }
355
375
  this.update((state) => {
@@ -416,19 +436,32 @@ var NetworkController = class extends BaseController {
416
436
  if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
417
437
  try {
418
438
  responseBody = JSON.parse(error.message);
419
- } catch {
439
+ } catch (parseError) {
440
+ __privateGet(this, _log)?.warn(
441
+ "NetworkController: lookupNetwork: json parse error",
442
+ parseError
443
+ );
420
444
  }
421
445
  }
422
446
  if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
423
447
  updatedNetworkStatus = "blocked" /* Blocked */;
424
448
  } else if (error.code === errorCodes.rpc.internal) {
425
449
  updatedNetworkStatus = "unknown" /* Unknown */;
450
+ __privateGet(this, _log)?.warn(
451
+ "NetworkController: lookupNetwork: rpc internal error",
452
+ error
453
+ );
426
454
  } else {
427
455
  updatedNetworkStatus = "unavailable" /* Unavailable */;
456
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
428
457
  }
429
458
  } else {
430
- log("NetworkController - could not determine network status", error);
459
+ debugLog(
460
+ "NetworkController - could not determine network status",
461
+ error
462
+ );
431
463
  updatedNetworkStatus = "unknown" /* Unknown */;
464
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
432
465
  }
433
466
  }
434
467
  if (networkChanged) {
@@ -753,6 +786,7 @@ _providerProxy = new WeakMap();
753
786
  _blockTrackerProxy = new WeakMap();
754
787
  _autoManagedNetworkClientRegistry = new WeakMap();
755
788
  _autoManagedNetworkClient = new WeakMap();
789
+ _log = new WeakMap();
756
790
  _refreshNetwork = new WeakSet();
757
791
  refreshNetwork_fn = async function(networkClientId) {
758
792
  this.messagingSystem.publish(
@@ -912,4 +946,4 @@ export {
912
946
  defaultState,
913
947
  NetworkController
914
948
  };
915
- //# sourceMappingURL=chunk-MTNLTXYW.mjs.map
949
+ //# sourceMappingURL=chunk-6PT34M4U.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NetworkController.ts"],"sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n isInfuraNetworkType,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { errorCodes } from '@metamask/rpc-errors';\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 type { Logger } from 'loglevel';\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 debugLog = createModuleLogger(projectLogger, 'NetworkController');\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function knownKeysOf<K extends PropertyKey>(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * The string that uniquely identifies an Infura network client.\n */\nexport type BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\nexport type 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 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 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 = ControllerStateChangeEvent<\n typeof name,\n NetworkState\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: [NetworkState];\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: [NetworkState];\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 = ControllerGetStateAction<\n typeof name,\n NetworkState\n>;\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\n};\n\nexport type NetworkControllerGetSelectedNetworkClientAction = {\n type: `NetworkController:getSelectedNetworkClient`;\n handler: NetworkController['getSelectedNetworkClient'];\n};\n\nexport type NetworkControllerGetEIP1559CompatibilityAction = {\n type: `NetworkController:getEIP1559Compatibility`;\n handler: NetworkController['getEIP1559Compatibility'];\n};\n\nexport type NetworkControllerFindNetworkClientIdByChainIdAction = {\n type: `NetworkController:findNetworkClientIdByChainId`;\n handler: NetworkController['findNetworkClientIdByChainId'];\n};\n\n/**\n * Change the currently selected network to the given built-in network type.\n *\n * @deprecated This action has been replaced by `setActiveNetwork`, and will be\n * removed in a future release.\n */\nexport type NetworkControllerSetProviderTypeAction = {\n type: `NetworkController:setProviderType`;\n handler: NetworkController['setProviderType'];\n};\n\nexport type NetworkControllerSetActiveNetworkAction = {\n type: `NetworkController:setActiveNetwork`;\n handler: NetworkController['setActiveNetwork'];\n};\n\nexport type NetworkControllerGetNetworkConfigurationByNetworkClientId = {\n type: `NetworkController:getNetworkConfigurationByNetworkClientId`;\n handler: NetworkController['getNetworkConfigurationByNetworkClientId'];\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n never,\n never\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n log?: Logger;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\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 BaseController<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previouslySelectedNetworkClientId: string;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n #autoManagedNetworkClient?:\n | AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n | AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n #log: Logger | undefined;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n log,\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 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\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getNetworkConfigurationByNetworkClientId`,\n this.getNetworkConfigurationByNetworkClientId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getSelectedNetworkClient`,\n this.getSelectedNetworkClient.bind(this),\n );\n\n this.#previouslySelectedNetworkClientId =\n this.state.selectedNetworkClientId;\n\n this.#log = log;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n * @returns The proxy and block tracker proxies.\n * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.\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 * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns an object with the provider and block tracker proxies for the currently selected network.\n */\n getSelectedNetworkClient():\n | {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n blockTracker: SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>;\n }\n | undefined {\n if (this.#providerProxy && this.#blockTrackerProxy) {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n return undefined;\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 (isInfuraNetworkType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n // This is impossible to reach\n /* istanbul ignore if */\n if (!infuraNetworkClient) {\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 switch the network:\n *\n * 1. Notifies subscribers via the messenger that the network is about to be\n * switched (and, really, that the global provider and block tracker proxies\n * will be re-pointed to a new network).\n * 2. Looks up a known and preinitialized network client matching the given\n * ID and uses it to re-point the aforementioned provider and block tracker\n * proxies.\n * 3. Notifies subscribers via the messenger that the network has switched.\n * 4. Captures metadata for the newly switched network in state.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n */\n async #refreshNetwork(networkClientId: string) {\n this.messagingSystem.publish(\n 'NetworkController:networkWillChange',\n this.state,\n );\n this.#applyNetworkSelection(networkClientId);\n this.messagingSystem.publish(\n 'NetworkController:networkDidChange',\n this.state,\n );\n await this.lookupNetwork();\n }\n\n /**\n * Creates network clients for built-in and custom networks, then establishes\n * the currently selected network client based on state.\n */\n async initializeProvider() {\n this.#applyNetworkSelection(this.state.selectedNetworkClientId);\n await this.lookupNetwork();\n }\n\n /**\n * Refreshes the network meta with EIP-1559 support and the network status\n * based on the given network client ID.\n *\n * @param networkClientId - The ID of the network client to update.\n */\n async lookupNetworkByClientId(networkClientId: NetworkClientId) {\n const isInfura = isInfuraNetworkType(networkClientId);\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n updatedIsEIP1559Compatible = await this.#determineEIP1559Compatibility(\n networkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n } catch (error) {\n debugLog('NetworkController: lookupNetworkByClientId: ', error);\n\n // TODO: mock ethQuery.sendAsync to throw error without error code\n /* istanbul ignore else */\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 this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: json parse error: ',\n error,\n );\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 this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: rpc internal error: ',\n error,\n );\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: ',\n error,\n );\n }\n } else if (\n typeof Error !== 'undefined' &&\n hasProperty(error as unknown as Error, 'message') &&\n typeof (error as unknown as Error).message === 'string' &&\n (error as unknown as Error).message.includes(\n 'No custom network client was found with the ID',\n )\n ) {\n throw error;\n } else {\n debugLog(\n 'NetworkController - could not determine network status',\n error,\n );\n updatedNetworkStatus = NetworkStatus.Unknown;\n this.#log?.warn('NetworkController: lookupNetworkByClientId: ', error);\n }\n }\n this.update((state) => {\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n const meta = state.networksMetadata[networkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n }\n\n /**\n * Persists the following metadata about the given or selected network to\n * state:\n *\n * - The status of the network, namely, whether it is available, geo-blocked\n * (Infura only), or unavailable, or whether the status is unknown\n * - Whether the network supports EIP-1559, or whether it is unknown\n *\n * Note that it is possible for the network to be switched while this data is\n * being collected. If that is the case, no metadata for the (now previously)\n * selected network will be updated.\n *\n * @param networkClientId - The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n */\n async lookupNetwork(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n await this.lookupNetworkByClientId(networkClientId);\n return;\n }\n\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura =\n this.#autoManagedNetworkClient?.configuration.type ===\n NetworkClientType.Infura;\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 this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n // TODO: mock ethQuery.sendAsync to throw error without error code\n /* istanbul ignore else */\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 (parseError) {\n // error.message must not be JSON\n this.#log?.warn(\n 'NetworkController: lookupNetwork: json parse error',\n parseError,\n );\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 this.#log?.warn(\n 'NetworkController: lookupNetwork: rpc internal error',\n error,\n );\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n this.#log?.warn('NetworkController: lookupNetwork: ', error);\n }\n } else {\n debugLog(\n 'NetworkController - could not determine network status',\n error,\n );\n updatedNetworkStatus = NetworkStatus.Unknown;\n this.#log?.warn('NetworkController: lookupNetwork: ', error);\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 * @deprecated This has been replaced by `setActiveNetwork`, and will be\n * removed in a future release\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraNetworkType(type),\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unknown Infura provider type \"${type}\".`,\n );\n\n await this.setActiveNetwork(type);\n }\n\n /**\n * Changes the selected network.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n * @throws if no network client is associated with the given\n * `networkClientId`.\n */\n async setActiveNetwork(networkClientId: string) {\n this.#previouslySelectedNetworkClientId =\n this.state.selectedNetworkClientId;\n\n await this.#refreshNetwork(networkClientId);\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.\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(networkClientId: NetworkClientId): Promise<Block> {\n if (networkClientId === undefined) {\n networkClientId = this.state.selectedNetworkClientId;\n }\n\n const networkClient = this.getNetworkClientById(networkClientId);\n const ethQuery = new EthQuery(networkClient.provider);\n\n return new Promise((resolve, reject) => {\n 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 * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.\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(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n return this.get1559CompatibilityWithNetworkClientId(networkClientId);\n }\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.state.selectedNetworkClientId,\n );\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 async get1559CompatibilityWithNetworkClientId(\n networkClientId: NetworkClientId,\n ) {\n let metadata = this.state.networksMetadata[networkClientId];\n if (metadata === undefined) {\n await this.lookupNetwork(networkClientId);\n metadata = this.state.networksMetadata[networkClientId];\n }\n const { EIPS } = metadata;\n\n // may want to include some 'freshness' value - something to make sure we refetch this from time to time\n return EIPS[1559];\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 * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility\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(\n networkClientId: NetworkClientId,\n ): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock(networkClientId);\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Ensures that the provider and block tracker proxies are pointed to the\n * currently selected network and refreshes the metadata for the\n */\n async resetConnection() {\n await this.#refreshNetwork(this.state.selectedNetworkClientId);\n }\n\n /**\n * Returns a configuration object for the network identified by the given\n * network client ID. If given an Infura network type, constructs one based on\n * what we know about the network; otherwise attempts locates a network\n * configuration in state that corresponds to the network client ID.\n *\n * @param networkClientId - The network client ID.\n * @returns The configuration for the referenced network if one exists, or\n * undefined otherwise.\n */\n getNetworkConfigurationByNetworkClientId(\n networkClientId: NetworkClientId,\n ): NetworkConfiguration | undefined {\n if (isInfuraNetworkType(networkClientId)) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const rpcUrl = `https://${networkClientId}.infura.io/v3/${\n this.#infuraProjectId\n }`;\n return {\n rpcUrl,\n ...BUILT_IN_NETWORKS[networkClientId],\n };\n }\n\n return this.state.networkConfigurations[networkClientId];\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 = upsertedNetworkConfigurationId;\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 ticker,\n });\n }\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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 = 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 * Assuming that the network has been previously switched, switches to this\n * new network.\n *\n * If the network has not been previously switched, this method is equivalent\n * to {@link resetConnection}.\n */\n async rollbackToPreviousProvider() {\n await this.#refreshNetwork(this.#previouslySelectedNetworkClientId);\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 ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\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 networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [NetworkClientType.Infura, network, networkClientConfiguration];\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 const networkClientId = networkConfigurationId;\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Updates the global provider and block tracker proxies (accessible via\n * {@link getSelectedNetworkClient}) to point to the same ones within the\n * given network client, thereby magically switching any consumers using these\n * proxies to use the new network.\n *\n * Also refreshes the EthQuery instance accessible via the `getEthQuery`\n * action to wrap the provider from the new network client. Note that this is\n * not a proxy, so consumers will need to call `getEthQuery` again after the\n * network switch.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n * @throws if no network client could be found matching the given ID.\n */\n #applyNetworkSelection(networkClientId: string) {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n let autoManagedNetworkClient:\n | AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n | AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n if (isInfuraNetworkType(networkClientId)) {\n const possibleAutoManagedNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n\n // This is impossible to reach\n /* istanbul ignore if */\n if (!possibleAutoManagedNetworkClient) {\n throw new Error(\n `Infura network client not found with ID '${networkClientId}'`,\n );\n }\n\n autoManagedNetworkClient = possibleAutoManagedNetworkClient;\n } else {\n const possibleAutoManagedNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n\n if (!possibleAutoManagedNetworkClient) {\n throw new Error(\n `Custom network client not found with ID '${networkClientId}'`,\n );\n }\n\n autoManagedNetworkClient = possibleAutoManagedNetworkClient;\n }\n\n this.#autoManagedNetworkClient = autoManagedNetworkClient;\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 if (this.#providerProxy) {\n this.#providerProxy.setTarget(this.#autoManagedNetworkClient.provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(\n this.#autoManagedNetworkClient.provider,\n );\n }\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(\n this.#autoManagedNetworkClient.blockTracker,\n );\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(\n this.#autoManagedNetworkClient.blockTracker,\n { eventFilter: 'skipInternal' },\n );\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AACrB,SAAS,kBAAkB;AAC3B,SAAS,+BAA+B;AAGxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,cAAc;AAEjC,SAAS,MAAM,cAAc;AAkB7B,I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AAe,UAAU,mBAAK,2BAA0B,QAAQ;AAAA,EACvE,OAAO;AACL,uBAAK,gBAAiB;AAAA,MACpB,mBAAK,2BAA0B;AAAA,IACjC;AAAA,EACF;AAEA,MAAI,mBAAK,qBAAoB;AAC3B,uBAAK,oBAAmB;AAAA,MACtB,mBAAK,2BAA0B;AAAA,IACjC;AAAA,EACF,OAAO;AACL,uBAAK,oBAAqB;AAAA,MACxB,mBAAK,2BAA0B;AAAA,MAC/B,EAAE,aAAa,eAAe;AAAA,IAChC;AAAA,EACF;AAEA,qBAAK,WAAY,IAAI,SAAS,mBAAK,eAAc;AACnD;","names":[]}
@@ -34,7 +34,7 @@ var _swappableobjproxy = require('@metamask/swappable-obj-proxy');
34
34
  var _utils = require('@metamask/utils');
35
35
  var _assert = require('assert');
36
36
  var _uuid = require('uuid');
37
- var log = _chunkVGYLDDJBjs.createModuleLogger.call(void 0, _chunkVGYLDDJBjs.projectLogger, "NetworkController");
37
+ var debugLog = _chunkVGYLDDJBjs.createModuleLogger.call(void 0, _chunkVGYLDDJBjs.projectLogger, "NetworkController");
38
38
  function knownKeysOf(object) {
39
39
  return Object.keys(object);
40
40
  }
@@ -64,13 +64,14 @@ var defaultState = {
64
64
  networksMetadata: {},
65
65
  networkConfigurations: {}
66
66
  };
67
- var _ethQuery, _infuraProjectId, _trackMetaMetricsEvent, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn, _applyNetworkSelection, applyNetworkSelection_fn;
67
+ var _ethQuery, _infuraProjectId, _trackMetaMetricsEvent, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _log, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn, _applyNetworkSelection, applyNetworkSelection_fn;
68
68
  var NetworkController = class extends _basecontroller.BaseController {
69
69
  constructor({
70
70
  messenger,
71
71
  state,
72
72
  infuraProjectId,
73
- trackMetaMetricsEvent
73
+ trackMetaMetricsEvent,
74
+ log
74
75
  }) {
75
76
  super({
76
77
  name,
@@ -182,6 +183,7 @@ var NetworkController = class extends _basecontroller.BaseController {
182
183
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _blockTrackerProxy, void 0);
183
184
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _autoManagedNetworkClientRegistry, void 0);
184
185
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _autoManagedNetworkClient, void 0);
186
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _log, void 0);
185
187
  if (!infuraProjectId || typeof infuraProjectId !== "string") {
186
188
  throw new Error("Invalid Infura project ID");
187
189
  }
@@ -238,6 +240,7 @@ var NetworkController = class extends _basecontroller.BaseController {
238
240
  this.getSelectedNetworkClient.bind(this)
239
241
  );
240
242
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
243
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _log, log);
241
244
  }
242
245
  /**
243
246
  * Accesses the provider and block tracker for the currently selected network.
@@ -328,28 +331,45 @@ var NetworkController = class extends _basecontroller.BaseController {
328
331
  updatedIsEIP1559Compatible = await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, networkClientId);
329
332
  updatedNetworkStatus = "available" /* Available */;
330
333
  } catch (error) {
334
+ debugLog("NetworkController: lookupNetworkByClientId: ", error);
331
335
  if (isErrorWithCode(error)) {
332
336
  let responseBody;
333
337
  if (isInfura && _utils.hasProperty.call(void 0, error, "message") && typeof error.message === "string") {
334
338
  try {
335
339
  responseBody = JSON.parse(error.message);
336
340
  } catch {
341
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn(
342
+ "NetworkController: lookupNetworkByClientId: json parse error: ",
343
+ error
344
+ );
337
345
  }
338
346
  }
339
347
  if (_utils.isPlainObject.call(void 0, responseBody) && responseBody.error === _chunkZKNI7MD3js.INFURA_BLOCKED_KEY) {
340
348
  updatedNetworkStatus = "blocked" /* Blocked */;
341
349
  } else if (error.code === _rpcerrors.errorCodes.rpc.internal) {
342
350
  updatedNetworkStatus = "unknown" /* Unknown */;
351
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn(
352
+ "NetworkController: lookupNetworkByClientId: rpc internal error: ",
353
+ error
354
+ );
343
355
  } else {
344
356
  updatedNetworkStatus = "unavailable" /* Unavailable */;
357
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn(
358
+ "NetworkController: lookupNetworkByClientId: ",
359
+ error
360
+ );
345
361
  }
346
362
  } else if (typeof Error !== "undefined" && _utils.hasProperty.call(void 0, error, "message") && typeof error.message === "string" && error.message.includes(
347
363
  "No custom network client was found with the ID"
348
364
  )) {
349
365
  throw error;
350
366
  } else {
351
- log("NetworkController - could not determine network status", error);
367
+ debugLog(
368
+ "NetworkController - could not determine network status",
369
+ error
370
+ );
352
371
  updatedNetworkStatus = "unknown" /* Unknown */;
372
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn("NetworkController: lookupNetworkByClientId: ", error);
353
373
  }
354
374
  }
355
375
  this.update((state) => {
@@ -416,19 +436,32 @@ var NetworkController = class extends _basecontroller.BaseController {
416
436
  if (isInfura && _utils.hasProperty.call(void 0, error, "message") && typeof error.message === "string") {
417
437
  try {
418
438
  responseBody = JSON.parse(error.message);
419
- } catch {
439
+ } catch (parseError) {
440
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn(
441
+ "NetworkController: lookupNetwork: json parse error",
442
+ parseError
443
+ );
420
444
  }
421
445
  }
422
446
  if (_utils.isPlainObject.call(void 0, responseBody) && responseBody.error === _chunkZKNI7MD3js.INFURA_BLOCKED_KEY) {
423
447
  updatedNetworkStatus = "blocked" /* Blocked */;
424
448
  } else if (error.code === _rpcerrors.errorCodes.rpc.internal) {
425
449
  updatedNetworkStatus = "unknown" /* Unknown */;
450
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn(
451
+ "NetworkController: lookupNetwork: rpc internal error",
452
+ error
453
+ );
426
454
  } else {
427
455
  updatedNetworkStatus = "unavailable" /* Unavailable */;
456
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn("NetworkController: lookupNetwork: ", error);
428
457
  }
429
458
  } else {
430
- log("NetworkController - could not determine network status", error);
459
+ debugLog(
460
+ "NetworkController - could not determine network status",
461
+ error
462
+ );
431
463
  updatedNetworkStatus = "unknown" /* Unknown */;
464
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _log)?.warn("NetworkController: lookupNetwork: ", error);
432
465
  }
433
466
  }
434
467
  if (networkChanged) {
@@ -753,6 +786,7 @@ _providerProxy = new WeakMap();
753
786
  _blockTrackerProxy = new WeakMap();
754
787
  _autoManagedNetworkClientRegistry = new WeakMap();
755
788
  _autoManagedNetworkClient = new WeakMap();
789
+ _log = new WeakMap();
756
790
  _refreshNetwork = new WeakSet();
757
791
  refreshNetwork_fn = async function(networkClientId) {
758
792
  this.messagingSystem.publish(
@@ -912,4 +946,4 @@ applyNetworkSelection_fn = function(networkClientId) {
912
946
 
913
947
 
914
948
  exports.knownKeysOf = knownKeysOf; exports.defaultState = defaultState; exports.NetworkController = NetworkController;
915
- //# sourceMappingURL=chunk-WBGETWDR.js.map
949
+ //# sourceMappingURL=chunk-WT5ZBF4X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AACrB,SAAS,kBAAkB;AAC3B,SAAS,+BAA+B;AAGxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,cAAc;AAEjC,SAAS,MAAM,cAAc;AAkB7B,IAAM,WAAW,mBAAmB,eAAe,mBAAmB;AAkE/D,SAAS,YAGd,QACA;AACA,SAAO,OAAO,KAAK,MAAM;AAC3B;AAcA,SAAS,aACP,OACA,UACA,SACuB;AACvB,SAAO,GAAG,SAAS,KAAK,GAAG,OAAO;AACpC;AAWA,SAAS,KACP,QACA,MACiB;AACjB,QAAM,eAAe,KAAK;AAAA,IACxB,CAAC,aAAa,QAAQ;AACpB,aAAO,EAAE,GAAG,aAAa,CAAC,GAAG,GAAG,OAAO,GAAG,EAAE;AAAA,IAC9C;AAAA,IACA,CAAC;AAAA,EACH;AACA;AAAA,IACE;AAAA,IACA,MAAM,KAAK,MAAM,CAAC,QAAQ,OAAO,YAAY;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AAWA,SAAS,gBAAgB,OAAoD;AAC3E,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU;AAClE;AAqCA,IAAM,OAAO;AAuJN,IAAM,e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L;AAEF,MAAI;AAIJ,MAAI,oBAAoB,eAAe,GAAG;AACxC,UAAM,mCACJ,sDAAyD,EACvD,eACF;AAIF,QAAI,CAAC,kCAAkC;AACrC,YAAM,IAAI;AAAA,QACR,4CAA4C,eAAe;AAAA,MAC7D;AAAA,IACF;AAEA,+BAA2B;AAAA,EAC7B,OAAO;AACL,UAAM,mCACJ,sDAAyD,EACvD,eACF;AAEF,QAAI,CAAC,kCAAkC;AACrC,YAAM,IAAI;AAAA,QACR,4CAA4C,eAAe;AAAA,MAC7D;AAAA,IACF;AAEA,+BAA2B;AAAA,EAC7B;AAEA,qBAAK,2BAA4B;AAEjC,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,0BAA0B;AAChC,QAAI,MAAM,iBAAiB,eAAe,MAAM,QAAW;AACzD,YAAM,iBAAiB,eAAe,IAAI;AAAA,QACxC;AAAA,QACA,MAAM,CAAC;AAAA,MACT;AAAA,IACF;AAAA,EACF,CAAC;AAED,MAAI,mBAAK,iBAAgB;AACvB,uBAAK,gBAAe,UAAU,mBAAK,2BAA0B,QAAQ;AAAA,EACvE,OAAO;AACL,uBAAK,gBAAiB;AAAA,MACpB,mBAAK,2BAA0B;AAAA,IACjC;AAAA,EACF;AAEA,MAAI,mBAAK,qBAAoB;AAC3B,uBAAK,oBAAmB;AAAA,MACtB,mBAAK,2BAA0B;AAAA,IACjC;AAAA,EACF,OAAO;AACL,uBAAK,oBAAqB;AAAA,MACxB,mBAAK,2BAA0B;AAAA,MAC/B,EAAE,aAAa,eAAe;AAAA,IAChC;AAAA,EACF;AAEA,qBAAK,WAAY,IAAI,SAAS,mBAAK,eAAc;AACnD","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n isInfuraNetworkType,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { errorCodes } from '@metamask/rpc-errors';\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 type { Logger } from 'loglevel';\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 debugLog = createModuleLogger(projectLogger, 'NetworkController');\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function knownKeysOf<K extends PropertyKey>(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * The string that uniquely identifies an Infura network client.\n */\nexport type BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\nexport type 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 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 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 = ControllerStateChangeEvent<\n typeof name,\n NetworkState\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: [NetworkState];\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: [NetworkState];\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 = ControllerGetStateAction<\n typeof name,\n NetworkState\n>;\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\n};\n\nexport type NetworkControllerGetSelectedNetworkClientAction = {\n type: `NetworkController:getSelectedNetworkClient`;\n handler: NetworkController['getSelectedNetworkClient'];\n};\n\nexport type NetworkControllerGetEIP1559CompatibilityAction = {\n type: `NetworkController:getEIP1559Compatibility`;\n handler: NetworkController['getEIP1559Compatibility'];\n};\n\nexport type NetworkControllerFindNetworkClientIdByChainIdAction = {\n type: `NetworkController:findNetworkClientIdByChainId`;\n handler: NetworkController['findNetworkClientIdByChainId'];\n};\n\n/**\n * Change the currently selected network to the given built-in network type.\n *\n * @deprecated This action has been replaced by `setActiveNetwork`, and will be\n * removed in a future release.\n */\nexport type NetworkControllerSetProviderTypeAction = {\n type: `NetworkController:setProviderType`;\n handler: NetworkController['setProviderType'];\n};\n\nexport type NetworkControllerSetActiveNetworkAction = {\n type: `NetworkController:setActiveNetwork`;\n handler: NetworkController['setActiveNetwork'];\n};\n\nexport type NetworkControllerGetNetworkConfigurationByNetworkClientId = {\n type: `NetworkController:getNetworkConfigurationByNetworkClientId`;\n handler: NetworkController['getNetworkConfigurationByNetworkClientId'];\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n never,\n never\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n log?: Logger;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\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 BaseController<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previouslySelectedNetworkClientId: string;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n #autoManagedNetworkClient?:\n | AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n | AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n #log: Logger | undefined;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n log,\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 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\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getNetworkConfigurationByNetworkClientId`,\n this.getNetworkConfigurationByNetworkClientId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getSelectedNetworkClient`,\n this.getSelectedNetworkClient.bind(this),\n );\n\n this.#previouslySelectedNetworkClientId =\n this.state.selectedNetworkClientId;\n\n this.#log = log;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n * @returns The proxy and block tracker proxies.\n * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.\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 * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns an object with the provider and block tracker proxies for the currently selected network.\n */\n getSelectedNetworkClient():\n | {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n blockTracker: SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>;\n }\n | undefined {\n if (this.#providerProxy && this.#blockTrackerProxy) {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n return undefined;\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 (isInfuraNetworkType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n // This is impossible to reach\n /* istanbul ignore if */\n if (!infuraNetworkClient) {\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 switch the network:\n *\n * 1. Notifies subscribers via the messenger that the network is about to be\n * switched (and, really, that the global provider and block tracker proxies\n * will be re-pointed to a new network).\n * 2. Looks up a known and preinitialized network client matching the given\n * ID and uses it to re-point the aforementioned provider and block tracker\n * proxies.\n * 3. Notifies subscribers via the messenger that the network has switched.\n * 4. Captures metadata for the newly switched network in state.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n */\n async #refreshNetwork(networkClientId: string) {\n this.messagingSystem.publish(\n 'NetworkController:networkWillChange',\n this.state,\n );\n this.#applyNetworkSelection(networkClientId);\n this.messagingSystem.publish(\n 'NetworkController:networkDidChange',\n this.state,\n );\n await this.lookupNetwork();\n }\n\n /**\n * Creates network clients for built-in and custom networks, then establishes\n * the currently selected network client based on state.\n */\n async initializeProvider() {\n this.#applyNetworkSelection(this.state.selectedNetworkClientId);\n await this.lookupNetwork();\n }\n\n /**\n * Refreshes the network meta with EIP-1559 support and the network status\n * based on the given network client ID.\n *\n * @param networkClientId - The ID of the network client to update.\n */\n async lookupNetworkByClientId(networkClientId: NetworkClientId) {\n const isInfura = isInfuraNetworkType(networkClientId);\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n updatedIsEIP1559Compatible = await this.#determineEIP1559Compatibility(\n networkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n } catch (error) {\n debugLog('NetworkController: lookupNetworkByClientId: ', error);\n\n // TODO: mock ethQuery.sendAsync to throw error without error code\n /* istanbul ignore else */\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 this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: json parse error: ',\n error,\n );\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 this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: rpc internal error: ',\n error,\n );\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n this.#log?.warn(\n 'NetworkController: lookupNetworkByClientId: ',\n error,\n );\n }\n } else if (\n typeof Error !== 'undefined' &&\n hasProperty(error as unknown as Error, 'message') &&\n typeof (error as unknown as Error).message === 'string' &&\n (error as unknown as Error).message.includes(\n 'No custom network client was found with the ID',\n )\n ) {\n throw error;\n } else {\n debugLog(\n 'NetworkController - could not determine network status',\n error,\n );\n updatedNetworkStatus = NetworkStatus.Unknown;\n this.#log?.warn('NetworkController: lookupNetworkByClientId: ', error);\n }\n }\n this.update((state) => {\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n const meta = state.networksMetadata[networkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n }\n\n /**\n * Persists the following metadata about the given or selected network to\n * state:\n *\n * - The status of the network, namely, whether it is available, geo-blocked\n * (Infura only), or unavailable, or whether the status is unknown\n * - Whether the network supports EIP-1559, or whether it is unknown\n *\n * Note that it is possible for the network to be switched while this data is\n * being collected. If that is the case, no metadata for the (now previously)\n * selected network will be updated.\n *\n * @param networkClientId - The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n */\n async lookupNetwork(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n await this.lookupNetworkByClientId(networkClientId);\n return;\n }\n\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura =\n this.#autoManagedNetworkClient?.configuration.type ===\n NetworkClientType.Infura;\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 this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n // TODO: mock ethQuery.sendAsync to throw error without error code\n /* istanbul ignore else */\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 (parseError) {\n // error.message must not be JSON\n this.#log?.warn(\n 'NetworkController: lookupNetwork: json parse error',\n parseError,\n );\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 this.#log?.warn(\n 'NetworkController: lookupNetwork: rpc internal error',\n error,\n );\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n this.#log?.warn('NetworkController: lookupNetwork: ', error);\n }\n } else {\n debugLog(\n 'NetworkController - could not determine network status',\n error,\n );\n updatedNetworkStatus = NetworkStatus.Unknown;\n this.#log?.warn('NetworkController: lookupNetwork: ', error);\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 * @deprecated This has been replaced by `setActiveNetwork`, and will be\n * removed in a future release\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraNetworkType(type),\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unknown Infura provider type \"${type}\".`,\n );\n\n await this.setActiveNetwork(type);\n }\n\n /**\n * Changes the selected network.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n * @throws if no network client is associated with the given\n * `networkClientId`.\n */\n async setActiveNetwork(networkClientId: string) {\n this.#previouslySelectedNetworkClientId =\n this.state.selectedNetworkClientId;\n\n await this.#refreshNetwork(networkClientId);\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.\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(networkClientId: NetworkClientId): Promise<Block> {\n if (networkClientId === undefined) {\n networkClientId = this.state.selectedNetworkClientId;\n }\n\n const networkClient = this.getNetworkClientById(networkClientId);\n const ethQuery = new EthQuery(networkClient.provider);\n\n return new Promise((resolve, reject) => {\n 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 * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.\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(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n return this.get1559CompatibilityWithNetworkClientId(networkClientId);\n }\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.state.selectedNetworkClientId,\n );\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 async get1559CompatibilityWithNetworkClientId(\n networkClientId: NetworkClientId,\n ) {\n let metadata = this.state.networksMetadata[networkClientId];\n if (metadata === undefined) {\n await this.lookupNetwork(networkClientId);\n metadata = this.state.networksMetadata[networkClientId];\n }\n const { EIPS } = metadata;\n\n // may want to include some 'freshness' value - something to make sure we refetch this from time to time\n return EIPS[1559];\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 * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility\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(\n networkClientId: NetworkClientId,\n ): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock(networkClientId);\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Ensures that the provider and block tracker proxies are pointed to the\n * currently selected network and refreshes the metadata for the\n */\n async resetConnection() {\n await this.#refreshNetwork(this.state.selectedNetworkClientId);\n }\n\n /**\n * Returns a configuration object for the network identified by the given\n * network client ID. If given an Infura network type, constructs one based on\n * what we know about the network; otherwise attempts locates a network\n * configuration in state that corresponds to the network client ID.\n *\n * @param networkClientId - The network client ID.\n * @returns The configuration for the referenced network if one exists, or\n * undefined otherwise.\n */\n getNetworkConfigurationByNetworkClientId(\n networkClientId: NetworkClientId,\n ): NetworkConfiguration | undefined {\n if (isInfuraNetworkType(networkClientId)) {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const rpcUrl = `https://${networkClientId}.infura.io/v3/${\n this.#infuraProjectId\n }`;\n return {\n rpcUrl,\n ...BUILT_IN_NETWORKS[networkClientId],\n };\n }\n\n return this.state.networkConfigurations[networkClientId];\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 = upsertedNetworkConfigurationId;\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 ticker,\n });\n }\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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 = 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 * Assuming that the network has been previously switched, switches to this\n * new network.\n *\n * If the network has not been previously switched, this method is equivalent\n * to {@link resetConnection}.\n */\n async rollbackToPreviousProvider() {\n await this.#refreshNetwork(this.#previouslySelectedNetworkClientId);\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 ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\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 networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [NetworkClientType.Infura, network, networkClientConfiguration];\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 const networkClientId = networkConfigurationId;\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Updates the global provider and block tracker proxies (accessible via\n * {@link getSelectedNetworkClient}) to point to the same ones within the\n * given network client, thereby magically switching any consumers using these\n * proxies to use the new network.\n *\n * Also refreshes the EthQuery instance accessible via the `getEthQuery`\n * action to wrap the provider from the new network client. Note that this is\n * not a proxy, so consumers will need to call `getEthQuery` again after the\n * network switch.\n *\n * @param networkClientId - The ID of a network client that requests will be\n * routed through (either the name of an Infura network or the ID of a custom\n * network configuration).\n * @throws if no network client could be found matching the given ID.\n */\n #applyNetworkSelection(networkClientId: string) {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n let autoManagedNetworkClient:\n | AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n | AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n if (isInfuraNetworkType(networkClientId)) {\n const possibleAutoManagedNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n\n // This is impossible to reach\n /* istanbul ignore if */\n if (!possibleAutoManagedNetworkClient) {\n throw new Error(\n `Infura network client not found with ID '${networkClientId}'`,\n );\n }\n\n autoManagedNetworkClient = possibleAutoManagedNetworkClient;\n } else {\n const possibleAutoManagedNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n\n if (!possibleAutoManagedNetworkClient) {\n throw new Error(\n `Custom network client not found with ID '${networkClientId}'`,\n );\n }\n\n autoManagedNetworkClient = possibleAutoManagedNetworkClient;\n }\n\n this.#autoManagedNetworkClient = autoManagedNetworkClient;\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 if (this.#providerProxy) {\n this.#providerProxy.setTarget(this.#autoManagedNetworkClient.provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(\n this.#autoManagedNetworkClient.provider,\n );\n }\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(\n this.#autoManagedNetworkClient.blockTracker,\n );\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(\n this.#autoManagedNetworkClient.blockTracker,\n { eventFilter: 'skipInternal' },\n );\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}