@metamask/network-controller 8.0.0 → 9.0.0

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,31 +22,39 @@ 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_mutex, _NetworkController_previousNetworkSpecifier, _NetworkController_provider, _NetworkController_providerProxy, _NetworkController_blockTrackerProxy, _NetworkController_configureProvider, _NetworkController_refreshNetwork, _NetworkController_registerProvider, _NetworkController_setupInfuraProvider, _NetworkController_setupStandardProvider, _NetworkController_updateProvider, _NetworkController_safelyStopProvider, _NetworkController_verifyNetwork, _NetworkController_getNetworkId, _NetworkController_setCurrentAsPreviousProvider, _NetworkController_getLatestBlock, _NetworkController_setProviderAndBlockTracker;
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;
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
27
  exports.NetworkController = exports.defaultState = void 0;
28
- const eth_query_1 = __importDefault(require("eth-query"));
29
- const provider_1 = __importDefault(require("web3-provider-engine/subproviders/provider"));
30
- const createProvider_1 = __importDefault(require("eth-json-rpc-infura/src/createProvider"));
31
- const zero_1 = __importDefault(require("web3-provider-engine/zero"));
32
28
  const swappable_obj_proxy_1 = require("@metamask/swappable-obj-proxy");
33
- const async_mutex_1 = require("async-mutex");
29
+ const eth_query_1 = __importDefault(require("eth-query"));
30
+ const base_controller_1 = require("@metamask/base-controller");
34
31
  const uuid_1 = require("uuid");
35
32
  const eth_rpc_errors_1 = require("eth-rpc-errors");
36
- const base_controller_1 = require("@metamask/base-controller");
37
33
  const controller_utils_1 = require("@metamask/controller-utils");
38
34
  const utils_1 = require("@metamask/utils");
39
35
  const constants_1 = require("./constants");
36
+ const logger_1 = require("./logger");
37
+ const create_network_client_1 = require("./create-network-client");
38
+ const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'NetworkController');
40
39
  /**
41
- * Asserts that the given value is a network ID, i.e., that it is a decimal
42
- * number represented as a string.
40
+ * Convert the given value into a valid network ID. The ID is accepted
41
+ * as either a number, a decimal string, or a 0x-prefixed hex string.
43
42
  *
44
- * @param value - The value to check.
43
+ * @param value - The network ID to convert, in an unknown format.
44
+ * @returns A valid network ID (as a decimal string)
45
+ * @throws If the given value cannot be safely parsed.
45
46
  */
46
- function assertNetworkId(value) {
47
- if (!/^\d+$/u.test(value) || Number.isNaN(Number(value))) {
48
- throw new Error('value is not a number');
47
+ function convertNetworkId(value) {
48
+ if (typeof value === 'number' && !Number.isNaN(value)) {
49
+ return `${value}`;
49
50
  }
51
+ else if ((0, utils_1.isStrictHexString)(value)) {
52
+ return `${(0, controller_utils_1.convertHexToDecimal)(value)}`;
53
+ }
54
+ else if (typeof value === 'string' && /^\d+$/u.test(value)) {
55
+ return value;
56
+ }
57
+ throw new Error(`Cannot parse as a valid network ID: '${value}'`);
50
58
  }
51
59
  /**
52
60
  * Type guard for determining whether the given value is an error object with a
@@ -60,16 +68,30 @@ function assertNetworkId(value) {
60
68
  function isErrorWithCode(error) {
61
69
  return typeof error === 'object' && error !== null && 'code' in error;
62
70
  }
63
- const LOCALHOST_RPC_URL = 'http://localhost:8545';
71
+ /**
72
+ * Returns whether the given argument is a type that our Infura middleware
73
+ * recognizes.
74
+ *
75
+ * @param type - A type to compare.
76
+ * @returns True or false, depending on whether the given type is one that our
77
+ * Infura middleware recognizes.
78
+ */
79
+ function isInfuraProviderType(type) {
80
+ return Object.keys(controller_utils_1.InfuraNetworkType).includes(type);
81
+ }
64
82
  const name = 'NetworkController';
65
83
  exports.defaultState = {
66
84
  networkId: null,
67
85
  networkStatus: constants_1.NetworkStatus.Unknown,
68
86
  providerConfig: {
69
87
  type: controller_utils_1.NetworkType.mainnet,
70
- chainId: controller_utils_1.NetworksChainId.mainnet,
88
+ chainId: controller_utils_1.ChainId.mainnet,
89
+ },
90
+ networkDetails: {
91
+ EIPS: {
92
+ 1559: false,
93
+ },
71
94
  },
72
- networkDetails: { isEIP1559Compatible: false },
73
95
  networkConfigurations: {},
74
96
  };
75
97
  /**
@@ -108,11 +130,12 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
108
130
  _NetworkController_ethQuery.set(this, void 0);
109
131
  _NetworkController_infuraProjectId.set(this, void 0);
110
132
  _NetworkController_trackMetaMetricsEvent.set(this, void 0);
111
- _NetworkController_mutex.set(this, new async_mutex_1.Mutex());
112
- _NetworkController_previousNetworkSpecifier.set(this, void 0);
113
- _NetworkController_provider.set(this, void 0);
133
+ _NetworkController_previousProviderConfig.set(this, void 0);
114
134
  _NetworkController_providerProxy.set(this, void 0);
115
135
  _NetworkController_blockTrackerProxy.set(this, void 0);
136
+ if (!infuraProjectId || typeof infuraProjectId !== 'string') {
137
+ throw new Error('Invalid Infura project ID');
138
+ }
116
139
  __classPrivateFieldSet(this, _NetworkController_infuraProjectId, infuraProjectId, "f");
117
140
  __classPrivateFieldSet(this, _NetworkController_trackMetaMetricsEvent, trackMetaMetricsEvent, "f");
118
141
  this.messagingSystem.registerActionHandler(`${this.name}:getProviderConfig`, () => {
@@ -121,7 +144,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
121
144
  this.messagingSystem.registerActionHandler(`${this.name}:getEthQuery`, () => {
122
145
  return __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
123
146
  });
124
- __classPrivateFieldSet(this, _NetworkController_previousNetworkSpecifier, this.state.providerConfig.type, "f");
147
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
125
148
  }
126
149
  getProviderAndBlockTracker() {
127
150
  return {
@@ -137,8 +160,8 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
137
160
  */
138
161
  initializeProvider() {
139
162
  return __awaiter(this, void 0, void 0, function* () {
140
- const { type, rpcTarget, chainId, ticker, nickname } = this.state.providerConfig;
141
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcTarget, chainId, ticker, nickname);
163
+ const { type, rpcUrl, chainId } = this.state.providerConfig;
164
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcUrl, chainId);
142
165
  __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
143
166
  yield this.lookupNetwork();
144
167
  });
@@ -148,40 +171,89 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
148
171
  * available, updates the network state with the network ID of the network and
149
172
  * stores whether the network supports EIP-1559; otherwise clears said
150
173
  * information about the network that may have been previously stored.
174
+ *
175
+ * @fires infuraIsBlocked if the network is Infura-supported and is blocking
176
+ * requests.
177
+ * @fires infuraIsUnblocked if the network is Infura-supported and is not
178
+ * blocking requests, or if the network is not Infura-supported.
151
179
  */
152
180
  lookupNetwork() {
153
181
  return __awaiter(this, void 0, void 0, function* () {
154
182
  if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
155
183
  return;
156
184
  }
157
- const releaseLock = yield __classPrivateFieldGet(this, _NetworkController_mutex, "f").acquire();
185
+ const isInfura = isInfuraProviderType(this.state.providerConfig.type);
186
+ let networkChanged = false;
187
+ const listener = () => {
188
+ networkChanged = true;
189
+ this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
190
+ };
191
+ this.messagingSystem.subscribe('NetworkController:networkDidChange', listener);
192
+ let updatedNetworkStatus;
193
+ let updatedNetworkId = null;
194
+ let updatedIsEIP1559Compatible = false;
158
195
  try {
159
- try {
160
- const [networkId] = yield Promise.all([
161
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this),
162
- this.getEIP1559Compatibility(),
163
- ]);
164
- if (this.state.networkId === networkId) {
165
- return;
196
+ const [networkId, isEIP1559Compatible] = yield Promise.all([
197
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this),
198
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this),
199
+ ]);
200
+ updatedNetworkStatus = constants_1.NetworkStatus.Available;
201
+ updatedNetworkId = networkId;
202
+ updatedIsEIP1559Compatible = isEIP1559Compatible;
203
+ }
204
+ catch (error) {
205
+ if (isErrorWithCode(error)) {
206
+ let responseBody;
207
+ if (isInfura &&
208
+ (0, utils_1.hasProperty)(error, 'message') &&
209
+ typeof error.message === 'string') {
210
+ try {
211
+ responseBody = JSON.parse(error.message);
212
+ }
213
+ catch (_a) {
214
+ // error.message must not be JSON
215
+ }
216
+ }
217
+ if ((0, utils_1.isPlainObject)(responseBody) &&
218
+ responseBody.error === constants_1.INFURA_BLOCKED_KEY) {
219
+ updatedNetworkStatus = constants_1.NetworkStatus.Blocked;
220
+ }
221
+ else if (error.code === eth_rpc_errors_1.errorCodes.rpc.internal) {
222
+ updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
223
+ }
224
+ else {
225
+ updatedNetworkStatus = constants_1.NetworkStatus.Unavailable;
166
226
  }
167
- this.update((state) => {
168
- state.networkId = networkId;
169
- state.networkStatus = constants_1.NetworkStatus.Available;
170
- });
171
227
  }
172
- catch (error) {
173
- const networkStatus = isErrorWithCode(error) && error.code !== eth_rpc_errors_1.errorCodes.rpc.internal
174
- ? constants_1.NetworkStatus.Unavailable
175
- : constants_1.NetworkStatus.Unknown;
176
- this.update((state) => {
177
- state.networkId = null;
178
- state.networkStatus = networkStatus;
179
- });
228
+ else {
229
+ log('NetworkController - could not determine network status', error);
230
+ updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
180
231
  }
181
- this.messagingSystem.publish(`NetworkController:providerConfigChange`, this.state.providerConfig);
182
232
  }
183
- finally {
184
- releaseLock();
233
+ if (networkChanged) {
234
+ // If the network has changed, then `lookupNetwork` either has been or is
235
+ // in the process of being called, so we don't need to go further.
236
+ return;
237
+ }
238
+ this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
239
+ this.update((state) => {
240
+ state.networkId = updatedNetworkId;
241
+ state.networkStatus = updatedNetworkStatus;
242
+ state.networkDetails.EIPS[1559] = updatedIsEIP1559Compatible;
243
+ });
244
+ if (isInfura) {
245
+ if (updatedNetworkStatus === constants_1.NetworkStatus.Available) {
246
+ this.messagingSystem.publish('NetworkController:infuraIsUnblocked');
247
+ }
248
+ else if (updatedNetworkStatus === constants_1.NetworkStatus.Blocked) {
249
+ this.messagingSystem.publish('NetworkController:infuraIsBlocked');
250
+ }
251
+ }
252
+ else {
253
+ // Always publish infuraIsUnblocked regardless of network status to
254
+ // prevent consumers from being stuck in a blocked state if they were
255
+ // previously connected to an Infura network that was blocked
256
+ this.messagingSystem.publish('NetworkController:infuraIsUnblocked');
185
257
  }
186
258
  });
187
259
  }
@@ -192,7 +264,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
192
264
  */
193
265
  setProviderType(type) {
194
266
  return __awaiter(this, void 0, void 0, function* () {
195
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setCurrentAsPreviousProvider).call(this);
267
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
196
268
  // If testnet the ticker symbol should use a testnet prefix
197
269
  const ticker = type in controller_utils_1.NetworksTicker && controller_utils_1.NetworksTicker[type].length > 0
198
270
  ? controller_utils_1.NetworksTicker[type]
@@ -200,9 +272,9 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
200
272
  this.update((state) => {
201
273
  state.providerConfig.type = type;
202
274
  state.providerConfig.ticker = ticker;
203
- state.providerConfig.chainId = controller_utils_1.NetworksChainId[type];
275
+ state.providerConfig.chainId = controller_utils_1.ChainId[type];
204
276
  state.providerConfig.rpcPrefs = controller_utils_1.BUILT_IN_NETWORKS[type].rpcPrefs;
205
- state.providerConfig.rpcTarget = undefined;
277
+ state.providerConfig.rpcUrl = undefined;
206
278
  state.providerConfig.nickname = undefined;
207
279
  state.providerConfig.id = undefined;
208
280
  });
@@ -216,14 +288,14 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
216
288
  */
217
289
  setActiveNetwork(networkConfigurationId) {
218
290
  return __awaiter(this, void 0, void 0, function* () {
219
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setCurrentAsPreviousProvider).call(this);
291
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
220
292
  const targetNetwork = this.state.networkConfigurations[networkConfigurationId];
221
293
  if (!targetNetwork) {
222
294
  throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
223
295
  }
224
296
  this.update((state) => {
225
297
  state.providerConfig.type = controller_utils_1.NetworkType.rpc;
226
- state.providerConfig.rpcTarget = targetNetwork.rpcUrl;
298
+ state.providerConfig.rpcUrl = targetNetwork.rpcUrl;
227
299
  state.providerConfig.chainId = targetNetwork.chainId;
228
300
  state.providerConfig.ticker = targetNetwork.ticker;
229
301
  state.providerConfig.nickname = targetNetwork.nickname;
@@ -233,17 +305,24 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
233
305
  yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
234
306
  });
235
307
  }
308
+ /**
309
+ * Determines whether the network supports EIP-1559 by checking whether the
310
+ * latest block has a `baseFeePerGas` property, then updates state
311
+ * appropriately.
312
+ *
313
+ * @returns A promise that resolves to true if the network supports EIP-1559
314
+ * and false otherwise.
315
+ */
236
316
  getEIP1559Compatibility() {
237
317
  return __awaiter(this, void 0, void 0, function* () {
238
- const { networkDetails = {} } = this.state;
239
- if (networkDetails.isEIP1559Compatible || !__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
318
+ const { networkDetails = { EIPS: {} } } = this.state;
319
+ if (networkDetails.EIPS[1559] || !__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
240
320
  return true;
241
321
  }
242
- const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
243
- const isEIP1559Compatible = typeof latestBlock.baseFeePerGas !== 'undefined';
244
- if (networkDetails.isEIP1559Compatible !== isEIP1559Compatible) {
322
+ const isEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this);
323
+ if (networkDetails.EIPS[1559] !== isEIP1559Compatible) {
245
324
  this.update((state) => {
246
- state.networkDetails.isEIP1559Compatible = isEIP1559Compatible;
325
+ state.networkDetails.EIPS[1559] = isEIP1559Compatible;
247
326
  });
248
327
  }
249
328
  return isEIP1559Compatible;
@@ -277,7 +356,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
277
356
  var _a;
278
357
  return __awaiter(this, void 0, void 0, function* () {
279
358
  (0, utils_1.assertIsStrictHexString)(chainId);
280
- if (!(0, controller_utils_1.isSafeChainId)(parseInt(chainId, 16))) {
359
+ if (!(0, controller_utils_1.isSafeChainId)(chainId)) {
281
360
  throw new Error(`Invalid chain ID "${chainId}": numerical value greater than max safe value.`);
282
361
  }
283
362
  if (!rpcUrl) {
@@ -287,7 +366,6 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
287
366
  throw new Error('referrer and source are required arguments for adding or updating a network configuration');
288
367
  }
289
368
  try {
290
- // eslint-disable-next-line no-new
291
369
  new URL(rpcUrl);
292
370
  }
293
371
  catch (e) {
@@ -345,129 +423,128 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
345
423
  });
346
424
  }
347
425
  /**
348
- * Rolls back provider config to the previous provider in case of errors or inability to connect during network switch.
426
+ * Switches to the previous network, assuming that the current network is
427
+ * different than the initial network (if it is, then this is equivalent to
428
+ * calling `resetConnection`).
349
429
  */
350
430
  rollbackToPreviousProvider() {
351
431
  return __awaiter(this, void 0, void 0, function* () {
352
- const specifier = __classPrivateFieldGet(this, _NetworkController_previousNetworkSpecifier, "f");
353
- if ((0, controller_utils_1.isNetworkType)(specifier)) {
354
- yield this.setProviderType(specifier);
355
- }
356
- else if (typeof specifier === 'string') {
357
- yield this.setActiveNetwork(specifier);
358
- }
432
+ this.update((state) => {
433
+ state.providerConfig = __classPrivateFieldGet(this, _NetworkController_previousProviderConfig, "f");
434
+ });
435
+ yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
436
+ });
437
+ }
438
+ /**
439
+ * Deactivates the controller, stopping any ongoing polling.
440
+ *
441
+ * In-progress requests will not be aborted.
442
+ */
443
+ destroy() {
444
+ var _a;
445
+ return __awaiter(this, void 0, void 0, function* () {
446
+ yield ((_a = __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) === null || _a === void 0 ? void 0 : _a.destroy());
359
447
  });
360
448
  }
361
449
  }
362
450
  exports.NetworkController = NetworkController;
363
- _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_mutex = new WeakMap(), _NetworkController_previousNetworkSpecifier = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_configureProvider = function _NetworkController_configureProvider(type, rpcTarget, chainId, ticker, nickname) {
451
+ _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) {
364
452
  switch (type) {
365
453
  case controller_utils_1.NetworkType.mainnet:
366
454
  case controller_utils_1.NetworkType.goerli:
367
455
  case controller_utils_1.NetworkType.sepolia:
368
456
  __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupInfuraProvider).call(this, type);
369
457
  break;
370
- case controller_utils_1.NetworkType.localhost:
371
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, LOCALHOST_RPC_URL);
372
- break;
373
458
  case controller_utils_1.NetworkType.rpc:
374
- rpcTarget &&
375
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, rpcTarget, chainId, ticker, nickname);
459
+ if (chainId === undefined) {
460
+ throw new Error('chainId must be provided for custom RPC endpoints');
461
+ }
462
+ if (rpcUrl === undefined) {
463
+ throw new Error('rpcUrl must be provided for custom RPC endpoints');
464
+ }
465
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, rpcUrl, chainId);
376
466
  break;
377
467
  default:
378
468
  throw new Error(`Unrecognized network type: '${type}'`);
379
469
  }
380
470
  }, _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
381
471
  return __awaiter(this, void 0, void 0, function* () {
472
+ this.messagingSystem.publish('NetworkController:networkWillChange');
382
473
  this.update((state) => {
383
474
  state.networkId = null;
384
475
  state.networkStatus = constants_1.NetworkStatus.Unknown;
385
- state.networkDetails = {};
476
+ state.networkDetails = {
477
+ EIPS: {},
478
+ };
386
479
  });
387
- const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;
388
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcTarget, chainId, ticker);
480
+ const { rpcUrl, type, chainId } = this.state.providerConfig;
481
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcUrl, chainId);
482
+ this.messagingSystem.publish('NetworkController:networkDidChange');
389
483
  yield this.lookupNetwork();
390
484
  });
391
485
  }, _NetworkController_registerProvider = function _NetworkController_registerProvider() {
392
486
  const { provider } = this.getProviderAndBlockTracker();
393
487
  if (provider) {
394
- provider.on('error', __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_verifyNetwork).bind(this));
395
488
  __classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(provider), "f");
396
489
  }
397
490
  }, _NetworkController_setupInfuraProvider = function _NetworkController_setupInfuraProvider(type) {
398
- const infuraProvider = (0, createProvider_1.default)({
491
+ const { provider, blockTracker } = (0, create_network_client_1.createNetworkClient)({
399
492
  network: type,
400
- projectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
493
+ infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
494
+ type: create_network_client_1.NetworkClientType.Infura,
401
495
  });
402
- const infuraSubprovider = new provider_1.default(infuraProvider);
403
- const config = {
404
- dataSubprovider: infuraSubprovider,
405
- engineParams: {
406
- blockTrackerProvider: infuraProvider,
407
- pollingInterval: 12000,
408
- },
409
- };
410
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, (0, zero_1.default)(config));
411
- }, _NetworkController_setupStandardProvider = function _NetworkController_setupStandardProvider(rpcTarget, chainId, ticker, nickname) {
412
- const config = {
496
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, provider, blockTracker);
497
+ }, _NetworkController_setupStandardProvider = function _NetworkController_setupStandardProvider(rpcUrl, chainId) {
498
+ const { provider, blockTracker } = (0, create_network_client_1.createNetworkClient)({
413
499
  chainId,
414
- engineParams: { pollingInterval: 12000 },
415
- nickname,
416
- rpcUrl: rpcTarget,
417
- ticker,
418
- };
419
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, (0, zero_1.default)(config));
420
- }, _NetworkController_updateProvider = function _NetworkController_updateProvider(provider) {
421
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_safelyStopProvider).call(this, __classPrivateFieldGet(this, _NetworkController_provider, "f"));
500
+ rpcUrl,
501
+ type: create_network_client_1.NetworkClientType.Custom,
502
+ });
503
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, provider, blockTracker);
504
+ }, _NetworkController_updateProvider = function _NetworkController_updateProvider(provider, blockTracker) {
422
505
  __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setProviderAndBlockTracker).call(this, {
423
506
  provider,
424
- blockTracker: provider._blockTracker,
507
+ blockTracker,
425
508
  });
426
509
  __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
427
- }, _NetworkController_safelyStopProvider = function _NetworkController_safelyStopProvider(provider) {
428
- setTimeout(() => {
429
- provider === null || provider === void 0 ? void 0 : provider.stop();
430
- }, 500);
431
- }, _NetworkController_verifyNetwork = function _NetworkController_verifyNetwork() {
432
- return __awaiter(this, void 0, void 0, function* () {
433
- if (this.state.networkStatus !== constants_1.NetworkStatus.Available) {
434
- yield this.lookupNetwork();
435
- }
436
- });
437
510
  }, _NetworkController_getNetworkId = function _NetworkController_getNetworkId() {
438
511
  return __awaiter(this, void 0, void 0, function* () {
439
512
  const possibleNetworkId = yield new Promise((resolve, reject) => {
513
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
514
+ throw new Error('Provider has not been initialized');
515
+ }
440
516
  __classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'net_version' }, (error, result) => {
441
517
  if (error) {
442
518
  reject(error);
443
519
  }
444
520
  else {
521
+ // TODO: Validate this type
445
522
  resolve(result);
446
523
  }
447
524
  });
448
525
  });
449
- assertNetworkId(possibleNetworkId);
450
- return possibleNetworkId;
526
+ return convertNetworkId(possibleNetworkId);
451
527
  });
452
- }, _NetworkController_setCurrentAsPreviousProvider = function _NetworkController_setCurrentAsPreviousProvider() {
453
- const { type, id } = this.state.providerConfig;
454
- if (type === controller_utils_1.NetworkType.rpc && id) {
455
- __classPrivateFieldSet(this, _NetworkController_previousNetworkSpecifier, id, "f");
456
- }
457
- else {
458
- __classPrivateFieldSet(this, _NetworkController_previousNetworkSpecifier, type, "f");
459
- }
460
528
  }, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock() {
461
529
  return new Promise((resolve, reject) => {
530
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
531
+ throw new Error('Provider has not been initialized');
532
+ }
462
533
  __classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
463
534
  if (error) {
464
535
  reject(error);
465
536
  }
466
537
  else {
538
+ // TODO: Validate this type
467
539
  resolve(block);
468
540
  }
469
541
  });
470
542
  });
543
+ }, _NetworkController_determineEIP1559Compatibility = function _NetworkController_determineEIP1559Compatibility() {
544
+ return __awaiter(this, void 0, void 0, function* () {
545
+ const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
546
+ return (latestBlock === null || latestBlock === void 0 ? void 0 : latestBlock.baseFeePerGas) !== undefined;
547
+ });
471
548
  }, _NetworkController_setProviderAndBlockTracker = function _NetworkController_setProviderAndBlockTracker({ provider, blockTracker, }) {
472
549
  if (__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")) {
473
550
  __classPrivateFieldGet(this, _NetworkController_providerProxy, "f").setTarget(provider);
@@ -475,7 +552,6 @@ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId
475
552
  else {
476
553
  __classPrivateFieldSet(this, _NetworkController_providerProxy, (0, swappable_obj_proxy_1.createEventEmitterProxy)(provider), "f");
477
554
  }
478
- __classPrivateFieldSet(this, _NetworkController_provider, provider, "f");
479
555
  if (__classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) {
480
556
  __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f").setTarget(blockTracker);
481
557
  }