@metamask-previews/network-controller 20.0.0-preview-e4ec85f → 20.0.0-preview-ee06f305

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,949 +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
- BUILT_IN_NETWORKS,
22
- InfuraNetworkType,
23
- NetworkType,
24
- isSafeChainId,
25
- isInfuraNetworkType
26
- } from "@metamask/controller-utils";
27
- import EthQuery from "@metamask/eth-query";
28
- import { errorCodes } from "@metamask/rpc-errors";
29
- import { createEventEmitterProxy } from "@metamask/swappable-obj-proxy";
30
- import {
31
- assertIsStrictHexString,
32
- hasProperty,
33
- isPlainObject
34
- } from "@metamask/utils";
35
- import { strict as assert } from "assert";
36
- import { v4 as random } from "uuid";
37
- var debugLog = createModuleLogger(projectLogger, "NetworkController");
38
- function knownKeysOf(object) {
39
- return Object.keys(object);
40
- }
41
- function assertOfType(value, validate, message) {
42
- assert.ok(validate(value), message);
43
- }
44
- function pick(object, keys) {
45
- const pickedObject = keys.reduce(
46
- (finalObject, key) => {
47
- return { ...finalObject, [key]: object[key] };
48
- },
49
- {}
50
- );
51
- assertOfType(
52
- pickedObject,
53
- () => keys.every((key) => key in pickedObject),
54
- "The reduce did not produce an object with all of the desired keys."
55
- );
56
- return pickedObject;
57
- }
58
- function isErrorWithCode(error) {
59
- return typeof error === "object" && error !== null && "code" in error;
60
- }
61
- var name = "NetworkController";
62
- var defaultState = {
63
- selectedNetworkClientId: NetworkType.mainnet,
64
- networksMetadata: {},
65
- networkConfigurations: {}
66
- };
67
- var _ethQuery, _infuraProjectId, _trackMetaMetricsEvent, _previouslySelectedNetworkClientId, _providerProxy, _blockTrackerProxy, _autoManagedNetworkClientRegistry, _autoManagedNetworkClient, _log, _refreshNetwork, refreshNetwork_fn, _getLatestBlock, getLatestBlock_fn, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn, _applyNetworkSelection, applyNetworkSelection_fn;
68
- var NetworkController = class extends BaseController {
69
- constructor({
70
- messenger,
71
- state,
72
- infuraProjectId,
73
- trackMetaMetricsEvent,
74
- log
75
- }) {
76
- super({
77
- name,
78
- metadata: {
79
- selectedNetworkClientId: {
80
- persist: true,
81
- anonymous: false
82
- },
83
- networksMetadata: {
84
- persist: true,
85
- anonymous: false
86
- },
87
- networkConfigurations: {
88
- persist: true,
89
- anonymous: false
90
- }
91
- },
92
- messenger,
93
- state: { ...defaultState, ...state }
94
- });
95
- /**
96
- * Executes a series of steps to switch the network:
97
- *
98
- * 1. Notifies subscribers via the messenger that the network is about to be
99
- * switched (and, really, that the global provider and block tracker proxies
100
- * will be re-pointed to a new network).
101
- * 2. Looks up a known and preinitialized network client matching the given
102
- * ID and uses it to re-point the aforementioned provider and block tracker
103
- * proxies.
104
- * 3. Notifies subscribers via the messenger that the network has switched.
105
- * 4. Captures metadata for the newly switched network in state.
106
- *
107
- * @param networkClientId - The ID of a network client that requests will be
108
- * routed through (either the name of an Infura network or the ID of a custom
109
- * network configuration).
110
- */
111
- __privateAdd(this, _refreshNetwork);
112
- /**
113
- * Fetches the latest block for the network.
114
- *
115
- * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.
116
- * @returns A promise that either resolves to the block header or null if
117
- * there is no latest block, or rejects with an error.
118
- */
119
- __privateAdd(this, _getLatestBlock);
120
- /**
121
- * Retrieves and checks the latest block from the currently selected
122
- * network; if the block has a `baseFeePerGas` property, then we know
123
- * that the network supports EIP-1559; otherwise it doesn't.
124
- *
125
- * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility
126
- * @returns A promise that resolves to `true` if the network supports EIP-1559,
127
- * `false` otherwise, or `undefined` if unable to retrieve the last block.
128
- */
129
- __privateAdd(this, _determineEIP1559Compatibility);
130
- /**
131
- * Before accessing or switching the network, the registry of network clients
132
- * needs to be populated. Otherwise, `#applyNetworkSelection` and
133
- * `getNetworkClientRegistry` will throw an error. This method checks to see if the
134
- * population step has happened yet, and if not, makes it happen.
135
- *
136
- * @returns The populated network client registry.
137
- */
138
- __privateAdd(this, _ensureAutoManagedNetworkClientRegistryPopulated);
139
- /**
140
- * Constructs the registry of network clients based on the set of built-in
141
- * networks as well as the custom networks in state.
142
- *
143
- * @returns The network clients keyed by ID.
144
- */
145
- __privateAdd(this, _createAutoManagedNetworkClientRegistry);
146
- /**
147
- * Constructs the list of network clients for built-in networks (that is,
148
- * the subset of the networks we know Infura supports that consumers do not
149
- * need to explicitly add).
150
- *
151
- * @returns The network clients.
152
- */
153
- __privateAdd(this, _buildIdentifiedInfuraNetworkClientConfigurations);
154
- /**
155
- * Constructs the list of network clients for custom networks (that is, those
156
- * which consumers have added via `networkConfigurations`).
157
- *
158
- * @returns The network clients.
159
- */
160
- __privateAdd(this, _buildIdentifiedCustomNetworkClientConfigurations);
161
- /**
162
- * Updates the global provider and block tracker proxies (accessible via
163
- * {@link getSelectedNetworkClient}) to point to the same ones within the
164
- * given network client, thereby magically switching any consumers using these
165
- * proxies to use the new network.
166
- *
167
- * Also refreshes the EthQuery instance accessible via the `getEthQuery`
168
- * action to wrap the provider from the new network client. Note that this is
169
- * not a proxy, so consumers will need to call `getEthQuery` again after the
170
- * network switch.
171
- *
172
- * @param networkClientId - The ID of a network client that requests will be
173
- * routed through (either the name of an Infura network or the ID of a custom
174
- * network configuration).
175
- * @throws if no network client could be found matching the given ID.
176
- */
177
- __privateAdd(this, _applyNetworkSelection);
178
- __privateAdd(this, _ethQuery, void 0);
179
- __privateAdd(this, _infuraProjectId, void 0);
180
- __privateAdd(this, _trackMetaMetricsEvent, void 0);
181
- __privateAdd(this, _previouslySelectedNetworkClientId, void 0);
182
- __privateAdd(this, _providerProxy, void 0);
183
- __privateAdd(this, _blockTrackerProxy, void 0);
184
- __privateAdd(this, _autoManagedNetworkClientRegistry, void 0);
185
- __privateAdd(this, _autoManagedNetworkClient, void 0);
186
- __privateAdd(this, _log, void 0);
187
- if (!infuraProjectId || typeof infuraProjectId !== "string") {
188
- throw new Error("Invalid Infura project ID");
189
- }
190
- __privateSet(this, _infuraProjectId, infuraProjectId);
191
- __privateSet(this, _trackMetaMetricsEvent, trackMetaMetricsEvent);
192
- this.messagingSystem.registerActionHandler(
193
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
194
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
195
- `${this.name}:getEthQuery`,
196
- () => {
197
- return __privateGet(this, _ethQuery);
198
- }
199
- );
200
- this.messagingSystem.registerActionHandler(
201
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
202
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
203
- `${this.name}:getNetworkClientById`,
204
- this.getNetworkClientById.bind(this)
205
- );
206
- this.messagingSystem.registerActionHandler(
207
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
208
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
209
- `${this.name}:getEIP1559Compatibility`,
210
- this.getEIP1559Compatibility.bind(this)
211
- );
212
- this.messagingSystem.registerActionHandler(
213
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
214
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
215
- `${this.name}:setActiveNetwork`,
216
- this.setActiveNetwork.bind(this)
217
- );
218
- this.messagingSystem.registerActionHandler(
219
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
220
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
221
- `${this.name}:setProviderType`,
222
- this.setProviderType.bind(this)
223
- );
224
- this.messagingSystem.registerActionHandler(
225
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
226
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
227
- `${this.name}:findNetworkClientIdByChainId`,
228
- this.findNetworkClientIdByChainId.bind(this)
229
- );
230
- this.messagingSystem.registerActionHandler(
231
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
232
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
233
- `${this.name}:getNetworkConfigurationByNetworkClientId`,
234
- this.getNetworkConfigurationByNetworkClientId.bind(this)
235
- );
236
- this.messagingSystem.registerActionHandler(
237
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
238
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
239
- `${this.name}:getSelectedNetworkClient`,
240
- this.getSelectedNetworkClient.bind(this)
241
- );
242
- __privateSet(this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
243
- __privateSet(this, _log, log);
244
- }
245
- /**
246
- * Accesses the provider and block tracker for the currently selected network.
247
- * @returns The proxy and block tracker proxies.
248
- * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.
249
- */
250
- getProviderAndBlockTracker() {
251
- return {
252
- provider: __privateGet(this, _providerProxy),
253
- blockTracker: __privateGet(this, _blockTrackerProxy)
254
- };
255
- }
256
- /**
257
- * Accesses the provider and block tracker for the currently selected network.
258
- *
259
- * @returns an object with the provider and block tracker proxies for the currently selected network.
260
- */
261
- getSelectedNetworkClient() {
262
- if (__privateGet(this, _providerProxy) && __privateGet(this, _blockTrackerProxy)) {
263
- return {
264
- provider: __privateGet(this, _providerProxy),
265
- blockTracker: __privateGet(this, _blockTrackerProxy)
266
- };
267
- }
268
- return void 0;
269
- }
270
- /**
271
- * Returns all of the network clients that have been created so far, keyed by
272
- * their identifier in the network client registry. This collection represents
273
- * not only built-in networks but also any custom networks that consumers have
274
- * added.
275
- *
276
- * @returns The list of known network clients.
277
- */
278
- getNetworkClientRegistry() {
279
- const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
280
- return Object.assign(
281
- {},
282
- autoManagedNetworkClientRegistry["infura" /* Infura */],
283
- autoManagedNetworkClientRegistry["custom" /* Custom */]
284
- );
285
- }
286
- getNetworkClientById(networkClientId) {
287
- if (!networkClientId) {
288
- throw new Error("No network client ID was provided.");
289
- }
290
- const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
291
- if (isInfuraNetworkType(networkClientId)) {
292
- const infuraNetworkClient = autoManagedNetworkClientRegistry["infura" /* Infura */][networkClientId];
293
- if (!infuraNetworkClient) {
294
- throw new Error(
295
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
296
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
297
- `No Infura network client was found with the ID "${networkClientId}".`
298
- );
299
- }
300
- return infuraNetworkClient;
301
- }
302
- const customNetworkClient = autoManagedNetworkClientRegistry["custom" /* Custom */][networkClientId];
303
- if (!customNetworkClient) {
304
- throw new Error(
305
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
306
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
307
- `No custom network client was found with the ID "${networkClientId}".`
308
- );
309
- }
310
- return customNetworkClient;
311
- }
312
- /**
313
- * Creates network clients for built-in and custom networks, then establishes
314
- * the currently selected network client based on state.
315
- */
316
- async initializeProvider() {
317
- __privateMethod(this, _applyNetworkSelection, applyNetworkSelection_fn).call(this, this.state.selectedNetworkClientId);
318
- await this.lookupNetwork();
319
- }
320
- /**
321
- * Refreshes the network meta with EIP-1559 support and the network status
322
- * based on the given network client ID.
323
- *
324
- * @param networkClientId - The ID of the network client to update.
325
- */
326
- async lookupNetworkByClientId(networkClientId) {
327
- const isInfura = isInfuraNetworkType(networkClientId);
328
- let updatedNetworkStatus;
329
- let updatedIsEIP1559Compatible;
330
- try {
331
- updatedIsEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, networkClientId);
332
- updatedNetworkStatus = "available" /* Available */;
333
- } catch (error) {
334
- debugLog("NetworkController: lookupNetworkByClientId: ", error);
335
- if (isErrorWithCode(error)) {
336
- let responseBody;
337
- if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
338
- try {
339
- responseBody = JSON.parse(error.message);
340
- } catch {
341
- __privateGet(this, _log)?.warn(
342
- "NetworkController: lookupNetworkByClientId: json parse error: ",
343
- error
344
- );
345
- }
346
- }
347
- if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
348
- updatedNetworkStatus = "blocked" /* Blocked */;
349
- } else if (error.code === errorCodes.rpc.internal) {
350
- updatedNetworkStatus = "unknown" /* Unknown */;
351
- __privateGet(this, _log)?.warn(
352
- "NetworkController: lookupNetworkByClientId: rpc internal error: ",
353
- error
354
- );
355
- } else {
356
- updatedNetworkStatus = "unavailable" /* Unavailable */;
357
- __privateGet(this, _log)?.warn(
358
- "NetworkController: lookupNetworkByClientId: ",
359
- error
360
- );
361
- }
362
- } else if (typeof Error !== "undefined" && hasProperty(error, "message") && typeof error.message === "string" && error.message.includes(
363
- "No custom network client was found with the ID"
364
- )) {
365
- throw error;
366
- } else {
367
- debugLog(
368
- "NetworkController - could not determine network status",
369
- error
370
- );
371
- updatedNetworkStatus = "unknown" /* Unknown */;
372
- __privateGet(this, _log)?.warn("NetworkController: lookupNetworkByClientId: ", error);
373
- }
374
- }
375
- this.update((state) => {
376
- if (state.networksMetadata[networkClientId] === void 0) {
377
- state.networksMetadata[networkClientId] = {
378
- status: "unknown" /* Unknown */,
379
- EIPS: {}
380
- };
381
- }
382
- const meta = state.networksMetadata[networkClientId];
383
- meta.status = updatedNetworkStatus;
384
- if (updatedIsEIP1559Compatible === void 0) {
385
- delete meta.EIPS[1559];
386
- } else {
387
- meta.EIPS[1559] = updatedIsEIP1559Compatible;
388
- }
389
- });
390
- }
391
- /**
392
- * Persists the following metadata about the given or selected network to
393
- * state:
394
- *
395
- * - The status of the network, namely, whether it is available, geo-blocked
396
- * (Infura only), or unavailable, or whether the status is unknown
397
- * - Whether the network supports EIP-1559, or whether it is unknown
398
- *
399
- * Note that it is possible for the network to be switched while this data is
400
- * being collected. If that is the case, no metadata for the (now previously)
401
- * selected network will be updated.
402
- *
403
- * @param networkClientId - The ID of the network client to update.
404
- * If no ID is provided, uses the currently selected network.
405
- */
406
- async lookupNetwork(networkClientId) {
407
- if (networkClientId) {
408
- await this.lookupNetworkByClientId(networkClientId);
409
- return;
410
- }
411
- if (!__privateGet(this, _ethQuery)) {
412
- return;
413
- }
414
- const isInfura = __privateGet(this, _autoManagedNetworkClient)?.configuration.type === "infura" /* Infura */;
415
- let networkChanged = false;
416
- const listener = () => {
417
- networkChanged = true;
418
- this.messagingSystem.unsubscribe(
419
- "NetworkController:networkDidChange",
420
- listener
421
- );
422
- };
423
- this.messagingSystem.subscribe(
424
- "NetworkController:networkDidChange",
425
- listener
426
- );
427
- let updatedNetworkStatus;
428
- let updatedIsEIP1559Compatible;
429
- try {
430
- const isEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, this.state.selectedNetworkClientId);
431
- updatedNetworkStatus = "available" /* Available */;
432
- updatedIsEIP1559Compatible = isEIP1559Compatible;
433
- } catch (error) {
434
- if (isErrorWithCode(error)) {
435
- let responseBody;
436
- if (isInfura && hasProperty(error, "message") && typeof error.message === "string") {
437
- try {
438
- responseBody = JSON.parse(error.message);
439
- } catch (parseError) {
440
- __privateGet(this, _log)?.warn(
441
- "NetworkController: lookupNetwork: json parse error",
442
- parseError
443
- );
444
- }
445
- }
446
- if (isPlainObject(responseBody) && responseBody.error === INFURA_BLOCKED_KEY) {
447
- updatedNetworkStatus = "blocked" /* Blocked */;
448
- } else if (error.code === errorCodes.rpc.internal) {
449
- updatedNetworkStatus = "unknown" /* Unknown */;
450
- __privateGet(this, _log)?.warn(
451
- "NetworkController: lookupNetwork: rpc internal error",
452
- error
453
- );
454
- } else {
455
- updatedNetworkStatus = "unavailable" /* Unavailable */;
456
- __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
457
- }
458
- } else {
459
- debugLog(
460
- "NetworkController - could not determine network status",
461
- error
462
- );
463
- updatedNetworkStatus = "unknown" /* Unknown */;
464
- __privateGet(this, _log)?.warn("NetworkController: lookupNetwork: ", error);
465
- }
466
- }
467
- if (networkChanged) {
468
- return;
469
- }
470
- this.messagingSystem.unsubscribe(
471
- "NetworkController:networkDidChange",
472
- listener
473
- );
474
- this.update((state) => {
475
- const meta = state.networksMetadata[state.selectedNetworkClientId];
476
- meta.status = updatedNetworkStatus;
477
- if (updatedIsEIP1559Compatible === void 0) {
478
- delete meta.EIPS[1559];
479
- } else {
480
- meta.EIPS[1559] = updatedIsEIP1559Compatible;
481
- }
482
- });
483
- if (isInfura) {
484
- if (updatedNetworkStatus === "available" /* Available */) {
485
- this.messagingSystem.publish("NetworkController:infuraIsUnblocked");
486
- } else if (updatedNetworkStatus === "blocked" /* Blocked */) {
487
- this.messagingSystem.publish("NetworkController:infuraIsBlocked");
488
- }
489
- } else {
490
- this.messagingSystem.publish("NetworkController:infuraIsUnblocked");
491
- }
492
- }
493
- /**
494
- * Convenience method to update provider network type settings.
495
- *
496
- * @param type - Human readable network name.
497
- * @deprecated This has been replaced by `setActiveNetwork`, and will be
498
- * removed in a future release
499
- */
500
- async setProviderType(type) {
501
- assert.notStrictEqual(
502
- type,
503
- NetworkType.rpc,
504
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
505
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
506
- `NetworkController - cannot call "setProviderType" with type "${NetworkType.rpc}". Use "setActiveNetwork"`
507
- );
508
- assert.ok(
509
- isInfuraNetworkType(type),
510
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
511
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
512
- `Unknown Infura provider type "${type}".`
513
- );
514
- await this.setActiveNetwork(type);
515
- }
516
- /**
517
- * Changes the selected network.
518
- *
519
- * @param networkClientId - The ID of a network client that requests will be
520
- * routed through (either the name of an Infura network or the ID of a custom
521
- * network configuration).
522
- * @throws if no network client is associated with the given
523
- * `networkClientId`.
524
- */
525
- async setActiveNetwork(networkClientId) {
526
- __privateSet(this, _previouslySelectedNetworkClientId, this.state.selectedNetworkClientId);
527
- await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, networkClientId);
528
- }
529
- /**
530
- * Determines whether the network supports EIP-1559 by checking whether the
531
- * latest block has a `baseFeePerGas` property, then updates state
532
- * appropriately.
533
- *
534
- * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.
535
- * @returns A promise that resolves to true if the network supports EIP-1559
536
- * , false otherwise, or `undefined` if unable to determine the compatibility.
537
- */
538
- async getEIP1559Compatibility(networkClientId) {
539
- if (networkClientId) {
540
- return this.get1559CompatibilityWithNetworkClientId(networkClientId);
541
- }
542
- if (!__privateGet(this, _ethQuery)) {
543
- return false;
544
- }
545
- const { EIPS } = this.state.networksMetadata[this.state.selectedNetworkClientId];
546
- if (EIPS[1559] !== void 0) {
547
- return EIPS[1559];
548
- }
549
- const isEIP1559Compatible = await __privateMethod(this, _determineEIP1559Compatibility, determineEIP1559Compatibility_fn).call(this, this.state.selectedNetworkClientId);
550
- this.update((state) => {
551
- if (isEIP1559Compatible !== void 0) {
552
- state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] = isEIP1559Compatible;
553
- }
554
- });
555
- return isEIP1559Compatible;
556
- }
557
- async get1559CompatibilityWithNetworkClientId(networkClientId) {
558
- let metadata = this.state.networksMetadata[networkClientId];
559
- if (metadata === void 0) {
560
- await this.lookupNetwork(networkClientId);
561
- metadata = this.state.networksMetadata[networkClientId];
562
- }
563
- const { EIPS } = metadata;
564
- return EIPS[1559];
565
- }
566
- /**
567
- * Ensures that the provider and block tracker proxies are pointed to the
568
- * currently selected network and refreshes the metadata for the
569
- */
570
- async resetConnection() {
571
- await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, this.state.selectedNetworkClientId);
572
- }
573
- /**
574
- * Returns a configuration object for the network identified by the given
575
- * network client ID. If given an Infura network type, constructs one based on
576
- * what we know about the network; otherwise attempts locates a network
577
- * configuration in state that corresponds to the network client ID.
578
- *
579
- * @param networkClientId - The network client ID.
580
- * @returns The configuration for the referenced network if one exists, or
581
- * undefined otherwise.
582
- */
583
- getNetworkConfigurationByNetworkClientId(networkClientId) {
584
- if (isInfuraNetworkType(networkClientId)) {
585
- const rpcUrl = `https://${networkClientId}.infura.io/v3/${__privateGet(this, _infuraProjectId)}`;
586
- return {
587
- rpcUrl,
588
- ...BUILT_IN_NETWORKS[networkClientId]
589
- };
590
- }
591
- return this.state.networkConfigurations[networkClientId];
592
- }
593
- /**
594
- * Adds a new custom network or updates the information for an existing
595
- * network.
596
- *
597
- * This may involve updating the `networkConfigurations` property in
598
- * state as well and/or adding a new network client to the network client
599
- * registry. The `rpcUrl` and `chainId` of the given object are used to
600
- * determine which action to take:
601
- *
602
- * - If the `rpcUrl` corresponds to an existing network configuration
603
- * (case-insensitively), then it is overwritten with the object. Furthermore,
604
- * if the `chainId` is different from the existing network configuration, then
605
- * the existing network client is replaced with a new one.
606
- * - If the `rpcUrl` does not correspond to an existing network configuration
607
- * (case-insensitively), then the object is used to add a new network
608
- * configuration along with a new network client.
609
- *
610
- * @param networkConfiguration - The network configuration to add or update.
611
- * @param options - Additional configuration options.
612
- * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.
613
- * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).
614
- * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).
615
- * @returns The ID for the added or updated network configuration.
616
- */
617
- async upsertNetworkConfiguration(networkConfiguration, {
618
- referrer,
619
- source,
620
- setActive = false
621
- }) {
622
- const sanitizedNetworkConfiguration = pick(
623
- networkConfiguration,
624
- ["rpcUrl", "chainId", "ticker", "nickname", "rpcPrefs"]
625
- );
626
- const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;
627
- assertIsStrictHexString(chainId);
628
- if (!isSafeChainId(chainId)) {
629
- throw new Error(
630
- `Invalid chain ID "${chainId}": numerical value greater than max safe value.`
631
- );
632
- }
633
- if (!rpcUrl) {
634
- throw new Error(
635
- "An rpcUrl is required to add or update network configuration"
636
- );
637
- }
638
- if (!referrer || !source) {
639
- throw new Error(
640
- "referrer and source are required arguments for adding or updating a network configuration"
641
- );
642
- }
643
- try {
644
- new URL(rpcUrl);
645
- } catch (e) {
646
- if (e.message.includes("Invalid URL")) {
647
- throw new Error("rpcUrl must be a valid URL");
648
- }
649
- }
650
- if (!ticker) {
651
- throw new Error(
652
- "A ticker is required to add or update networkConfiguration"
653
- );
654
- }
655
- const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
656
- const existingNetworkConfiguration = Object.values(
657
- this.state.networkConfigurations
658
- ).find(
659
- (networkConfig) => networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase()
660
- );
661
- const upsertedNetworkConfigurationId = existingNetworkConfiguration ? existingNetworkConfiguration.id : random();
662
- const networkClientId = upsertedNetworkConfigurationId;
663
- const customNetworkClientRegistry = autoManagedNetworkClientRegistry["custom" /* Custom */];
664
- const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
665
- const shouldDestroyExistingNetworkClient = existingAutoManagedNetworkClient && existingAutoManagedNetworkClient.configuration.chainId !== chainId;
666
- if (shouldDestroyExistingNetworkClient) {
667
- existingAutoManagedNetworkClient.destroy();
668
- }
669
- if (!existingAutoManagedNetworkClient || shouldDestroyExistingNetworkClient) {
670
- customNetworkClientRegistry[networkClientId] = createAutoManagedNetworkClient({
671
- type: "custom" /* Custom */,
672
- chainId,
673
- rpcUrl,
674
- ticker
675
- });
676
- }
677
- this.update((state) => {
678
- state.networkConfigurations[upsertedNetworkConfigurationId] = {
679
- id: upsertedNetworkConfigurationId,
680
- ...sanitizedNetworkConfiguration
681
- };
682
- });
683
- if (!existingNetworkConfiguration) {
684
- __privateGet(this, _trackMetaMetricsEvent).call(this, {
685
- event: "Custom Network Added",
686
- category: "Network",
687
- referrer: {
688
- url: referrer
689
- },
690
- properties: {
691
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
692
- // eslint-disable-next-line @typescript-eslint/naming-convention
693
- chain_id: chainId,
694
- symbol: ticker,
695
- source
696
- }
697
- });
698
- }
699
- if (setActive) {
700
- await this.setActiveNetwork(upsertedNetworkConfigurationId);
701
- }
702
- return upsertedNetworkConfigurationId;
703
- }
704
- /**
705
- * Removes a custom network from state.
706
- *
707
- * This involves updating the `networkConfigurations` property in state as
708
- * well and removing the network client that corresponds to the network from
709
- * the client registry.
710
- *
711
- * @param networkConfigurationId - The ID of an existing network
712
- * configuration.
713
- */
714
- removeNetworkConfiguration(networkConfigurationId) {
715
- if (!this.state.networkConfigurations[networkConfigurationId]) {
716
- throw new Error(
717
- `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`
718
- );
719
- }
720
- const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
721
- const networkClientId = networkConfigurationId;
722
- this.update((state) => {
723
- delete state.networkConfigurations[networkConfigurationId];
724
- });
725
- const customNetworkClientRegistry = autoManagedNetworkClientRegistry["custom" /* Custom */];
726
- const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
727
- existingAutoManagedNetworkClient.destroy();
728
- delete customNetworkClientRegistry[networkClientId];
729
- }
730
- /**
731
- * Assuming that the network has been previously switched, switches to this
732
- * new network.
733
- *
734
- * If the network has not been previously switched, this method is equivalent
735
- * to {@link resetConnection}.
736
- */
737
- async rollbackToPreviousProvider() {
738
- await __privateMethod(this, _refreshNetwork, refreshNetwork_fn).call(this, __privateGet(this, _previouslySelectedNetworkClientId));
739
- }
740
- /**
741
- * Deactivates the controller, stopping any ongoing polling.
742
- *
743
- * In-progress requests will not be aborted.
744
- */
745
- async destroy() {
746
- await __privateGet(this, _blockTrackerProxy)?.destroy();
747
- }
748
- /**
749
- * Updates the controller using the given backup data.
750
- *
751
- * @param backup - The data that has been backed up.
752
- * @param backup.networkConfigurations - Network configurations in the backup.
753
- */
754
- loadBackup({
755
- networkConfigurations
756
- }) {
757
- this.update((state) => {
758
- state.networkConfigurations = {
759
- ...state.networkConfigurations,
760
- ...networkConfigurations
761
- };
762
- });
763
- }
764
- /**
765
- * Searches for a network configuration ID with the given ChainID and returns it.
766
- *
767
- * @param chainId - ChainId to search for
768
- * @returns networkClientId of the network configuration with the given chainId
769
- */
770
- findNetworkClientIdByChainId(chainId) {
771
- const networkClients = this.getNetworkClientRegistry();
772
- const networkClientEntry = Object.entries(networkClients).find(
773
- ([_, networkClient]) => networkClient.configuration.chainId === chainId
774
- );
775
- if (networkClientEntry === void 0) {
776
- throw new Error("Couldn't find networkClientId for chainId");
777
- }
778
- return networkClientEntry[0];
779
- }
780
- };
781
- _ethQuery = new WeakMap();
782
- _infuraProjectId = new WeakMap();
783
- _trackMetaMetricsEvent = new WeakMap();
784
- _previouslySelectedNetworkClientId = new WeakMap();
785
- _providerProxy = new WeakMap();
786
- _blockTrackerProxy = new WeakMap();
787
- _autoManagedNetworkClientRegistry = new WeakMap();
788
- _autoManagedNetworkClient = new WeakMap();
789
- _log = new WeakMap();
790
- _refreshNetwork = new WeakSet();
791
- refreshNetwork_fn = async function(networkClientId) {
792
- this.messagingSystem.publish(
793
- "NetworkController:networkWillChange",
794
- this.state
795
- );
796
- __privateMethod(this, _applyNetworkSelection, applyNetworkSelection_fn).call(this, networkClientId);
797
- this.messagingSystem.publish(
798
- "NetworkController:networkDidChange",
799
- this.state
800
- );
801
- await this.lookupNetwork();
802
- };
803
- _getLatestBlock = new WeakSet();
804
- getLatestBlock_fn = function(networkClientId) {
805
- if (networkClientId === void 0) {
806
- networkClientId = this.state.selectedNetworkClientId;
807
- }
808
- const networkClient = this.getNetworkClientById(networkClientId);
809
- const ethQuery = new EthQuery(networkClient.provider);
810
- return new Promise((resolve, reject) => {
811
- ethQuery.sendAsync(
812
- { method: "eth_getBlockByNumber", params: ["latest", false] },
813
- (error, block) => {
814
- if (error) {
815
- reject(error);
816
- } else {
817
- resolve(block);
818
- }
819
- }
820
- );
821
- });
822
- };
823
- _determineEIP1559Compatibility = new WeakSet();
824
- determineEIP1559Compatibility_fn = async function(networkClientId) {
825
- const latestBlock = await __privateMethod(this, _getLatestBlock, getLatestBlock_fn).call(this, networkClientId);
826
- if (!latestBlock) {
827
- return void 0;
828
- }
829
- return latestBlock.baseFeePerGas !== void 0;
830
- };
831
- _ensureAutoManagedNetworkClientRegistryPopulated = new WeakSet();
832
- ensureAutoManagedNetworkClientRegistryPopulated_fn = function() {
833
- const autoManagedNetworkClientRegistry = __privateGet(this, _autoManagedNetworkClientRegistry) ?? __privateMethod(this, _createAutoManagedNetworkClientRegistry, createAutoManagedNetworkClientRegistry_fn).call(this);
834
- __privateSet(this, _autoManagedNetworkClientRegistry, autoManagedNetworkClientRegistry);
835
- return autoManagedNetworkClientRegistry;
836
- };
837
- _createAutoManagedNetworkClientRegistry = new WeakSet();
838
- createAutoManagedNetworkClientRegistry_fn = function() {
839
- return [
840
- ...__privateMethod(this, _buildIdentifiedInfuraNetworkClientConfigurations, buildIdentifiedInfuraNetworkClientConfigurations_fn).call(this),
841
- ...__privateMethod(this, _buildIdentifiedCustomNetworkClientConfigurations, buildIdentifiedCustomNetworkClientConfigurations_fn).call(this)
842
- ].reduce(
843
- (registry, [networkClientType, networkClientId, networkClientConfiguration]) => {
844
- const autoManagedNetworkClient = createAutoManagedNetworkClient(
845
- networkClientConfiguration
846
- );
847
- return {
848
- ...registry,
849
- [networkClientType]: {
850
- ...registry[networkClientType],
851
- [networkClientId]: autoManagedNetworkClient
852
- }
853
- };
854
- },
855
- {
856
- ["infura" /* Infura */]: {},
857
- ["custom" /* Custom */]: {}
858
- }
859
- );
860
- };
861
- _buildIdentifiedInfuraNetworkClientConfigurations = new WeakSet();
862
- buildIdentifiedInfuraNetworkClientConfigurations_fn = function() {
863
- return knownKeysOf(InfuraNetworkType).map((network) => {
864
- const networkClientConfiguration = {
865
- type: "infura" /* Infura */,
866
- network,
867
- infuraProjectId: __privateGet(this, _infuraProjectId),
868
- chainId: BUILT_IN_NETWORKS[network].chainId,
869
- ticker: BUILT_IN_NETWORKS[network].ticker
870
- };
871
- return ["infura" /* Infura */, network, networkClientConfiguration];
872
- });
873
- };
874
- _buildIdentifiedCustomNetworkClientConfigurations = new WeakSet();
875
- buildIdentifiedCustomNetworkClientConfigurations_fn = function() {
876
- return Object.entries(this.state.networkConfigurations).map(
877
- ([networkConfigurationId, networkConfiguration]) => {
878
- const networkClientId = networkConfigurationId;
879
- const networkClientConfiguration = {
880
- type: "custom" /* Custom */,
881
- chainId: networkConfiguration.chainId,
882
- rpcUrl: networkConfiguration.rpcUrl,
883
- ticker: networkConfiguration.ticker
884
- };
885
- return [
886
- "custom" /* Custom */,
887
- networkClientId,
888
- networkClientConfiguration
889
- ];
890
- }
891
- );
892
- };
893
- _applyNetworkSelection = new WeakSet();
894
- applyNetworkSelection_fn = function(networkClientId) {
895
- const autoManagedNetworkClientRegistry = __privateMethod(this, _ensureAutoManagedNetworkClientRegistryPopulated, ensureAutoManagedNetworkClientRegistryPopulated_fn).call(this);
896
- let autoManagedNetworkClient;
897
- if (isInfuraNetworkType(networkClientId)) {
898
- const possibleAutoManagedNetworkClient = autoManagedNetworkClientRegistry["infura" /* Infura */][networkClientId];
899
- if (!possibleAutoManagedNetworkClient) {
900
- throw new Error(
901
- `Infura network client not found with ID '${networkClientId}'`
902
- );
903
- }
904
- autoManagedNetworkClient = possibleAutoManagedNetworkClient;
905
- } else {
906
- const possibleAutoManagedNetworkClient = autoManagedNetworkClientRegistry["custom" /* Custom */][networkClientId];
907
- if (!possibleAutoManagedNetworkClient) {
908
- throw new Error(
909
- `Custom network client not found with ID '${networkClientId}'`
910
- );
911
- }
912
- autoManagedNetworkClient = possibleAutoManagedNetworkClient;
913
- }
914
- __privateSet(this, _autoManagedNetworkClient, autoManagedNetworkClient);
915
- this.update((state) => {
916
- state.selectedNetworkClientId = networkClientId;
917
- if (state.networksMetadata[networkClientId] === void 0) {
918
- state.networksMetadata[networkClientId] = {
919
- status: "unknown" /* Unknown */,
920
- EIPS: {}
921
- };
922
- }
923
- });
924
- if (__privateGet(this, _providerProxy)) {
925
- __privateGet(this, _providerProxy).setTarget(__privateGet(this, _autoManagedNetworkClient).provider);
926
- } else {
927
- __privateSet(this, _providerProxy, createEventEmitterProxy(
928
- __privateGet(this, _autoManagedNetworkClient).provider
929
- ));
930
- }
931
- if (__privateGet(this, _blockTrackerProxy)) {
932
- __privateGet(this, _blockTrackerProxy).setTarget(
933
- __privateGet(this, _autoManagedNetworkClient).blockTracker
934
- );
935
- } else {
936
- __privateSet(this, _blockTrackerProxy, createEventEmitterProxy(
937
- __privateGet(this, _autoManagedNetworkClient).blockTracker,
938
- { eventFilter: "skipInternal" }
939
- ));
940
- }
941
- __privateSet(this, _ethQuery, new EthQuery(__privateGet(this, _providerProxy)));
942
- };
943
-
944
- export {
945
- knownKeysOf,
946
- defaultState,
947
- NetworkController
948
- };
949
- //# sourceMappingURL=chunk-6PT34M4U.mjs.map