@metamask/network-controller 10.2.0 → 10.3.1

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.
@@ -22,9 +22,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
22
22
  var __importDefault = (this && this.__importDefault) || function (mod) {
23
23
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
24
  };
25
- var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_blockTrackerProxy, _NetworkController_configureProvider, _NetworkController_refreshNetwork, _NetworkController_registerProvider, _NetworkController_setupInfuraProvider, _NetworkController_setupStandardProvider, _NetworkController_updateProvider, _NetworkController_getNetworkId, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_setProviderAndBlockTracker;
25
+ var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_provider, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_refreshNetwork, _NetworkController_getNetworkId, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated, _NetworkController_createAutoManagedNetworkClientRegistry, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig, _NetworkController_applyNetworkSelection;
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.NetworkController = exports.defaultState = void 0;
27
+ exports.NetworkController = exports.defaultState = exports.knownKeysOf = void 0;
28
28
  const assert_1 = require("assert");
29
29
  const swappable_obj_proxy_1 = require("@metamask/swappable-obj-proxy");
30
30
  const eth_query_1 = __importDefault(require("eth-query"));
@@ -35,8 +35,55 @@ const controller_utils_1 = require("@metamask/controller-utils");
35
35
  const utils_1 = require("@metamask/utils");
36
36
  const constants_1 = require("./constants");
37
37
  const logger_1 = require("./logger");
38
- const create_network_client_1 = require("./create-network-client");
38
+ const types_1 = require("./types");
39
+ const create_auto_managed_network_client_1 = require("./create-auto-managed-network-client");
39
40
  const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'NetworkController');
41
+ /**
42
+ * `Object.keys()` is intentionally generic: it returns the keys of an object,
43
+ * but it cannot make guarantees about the contents of that object, so the type
44
+ * of the keys is merely `string[]`. While this is technically accurate, it is
45
+ * also unnecessary if we have an object that we own and whose contents are
46
+ * known exactly.
47
+ *
48
+ * TODO: Move to @metamask/utils.
49
+ *
50
+ * @param object - The object.
51
+ * @returns The keys of an object, typed according to the type of the object
52
+ * itself.
53
+ */
54
+ function knownKeysOf(object) {
55
+ return Object.keys(object);
56
+ }
57
+ exports.knownKeysOf = knownKeysOf;
58
+ /**
59
+ * Asserts that the given value is of the given type if the given validation
60
+ * function returns a truthy result.
61
+ *
62
+ * @param value - The value to validate.
63
+ * @param validate - A function used to validate that the value is of the given
64
+ * type. Takes the `value` as an argument and is expected to return true or
65
+ * false.
66
+ * @param message - The message to throw if the function does not return a
67
+ * truthy result.
68
+ * @throws if the function does not return a truthy result.
69
+ */
70
+ function assertOfType(value, validate, message) {
71
+ assert_1.strict.ok(validate(value), message);
72
+ }
73
+ /**
74
+ * Returns a portion of the given object with only the given keys.
75
+ *
76
+ * @param object - An object.
77
+ * @param keys - The keys to pick from the object.
78
+ * @returns the portion of the object.
79
+ */
80
+ function pick(object, keys) {
81
+ const pickedObject = keys.reduce((finalObject, key) => {
82
+ return Object.assign(Object.assign({}, finalObject), { [key]: object[key] });
83
+ }, {});
84
+ assertOfType(pickedObject, () => keys.every((key) => key in pickedObject), 'The reduce did not produce an object with all of the desired keys.');
85
+ return pickedObject;
86
+ }
40
87
  /**
41
88
  * Convert the given value into a valid network ID. The ID is accepted
42
89
  * as either a number, a decimal string, or a 0x-prefixed hex string.
@@ -80,6 +127,86 @@ function isErrorWithCode(error) {
80
127
  function isInfuraProviderType(type) {
81
128
  return Object.keys(controller_utils_1.InfuraNetworkType).includes(type);
82
129
  }
130
+ /**
131
+ * Builds an identifier for an Infura network client for lookup purposes.
132
+ *
133
+ * @param infuraNetworkOrProviderConfig - The name of an Infura network or a
134
+ * provider config.
135
+ * @returns The built identifier.
136
+ */
137
+ function buildInfuraNetworkClientId(infuraNetworkOrProviderConfig) {
138
+ if (typeof infuraNetworkOrProviderConfig === 'string') {
139
+ return infuraNetworkOrProviderConfig;
140
+ }
141
+ return infuraNetworkOrProviderConfig.type;
142
+ }
143
+ /**
144
+ * Builds an identifier for a custom network client for lookup purposes.
145
+ *
146
+ * @param args - This function can be called two ways:
147
+ * 1. The ID of a network configuration.
148
+ * 2. A provider config and a set of network configurations.
149
+ * @returns The built identifier.
150
+ */
151
+ function buildCustomNetworkClientId(...args) {
152
+ if (args.length === 1) {
153
+ return args[0];
154
+ }
155
+ const [{ id, rpcUrl }, networkConfigurations] = args;
156
+ if (id === undefined) {
157
+ const matchingNetworkConfiguration = Object.values(networkConfigurations).find((networkConfiguration) => {
158
+ return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();
159
+ });
160
+ if (matchingNetworkConfiguration) {
161
+ return matchingNetworkConfiguration.id;
162
+ }
163
+ return rpcUrl.toLowerCase();
164
+ }
165
+ return id;
166
+ }
167
+ /**
168
+ * Returns whether the given provider config refers to an Infura network.
169
+ *
170
+ * @param providerConfig - The provider config.
171
+ * @returns True if the provider config refers to an Infura network, false
172
+ * otherwise.
173
+ */
174
+ function isInfuraProviderConfig(providerConfig) {
175
+ return isInfuraProviderType(providerConfig.type);
176
+ }
177
+ /**
178
+ * Returns whether the given provider config refers to an Infura network.
179
+ *
180
+ * @param providerConfig - The provider config.
181
+ * @returns True if the provider config refers to an Infura network, false
182
+ * otherwise.
183
+ */
184
+ function isCustomProviderConfig(providerConfig) {
185
+ return providerConfig.type === controller_utils_1.NetworkType.rpc;
186
+ }
187
+ /**
188
+ * As a provider config represents the settings that are used to interface with
189
+ * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents
190
+ * a custom network. These properties _should_ be set as they are validated in
191
+ * the UI when a user adds a custom network, but just to be safe we validate
192
+ * them here.
193
+ *
194
+ * In addition, historically the `rpcUrl` property on the ProviderConfig type
195
+ * has been optional, even though it should not be. Making this non-optional
196
+ * would be a breaking change, so this function types the provider config
197
+ * correctly so that we don't have to check `rpcUrl` in other places.
198
+ *
199
+ * @param providerConfig - A provider config.
200
+ * @throws if the provider config does not have a chain ID or an RPC URL.
201
+ */
202
+ function validateCustomProviderConfig(providerConfig) {
203
+ if (providerConfig.chainId === undefined) {
204
+ throw new Error('chainId must be provided for custom RPC endpoints');
205
+ }
206
+ if (providerConfig.rpcUrl === undefined) {
207
+ throw new Error('rpcUrl must be provided for custom RPC endpoints');
208
+ }
209
+ }
83
210
  const name = 'NetworkController';
84
211
  exports.defaultState = {
85
212
  networkId: null,
@@ -131,7 +258,9 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
131
258
  _NetworkController_trackMetaMetricsEvent.set(this, void 0);
132
259
  _NetworkController_previousProviderConfig.set(this, void 0);
133
260
  _NetworkController_providerProxy.set(this, void 0);
261
+ _NetworkController_provider.set(this, void 0);
134
262
  _NetworkController_blockTrackerProxy.set(this, void 0);
263
+ _NetworkController_autoManagedNetworkClientRegistry.set(this, void 0);
135
264
  if (!infuraProjectId || typeof infuraProjectId !== 'string') {
136
265
  throw new Error('Invalid Infura project ID');
137
266
  }
@@ -145,6 +274,11 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
145
274
  });
146
275
  __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
147
276
  }
277
+ /**
278
+ * Accesses the provider and block tracker for the currently selected network.
279
+ *
280
+ * @returns The proxy and block tracker proxies.
281
+ */
148
282
  getProviderAndBlockTracker() {
149
283
  return {
150
284
  provider: __classPrivateFieldGet(this, _NetworkController_providerProxy, "f"),
@@ -152,16 +286,25 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
152
286
  };
153
287
  }
154
288
  /**
155
- * Method to inilialize the provider,
156
- * Creates the provider and block tracker for the configured network,
157
- * using the provider to gather details about the network.
289
+ * Returns all of the network clients that have been created so far, keyed by
290
+ * their identifier in the network client registry. This collection represents
291
+ * not only built-in networks but also any custom networks that consumers have
292
+ * added.
158
293
  *
294
+ * @returns The list of known network clients.
295
+ */
296
+ getNetworkClientsById() {
297
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
298
+ return Object.assign({}, autoManagedNetworkClientRegistry[types_1.NetworkClientType.Infura], autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom]);
299
+ }
300
+ /**
301
+ * Populates the network clients and establishes the initial network based on
302
+ * the provider configuration in state.
159
303
  */
160
304
  initializeProvider() {
161
305
  return __awaiter(this, void 0, void 0, function* () {
162
- const { type, rpcUrl, chainId } = this.state.providerConfig;
163
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcUrl, chainId);
164
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
306
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
307
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
165
308
  yield this.lookupNetwork();
166
309
  });
167
310
  }
@@ -181,7 +324,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
181
324
  if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
182
325
  return;
183
326
  }
184
- const isInfura = isInfuraProviderType(this.state.providerConfig.type);
327
+ const isInfura = isInfuraProviderConfig(this.state.providerConfig);
185
328
  let networkChanged = false;
186
329
  const listener = () => {
187
330
  networkChanged = true;
@@ -275,6 +418,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
275
418
  const ticker = type in controller_utils_1.NetworksTicker && controller_utils_1.NetworksTicker[type].length > 0
276
419
  ? controller_utils_1.NetworksTicker[type]
277
420
  : 'ETH';
421
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
278
422
  this.update((state) => {
279
423
  state.providerConfig.type = type;
280
424
  state.providerConfig.ticker = ticker;
@@ -299,6 +443,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
299
443
  if (!targetNetwork) {
300
444
  throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
301
445
  }
446
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
302
447
  this.update((state) => {
303
448
  state.providerConfig.type = controller_utils_1.NetworkType.rpc;
304
449
  state.providerConfig.rpcUrl = targetNetwork.rpcUrl;
@@ -340,28 +485,38 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
340
485
  */
341
486
  resetConnection() {
342
487
  return __awaiter(this, void 0, void 0, function* () {
488
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
343
489
  yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
344
490
  });
345
491
  }
346
492
  /**
347
- * Adds a network configuration if the rpcUrl is not already present on an
348
- * existing network configuration. Otherwise updates the entry with the matching rpcUrl.
493
+ * Adds a new custom network or updates the information for an existing
494
+ * network.
495
+ *
496
+ * This may involve updating the `networkConfigurations` property in
497
+ * state as well and/or adding a new network client to the network client
498
+ * registry. The `rpcUrl` and `chainId` of the given object are used to
499
+ * determine which action to take:
500
+ *
501
+ * - If the `rpcUrl` corresponds to an existing network configuration
502
+ * (case-insensitively), then it is overwritten with the object. Furthermore,
503
+ * if the `chainId` is different from the existing network configuration, then
504
+ * the existing network client is replaced with a new one.
505
+ * - If the `rpcUrl` does not correspond to an existing network configuration
506
+ * (case-insensitively), then the object is used to add a new network
507
+ * configuration along with a new network client.
349
508
  *
350
- * @param networkConfiguration - The network configuration to add or, if rpcUrl matches an existing entry, to modify.
351
- * @param networkConfiguration.rpcUrl - RPC provider url.
352
- * @param networkConfiguration.chainId - Network ID as per EIP-155.
353
- * @param networkConfiguration.ticker - Currency ticker.
354
- * @param networkConfiguration.nickname - Personalized network name.
355
- * @param networkConfiguration.rpcPrefs - Personalized preferences (i.e. preferred blockExplorer)
356
- * @param options - additional configuration options.
357
- * @param options.setActive - An option to set the newly added networkConfiguration as the active provider.
358
- * @param options.referrer - The site from which the call originated, or 'metamask' for internal calls - used for event metrics.
359
- * @param options.source - Where the upsertNetwork event originated (i.e. from a dapp or from the network form) - used for event metrics.
360
- * @returns id for the added or updated network configuration
509
+ * @param networkConfiguration - The network configuration to add or update.
510
+ * @param options - Additional configuration options.
511
+ * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.
512
+ * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).
513
+ * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).
514
+ * @returns The ID for the added or updated network configuration.
361
515
  */
362
- upsertNetworkConfiguration({ rpcUrl, chainId, ticker, nickname, rpcPrefs }, { setActive = false, referrer, source, }) {
363
- var _a;
516
+ upsertNetworkConfiguration(networkConfiguration, { referrer, source, setActive = false, }) {
364
517
  return __awaiter(this, void 0, void 0, function* () {
518
+ const sanitizedNetworkConfiguration = pick(networkConfiguration, ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs']);
519
+ const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;
365
520
  (0, utils_1.assertIsStrictHexString)(chainId);
366
521
  if (!(0, controller_utils_1.isSafeChainId)(chainId)) {
367
522
  throw new Error(`Invalid chain ID "${chainId}": numerical value greater than max safe value.`);
@@ -383,20 +538,32 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
383
538
  if (!ticker) {
384
539
  throw new Error('A ticker is required to add or update networkConfiguration');
385
540
  }
386
- const newNetworkConfiguration = {
387
- rpcUrl,
388
- chainId,
389
- ticker,
390
- nickname,
391
- rpcPrefs,
392
- };
393
- const oldNetworkConfigurations = this.state.networkConfigurations;
394
- const oldNetworkConfigurationId = (_a = Object.values(oldNetworkConfigurations).find((networkConfiguration) => { var _a; return ((_a = networkConfiguration.rpcUrl) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === (rpcUrl === null || rpcUrl === void 0 ? void 0 : rpcUrl.toLowerCase()); })) === null || _a === void 0 ? void 0 : _a.id;
395
- const newNetworkConfigurationId = oldNetworkConfigurationId || (0, uuid_1.v4)();
541
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
542
+ const existingNetworkConfiguration = Object.values(this.state.networkConfigurations).find((networkConfig) => networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase());
543
+ const upsertedNetworkConfigurationId = existingNetworkConfiguration
544
+ ? existingNetworkConfiguration.id
545
+ : (0, uuid_1.v4)();
546
+ const networkClientId = buildCustomNetworkClientId(upsertedNetworkConfigurationId);
396
547
  this.update((state) => {
397
- state.networkConfigurations = Object.assign(Object.assign({}, oldNetworkConfigurations), { [newNetworkConfigurationId]: Object.assign(Object.assign({}, newNetworkConfiguration), { id: newNetworkConfigurationId }) });
548
+ state.networkConfigurations[upsertedNetworkConfigurationId] = Object.assign({ id: upsertedNetworkConfigurationId }, sanitizedNetworkConfiguration);
398
549
  });
399
- if (!oldNetworkConfigurationId) {
550
+ const customNetworkClientRegistry = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom];
551
+ const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
552
+ const shouldDestroyExistingNetworkClient = existingAutoManagedNetworkClient &&
553
+ existingAutoManagedNetworkClient.configuration.chainId !== chainId;
554
+ if (shouldDestroyExistingNetworkClient) {
555
+ existingAutoManagedNetworkClient.destroy();
556
+ }
557
+ if (!existingAutoManagedNetworkClient ||
558
+ shouldDestroyExistingNetworkClient) {
559
+ customNetworkClientRegistry[networkClientId] =
560
+ (0, create_auto_managed_network_client_1.createAutoManagedNetworkClient)({
561
+ type: types_1.NetworkClientType.Custom,
562
+ chainId,
563
+ rpcUrl,
564
+ });
565
+ }
566
+ if (!existingNetworkConfiguration) {
400
567
  __classPrivateFieldGet(this, _NetworkController_trackMetaMetricsEvent, "f").call(this, {
401
568
  event: 'Custom Network Added',
402
569
  category: 'Network',
@@ -411,31 +578,43 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
411
578
  });
412
579
  }
413
580
  if (setActive) {
414
- yield this.setActiveNetwork(newNetworkConfigurationId);
581
+ yield this.setActiveNetwork(upsertedNetworkConfigurationId);
415
582
  }
416
- return newNetworkConfigurationId;
583
+ return upsertedNetworkConfigurationId;
417
584
  });
418
585
  }
419
586
  /**
420
- * Removes network configuration from state.
587
+ * Removes a custom network from state.
588
+ *
589
+ * This involves updating the `networkConfigurations` property in state as
590
+ * well and removing the network client that corresponds to the network from
591
+ * the client registry.
421
592
  *
422
- * @param networkConfigurationId - The networkConfigurationId of an existing network configuration
593
+ * @param networkConfigurationId - The ID of an existing network
594
+ * configuration.
423
595
  */
424
596
  removeNetworkConfiguration(networkConfigurationId) {
425
597
  if (!this.state.networkConfigurations[networkConfigurationId]) {
426
598
  throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
427
599
  }
600
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
601
+ const networkClientId = buildCustomNetworkClientId(networkConfigurationId);
428
602
  this.update((state) => {
429
603
  delete state.networkConfigurations[networkConfigurationId];
430
604
  });
605
+ const customNetworkClientRegistry = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom];
606
+ const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
607
+ existingAutoManagedNetworkClient.destroy();
608
+ delete customNetworkClientRegistry[networkClientId];
431
609
  }
432
610
  /**
433
- * Switches to the previous network, assuming that the current network is
434
- * different than the initial network (if it is, then this is equivalent to
435
- * calling `resetConnection`).
611
+ * Switches to the previously selected network, assuming that there is one
612
+ * (if not and `initializeProvider` has not been previously called, then this
613
+ * method is equivalent to calling `resetConnection`).
436
614
  */
437
615
  rollbackToPreviousProvider() {
438
616
  return __awaiter(this, void 0, void 0, function* () {
617
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
439
618
  this.update((state) => {
440
619
  state.providerConfig = __classPrivateFieldGet(this, _NetworkController_previousProviderConfig, "f");
441
620
  });
@@ -466,26 +645,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
466
645
  }
467
646
  }
468
647
  exports.NetworkController = NetworkController;
469
- _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_previousProviderConfig = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_configureProvider = function _NetworkController_configureProvider(type, rpcUrl, chainId) {
470
- switch (type) {
471
- case controller_utils_1.NetworkType.mainnet:
472
- case controller_utils_1.NetworkType.goerli:
473
- case controller_utils_1.NetworkType.sepolia:
474
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupInfuraProvider).call(this, type);
475
- break;
476
- case controller_utils_1.NetworkType.rpc:
477
- if (chainId === undefined) {
478
- throw new Error('chainId must be provided for custom RPC endpoints');
479
- }
480
- if (rpcUrl === undefined) {
481
- throw new Error('rpcUrl must be provided for custom RPC endpoints');
482
- }
483
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, rpcUrl, chainId);
484
- break;
485
- default:
486
- throw new Error(`Unrecognized network type: '${type}'`);
487
- }
488
- }, _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
648
+ _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() {
489
649
  return __awaiter(this, void 0, void 0, function* () {
490
650
  this.messagingSystem.publish('NetworkController:networkWillChange');
491
651
  this.update((state) => {
@@ -495,36 +655,10 @@ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId
495
655
  EIPS: {},
496
656
  };
497
657
  });
498
- const { rpcUrl, type, chainId } = this.state.providerConfig;
499
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcUrl, chainId);
658
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
500
659
  this.messagingSystem.publish('NetworkController:networkDidChange');
501
660
  yield this.lookupNetwork();
502
661
  });
503
- }, _NetworkController_registerProvider = function _NetworkController_registerProvider() {
504
- const { provider } = this.getProviderAndBlockTracker();
505
- if (provider) {
506
- __classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(provider), "f");
507
- }
508
- }, _NetworkController_setupInfuraProvider = function _NetworkController_setupInfuraProvider(type) {
509
- const { provider, blockTracker } = (0, create_network_client_1.createNetworkClient)({
510
- network: type,
511
- infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
512
- type: create_network_client_1.NetworkClientType.Infura,
513
- });
514
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, provider, blockTracker);
515
- }, _NetworkController_setupStandardProvider = function _NetworkController_setupStandardProvider(rpcUrl, chainId) {
516
- const { provider, blockTracker } = (0, create_network_client_1.createNetworkClient)({
517
- chainId,
518
- rpcUrl,
519
- type: create_network_client_1.NetworkClientType.Custom,
520
- });
521
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, provider, blockTracker);
522
- }, _NetworkController_updateProvider = function _NetworkController_updateProvider(provider, blockTracker) {
523
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setProviderAndBlockTracker).call(this, {
524
- provider,
525
- blockTracker,
526
- });
527
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
528
662
  }, _NetworkController_getNetworkId = function _NetworkController_getNetworkId() {
529
663
  return __awaiter(this, void 0, void 0, function* () {
530
664
  const possibleNetworkId = yield new Promise((resolve, reject) => {
@@ -563,13 +697,114 @@ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId
563
697
  const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
564
698
  return (latestBlock === null || latestBlock === void 0 ? void 0 : latestBlock.baseFeePerGas) !== undefined;
565
699
  });
566
- }, _NetworkController_setProviderAndBlockTracker = function _NetworkController_setProviderAndBlockTracker({ provider, blockTracker, }) {
700
+ }, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated = function _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated() {
701
+ var _a;
702
+ const autoManagedNetworkClientRegistry = (_a = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_createAutoManagedNetworkClientRegistry).call(this);
703
+ __classPrivateFieldSet(this, _NetworkController_autoManagedNetworkClientRegistry, autoManagedNetworkClientRegistry, "f");
704
+ return autoManagedNetworkClientRegistry;
705
+ }, _NetworkController_createAutoManagedNetworkClientRegistry = function _NetworkController_createAutoManagedNetworkClientRegistry() {
706
+ return [
707
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations).call(this),
708
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedCustomNetworkClientConfigurations).call(this),
709
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig).call(this),
710
+ ].reduce((registry, [networkClientType, networkClientId, networkClientConfiguration]) => {
711
+ const autoManagedNetworkClient = (0, create_auto_managed_network_client_1.createAutoManagedNetworkClient)(networkClientConfiguration);
712
+ if (networkClientId in registry[networkClientType]) {
713
+ return registry;
714
+ }
715
+ return Object.assign(Object.assign({}, registry), { [networkClientType]: Object.assign(Object.assign({}, registry[networkClientType]), { [networkClientId]: autoManagedNetworkClient }) });
716
+ }, {
717
+ [types_1.NetworkClientType.Infura]: {},
718
+ [types_1.NetworkClientType.Custom]: {},
719
+ });
720
+ }, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations = function _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations() {
721
+ return knownKeysOf(controller_utils_1.InfuraNetworkType).map((network) => {
722
+ const networkClientId = buildInfuraNetworkClientId(network);
723
+ const networkClientConfiguration = {
724
+ type: types_1.NetworkClientType.Infura,
725
+ network,
726
+ infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
727
+ };
728
+ return [
729
+ types_1.NetworkClientType.Infura,
730
+ networkClientId,
731
+ networkClientConfiguration,
732
+ ];
733
+ });
734
+ }, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations = function _NetworkController_buildIdentifiedCustomNetworkClientConfigurations() {
735
+ return Object.entries(this.state.networkConfigurations).map(([networkConfigurationId, networkConfiguration]) => {
736
+ if (networkConfiguration.chainId === undefined) {
737
+ throw new Error('chainId must be provided for custom RPC endpoints');
738
+ }
739
+ if (networkConfiguration.rpcUrl === undefined) {
740
+ throw new Error('rpcUrl must be provided for custom RPC endpoints');
741
+ }
742
+ const networkClientId = buildCustomNetworkClientId(networkConfigurationId);
743
+ const networkClientConfiguration = {
744
+ type: types_1.NetworkClientType.Custom,
745
+ chainId: networkConfiguration.chainId,
746
+ rpcUrl: networkConfiguration.rpcUrl,
747
+ };
748
+ return [
749
+ types_1.NetworkClientType.Custom,
750
+ networkClientId,
751
+ networkClientConfiguration,
752
+ ];
753
+ });
754
+ }, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig = function _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig() {
755
+ const { providerConfig } = this.state;
756
+ if (isCustomProviderConfig(providerConfig)) {
757
+ validateCustomProviderConfig(providerConfig);
758
+ const networkClientId = buildCustomNetworkClientId(providerConfig, this.state.networkConfigurations);
759
+ const networkClientConfiguration = {
760
+ chainId: providerConfig.chainId,
761
+ rpcUrl: providerConfig.rpcUrl,
762
+ type: types_1.NetworkClientType.Custom,
763
+ };
764
+ return [
765
+ [types_1.NetworkClientType.Custom, networkClientId, networkClientConfiguration],
766
+ ];
767
+ }
768
+ if (isInfuraProviderConfig(providerConfig)) {
769
+ return [];
770
+ }
771
+ throw new Error(`Unrecognized network type: '${providerConfig.type}'`);
772
+ }, _NetworkController_applyNetworkSelection = function _NetworkController_applyNetworkSelection() {
773
+ if (!__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")) {
774
+ throw new Error('initializeProvider must be called first in order to switch the network');
775
+ }
776
+ const { providerConfig } = this.state;
777
+ let autoManagedNetworkClient;
778
+ if (isInfuraProviderConfig(providerConfig)) {
779
+ const networkClientType = types_1.NetworkClientType.Infura;
780
+ const networkClientId = buildInfuraNetworkClientId(providerConfig);
781
+ const builtInNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")[networkClientType];
782
+ autoManagedNetworkClient = builtInNetworkClientRegistry[networkClientId];
783
+ if (!autoManagedNetworkClient) {
784
+ throw new Error(`Could not find custom network matching ${networkClientId}`);
785
+ }
786
+ }
787
+ else if (isCustomProviderConfig(providerConfig)) {
788
+ validateCustomProviderConfig(providerConfig);
789
+ const networkClientType = types_1.NetworkClientType.Custom;
790
+ const networkClientId = buildCustomNetworkClientId(providerConfig, this.state.networkConfigurations);
791
+ const customNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")[networkClientType];
792
+ autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
793
+ if (!autoManagedNetworkClient) {
794
+ throw new Error(`Could not find built-in network matching ${networkClientId}`);
795
+ }
796
+ }
797
+ else {
798
+ throw new Error('Could not determine type of provider config');
799
+ }
800
+ const { provider, blockTracker } = autoManagedNetworkClient;
567
801
  if (__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")) {
568
802
  __classPrivateFieldGet(this, _NetworkController_providerProxy, "f").setTarget(provider);
569
803
  }
570
804
  else {
571
805
  __classPrivateFieldSet(this, _NetworkController_providerProxy, (0, swappable_obj_proxy_1.createEventEmitterProxy)(provider), "f");
572
806
  }
807
+ __classPrivateFieldSet(this, _NetworkController_provider, provider, "f");
573
808
  if (__classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) {
574
809
  __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f").setTarget(blockTracker);
575
810
  }
@@ -578,6 +813,6 @@ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId
578
813
  eventFilter: 'skipInternal',
579
814
  }), "f");
580
815
  }
816
+ __classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")), "f");
581
817
  };
582
- exports.default = NetworkController;
583
818
  //# sourceMappingURL=NetworkController.js.map