@metamask/network-controller 20.1.0 → 21.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.
@@ -0,0 +1,1485 @@
1
+ import {
2
+ INFURA_BLOCKED_KEY
3
+ } from "./chunk-2QJYHWIP.mjs";
4
+ import {
5
+ createAutoManagedNetworkClient
6
+ } from "./chunk-TZA3CBEI.mjs";
7
+ import {
8
+ createModuleLogger,
9
+ projectLogger
10
+ } from "./chunk-VTLOAS2R.mjs";
11
+ import {
12
+ __privateAdd,
13
+ __privateGet,
14
+ __privateMethod,
15
+ __privateSet
16
+ } from "./chunk-XUI43LEZ.mjs";
17
+
18
+ // src/NetworkController.ts
19
+ import { BaseController } from "@metamask/base-controller";
20
+ import {
21
+ InfuraNetworkType,
22
+ NetworkType,
23
+ isSafeChainId,
24
+ isInfuraNetworkType,
25
+ ChainId,
26
+ NetworksTicker,
27
+ NetworkNickname
28
+ } from "@metamask/controller-utils";
29
+ import EthQuery from "@metamask/eth-query";
30
+ import { errorCodes } from "@metamask/rpc-errors";
31
+ import { createEventEmitterProxy } from "@metamask/swappable-obj-proxy";
32
+ import { isStrictHexString, hasProperty, isPlainObject } from "@metamask/utils";
33
+ import { strict as assert } from "assert";
34
+ import { createSelector } from "reselect";
35
+ import * as URI from "uri-js";
36
+ import { inspect } from "util";
37
+ import { v4 as uuidV4 } from "uuid";
38
+ var debugLog = createModuleLogger(projectLogger, "NetworkController");
39
+ var INFURA_URL_REGEX = /^https:\/\/(?<networkName>[^.]+)\.infura\.io\/v\d+\/(?<apiKey>.+)$/u;
40
+ var RpcEndpointType = /* @__PURE__ */ ((RpcEndpointType2) => {
41
+ RpcEndpointType2["Custom"] = "custom";
42
+ RpcEndpointType2["Infura"] = "infura";
43
+ return RpcEndpointType2;
44
+ })(RpcEndpointType || {});
45
+ function knownKeysOf(object) {
46
+ return Object.keys(object);
47
+ }
48
+ function isErrorWithCode(error) {
49
+ return typeof error === "object" && error !== null && "code" in error;
50
+ }
51
+ var controllerName = "NetworkController";
52
+ function getDefaultNetworkConfigurationsByChainId() {
53
+ return Object.values(InfuraNetworkType).reduce((obj, infuraNetworkType) => {
54
+ const chainId = ChainId[infuraNetworkType];
55
+ const rpcEndpointUrl = (
56
+ // False negative - this is a string.
57
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
58
+ `https://${infuraNetworkType}.infura.io/v3/{infuraProjectId}`
59
+ );
60
+ const networkConfiguration = {
61
+ blockExplorerUrls: [],
62
+ chainId,
63
+ defaultRpcEndpointIndex: 0,
64
+ name: NetworkNickname[infuraNetworkType],
65
+ nativeCurrency: NetworksTicker[infuraNetworkType],
66
+ rpcEndpoints: [
67
+ {
68
+ networkClientId: infuraNetworkType,
69
+ type: "infura" /* Infura */,
70
+ url: rpcEndpointUrl
71
+ }
72
+ ]
73
+ };
74
+ return { ...obj, [chainId]: networkConfiguration };
75
+ }, {});
76
+ }
77
+ function getDefaultNetworkControllerState() {
78
+ const networksMetadata = {};
79
+ const networkConfigurationsByChainId = getDefaultNetworkConfigurationsByChainId();
80
+ return {
81
+ selectedNetworkClientId: InfuraNetworkType.mainnet,
82
+ networksMetadata,
83
+ networkConfigurationsByChainId
84
+ };
85
+ }
86
+ function getNetworkConfigurations(state) {
87
+ return Object.values(state.networkConfigurationsByChainId);
88
+ }
89
+ function getAvailableNetworkClientIds(networkConfigurations) {
90
+ return networkConfigurations.flatMap(
91
+ (networkConfiguration) => networkConfiguration.rpcEndpoints.map(
92
+ (rpcEndpoint) => rpcEndpoint.networkClientId
93
+ )
94
+ );
95
+ }
96
+ var selectAvailableNetworkClientIds = createSelector(
97
+ [getNetworkConfigurations],
98
+ getAvailableNetworkClientIds
99
+ );
100
+ function isValidUrl(url) {
101
+ const uri = URI.parse(url);
102
+ return uri.error === void 0 && (uri.scheme === "http" || uri.scheme === "https");
103
+ }
104
+ function deriveInfuraNetworkNameFromRpcEndpointUrl(rpcEndpointUrl) {
105
+ const match = INFURA_URL_REGEX.exec(rpcEndpointUrl);
106
+ if (match?.groups) {
107
+ if (isInfuraNetworkType(match.groups.networkName)) {
108
+ return match.groups.networkName;
109
+ }
110
+ throw new Error(`Unknown Infura network '${match.groups.networkName}'`);
111
+ }
112
+ throw new Error("Could not derive Infura network from RPC endpoint URL");
113
+ }
114
+ function validateNetworkControllerState(state) {
115
+ const networkConfigurationEntries = Object.entries(
116
+ state.networkConfigurationsByChainId
117
+ );
118
+ const networkClientIds = selectAvailableNetworkClientIds(state);
119
+ if (networkConfigurationEntries.length === 0) {
120
+ throw new Error(
121
+ "NetworkController state is invalid: `networkConfigurationsByChainId` cannot be empty"
122
+ );
123
+ }
124
+ for (const [chainId, networkConfiguration] of networkConfigurationEntries) {
125
+ if (chainId !== networkConfiguration.chainId) {
126
+ throw new Error(
127
+ `NetworkController state has invalid \`networkConfigurationsByChainId\`: Network configuration '${networkConfiguration.name}' is filed under '${chainId}' which does not match its \`chainId\` of '${networkConfiguration.chainId}'`
128
+ );
129
+ }
130
+ const isInvalidDefaultBlockExplorerUrlIndex = networkConfiguration.blockExplorerUrls.length > 0 ? networkConfiguration.defaultBlockExplorerUrlIndex === void 0 || networkConfiguration.blockExplorerUrls[networkConfiguration.defaultBlockExplorerUrlIndex] === void 0 : networkConfiguration.defaultBlockExplorerUrlIndex !== void 0;
131
+ if (isInvalidDefaultBlockExplorerUrlIndex) {
132
+ throw new Error(
133
+ `NetworkController state has invalid \`networkConfigurationsByChainId\`: Network configuration '${networkConfiguration.name}' has a \`defaultBlockExplorerUrlIndex\` that does not refer to an entry in \`blockExplorerUrls\``
134
+ );
135
+ }
136
+ if (networkConfiguration.rpcEndpoints[networkConfiguration.defaultRpcEndpointIndex] === void 0) {
137
+ throw new Error(
138
+ `NetworkController state has invalid \`networkConfigurationsByChainId\`: Network configuration '${networkConfiguration.name}' has a \`defaultRpcEndpointIndex\` that does not refer to an entry in \`rpcEndpoints\``
139
+ );
140
+ }
141
+ }
142
+ if ([...new Set(networkClientIds)].length < networkClientIds.length) {
143
+ throw new Error(
144
+ "NetworkController state has invalid `networkConfigurationsByChainId`: Every RPC endpoint across all network configurations must have a unique `networkClientId`"
145
+ );
146
+ }
147
+ if (!networkClientIds.includes(state.selectedNetworkClientId)) {
148
+ throw new Error(
149
+ `NetworkController state is invalid: \`selectedNetworkClientId\` ${inspect(
150
+ state.selectedNetworkClientId
151
+ )} does not refer to an RPC endpoint within a network configuration`
152
+ );
153
+ }
154
+ }
155
+ function buildNetworkConfigurationsByNetworkClientId(networkConfigurationsByChainId) {
156
+ return new Map(
157
+ Object.values(networkConfigurationsByChainId).flatMap(
158
+ (networkConfiguration) => {
159
+ return networkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
160
+ return [rpcEndpoint.networkClientId, networkConfiguration];
161
+ });
162
+ }
163
+ )
164
+ );
165
+ }
166
+ var _ethQuery, _infuraProjectId, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _log, _networkConfigurationsByNetworkClientId, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _validateNetworkFields, validateNetworkFields_fn, _determineNetworkConfigurationToPersist, determineNetworkConfigurationToPersist_fn, _registerNetworkClientsAsNeeded, registerNetworkClientsAsNeeded_fn, _unregisterNetworkClientsAsNeeded, unregisterNetworkClientsAsNeeded_fn, _updateNetworkConfigurations, updateNetworkConfigurations_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _applyNetworkSelection, applyNetworkSelection_fn;
167
+ var NetworkController = class extends BaseController {
168
+ constructor({
169
+ messenger,
170
+ state,
171
+ infuraProjectId,
172
+ log
173
+ }) {
174
+ const initialState = { ...getDefaultNetworkControllerState(), ...state };
175
+ validateNetworkControllerState(initialState);
176
+ if (!infuraProjectId || typeof infuraProjectId !== "string") {
177
+ throw new Error("Invalid Infura project ID");
178
+ }
179
+ super({
180
+ name: controllerName,
181
+ metadata: {
182
+ selectedNetworkClientId: {
183
+ persist: true,
184
+ anonymous: false
185
+ },
186
+ networksMetadata: {
187
+ persist: true,
188
+ anonymous: false
189
+ },
190
+ networkConfigurationsByChainId: {
191
+ persist: true,
192
+ anonymous: false
193
+ }
194
+ },
195
+ messenger,
196
+ state: initialState
197
+ });
198
+ /**
199
+ * Executes a series of steps to switch the network:
200
+ *
201
+ * 1. Notifies subscribers via the messenger that the network is about to be
202
+ * switched (and, really, that the global provider and block tracker proxies
203
+ * will be re-pointed to a new network).
204
+ * 2. Looks up a known and preinitialized network client matching the given
205
+ * ID and uses it to re-point the aforementioned provider and block tracker
206
+ * proxies.
207
+ * 3. Notifies subscribers via the messenger that the network has switched.
208
+ * 4. Captures metadata for the newly switched network in state.
209
+ *
210
+ * @param networkClientId - The ID of a network client that requests will be
211
+ * routed through (either the name of an Infura network or the ID of a custom
212
+ * network configuration).
213
+ * @param options - Options for this method.
214
+ * @param options.updateState - Allows for updating state.
215
+ */
216
+ __privateAdd(this, _refreshNetwork);
217
+ /**
218
+ * Fetches the latest block for the network.
219
+ *
220
+ * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.
221
+ * @returns A promise that either resolves to the block header or null if
222
+ * there is no latest block, or rejects with an error.
223
+ */
224
+ __privateAdd(this, _getLatestBlock);
225
+ /**
226
+ * Retrieves and checks the latest block from the currently selected
227
+ * network; if the block has a `baseFeePerGas` property, then we know
228
+ * that the network supports EIP-1559; otherwise it doesn't.
229
+ *
230
+ * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility
231
+ * @returns A promise that resolves to `true` if the network supports EIP-1559,
232
+ * `false` otherwise, or `undefined` if unable to retrieve the last block.
233
+ */
234
+ __privateAdd(this, _determineEIP1559Compatibility);
235
+ /**
236
+ * Ensure that the given fields which will be used to either add or update a
237
+ * network are valid.
238
+ *
239
+ * @param args - The arguments.
240
+ */
241
+ __privateAdd(this, _validateNetworkFields);
242
+ /**
243
+ * Constructs a network configuration that will be persisted to state when
244
+ * adding or updating a network.
245
+ *
246
+ * @param args - The arguments to this function.
247
+ * @param args.networkFields - The fields used to add or update a network.
248
+ * @param args.networkClientOperations - Operations which were calculated for
249
+ * updating the network client registry but which also map back to RPC
250
+ * endpoints (and so can be used to save those RPC endpoints).
251
+ * @returns The network configuration to persist.
252
+ */
253
+ __privateAdd(this, _determineNetworkConfigurationToPersist);
254
+ /**
255
+ * Creates and registers network clients using the given operations calculated
256
+ * as a part of adding or updating a network.
257
+ *
258
+ * @param args - The arguments to this function.
259
+ * @param args.networkFields - The fields used to add or update a network.
260
+ * @param args.networkClientOperations - Dictate which network clients need to
261
+ * be created.
262
+ * @param args.autoManagedNetworkClientRegistry - The network client registry
263
+ * to update.
264
+ */
265
+ __privateAdd(this, _registerNetworkClientsAsNeeded);
266
+ /**
267
+ * Destroys and removes network clients using the given operations calculated
268
+ * as a part of updating or removing a network.
269
+ *
270
+ * @param args - The arguments to this function.
271
+ * @param args.networkClientOperations - Dictate which network clients to
272
+ * remove.
273
+ * @param args.autoManagedNetworkClientRegistry - The network client registry
274
+ * to update.
275
+ */
276
+ __privateAdd(this, _unregisterNetworkClientsAsNeeded);
277
+ /**
278
+ * Updates `networkConfigurationsByChainId` in state depending on whether a
279
+ * network is being added, updated, or removed.
280
+ *
281
+ * - The existing network configuration will be removed when a network is
282
+ * being filed under a different chain or removed.
283
+ * - A network configuration will be stored when a network is being added or
284
+ * when a network is being updated.
285
+ *
286
+ * @param args - The arguments to this function.
287
+ */
288
+ __privateAdd(this, _updateNetworkConfigurations);
289
+ /**
290
+ * Before accessing or switching the network, the registry of network clients
291
+ * needs to be populated. Otherwise, `#applyNetworkSelection` and
292
+ * `getNetworkClientRegistry` will throw an error. This method checks to see if the
293
+ * population step has happened yet, and if not, makes it happen.
294
+ *
295
+ * @returns The populated network client registry.
296
+ */
297
+ __privateAdd(this, _ensureAutoManagedNetworkClientRegistryPopulated);
298
+ /**
299
+ * Constructs the registry of network clients based on the set of default
300
+ * and custom networks in state.
301
+ *
302
+ * @returns The network clients keyed by ID.
303
+ */
304
+ __privateAdd(this, _createAutoManagedNetworkClientRegistry);
305
+ /**
306
+ * Updates the global provider and block tracker proxies (accessible via
307
+ * {@link getSelectedNetworkClient}) to point to the same ones within the
308
+ * given network client, thereby magically switching any consumers using these
309
+ * proxies to use the new network.
310
+ *
311
+ * Also refreshes the EthQuery instance accessible via the `getEthQuery`
312
+ * action to wrap the provider from the new network client. Note that this is
313
+ * not a proxy, so consumers will need to call `getEthQuery` again after the
314
+ * network switch.
315
+ *
316
+ * @param networkClientId - The ID of a network client that requests will be
317
+ * routed through (either the name of an Infura network or the ID of a custom
318
+ * network configuration).
319
+ * @param options - Options for this method.
320
+ * @param options.updateState - Allows for updating state.
321
+ * @throws if no network client could be found matching the given ID.
322
+ */
323
+ __privateAdd(this, _applyNetworkSelection);
324
+ __privateAdd(this, _ethQuery, void 0);
325
+ __privateAdd(this, _infuraProjectId, void 0);
326
+ __privateAdd(this, _previouslySelectedNetworkClientId, void 0);
327
+ __privateAdd(this, _providerProxy, void 0);
328
+ __privateAdd(this, _blockTrackerProxy, void 0);
329
+ __privateAdd(this, _autoManagedNetworkClientRegistry, void 0);
330
+ __privateAdd(this, _autoManagedNetworkClient, void 0);
331
+ __privateAdd(this, _log, void 0);
332
+ __privateAdd(this, _networkConfigurationsByNetworkClientId, void 0);
333
+ __privateSet(this, _infuraProjectId, infuraProjectId);
334
+ __privateSet(this, _log, log);
335
+ __privateSet(this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
336
+ __privateSet(this, _networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId(
337
+ this.state.networkConfigurationsByChainId
338
+ ));
339
+ this.messagingSystem.registerActionHandler(
340
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
341
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
342
+ `${this.name}:getEthQuery`,
343
+ () => {
344
+ return __privateGet(this, _ethQuery);
345
+ }
346
+ );
347
+ this.messagingSystem.registerActionHandler(
348
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
349
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
350
+ `${this.name}:getNetworkClientById`,
351
+ this.getNetworkClientById.bind(this)
352
+ );
353
+ this.messagingSystem.registerActionHandler(
354
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
355
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
356
+ `${this.name}:getEIP1559Compatibility`,
357
+ this.getEIP1559Compatibility.bind(this)
358
+ );
359
+ this.messagingSystem.registerActionHandler(
360
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
361
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
362
+ `${this.name}:setActiveNetwork`,
363
+ this.setActiveNetwork.bind(this)
364
+ );
365
+ this.messagingSystem.registerActionHandler(
366
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
367
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
368
+ `${this.name}:setProviderType`,
369
+ this.setProviderType.bind(this)
370
+ );
371
+ this.messagingSystem.registerActionHandler(
372
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
373
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
374
+ `${this.name}:findNetworkClientIdByChainId`,
375
+ this.findNetworkClientIdByChainId.bind(this)
376
+ );
377
+ this.messagingSystem.registerActionHandler(
378
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
379
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
380
+ `${this.name}:getNetworkConfigurationByChainId`,
381
+ this.getNetworkConfigurationByChainId.bind(this)
382
+ );
383
+ this.messagingSystem.registerActionHandler(
384
+ // ESLint is mistaken here; `name` is a string.
385
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
386
+ `${this.name}:getNetworkConfigurationByNetworkClientId`,
387
+ this.getNetworkConfigurationByNetworkClientId.bind(this)
388
+ );
389
+ this.messagingSystem.registerActionHandler(
390
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
391
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
392
+ `${this.name}:getSelectedNetworkClient`,
393
+ this.getSelectedNetworkClient.bind(this)
394
+ );
395
+ }
396
+ /**
397
+ * Accesses the provider and block tracker for the currently selected network.
398
+ * @returns The proxy and block tracker proxies.
399
+ * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.
400
+ */
401
+ getProviderAndBlockTracker() {
402
+ return {
403
+ provider: __privateGet(this, _providerProxy),
404
+ blockTracker: __privateGet(this, _blockTrackerProxy)
405
+ };
406
+ }
407
+ /**
408
+ * Accesses the provider and block tracker for the currently selected network.
409
+ *
410
+ * @returns an object with the provider and block tracker proxies for the currently selected network.
411
+ */
412
+ getSelectedNetworkClient() {
413
+ if (__privateGet(this, _providerProxy) && __privateGet(this, _blockTrackerProxy)) {
414
+ return {
415
+ provider: __privateGet(this, _providerProxy),
416
+ blockTracker: __privateGet(this, _blockTrackerProxy)
417
+ };
418
+ }
419
+ return void 0;
420
+ }
421
+ /**
422
+ * Internally, the Infura and custom network clients are categorized by type
423
+ * so that when accessing either kind of network client, TypeScript knows
424
+ * which type to assign to the network client. For some cases it's more useful
425
+ * to be able to access network clients by ID instead of by type and then ID,
426
+ * so this function makes that possible.
427
+ *
428
+ * @returns The network clients registered so far, keyed by ID.
429
+ */
430
+ getNetworkClientRegistry() {
431
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
432
+ return Object.assign(
433
+ {},
434
+ autoManagedNetworkClientRegistry["infura" /* Infura */],
435
+ autoManagedNetworkClientRegistry["custom" /* Custom */]
436
+ );
437
+ }
438
+ getNetworkClientById(networkClientId) {
439
+ if (!networkClientId) {
440
+ throw new Error("No network client ID was provided.");
441
+ }
442
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
443
+ if (isInfuraNetworkType(networkClientId)) {
444
+ const infuraNetworkClient = autoManagedNetworkClientRegistry["infura" /* Infura */][networkClientId];
445
+ if (!infuraNetworkClient) {
446
+ throw new Error(
447
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
448
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
449
+ `No Infura network client was found with the ID "${networkClientId}".`
450
+ );
451
+ }
452
+ return infuraNetworkClient;
453
+ }
454
+ const customNetworkClient = autoManagedNetworkClientRegistry["custom" /* Custom */][networkClientId];
455
+ if (!customNetworkClient) {
456
+ throw new Error(
457
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
458
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
459
+ `No custom network client was found with the ID "${networkClientId}".`
460
+ );
461
+ }
462
+ return customNetworkClient;
463
+ }
464
+ /**
465
+ * Ensures that network clients for Infura and custom RPC endpoints have been
466
+ * created. Then, consulting state, initializes and establishes the currently
467
+ * selected network client.
468
+ */
469
+ async initializeProvider() {
470
+ __privateMethod(this, _applyNetworkSelection, applyNetworkSelection_fn).call(this, this.state.selectedNetworkClientId);
471
+ await this.lookupNetwork();
472
+ }
473
+ /**
474
+ * Refreshes the network meta with EIP-1559 support and the network status
475
+ * based on the given network client ID.
476
+ *
477
+ * @param networkClientId - The ID of the network client to update.
478
+ */
479
+ async lookupNetworkByClientId(networkClientId) {
480
+ const isInfura = isInfuraNetworkType(networkClientId);
481
+ let updatedNetworkStatus;
482
+ let updatedIsEIP1559Compatible;
483
+ try {
484
+ updatedIsEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, networkClientId);
485
+ updatedNetworkStatus = "available" /* Available */;
486
+ } catch (error) {
487
+ debugLog("NetworkController: lookupNetworkByClientId: ", error);
488
+ if (isErrorWithCode(error)) {
489
+ let responseBody;
490
+ if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
491
+ try {
492
+ responseBody = JSON.parse(error.message);
493
+ } catch {
494
+ __privateGet(this, _log)?.warn(
495
+ "NetworkController: lookupNetworkByClientId: json parse error: ",
496
+ error
497
+ );
498
+ }
499
+ }
500
+ if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
501
+ updatedNetworkStatus = "blocked" /* Blocked */;
502
+ } else if (error.code === errorCodes.rpc.internal) {
503
+ updatedNetworkStatus = "unknown" /* Unknown */;
504
+ __privateGet(this, _log)?.warn(
505
+ "NetworkController: lookupNetworkByClientId: rpc internal error: ",
506
+ error
507
+ );
508
+ } else {
509
+ updatedNetworkStatus = "unavailable" /* Unavailable */;
510
+ __privateGet(this, _log)?.warn(
511
+ "NetworkController: lookupNetworkByClientId: ",
512
+ error
513
+ );
514
+ }
515
+ } else if (typeof Error !== "undefined" && hasProperty(error, "message") && typeof error.message === "string" && error.message.includes(
516
+ "No custom network client was found with the ID"
517
+ )) {
518
+ throw error;
519
+ } else {
520
+ debugLog(
521
+ "NetworkController - could not determine network status",
522
+ error
523
+ );
524
+ updatedNetworkStatus = "unknown" /* Unknown */;
525
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetworkByClientId: ", error);
526
+ }
527
+ }
528
+ this.update((state) => {
529
+ if (state.networksMetadata[networkClientId] === void 0) {
530
+ state.networksMetadata[networkClientId] = {
531
+ status: "unknown" /* Unknown */,
532
+ EIPS: {}
533
+ };
534
+ }
535
+ const meta = state.networksMetadata[networkClientId];
536
+ meta.status = updatedNetworkStatus;
537
+ if (updatedIsEIP1559Compatible === void 0) {
538
+ delete meta.EIPS[1559];
539
+ } else {
540
+ meta.EIPS[1559] = updatedIsEIP1559Compatible;
541
+ }
542
+ });
543
+ }
544
+ /**
545
+ * Persists the following metadata about the given or selected network to
546
+ * state:
547
+ *
548
+ * - The status of the network, namely, whether it is available, geo-blocked
549
+ * (Infura only), or unavailable, or whether the status is unknown
550
+ * - Whether the network supports EIP-1559, or whether it is unknown
551
+ *
552
+ * Note that it is possible for the network to be switched while this data is
553
+ * being collected. If that is the case, no metadata for the (now previously)
554
+ * selected network will be updated.
555
+ *
556
+ * @param networkClientId - The ID of the network client to update.
557
+ * If no ID is provided, uses the currently selected network.
558
+ */
559
+ async lookupNetwork(networkClientId) {
560
+ if (networkClientId) {
561
+ await this.lookupNetworkByClientId(networkClientId);
562
+ return;
563
+ }
564
+ if (!__privateGet(this, _ethQuery)) {
565
+ return;
566
+ }
567
+ const isInfura = __privateGet(this, _autoManagedNetworkClient)?.configuration.type === "infura" /* Infura */;
568
+ let networkChanged = false;
569
+ const listener = () => {
570
+ networkChanged = true;
571
+ this.messagingSystem.unsubscribe(
572
+ "NetworkController:networkDidChange",
573
+ listener
574
+ );
575
+ };
576
+ this.messagingSystem.subscribe(
577
+ "NetworkController:networkDidChange",
578
+ listener
579
+ );
580
+ let updatedNetworkStatus;
581
+ let updatedIsEIP1559Compatible;
582
+ try {
583
+ const isEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, this.state.selectedNetworkClientId);
584
+ updatedNetworkStatus = "available" /* Available */;
585
+ updatedIsEIP1559Compatible = isEIP1559Compatible;
586
+ } catch (error) {
587
+ if (isErrorWithCode(error)) {
588
+ let responseBody;
589
+ if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
590
+ try {
591
+ responseBody = JSON.parse(error.message);
592
+ } catch (parseError) {
593
+ __privateGet(this, _log)?.warn(
594
+ "NetworkController: lookupNetwork: json parse error",
595
+ parseError
596
+ );
597
+ }
598
+ }
599
+ if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
600
+ updatedNetworkStatus = "blocked" /* Blocked */;
601
+ } else if (error.code === errorCodes.rpc.internal) {
602
+ updatedNetworkStatus = "unknown" /* Unknown */;
603
+ __privateGet(this, _log)?.warn(
604
+ "NetworkController: lookupNetwork: rpc internal error",
605
+ error
606
+ );
607
+ } else {
608
+ updatedNetworkStatus = "unavailable" /* Unavailable */;
609
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
610
+ }
611
+ } else {
612
+ debugLog(
613
+ "NetworkController - could not determine network status",
614
+ error
615
+ );
616
+ updatedNetworkStatus = "unknown" /* Unknown */;
617
+ __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
618
+ }
619
+ }
620
+ if (networkChanged) {
621
+ return;
622
+ }
623
+ this.messagingSystem.unsubscribe(
624
+ "NetworkController:networkDidChange",
625
+ listener
626
+ );
627
+ this.update((state) => {
628
+ const meta = state.networksMetadata[state.selectedNetworkClientId];
629
+ meta.status = updatedNetworkStatus;
630
+ if (updatedIsEIP1559Compatible === void 0) {
631
+ delete meta.EIPS[1559];
632
+ } else {
633
+ meta.EIPS[1559] = updatedIsEIP1559Compatible;
634
+ }
635
+ });
636
+ if (isInfura) {
637
+ if (updatedNetworkStatus === "available" /* Available */) {
638
+ this.messagingSystem.publish("NetworkController:infuraIsUnblocked");
639
+ } else if (updatedNetworkStatus === "blocked" /* Blocked */) {
640
+ this.messagingSystem.publish("NetworkController:infuraIsBlocked");
641
+ }
642
+ } else {
643
+ this.messagingSystem.publish("NetworkController:infuraIsUnblocked");
644
+ }
645
+ }
646
+ /**
647
+ * Convenience method to update provider network type settings.
648
+ *
649
+ * @param type - Human readable network name.
650
+ * @deprecated This has been replaced by `setActiveNetwork`, and will be
651
+ * removed in a future release
652
+ */
653
+ async setProviderType(type) {
654
+ assert.notStrictEqual(
655
+ type,
656
+ NetworkType.rpc,
657
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
658
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
659
+ `NetworkController - cannot call "setProviderType" with type "${NetworkType.rpc}". Use "setActiveNetwork"`
660
+ );
661
+ assert.ok(
662
+ isInfuraNetworkType(type),
663
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
664
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
665
+ `Unknown Infura provider type "${type}".`
666
+ );
667
+ await this.setActiveNetwork(type);
668
+ }
669
+ /**
670
+ * Changes the selected network.
671
+ *
672
+ * @param networkClientId - The ID of a network client that will be used to
673
+ * make requests.
674
+ * @param options - Options for this method.
675
+ * @param options.updateState - Allows for updating state.
676
+ * @throws if no network client is associated with the given
677
+ * network client ID.
678
+ */
679
+ async setActiveNetwork(networkClientId, options = {}) {
680
+ __privateSet(this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
681
+ await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, networkClientId, options);
682
+ }
683
+ /**
684
+ * Determines whether the network supports EIP-1559 by checking whether the
685
+ * latest block has a `baseFeePerGas` property, then updates state
686
+ * appropriately.
687
+ *
688
+ * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.
689
+ * @returns A promise that resolves to true if the network supports EIP-1559
690
+ * , false otherwise, or `undefined` if unable to determine the compatibility.
691
+ */
692
+ async getEIP1559Compatibility(networkClientId) {
693
+ if (networkClientId) {
694
+ return this.get1559CompatibilityWithNetworkClientId(networkClientId);
695
+ }
696
+ if (!__privateGet(this, _ethQuery)) {
697
+ return false;
698
+ }
699
+ const { EIPS } = this.state.networksMetadata[this.state.selectedNetworkClientId];
700
+ if (EIPS[1559] !== void 0) {
701
+ return EIPS[1559];
702
+ }
703
+ const isEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, this.state.selectedNetworkClientId);
704
+ this.update((state) => {
705
+ if (isEIP1559Compatible !== void 0) {
706
+ state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] = isEIP1559Compatible;
707
+ }
708
+ });
709
+ return isEIP1559Compatible;
710
+ }
711
+ async get1559CompatibilityWithNetworkClientId(networkClientId) {
712
+ let metadata = this.state.networksMetadata[networkClientId];
713
+ if (metadata === void 0) {
714
+ await this.lookupNetwork(networkClientId);
715
+ metadata = this.state.networksMetadata[networkClientId];
716
+ }
717
+ const { EIPS } = metadata;
718
+ return EIPS[1559];
719
+ }
720
+ /**
721
+ * Ensures that the provider and block tracker proxies are pointed to the
722
+ * currently selected network and refreshes the metadata for the
723
+ */
724
+ async resetConnection() {
725
+ await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, this.state.selectedNetworkClientId);
726
+ }
727
+ /**
728
+ * Returns the network configuration that has been filed under the given chain
729
+ * ID.
730
+ *
731
+ * @param chainId - The chain ID to use as a key.
732
+ * @returns The network configuration if one exists, or undefined.
733
+ */
734
+ getNetworkConfigurationByChainId(chainId) {
735
+ return this.state.networkConfigurationsByChainId[chainId];
736
+ }
737
+ /**
738
+ * Returns the network configuration that contains an RPC endpoint with the
739
+ * given network client ID.
740
+ *
741
+ * @param networkClientId - The network client ID to use as a key.
742
+ * @returns The network configuration if one exists, or undefined.
743
+ */
744
+ getNetworkConfigurationByNetworkClientId(networkClientId) {
745
+ return __privateGet(this, _networkConfigurationsByNetworkClientId).get(networkClientId);
746
+ }
747
+ /**
748
+ * Creates and registers network clients for the collection of Infura and
749
+ * custom RPC endpoints that can be used to make requests for a particular
750
+ * chain, storing the given configuration object in state for later reference.
751
+ *
752
+ * @param fields - The object that describes the new network/chain and lists
753
+ * the RPC endpoints which front that chain.
754
+ * @returns The newly added network configuration.
755
+ * @throws if any part of `fields` would produce invalid state.
756
+ * @see {@link NetworkConfiguration}
757
+ */
758
+ addNetwork(fields) {
759
+ const { rpcEndpoints: setOfRpcEndpointFields } = fields;
760
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
761
+ __privateMethod(this, _validateNetworkFields, validateNetworkFields_fn).call(this, {
762
+ mode: "add",
763
+ networkFields: fields,
764
+ autoManagedNetworkClientRegistry
765
+ });
766
+ const networkClientOperations = setOfRpcEndpointFields.map(
767
+ (defaultOrCustomRpcEndpointFields) => {
768
+ const rpcEndpoint = defaultOrCustomRpcEndpointFields.type === "custom" /* Custom */ ? {
769
+ ...defaultOrCustomRpcEndpointFields,
770
+ networkClientId: uuidV4()
771
+ } : defaultOrCustomRpcEndpointFields;
772
+ return {
773
+ type: "add",
774
+ rpcEndpoint
775
+ };
776
+ }
777
+ );
778
+ const newNetworkConfiguration = __privateMethod(this, _determineNetworkConfigurationToPersist, determineNetworkConfigurationToPersist_fn).call(this, {
779
+ networkFields: fields,
780
+ networkClientOperations
781
+ });
782
+ __privateMethod(this, _registerNetworkClientsAsNeeded, registerNetworkClientsAsNeeded_fn).call(this, {
783
+ networkFields: fields,
784
+ networkClientOperations,
785
+ autoManagedNetworkClientRegistry
786
+ });
787
+ this.update((state) => {
788
+ __privateMethod(this, _updateNetworkConfigurations, updateNetworkConfigurations_fn).call(this, {
789
+ state,
790
+ mode: "add",
791
+ networkFields: fields,
792
+ networkConfigurationToPersist: newNetworkConfiguration
793
+ });
794
+ });
795
+ __privateSet(this, _networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId(
796
+ this.state.networkConfigurationsByChainId
797
+ ));
798
+ this.messagingSystem.publish(
799
+ `${controllerName}:networkAdded`,
800
+ newNetworkConfiguration
801
+ );
802
+ return newNetworkConfiguration;
803
+ }
804
+ /**
805
+ * Updates the configuration for a previously stored network filed under the
806
+ * given chain ID, creating + registering new network clients to represent RPC
807
+ * endpoints that have been added and destroying + unregistering existing
808
+ * network clients for RPC endpoints that have been removed.
809
+ *
810
+ * Note that if `chainId` is changed, then all network clients associated with
811
+ * that chain will be removed and re-added, even if none of the RPC endpoints
812
+ * have changed.
813
+ *
814
+ * @param chainId - The chain ID associated with an existing network.
815
+ * @param fields - The object that describes the updates to the network/chain,
816
+ * including the new set of RPC endpoints which should front that chain.
817
+ * @param options - Options to provide.
818
+ * @param options.replacementSelectedRpcEndpointIndex - Usually you cannot
819
+ * remove an RPC endpoint that is being represented by the currently selected
820
+ * network client. This option allows you to specify another RPC endpoint
821
+ * (either an existing one or a new one) that should be used to select a new
822
+ * network instead.
823
+ * @returns The updated network configuration.
824
+ * @throws if `chainId` does not refer to an existing network configuration,
825
+ * if any part of `fields` would produce invalid state, etc.
826
+ * @see {@link NetworkConfiguration}
827
+ */
828
+ async updateNetwork(chainId, fields, {
829
+ replacementSelectedRpcEndpointIndex
830
+ } = {}) {
831
+ const existingNetworkConfiguration = this.state.networkConfigurationsByChainId[chainId];
832
+ if (existingNetworkConfiguration === void 0) {
833
+ throw new Error(
834
+ `Could not update network: Cannot find network configuration for chain ${inspect(
835
+ chainId
836
+ )}`
837
+ );
838
+ }
839
+ const existingChainId = chainId;
840
+ const { chainId: newChainId, rpcEndpoints: setOfNewRpcEndpointFields } = fields;
841
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
842
+ __privateMethod(this, _validateNetworkFields, validateNetworkFields_fn).call(this, {
843
+ mode: "update",
844
+ networkFields: fields,
845
+ existingNetworkConfiguration,
846
+ autoManagedNetworkClientRegistry
847
+ });
848
+ const networkClientOperations = [];
849
+ for (const newRpcEndpointFields of setOfNewRpcEndpointFields) {
850
+ const existingRpcEndpointForNoop = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
851
+ return rpcEndpoint.type === newRpcEndpointFields.type && rpcEndpoint.url === newRpcEndpointFields.url && (rpcEndpoint.networkClientId === newRpcEndpointFields.networkClientId || newRpcEndpointFields.networkClientId === void 0);
852
+ });
853
+ const existingRpcEndpointForReplaceWhenChainChanged = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
854
+ return rpcEndpoint.type === "infura" /* Infura */ && newRpcEndpointFields.type === "infura" /* Infura */ || rpcEndpoint.type === newRpcEndpointFields.type && rpcEndpoint.networkClientId === newRpcEndpointFields.networkClientId && rpcEndpoint.url === newRpcEndpointFields.url;
855
+ });
856
+ const existingRpcEndpointForReplaceWhenChainNotChanged = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
857
+ return rpcEndpoint.type === newRpcEndpointFields.type && (rpcEndpoint.url === newRpcEndpointFields.url || rpcEndpoint.networkClientId === newRpcEndpointFields.networkClientId);
858
+ });
859
+ if (newChainId !== existingChainId && existingRpcEndpointForReplaceWhenChainChanged !== void 0) {
860
+ const newRpcEndpoint = newRpcEndpointFields.type === "infura" /* Infura */ ? newRpcEndpointFields : { ...newRpcEndpointFields, networkClientId: uuidV4() };
861
+ networkClientOperations.push({
862
+ type: "replace",
863
+ oldRpcEndpoint: existingRpcEndpointForReplaceWhenChainChanged,
864
+ newRpcEndpoint
865
+ });
866
+ } else if (existingRpcEndpointForNoop !== void 0) {
867
+ let newRpcEndpoint;
868
+ if (existingRpcEndpointForNoop.type === "infura" /* Infura */) {
869
+ newRpcEndpoint = existingRpcEndpointForNoop;
870
+ } else {
871
+ newRpcEndpoint = Object.assign({}, newRpcEndpointFields, {
872
+ networkClientId: existingRpcEndpointForNoop.networkClientId
873
+ });
874
+ }
875
+ networkClientOperations.push({
876
+ type: "noop",
877
+ rpcEndpoint: newRpcEndpoint
878
+ });
879
+ } else if (existingRpcEndpointForReplaceWhenChainNotChanged !== void 0) {
880
+ let newRpcEndpoint;
881
+ if (newRpcEndpointFields.type === "infura" /* Infura */) {
882
+ newRpcEndpoint = newRpcEndpointFields;
883
+ } else {
884
+ newRpcEndpoint = {
885
+ ...newRpcEndpointFields,
886
+ networkClientId: uuidV4()
887
+ };
888
+ }
889
+ networkClientOperations.push({
890
+ type: "replace",
891
+ oldRpcEndpoint: existingRpcEndpointForReplaceWhenChainNotChanged,
892
+ newRpcEndpoint
893
+ });
894
+ } else {
895
+ const newRpcEndpoint = newRpcEndpointFields.type === "infura" /* Infura */ ? newRpcEndpointFields : { ...newRpcEndpointFields, networkClientId: uuidV4() };
896
+ const networkClientOperation = {
897
+ type: "add",
898
+ rpcEndpoint: newRpcEndpoint
899
+ };
900
+ networkClientOperations.push(networkClientOperation);
901
+ }
902
+ }
903
+ for (const existingRpcEndpoint of existingNetworkConfiguration.rpcEndpoints) {
904
+ if (!networkClientOperations.some((networkClientOperation) => {
905
+ const otherRpcEndpoint = networkClientOperation.type === "replace" ? networkClientOperation.oldRpcEndpoint : networkClientOperation.rpcEndpoint;
906
+ return otherRpcEndpoint.type === existingRpcEndpoint.type && otherRpcEndpoint.networkClientId === existingRpcEndpoint.networkClientId && otherRpcEndpoint.url === existingRpcEndpoint.url;
907
+ })) {
908
+ const networkClientOperation = {
909
+ type: "remove",
910
+ rpcEndpoint: existingRpcEndpoint
911
+ };
912
+ networkClientOperations.push(networkClientOperation);
913
+ }
914
+ }
915
+ const updatedNetworkConfiguration = __privateMethod(this, _determineNetworkConfigurationToPersist, determineNetworkConfigurationToPersist_fn).call(this, {
916
+ networkFields: fields,
917
+ networkClientOperations
918
+ });
919
+ if (replacementSelectedRpcEndpointIndex === void 0 && networkClientOperations.some((networkClientOperation) => {
920
+ return networkClientOperation.type === "remove" && networkClientOperation.rpcEndpoint.networkClientId === this.state.selectedNetworkClientId;
921
+ }) && !networkClientOperations.some((networkClientOperation) => {
922
+ return networkClientOperation.type === "replace" && networkClientOperation.oldRpcEndpoint.networkClientId === this.state.selectedNetworkClientId;
923
+ })) {
924
+ throw new Error(
925
+ // False negative - this is a string.
926
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
927
+ `Could not update network: Cannot update RPC endpoints in such a way that the selected network '${this.state.selectedNetworkClientId}' would be removed without a replacement. Choose a different RPC endpoint as the selected network via the \`replacementSelectedRpcEndpointIndex\` option.`
928
+ );
929
+ }
930
+ __privateMethod(this, _registerNetworkClientsAsNeeded, registerNetworkClientsAsNeeded_fn).call(this, {
931
+ networkFields: fields,
932
+ networkClientOperations,
933
+ autoManagedNetworkClientRegistry
934
+ });
935
+ const replacementSelectedRpcEndpointWithIndex = networkClientOperations.map(
936
+ (networkClientOperation, index) => [networkClientOperation, index]
937
+ ).find(([networkClientOperation, _index]) => {
938
+ return networkClientOperation.type === "replace" && networkClientOperation.oldRpcEndpoint.networkClientId === this.state.selectedNetworkClientId;
939
+ });
940
+ const correctedReplacementSelectedRpcEndpointIndex = replacementSelectedRpcEndpointIndex ?? replacementSelectedRpcEndpointWithIndex?.[1];
941
+ let rpcEndpointToSelect;
942
+ if (correctedReplacementSelectedRpcEndpointIndex !== void 0) {
943
+ rpcEndpointToSelect = updatedNetworkConfiguration.rpcEndpoints[correctedReplacementSelectedRpcEndpointIndex];
944
+ if (rpcEndpointToSelect === void 0) {
945
+ throw new Error(
946
+ `Could not update network: \`replacementSelectedRpcEndpointIndex\` ${correctedReplacementSelectedRpcEndpointIndex} does not refer to an entry in \`rpcEndpoints\``
947
+ );
948
+ }
949
+ }
950
+ if (rpcEndpointToSelect && rpcEndpointToSelect.networkClientId !== this.state.selectedNetworkClientId) {
951
+ await this.setActiveNetwork(rpcEndpointToSelect.networkClientId, {
952
+ updateState: (state) => {
953
+ __privateMethod(this, _updateNetworkConfigurations, updateNetworkConfigurations_fn).call(this, {
954
+ state,
955
+ mode: "update",
956
+ networkFields: fields,
957
+ networkConfigurationToPersist: updatedNetworkConfiguration,
958
+ existingNetworkConfiguration
959
+ });
960
+ }
961
+ });
962
+ } else {
963
+ this.update((state) => {
964
+ __privateMethod(this, _updateNetworkConfigurations, updateNetworkConfigurations_fn).call(this, {
965
+ state,
966
+ mode: "update",
967
+ networkFields: fields,
968
+ networkConfigurationToPersist: updatedNetworkConfiguration,
969
+ existingNetworkConfiguration
970
+ });
971
+ });
972
+ }
973
+ __privateSet(this, _networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId(
974
+ this.state.networkConfigurationsByChainId
975
+ ));
976
+ __privateMethod(this, _unregisterNetworkClientsAsNeeded, unregisterNetworkClientsAsNeeded_fn).call(this, {
977
+ networkClientOperations,
978
+ autoManagedNetworkClientRegistry
979
+ });
980
+ return updatedNetworkConfiguration;
981
+ }
982
+ /**
983
+ * Destroys and unregisters the network identified by the given chain ID, also
984
+ * removing the associated network configuration from state.
985
+ *
986
+ * @param chainId - The chain ID associated with an existing network.
987
+ * @throws if `chainId` does not refer to an existing network configuration,
988
+ * or if the currently selected network is being removed.
989
+ * @see {@link NetworkConfiguration}
990
+ */
991
+ removeNetwork(chainId) {
992
+ const existingNetworkConfiguration = this.state.networkConfigurationsByChainId[chainId];
993
+ if (existingNetworkConfiguration === void 0) {
994
+ throw new Error(
995
+ `Cannot find network configuration for chain ${inspect(chainId)}`
996
+ );
997
+ }
998
+ if (existingNetworkConfiguration.rpcEndpoints.some(
999
+ (rpcEndpoint) => rpcEndpoint.networkClientId === this.state.selectedNetworkClientId
1000
+ )) {
1001
+ throw new Error(`Cannot remove the currently selected network`);
1002
+ }
1003
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
1004
+ const networkClientOperations = existingNetworkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
1005
+ return {
1006
+ type: "remove",
1007
+ rpcEndpoint
1008
+ };
1009
+ });
1010
+ __privateMethod(this, _unregisterNetworkClientsAsNeeded, unregisterNetworkClientsAsNeeded_fn).call(this, {
1011
+ networkClientOperations,
1012
+ autoManagedNetworkClientRegistry
1013
+ });
1014
+ this.update((state) => {
1015
+ __privateMethod(this, _updateNetworkConfigurations, updateNetworkConfigurations_fn).call(this, {
1016
+ state,
1017
+ mode: "remove",
1018
+ existingNetworkConfiguration
1019
+ });
1020
+ });
1021
+ __privateSet(this, _networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId(
1022
+ this.state.networkConfigurationsByChainId
1023
+ ));
1024
+ }
1025
+ /**
1026
+ * Assuming that the network has been previously switched, switches to this
1027
+ * new network.
1028
+ *
1029
+ * If the network has not been previously switched, this method is equivalent
1030
+ * to {@link resetConnection}.
1031
+ */
1032
+ async rollbackToPreviousProvider() {
1033
+ await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, __privateGet(this, _previouslySelectedNetworkClientId));
1034
+ }
1035
+ /**
1036
+ * Deactivates the controller, stopping any ongoing polling.
1037
+ *
1038
+ * In-progress requests will not be aborted.
1039
+ */
1040
+ async destroy() {
1041
+ await __privateGet(this, _blockTrackerProxy)?.destroy();
1042
+ }
1043
+ /**
1044
+ * Merges the given backup data into controller state.
1045
+ *
1046
+ * @param backup - The data that has been backed up.
1047
+ * @param backup.networkConfigurationsByChainId - Network configurations,
1048
+ * keyed by chain ID.
1049
+ */
1050
+ loadBackup({
1051
+ networkConfigurationsByChainId
1052
+ }) {
1053
+ this.update((state) => {
1054
+ state.networkConfigurationsByChainId = {
1055
+ ...state.networkConfigurationsByChainId,
1056
+ ...networkConfigurationsByChainId
1057
+ };
1058
+ });
1059
+ }
1060
+ /**
1061
+ * Searches for a network configuration ID with the given ChainID and returns it.
1062
+ *
1063
+ * @param chainId - ChainId to search for
1064
+ * @returns networkClientId of the network configuration with the given chainId
1065
+ */
1066
+ findNetworkClientIdByChainId(chainId) {
1067
+ const networkClients = this.getNetworkClientRegistry();
1068
+ const networkClientEntry = Object.entries(networkClients).find(
1069
+ ([_, networkClient]) => networkClient.configuration.chainId === chainId
1070
+ );
1071
+ if (networkClientEntry === void 0) {
1072
+ throw new Error("Couldn't find networkClientId for chainId");
1073
+ }
1074
+ return networkClientEntry[0];
1075
+ }
1076
+ };
1077
+ _ethQuery = new WeakMap();
1078
+ _infuraProjectId = new WeakMap();
1079
+ _previouslySelectedNetworkClientId = new WeakMap();
1080
+ _providerProxy = new WeakMap();
1081
+ _blockTrackerProxy = new WeakMap();
1082
+ _autoManagedNetworkClientRegistry = new WeakMap();
1083
+ _autoManagedNetworkClient = new WeakMap();
1084
+ _log = new WeakMap();
1085
+ _networkConfigurationsByNetworkClientId = new WeakMap();
1086
+ _refreshNetwork = new WeakSet();
1087
+ refreshNetwork_fn = async function(networkClientId, options = {}) {
1088
+ this.messagingSystem.publish(
1089
+ "NetworkController:networkWillChange",
1090
+ this.state
1091
+ );
1092
+ __privateMethod(this, _applyNetworkSelection, applyNetworkSelection_fn).call(this, networkClientId, options);
1093
+ this.messagingSystem.publish(
1094
+ "NetworkController:networkDidChange",
1095
+ this.state
1096
+ );
1097
+ await this.lookupNetwork();
1098
+ };
1099
+ _getLatestBlock = new WeakSet();
1100
+ getLatestBlock_fn = function(networkClientId) {
1101
+ if (networkClientId === void 0) {
1102
+ networkClientId = this.state.selectedNetworkClientId;
1103
+ }
1104
+ const networkClient = this.getNetworkClientById(networkClientId);
1105
+ const ethQuery = new EthQuery(networkClient.provider);
1106
+ return new Promise((resolve, reject) => {
1107
+ ethQuery.sendAsync(
1108
+ { method: "eth_getBlockByNumber", params: ["latest", false] },
1109
+ (error, block) => {
1110
+ if (error) {
1111
+ reject(error);
1112
+ } else {
1113
+ resolve(block);
1114
+ }
1115
+ }
1116
+ );
1117
+ });
1118
+ };
1119
+ _determineEIP1559Compatibility = new WeakSet();
1120
+ determineEIP1559Compatibility_fn = async function(networkClientId) {
1121
+ const latestBlock = await __privateMethod(this, _getLatestBlock, getLatestBlock_fn).call(this, networkClientId);
1122
+ if (!latestBlock) {
1123
+ return void 0;
1124
+ }
1125
+ return latestBlock.baseFeePerGas !== void 0;
1126
+ };
1127
+ _validateNetworkFields = new WeakSet();
1128
+ validateNetworkFields_fn = function(args) {
1129
+ const { mode, networkFields, autoManagedNetworkClientRegistry } = args;
1130
+ const existingNetworkConfiguration = "existingNetworkConfiguration" in args ? args.existingNetworkConfiguration : null;
1131
+ const errorMessagePrefix = mode === "update" ? "Could not update network" : "Could not add network";
1132
+ if (!isStrictHexString(networkFields.chainId) || !isSafeChainId(networkFields.chainId)) {
1133
+ throw new Error(
1134
+ `${errorMessagePrefix}: Invalid \`chainId\` ${inspect(
1135
+ networkFields.chainId
1136
+ )} (must start with "0x" and not exceed the maximum)`
1137
+ );
1138
+ }
1139
+ if (existingNetworkConfiguration === null || networkFields.chainId !== existingNetworkConfiguration.chainId) {
1140
+ const existingNetworkConfigurationViaChainId = this.state.networkConfigurationsByChainId[networkFields.chainId];
1141
+ if (existingNetworkConfigurationViaChainId !== void 0) {
1142
+ if (existingNetworkConfiguration === null) {
1143
+ throw new Error(
1144
+ // False negative - these are strings.
1145
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1146
+ `Could not add network for chain ${args.networkFields.chainId} as another network for that chain already exists ('${existingNetworkConfigurationViaChainId.name}')`
1147
+ );
1148
+ } else {
1149
+ throw new Error(
1150
+ // False negative - these are strings.
1151
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1152
+ `Cannot move network from chain ${existingNetworkConfiguration.chainId} to ${networkFields.chainId} as another network for that chain already exists ('${existingNetworkConfigurationViaChainId.name}')`
1153
+ );
1154
+ }
1155
+ }
1156
+ }
1157
+ const isInvalidDefaultBlockExplorerUrlIndex = networkFields.blockExplorerUrls.length > 0 ? networkFields.defaultBlockExplorerUrlIndex === void 0 || networkFields.blockExplorerUrls[networkFields.defaultBlockExplorerUrlIndex] === void 0 : networkFields.defaultBlockExplorerUrlIndex !== void 0;
1158
+ if (isInvalidDefaultBlockExplorerUrlIndex) {
1159
+ throw new Error(
1160
+ `${errorMessagePrefix}: \`defaultBlockExplorerUrlIndex\` must refer to an entry in \`blockExplorerUrls\``
1161
+ );
1162
+ }
1163
+ if (networkFields.rpcEndpoints.length === 0) {
1164
+ throw new Error(
1165
+ `${errorMessagePrefix}: \`rpcEndpoints\` must be a non-empty array`
1166
+ );
1167
+ }
1168
+ for (const rpcEndpointFields of networkFields.rpcEndpoints) {
1169
+ if (!isValidUrl(rpcEndpointFields.url)) {
1170
+ throw new Error(
1171
+ `${errorMessagePrefix}: An entry in \`rpcEndpoints\` has invalid URL ${inspect(
1172
+ rpcEndpointFields.url
1173
+ )}`
1174
+ );
1175
+ }
1176
+ const networkClientId = "networkClientId" in rpcEndpointFields ? rpcEndpointFields.networkClientId : void 0;
1177
+ if (rpcEndpointFields.type === "custom" /* Custom */ && networkClientId !== void 0 && isInfuraNetworkType(networkClientId)) {
1178
+ throw new Error(
1179
+ // This is a string.
1180
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1181
+ `${errorMessagePrefix}: Custom RPC endpoint '${rpcEndpointFields.url}' has invalid network client ID '${networkClientId}'`
1182
+ );
1183
+ }
1184
+ if (mode === "update" && networkClientId !== void 0 && rpcEndpointFields.type === "custom" /* Custom */ && !Object.values(autoManagedNetworkClientRegistry).some(
1185
+ (networkClientsById) => networkClientId in networkClientsById
1186
+ )) {
1187
+ throw new Error(
1188
+ `${errorMessagePrefix}: RPC endpoint '${// This is a string.
1189
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1190
+ rpcEndpointFields.url}' refers to network client ${inspect(
1191
+ networkClientId
1192
+ )} that does not exist`
1193
+ );
1194
+ }
1195
+ if (networkFields.rpcEndpoints.some(
1196
+ (otherRpcEndpointFields) => otherRpcEndpointFields !== rpcEndpointFields && URI.equal(otherRpcEndpointFields.url, rpcEndpointFields.url)
1197
+ )) {
1198
+ throw new Error(
1199
+ `${errorMessagePrefix}: Each entry in rpcEndpoints must have a unique URL`
1200
+ );
1201
+ }
1202
+ const networkConfigurationsForOtherChains = Object.values(
1203
+ this.state.networkConfigurationsByChainId
1204
+ ).filter(
1205
+ (networkConfiguration) => existingNetworkConfiguration ? networkConfiguration.chainId !== existingNetworkConfiguration.chainId : true
1206
+ );
1207
+ for (const networkConfiguration of networkConfigurationsForOtherChains) {
1208
+ const rpcEndpoint = networkConfiguration.rpcEndpoints.find(
1209
+ (existingRpcEndpoint) => URI.equal(rpcEndpointFields.url, existingRpcEndpoint.url)
1210
+ );
1211
+ if (rpcEndpoint) {
1212
+ throw new Error(
1213
+ mode === "update" ? (
1214
+ // False negative - these are strings.
1215
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1216
+ `Could not update network to point to same RPC endpoint as existing network for chain ${networkConfiguration.chainId} ('${networkConfiguration.name}')`
1217
+ ) : (
1218
+ // False negative - these are strings.
1219
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1220
+ `Could not add network that points to same RPC endpoint as existing network for chain ${networkConfiguration.chainId} ('${networkConfiguration.name}')`
1221
+ )
1222
+ );
1223
+ }
1224
+ }
1225
+ }
1226
+ if ([...new Set(networkFields.rpcEndpoints)].length < networkFields.rpcEndpoints.length) {
1227
+ throw new Error(
1228
+ `${errorMessagePrefix}: Each entry in rpcEndpoints must be unique`
1229
+ );
1230
+ }
1231
+ const networkClientIds = networkFields.rpcEndpoints.map(
1232
+ (rpcEndpoint) => "networkClientId" in rpcEndpoint ? rpcEndpoint.networkClientId : void 0
1233
+ ).filter(
1234
+ (networkClientId) => networkClientId !== void 0
1235
+ );
1236
+ if ([...new Set(networkClientIds)].length < networkClientIds.length) {
1237
+ throw new Error(
1238
+ `${errorMessagePrefix}: Each entry in rpcEndpoints must have a unique networkClientId`
1239
+ );
1240
+ }
1241
+ const infuraRpcEndpoints = networkFields.rpcEndpoints.filter(
1242
+ (rpcEndpointFields) => rpcEndpointFields.type === "infura" /* Infura */
1243
+ );
1244
+ if (infuraRpcEndpoints.length > 1) {
1245
+ throw new Error(
1246
+ `${errorMessagePrefix}: There cannot be more than one Infura RPC endpoint`
1247
+ );
1248
+ }
1249
+ const soleInfuraRpcEndpoint = infuraRpcEndpoints[0];
1250
+ if (soleInfuraRpcEndpoint) {
1251
+ const infuraNetworkName = deriveInfuraNetworkNameFromRpcEndpointUrl(
1252
+ soleInfuraRpcEndpoint.url
1253
+ );
1254
+ const infuraNetworkNickname = NetworkNickname[infuraNetworkName];
1255
+ const infuraChainId = ChainId[infuraNetworkName];
1256
+ if (networkFields.chainId !== infuraChainId) {
1257
+ throw new Error(
1258
+ mode === "add" ? (
1259
+ // This is a string.
1260
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1261
+ `Could not add network with chain ID ${networkFields.chainId} and Infura RPC endpoint for '${infuraNetworkNickname}' which represents ${infuraChainId}, as the two conflict`
1262
+ ) : (
1263
+ // This is a string.
1264
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1265
+ `Could not update network with chain ID ${networkFields.chainId} and Infura RPC endpoint for '${infuraNetworkNickname}' which represents ${infuraChainId}, as the two conflict`
1266
+ )
1267
+ );
1268
+ }
1269
+ }
1270
+ if (networkFields.rpcEndpoints[networkFields.defaultRpcEndpointIndex] === void 0) {
1271
+ throw new Error(
1272
+ `${errorMessagePrefix}: \`defaultRpcEndpointIndex\` must refer to an entry in \`rpcEndpoints\``
1273
+ );
1274
+ }
1275
+ };
1276
+ _determineNetworkConfigurationToPersist = new WeakSet();
1277
+ determineNetworkConfigurationToPersist_fn = function({
1278
+ networkFields,
1279
+ networkClientOperations
1280
+ }) {
1281
+ const rpcEndpointsToPersist = networkClientOperations.filter(
1282
+ (networkClientOperation) => {
1283
+ return networkClientOperation.type === "add" || networkClientOperation.type === "noop";
1284
+ }
1285
+ ).map((networkClientOperation) => networkClientOperation.rpcEndpoint).concat(
1286
+ networkClientOperations.filter(
1287
+ (networkClientOperation) => {
1288
+ return networkClientOperation.type === "replace";
1289
+ }
1290
+ ).map(
1291
+ (networkClientOperation) => networkClientOperation.newRpcEndpoint
1292
+ )
1293
+ );
1294
+ return { ...networkFields, rpcEndpoints: rpcEndpointsToPersist };
1295
+ };
1296
+ _registerNetworkClientsAsNeeded = new WeakSet();
1297
+ registerNetworkClientsAsNeeded_fn = function({
1298
+ networkFields,
1299
+ networkClientOperations,
1300
+ autoManagedNetworkClientRegistry
1301
+ }) {
1302
+ const addedRpcEndpoints = networkClientOperations.filter(
1303
+ (networkClientOperation) => {
1304
+ return networkClientOperation.type === "add";
1305
+ }
1306
+ ).map((networkClientOperation) => networkClientOperation.rpcEndpoint).concat(
1307
+ networkClientOperations.filter(
1308
+ (networkClientOperation) => {
1309
+ return networkClientOperation.type === "replace";
1310
+ }
1311
+ ).map(
1312
+ (networkClientOperation) => networkClientOperation.newRpcEndpoint
1313
+ )
1314
+ );
1315
+ for (const addedRpcEndpoint of addedRpcEndpoints) {
1316
+ if (addedRpcEndpoint.type === "infura" /* Infura */) {
1317
+ autoManagedNetworkClientRegistry["infura" /* Infura */][addedRpcEndpoint.networkClientId] = createAutoManagedNetworkClient({
1318
+ type: "infura" /* Infura */,
1319
+ chainId: networkFields.chainId,
1320
+ network: addedRpcEndpoint.networkClientId,
1321
+ infuraProjectId: __privateGet(this, _infuraProjectId),
1322
+ ticker: networkFields.nativeCurrency
1323
+ });
1324
+ } else {
1325
+ autoManagedNetworkClientRegistry["custom" /* Custom */][addedRpcEndpoint.networkClientId] = createAutoManagedNetworkClient({
1326
+ type: "custom" /* Custom */,
1327
+ chainId: networkFields.chainId,
1328
+ rpcUrl: addedRpcEndpoint.url,
1329
+ ticker: networkFields.nativeCurrency
1330
+ });
1331
+ }
1332
+ }
1333
+ };
1334
+ _unregisterNetworkClientsAsNeeded = new WeakSet();
1335
+ unregisterNetworkClientsAsNeeded_fn = function({
1336
+ networkClientOperations,
1337
+ autoManagedNetworkClientRegistry
1338
+ }) {
1339
+ const removedRpcEndpoints = networkClientOperations.filter(
1340
+ (networkClientOperation) => {
1341
+ return networkClientOperation.type === "remove";
1342
+ }
1343
+ ).map((networkClientOperation) => networkClientOperation.rpcEndpoint).concat(
1344
+ networkClientOperations.filter(
1345
+ (networkClientOperation) => {
1346
+ return networkClientOperation.type === "replace";
1347
+ }
1348
+ ).map(
1349
+ (networkClientOperation) => networkClientOperation.oldRpcEndpoint
1350
+ )
1351
+ );
1352
+ for (const rpcEndpoint of removedRpcEndpoints) {
1353
+ const networkClient = this.getNetworkClientById(
1354
+ rpcEndpoint.networkClientId
1355
+ );
1356
+ networkClient.destroy();
1357
+ delete autoManagedNetworkClientRegistry[networkClient.configuration.type][rpcEndpoint.networkClientId];
1358
+ }
1359
+ };
1360
+ _updateNetworkConfigurations = new WeakSet();
1361
+ updateNetworkConfigurations_fn = function(args) {
1362
+ const { state, mode } = args;
1363
+ if (mode === "remove" || mode === "update" && args.networkFields.chainId !== args.existingNetworkConfiguration.chainId) {
1364
+ delete state.networkConfigurationsByChainId[args.existingNetworkConfiguration.chainId];
1365
+ }
1366
+ if (mode === "add" || mode === "update") {
1367
+ state.networkConfigurationsByChainId[args.networkFields.chainId] = args.networkConfigurationToPersist;
1368
+ }
1369
+ };
1370
+ _ensureAutoManagedNetworkClientRegistryPopulated = new WeakSet();
1371
+ ensureAutoManagedNetworkClientRegistryPopulated_fn = function() {
1372
+ return __privateGet(this, _autoManagedNetworkClientRegistry) ?? __privateSet(this, _autoManagedNetworkClientRegistry, __privateMethod(this, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn).call(this));
1373
+ };
1374
+ _createAutoManagedNetworkClientRegistry = new WeakSet();
1375
+ createAutoManagedNetworkClientRegistry_fn = function() {
1376
+ const chainIds = knownKeysOf(this.state.networkConfigurationsByChainId);
1377
+ const networkClientsWithIds = chainIds.flatMap((chainId) => {
1378
+ const networkConfiguration = this.state.networkConfigurationsByChainId[chainId];
1379
+ return networkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
1380
+ if (rpcEndpoint.type === "infura" /* Infura */) {
1381
+ const infuraNetworkName = deriveInfuraNetworkNameFromRpcEndpointUrl(
1382
+ rpcEndpoint.url
1383
+ );
1384
+ return [
1385
+ rpcEndpoint.networkClientId,
1386
+ createAutoManagedNetworkClient({
1387
+ type: "infura" /* Infura */,
1388
+ network: infuraNetworkName,
1389
+ infuraProjectId: __privateGet(this, _infuraProjectId),
1390
+ chainId: networkConfiguration.chainId,
1391
+ ticker: networkConfiguration.nativeCurrency
1392
+ })
1393
+ ];
1394
+ }
1395
+ return [
1396
+ rpcEndpoint.networkClientId,
1397
+ createAutoManagedNetworkClient({
1398
+ type: "custom" /* Custom */,
1399
+ chainId: networkConfiguration.chainId,
1400
+ rpcUrl: rpcEndpoint.url,
1401
+ ticker: networkConfiguration.nativeCurrency
1402
+ })
1403
+ ];
1404
+ });
1405
+ });
1406
+ return networkClientsWithIds.reduce(
1407
+ (obj, [networkClientId, networkClient]) => {
1408
+ return {
1409
+ ...obj,
1410
+ [networkClient.configuration.type]: {
1411
+ ...obj[networkClient.configuration.type],
1412
+ [networkClientId]: networkClient
1413
+ }
1414
+ };
1415
+ },
1416
+ {
1417
+ ["custom" /* Custom */]: {},
1418
+ ["infura" /* Infura */]: {}
1419
+ }
1420
+ );
1421
+ };
1422
+ _applyNetworkSelection = new WeakSet();
1423
+ applyNetworkSelection_fn = function(networkClientId, {
1424
+ updateState
1425
+ } = {}) {
1426
+ const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
1427
+ let autoManagedNetworkClient;
1428
+ if (isInfuraNetworkType(networkClientId)) {
1429
+ const possibleAutoManagedNetworkClient = autoManagedNetworkClientRegistry["infura" /* Infura */][networkClientId];
1430
+ if (!possibleAutoManagedNetworkClient) {
1431
+ throw new Error(
1432
+ `No Infura network client found with ID ${inspect(networkClientId)}`
1433
+ );
1434
+ }
1435
+ autoManagedNetworkClient = possibleAutoManagedNetworkClient;
1436
+ } else {
1437
+ const possibleAutoManagedNetworkClient = autoManagedNetworkClientRegistry["custom" /* Custom */][networkClientId];
1438
+ if (!possibleAutoManagedNetworkClient) {
1439
+ throw new Error(
1440
+ `No network client found with ID ${inspect(networkClientId)}`
1441
+ );
1442
+ }
1443
+ autoManagedNetworkClient = possibleAutoManagedNetworkClient;
1444
+ }
1445
+ __privateSet(this, _autoManagedNetworkClient, autoManagedNetworkClient);
1446
+ this.update((state) => {
1447
+ state.selectedNetworkClientId = networkClientId;
1448
+ if (state.networksMetadata[networkClientId] === void 0) {
1449
+ state.networksMetadata[networkClientId] = {
1450
+ status: "unknown" /* Unknown */,
1451
+ EIPS: {}
1452
+ };
1453
+ }
1454
+ updateState?.(state);
1455
+ });
1456
+ if (__privateGet(this, _providerProxy)) {
1457
+ __privateGet(this, _providerProxy).setTarget(__privateGet(this, _autoManagedNetworkClient).provider);
1458
+ } else {
1459
+ __privateSet(this, _providerProxy, createEventEmitterProxy(
1460
+ __privateGet(this, _autoManagedNetworkClient).provider
1461
+ ));
1462
+ }
1463
+ if (__privateGet(this, _blockTrackerProxy)) {
1464
+ __privateGet(this, _blockTrackerProxy).setTarget(
1465
+ __privateGet(this, _autoManagedNetworkClient).blockTracker
1466
+ );
1467
+ } else {
1468
+ __privateSet(this, _blockTrackerProxy, createEventEmitterProxy(
1469
+ __privateGet(this, _autoManagedNetworkClient).blockTracker,
1470
+ { eventFilter: "skipInternal" }
1471
+ ));
1472
+ }
1473
+ __privateSet(this, _ethQuery, new EthQuery(__privateGet(this, _providerProxy)));
1474
+ };
1475
+
1476
+ export {
1477
+ RpcEndpointType,
1478
+ knownKeysOf,
1479
+ getDefaultNetworkControllerState,
1480
+ getNetworkConfigurations,
1481
+ getAvailableNetworkClientIds,
1482
+ selectAvailableNetworkClientIds,
1483
+ NetworkController
1484
+ };
1485
+ //# sourceMappingURL=chunk-BV3ZGWII.mjs.map