@metamask-previews/network-controller 16.0.0-preview.eb58a59 → 17.0.0-preview.3fbb6b41

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
+ ### Added
9
+ - Add `getNetworkConfigurationByNetworkClientId` method which can be used to retrieve details for both custom and built-in networks (using the network configuration object shape) ([#2055](https://github.com/MetaMask/core/pull/2055))
10
+ - Add `NetworkController:getNetworkConfigurationByNetworkClientId` messenger action for the previous method ([#2055](https://github.com/MetaMask/core/pull/2055))
11
+
12
+ ## [17.0.0]
13
+ ### Changed
14
+ - **BREAKING:** Bump `@metamask/base-controller` to ^4.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
15
+ - This is breaking because the type of the `messenger` has backward-incompatible changes. See the changelog for this package for more.
16
+ - Bump `@metamask/controller-utils` to ^6.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
8
17
 
9
18
  ## [16.0.0]
10
19
  ### Changed
@@ -309,7 +318,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
309
318
 
310
319
  All changes listed after this point were applied to this package following the monorepo conversion.
311
320
 
312
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@16.0.0...HEAD
321
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@17.0.0...HEAD
322
+ [17.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@16.0.0...@metamask/network-controller@17.0.0
313
323
  [16.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@15.2.0...@metamask/network-controller@16.0.0
314
324
  [15.2.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@15.1.0...@metamask/network-controller@15.2.0
315
325
  [15.1.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@15.0.0...@metamask/network-controller@15.1.0
@@ -1,5 +1,5 @@
1
1
  import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
2
- import { BaseControllerV2 } from '@metamask/base-controller';
2
+ import { BaseController } from '@metamask/base-controller';
3
3
  import { InfuraNetworkType, NetworkType } from '@metamask/controller-utils';
4
4
  import EthQuery from '@metamask/eth-query';
5
5
  import type { SwappableProxy } from '@metamask/swappable-obj-proxy';
@@ -142,7 +142,7 @@ export declare type NetworkControllerStateChangeEvent = ControllerStateChangeEve
142
142
  */
143
143
  export declare type NetworkControllerNetworkWillChangeEvent = {
144
144
  type: 'NetworkController:networkWillChange';
145
- payload: [];
145
+ payload: [NetworkState];
146
146
  };
147
147
  /**
148
148
  * `networkDidChange` is published after a provider has been created for a newly
@@ -150,7 +150,7 @@ export declare type NetworkControllerNetworkWillChangeEvent = {
150
150
  */
151
151
  export declare type NetworkControllerNetworkDidChangeEvent = {
152
152
  type: 'NetworkController:networkDidChange';
153
- payload: [];
153
+ payload: [NetworkState];
154
154
  };
155
155
  /**
156
156
  * `infuraIsBlocked` is published after the network is switched to an Infura
@@ -200,7 +200,11 @@ export declare type NetworkControllerSetActiveNetworkAction = {
200
200
  type: `NetworkController:setActiveNetwork`;
201
201
  handler: NetworkController['setActiveNetwork'];
202
202
  };
203
- export declare type NetworkControllerActions = NetworkControllerGetStateAction | NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetEIP1559CompatibilityAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerSetActiveNetworkAction | NetworkControllerSetProviderTypeAction;
203
+ export declare type NetworkControllerGetNetworkConfigurationByNetworkClientId = {
204
+ type: `NetworkController:getNetworkConfigurationByNetworkClientId`;
205
+ handler: NetworkController['getNetworkConfigurationByNetworkClientId'];
206
+ };
207
+ export declare type NetworkControllerActions = NetworkControllerGetStateAction | NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetEIP1559CompatibilityAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerSetActiveNetworkAction | NetworkControllerSetProviderTypeAction | NetworkControllerGetNetworkConfigurationByNetworkClientId;
204
208
  export declare type NetworkControllerMessenger = RestrictedControllerMessenger<typeof name, NetworkControllerActions, NetworkControllerEvents, string, string>;
205
209
  export declare type NetworkControllerOptions = {
206
210
  messenger: NetworkControllerMessenger;
@@ -221,7 +225,7 @@ declare type AutoManagedCustomNetworkClientRegistry = Record<CustomNetworkClient
221
225
  /**
222
226
  * Controller that creates and manages an Ethereum network provider.
223
227
  */
224
- export declare class NetworkController extends BaseControllerV2<typeof name, NetworkState, NetworkControllerMessenger> {
228
+ export declare class NetworkController extends BaseController<typeof name, NetworkState, NetworkControllerMessenger> {
225
229
  #private;
226
230
  constructor({ messenger, state, infuraProjectId, trackMetaMetricsEvent, }: NetworkControllerOptions);
227
231
  /**
@@ -311,6 +315,17 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
311
315
  * Re-initializes the provider and block tracker for the current network.
312
316
  */
313
317
  resetConnection(): Promise<void>;
318
+ /**
319
+ * Returns a configuration object for the network identified by the given
320
+ * network client ID. If given an Infura network type, constructs one based on
321
+ * what we know about the network; otherwise attempts locates a network
322
+ * configuration in state that corresponds to the network client ID.
323
+ *
324
+ * @param networkClientId - The network client ID.
325
+ * @returns The configuration for the referenced network if one exists, or
326
+ * undefined otherwise.
327
+ */
328
+ getNetworkConfigurationByNetworkClientId(networkClientId: NetworkClientId): NetworkConfiguration | undefined;
314
329
  /**
315
330
  * Adds a new custom network or updates the information for an existing
316
331
  * network.
@@ -1 +1 @@
1
- {"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6B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e;IAkClC;;OAEG;IACG,eAAe;IAKrB;;;;;;;;;OASG;IACH,wCAAwC,CACtC,eAAe,EAAE,eAAe,GAC/B,oBAAoB,GAAG,SAAS;IAcnC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,0BAA0B,CAC9B,oBAAoB,EAAE,oBAAoB,EAC1C,EACE,QAAQ,EACR,MAAM,EACN,SAAiB,GAClB,EAAE;QACD,QAAQ,EAAE,MAAM,CAAC;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,OAAO,CAAC;KACrB,GACA,OAAO,CAAC,MAAM,CAAC;IAwGlB;;;;;;;;;OASG;IACH,0BAA0B,CAAC,sBAAsB,EAAE,MAAM;IAuBzD;;;;OAIG;IACG,0BAA0B;IAUhC;;;;OAIG;IACG,OAAO;IAIb;;;;;OAKG;IACH,UAAU,CAAC,EACT,qBAAqB,GACtB,EAAE;QACD,qBAAqB,EAAE,YAAY,CAAC,uBAAuB,CAAC,CAAC;KAC9D,GAAG,IAAI;IASR;;;;;OAKG;IACH,4BAA4B,CAAC,OAAO,EAAE,GAAG,GAAG,eAAe;CA8P5D"}
@@ -96,17 +96,6 @@ function pick(object, keys) {
96
96
  function isErrorWithCode(error) {
97
97
  return typeof error === 'object' && error !== null && 'code' in error;
98
98
  }
99
- /**
100
- * Returns whether the given argument is a type that our Infura middleware
101
- * recognizes.
102
- *
103
- * @param type - A type to compare.
104
- * @returns True or false, depending on whether the given type is one that our
105
- * Infura middleware recognizes.
106
- */
107
- function isInfuraProviderType(type) {
108
- return Object.keys(controller_utils_1.InfuraNetworkType).includes(type);
109
- }
110
99
  /**
111
100
  * Builds an identifier for an Infura network client for lookup purposes.
112
101
  *
@@ -152,7 +141,7 @@ function buildCustomNetworkClientId(...args) {
152
141
  * otherwise.
153
142
  */
154
143
  function isInfuraProviderConfig(providerConfig) {
155
- return isInfuraProviderType(providerConfig.type);
144
+ return (0, controller_utils_1.isInfuraNetworkType)(providerConfig.type);
156
145
  }
157
146
  /**
158
147
  * Returns whether the given provider config refers to an Infura network.
@@ -201,7 +190,7 @@ exports.defaultState = {
201
190
  /**
202
191
  * Controller that creates and manages an Ethereum network provider.
203
192
  */
204
- class NetworkController extends base_controller_1.BaseControllerV2 {
193
+ class NetworkController extends base_controller_1.BaseController {
205
194
  constructor({ messenger, state, infuraProjectId, trackMetaMetricsEvent, }) {
206
195
  super({
207
196
  name,
@@ -251,6 +240,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
251
240
  this.messagingSystem.registerActionHandler(`${this.name}:setActiveNetwork`, this.setActiveNetwork.bind(this));
252
241
  this.messagingSystem.registerActionHandler(`${this.name}:setProviderType`, this.setProviderType.bind(this));
253
242
  this.messagingSystem.registerActionHandler(`${this.name}:findNetworkClientIdByChainId`, this.findNetworkClientIdByChainId.bind(this));
243
+ this.messagingSystem.registerActionHandler(`${this.name}:getNetworkConfigurationByNetworkClientId`, this.getNetworkConfigurationByNetworkClientId.bind(this));
254
244
  __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
255
245
  }
256
246
  /**
@@ -281,7 +271,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
281
271
  throw new Error('No network client ID was provided.');
282
272
  }
283
273
  const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
284
- if (isInfuraProviderType(networkClientId)) {
274
+ if ((0, controller_utils_1.isInfuraNetworkType)(networkClientId)) {
285
275
  const infuraNetworkClient = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Infura][networkClientId];
286
276
  if (!infuraNetworkClient) {
287
277
  throw new Error(`No Infura network client was found with the ID "${networkClientId}".`);
@@ -313,7 +303,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
313
303
  */
314
304
  lookupNetworkByClientId(networkClientId) {
315
305
  return __awaiter(this, void 0, void 0, function* () {
316
- const isInfura = isInfuraProviderType(networkClientId);
306
+ const isInfura = (0, controller_utils_1.isInfuraNetworkType)(networkClientId);
317
307
  let updatedNetworkStatus;
318
308
  let updatedIsEIP1559Compatible;
319
309
  try {
@@ -478,7 +468,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
478
468
  setProviderType(type) {
479
469
  return __awaiter(this, void 0, void 0, function* () {
480
470
  assert_1.strict.notStrictEqual(type, controller_utils_1.NetworkType.rpc, `NetworkController - cannot call "setProviderType" with type "${controller_utils_1.NetworkType.rpc}". Use "setActiveNetwork"`);
481
- assert_1.strict.ok(isInfuraProviderType(type), `Unknown Infura provider type "${type}".`);
471
+ assert_1.strict.ok((0, controller_utils_1.isInfuraNetworkType)(type), `Unknown Infura provider type "${type}".`);
482
472
  __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
483
473
  // If testnet the ticker symbol should use a testnet prefix
484
474
  const ticker = type in controller_utils_1.NetworksTicker && controller_utils_1.NetworksTicker[type].length > 0
@@ -574,6 +564,23 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
574
564
  yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
575
565
  });
576
566
  }
567
+ /**
568
+ * Returns a configuration object for the network identified by the given
569
+ * network client ID. If given an Infura network type, constructs one based on
570
+ * what we know about the network; otherwise attempts locates a network
571
+ * configuration in state that corresponds to the network client ID.
572
+ *
573
+ * @param networkClientId - The network client ID.
574
+ * @returns The configuration for the referenced network if one exists, or
575
+ * undefined otherwise.
576
+ */
577
+ getNetworkConfigurationByNetworkClientId(networkClientId) {
578
+ if ((0, controller_utils_1.isInfuraNetworkType)(networkClientId)) {
579
+ const rpcUrl = `https://${networkClientId}.infura.io/v3/${__classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f")}`;
580
+ return Object.assign({ rpcUrl }, controller_utils_1.BUILT_IN_NETWORKS[networkClientId]);
581
+ }
582
+ return this.state.networkConfigurations[networkClientId];
583
+ }
577
584
  /**
578
585
  * Adds a new custom network or updates the information for an existing
579
586
  * network.
@@ -747,9 +754,9 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
747
754
  exports.NetworkController = NetworkController;
748
755
  _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_previousProviderConfig = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_autoManagedNetworkClientRegistry = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
749
756
  return __awaiter(this, void 0, void 0, function* () {
750
- this.messagingSystem.publish('NetworkController:networkWillChange');
757
+ this.messagingSystem.publish('NetworkController:networkWillChange', this.state);
751
758
  __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
752
- this.messagingSystem.publish('NetworkController:networkDidChange');
759
+ this.messagingSystem.publish('NetworkController:networkDidChange', this.state);
753
760
  yield this.lookupNetwork();
754
761
  });
755
762
  }, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock(networkClientId) {
@@ -1 +1 @@
1
- {"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,+DAA6D;AAC7D,iEAOoC;AACpC,oEAA2C;AAC3C,qDAAkD;AAClD,uEAAwE;AAGxE,2CAIyB;AACzB,mCAA0C;AAC1C,+BAAoC;AAEpC,2CAAgE;AAKhE,6FAAsF;AACtF,qCAA6D;AAC7D,mCAA4C;AAS5C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,mBAAmB,CAAC,CAAC;AAsEnE;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CACzB,MAA+B;IAE/B,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAQ,CAAC;AACpC,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6C,CAAC,CAAC;KAChE;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,uBAAuB,GAAG,eAAe,CAAC;QAChD,IAAI,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE;YACzD,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,GAAG;gBACxC,MAAM,EAAE,yBAAa,CAAC,OAAO;gBAC7B,IAAI,EAAE,EAAE;aACT,CAAC;SACH;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,wBAAwB,CAAC;IAE5D,IAAI,uBAAA,IAAI,wCAAe,EAAE;QACvB,uBAAA,IAAI,wCAAe,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;KACzC;SAAM;QACL,uBAAA,IAAI,oCAAkB,IAAA,6CAAuB,EAAC,QAAQ,CAAC,MAAA,CAAC;KACzD;IACD,uBAAA,IAAI,+BAAa,QAAQ,MAAA,CAAC;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { 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 { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Returns whether the given argument is a type that our Infura middleware\n * recognizes.\n *\n * @param type - A type to compare.\n * @returns True or false, depending on whether the given type is one that our\n * Infura middleware recognizes.\n */\nfunction isInfuraProviderType(type: string): type is InfuraNetworkType {\n return Object.keys(InfuraNetworkType).includes(type);\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraProviderType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = 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: [];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = ControllerGetStateAction<\n typeof name,\n NetworkState\n>;\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\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\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 NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraProviderType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish('NetworkController:networkWillChange');\n this.#applyNetworkSelection();\n this.messagingSystem.publish('NetworkController:networkDidChange');\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * 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 = isInfuraProviderType(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 if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else 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 log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\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 * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @param networkClientId - (Optional) The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork(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 = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraProviderType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @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 * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n ticker,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n ticker: providerConfig.ticker,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
1
+ {"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,+DAA2D;AAC3D,iEAQoC;A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C;KACzC;SAAM;QACL,uBAAA,IAAI,oCAAkB,IAAA,6CAAuB,EAAC,QAAQ,CAAC,MAAA,CAAC;KACzD;IACD,uBAAA,IAAI,+BAAa,QAAQ,MAAA,CAAC;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\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 { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraNetworkType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = 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 NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\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\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 | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseController<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkConfigurationByNetworkClientId`,\n this.getNetworkConfigurationByNetworkClientId.bind(this),\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraNetworkType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish(\n 'NetworkController:networkWillChange',\n this.state,\n );\n this.#applyNetworkSelection();\n this.messagingSystem.publish(\n 'NetworkController:networkDidChange',\n this.state,\n );\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * 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 if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else 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 log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\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 * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @param networkClientId - (Optional) The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork(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 = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraNetworkType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @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 * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * 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 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 } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n ticker,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n ticker: providerConfig.ticker,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/network-controller",
3
- "version": "16.0.0-preview.eb58a59",
3
+ "version": "17.0.0-preview.3fbb6b41",
4
4
  "description": "Provides an interface to the currently selected network via a MetaMask-compatible provider object",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -30,8 +30,8 @@
30
30
  "test:watch": "jest --watch"
31
31
  },
32
32
  "dependencies": {
33
- "@metamask/base-controller": "^3.2.3",
34
- "@metamask/controller-utils": "^5.0.2",
33
+ "@metamask/base-controller": "^4.0.0",
34
+ "@metamask/controller-utils": "^6.1.0",
35
35
  "@metamask/eth-json-rpc-infura": "^9.0.0",
36
36
  "@metamask/eth-json-rpc-middleware": "^12.0.1",
37
37
  "@metamask/eth-json-rpc-provider": "^2.3.0",