@metamask-previews/network-controller 20.0.0-preview-5ba43a24 → 20.0.0-preview-e4ec85f

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