@metamask-previews/network-controller 12.1.1-preview.d32a7cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,864 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_provider, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_refreshNetwork, _NetworkController_getNetworkId, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated, _NetworkController_createAutoManagedNetworkClientRegistry, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig, _NetworkController_applyNetworkSelection;
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.NetworkController = exports.defaultState = exports.knownKeysOf = void 0;
28
+ const base_controller_1 = require("@metamask/base-controller");
29
+ const controller_utils_1 = require("@metamask/controller-utils");
30
+ const eth_query_1 = __importDefault(require("@metamask/eth-query"));
31
+ const swappable_obj_proxy_1 = require("@metamask/swappable-obj-proxy");
32
+ const utils_1 = require("@metamask/utils");
33
+ const assert_1 = require("assert");
34
+ const eth_rpc_errors_1 = require("eth-rpc-errors");
35
+ const uuid_1 = require("uuid");
36
+ const constants_1 = require("./constants");
37
+ const create_auto_managed_network_client_1 = require("./create-auto-managed-network-client");
38
+ const logger_1 = require("./logger");
39
+ const types_1 = require("./types");
40
+ const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'NetworkController');
41
+ /**
42
+ * `Object.keys()` is intentionally generic: it returns the keys of an object,
43
+ * but it cannot make guarantees about the contents of that object, so the type
44
+ * of the keys is merely `string[]`. While this is technically accurate, it is
45
+ * also unnecessary if we have an object that we own and whose contents are
46
+ * known exactly.
47
+ *
48
+ * TODO: Move to @metamask/utils.
49
+ *
50
+ * @param object - The object.
51
+ * @returns The keys of an object, typed according to the type of the object
52
+ * itself.
53
+ */
54
+ function knownKeysOf(object) {
55
+ return Object.keys(object);
56
+ }
57
+ exports.knownKeysOf = knownKeysOf;
58
+ /**
59
+ * Asserts that the given value is of the given type if the given validation
60
+ * function returns a truthy result.
61
+ *
62
+ * @param value - The value to validate.
63
+ * @param validate - A function used to validate that the value is of the given
64
+ * type. Takes the `value` as an argument and is expected to return true or
65
+ * false.
66
+ * @param message - The message to throw if the function does not return a
67
+ * truthy result.
68
+ * @throws if the function does not return a truthy result.
69
+ */
70
+ function assertOfType(value, validate, message) {
71
+ assert_1.strict.ok(validate(value), message);
72
+ }
73
+ /**
74
+ * Returns a portion of the given object with only the given keys.
75
+ *
76
+ * @param object - An object.
77
+ * @param keys - The keys to pick from the object.
78
+ * @returns the portion of the object.
79
+ */
80
+ function pick(object, keys) {
81
+ const pickedObject = keys.reduce((finalObject, key) => {
82
+ return Object.assign(Object.assign({}, finalObject), { [key]: object[key] });
83
+ }, {});
84
+ assertOfType(pickedObject, () => keys.every((key) => key in pickedObject), 'The reduce did not produce an object with all of the desired keys.');
85
+ return pickedObject;
86
+ }
87
+ /**
88
+ * Convert the given value into a valid network ID. The ID is accepted
89
+ * as either a number, a decimal string, or a 0x-prefixed hex string.
90
+ *
91
+ * @param value - The network ID to convert, in an unknown format.
92
+ * @returns A valid network ID (as a decimal string)
93
+ * @throws If the given value cannot be safely parsed.
94
+ */
95
+ function convertNetworkId(value) {
96
+ if (typeof value === 'number' && !Number.isNaN(value)) {
97
+ return `${value}`;
98
+ }
99
+ else if ((0, utils_1.isStrictHexString)(value)) {
100
+ return `${(0, controller_utils_1.convertHexToDecimal)(value)}`;
101
+ }
102
+ else if (typeof value === 'string' && /^\d+$/u.test(value)) {
103
+ return value;
104
+ }
105
+ throw new Error(`Cannot parse as a valid network ID: '${value}'`);
106
+ }
107
+ /**
108
+ * Type guard for determining whether the given value is an error object with a
109
+ * `code` property, such as an instance of Error.
110
+ *
111
+ * TODO: Move this to @metamask/utils.
112
+ *
113
+ * @param error - The object to check.
114
+ * @returns True if `error` has a `code`, false otherwise.
115
+ */
116
+ function isErrorWithCode(error) {
117
+ return typeof error === 'object' && error !== null && 'code' in error;
118
+ }
119
+ /**
120
+ * Returns whether the given argument is a type that our Infura middleware
121
+ * recognizes.
122
+ *
123
+ * @param type - A type to compare.
124
+ * @returns True or false, depending on whether the given type is one that our
125
+ * Infura middleware recognizes.
126
+ */
127
+ function isInfuraProviderType(type) {
128
+ return Object.keys(controller_utils_1.InfuraNetworkType).includes(type);
129
+ }
130
+ /**
131
+ * Builds an identifier for an Infura network client for lookup purposes.
132
+ *
133
+ * @param infuraNetworkOrProviderConfig - The name of an Infura network or a
134
+ * provider config.
135
+ * @returns The built identifier.
136
+ */
137
+ function buildInfuraNetworkClientId(infuraNetworkOrProviderConfig) {
138
+ if (typeof infuraNetworkOrProviderConfig === 'string') {
139
+ return infuraNetworkOrProviderConfig;
140
+ }
141
+ return infuraNetworkOrProviderConfig.type;
142
+ }
143
+ /**
144
+ * Builds an identifier for a custom network client for lookup purposes.
145
+ *
146
+ * @param args - This function can be called two ways:
147
+ * 1. The ID of a network configuration.
148
+ * 2. A provider config and a set of network configurations.
149
+ * @returns The built identifier.
150
+ */
151
+ function buildCustomNetworkClientId(...args) {
152
+ if (args.length === 1) {
153
+ return args[0];
154
+ }
155
+ const [{ id, rpcUrl }, networkConfigurations] = args;
156
+ if (id === undefined) {
157
+ const matchingNetworkConfiguration = Object.values(networkConfigurations).find((networkConfiguration) => {
158
+ return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();
159
+ });
160
+ if (matchingNetworkConfiguration) {
161
+ return matchingNetworkConfiguration.id;
162
+ }
163
+ return rpcUrl.toLowerCase();
164
+ }
165
+ return id;
166
+ }
167
+ /**
168
+ * Returns whether the given provider config refers to an Infura network.
169
+ *
170
+ * @param providerConfig - The provider config.
171
+ * @returns True if the provider config refers to an Infura network, false
172
+ * otherwise.
173
+ */
174
+ function isInfuraProviderConfig(providerConfig) {
175
+ return isInfuraProviderType(providerConfig.type);
176
+ }
177
+ /**
178
+ * Returns whether the given provider config refers to an Infura network.
179
+ *
180
+ * @param providerConfig - The provider config.
181
+ * @returns True if the provider config refers to an Infura network, false
182
+ * otherwise.
183
+ */
184
+ function isCustomProviderConfig(providerConfig) {
185
+ return providerConfig.type === controller_utils_1.NetworkType.rpc;
186
+ }
187
+ /**
188
+ * As a provider config represents the settings that are used to interface with
189
+ * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents
190
+ * a custom network. These properties _should_ be set as they are validated in
191
+ * the UI when a user adds a custom network, but just to be safe we validate
192
+ * them here.
193
+ *
194
+ * In addition, historically the `rpcUrl` property on the ProviderConfig type
195
+ * has been optional, even though it should not be. Making this non-optional
196
+ * would be a breaking change, so this function types the provider config
197
+ * correctly so that we don't have to check `rpcUrl` in other places.
198
+ *
199
+ * @param providerConfig - A provider config.
200
+ * @throws if the provider config does not have a chain ID or an RPC URL.
201
+ */
202
+ function validateCustomProviderConfig(providerConfig) {
203
+ if (providerConfig.chainId === undefined) {
204
+ throw new Error('chainId must be provided for custom RPC endpoints');
205
+ }
206
+ if (providerConfig.rpcUrl === undefined) {
207
+ throw new Error('rpcUrl must be provided for custom RPC endpoints');
208
+ }
209
+ }
210
+ const name = 'NetworkController';
211
+ exports.defaultState = {
212
+ selectedNetworkClientId: controller_utils_1.NetworkType.mainnet,
213
+ networkId: null,
214
+ providerConfig: {
215
+ type: controller_utils_1.NetworkType.mainnet,
216
+ chainId: controller_utils_1.ChainId.mainnet,
217
+ ticker: controller_utils_1.NetworksTicker.mainnet,
218
+ },
219
+ networksMetadata: {},
220
+ networkConfigurations: {},
221
+ };
222
+ /**
223
+ * Controller that creates and manages an Ethereum network provider.
224
+ */
225
+ class NetworkController extends base_controller_1.BaseControllerV2 {
226
+ constructor({ messenger, state, infuraProjectId, trackMetaMetricsEvent, }) {
227
+ super({
228
+ name,
229
+ metadata: {
230
+ selectedNetworkClientId: {
231
+ persist: true,
232
+ anonymous: false,
233
+ },
234
+ networkId: {
235
+ persist: true,
236
+ anonymous: false,
237
+ },
238
+ networksMetadata: {
239
+ persist: true,
240
+ anonymous: false,
241
+ },
242
+ providerConfig: {
243
+ persist: true,
244
+ anonymous: false,
245
+ },
246
+ networkConfigurations: {
247
+ persist: true,
248
+ anonymous: false,
249
+ },
250
+ },
251
+ messenger,
252
+ state: Object.assign(Object.assign({}, exports.defaultState), state),
253
+ });
254
+ _NetworkController_instances.add(this);
255
+ _NetworkController_ethQuery.set(this, void 0);
256
+ _NetworkController_infuraProjectId.set(this, void 0);
257
+ _NetworkController_trackMetaMetricsEvent.set(this, void 0);
258
+ _NetworkController_previousProviderConfig.set(this, void 0);
259
+ _NetworkController_providerProxy.set(this, void 0);
260
+ _NetworkController_provider.set(this, void 0);
261
+ _NetworkController_blockTrackerProxy.set(this, void 0);
262
+ _NetworkController_autoManagedNetworkClientRegistry.set(this, void 0);
263
+ if (!infuraProjectId || typeof infuraProjectId !== 'string') {
264
+ throw new Error('Invalid Infura project ID');
265
+ }
266
+ __classPrivateFieldSet(this, _NetworkController_infuraProjectId, infuraProjectId, "f");
267
+ __classPrivateFieldSet(this, _NetworkController_trackMetaMetricsEvent, trackMetaMetricsEvent, "f");
268
+ this.messagingSystem.registerActionHandler(`${this.name}:getProviderConfig`, () => {
269
+ return this.state.providerConfig;
270
+ });
271
+ this.messagingSystem.registerActionHandler(`${this.name}:getEthQuery`, () => {
272
+ return __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
273
+ });
274
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
275
+ }
276
+ /**
277
+ * Accesses the provider and block tracker for the currently selected network.
278
+ *
279
+ * @returns The proxy and block tracker proxies.
280
+ */
281
+ getProviderAndBlockTracker() {
282
+ return {
283
+ provider: __classPrivateFieldGet(this, _NetworkController_providerProxy, "f"),
284
+ blockTracker: __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f"),
285
+ };
286
+ }
287
+ /**
288
+ * Returns all of the network clients that have been created so far, keyed by
289
+ * their identifier in the network client registry. This collection represents
290
+ * not only built-in networks but also any custom networks that consumers have
291
+ * added.
292
+ *
293
+ * @returns The list of known network clients.
294
+ */
295
+ getNetworkClientRegistry() {
296
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
297
+ return Object.assign({}, autoManagedNetworkClientRegistry[types_1.NetworkClientType.Infura], autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom]);
298
+ }
299
+ getNetworkClientById(networkClientId) {
300
+ if (!networkClientId) {
301
+ throw new Error('No network client ID was provided.');
302
+ }
303
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
304
+ if (isInfuraProviderType(networkClientId)) {
305
+ const infuraNetworkClient = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Infura][networkClientId];
306
+ if (!infuraNetworkClient) {
307
+ throw new Error(`No Infura network client was found with the ID "${networkClientId}".`);
308
+ }
309
+ return infuraNetworkClient;
310
+ }
311
+ const customNetworkClient = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom][networkClientId];
312
+ if (!customNetworkClient) {
313
+ throw new Error(`No custom network client was found with the ID "${networkClientId}".`);
314
+ }
315
+ return customNetworkClient;
316
+ }
317
+ /**
318
+ * Populates the network clients and establishes the initial network based on
319
+ * the provider configuration in state.
320
+ */
321
+ initializeProvider() {
322
+ return __awaiter(this, void 0, void 0, function* () {
323
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
324
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
325
+ yield this.lookupNetwork();
326
+ });
327
+ }
328
+ /**
329
+ * Performs side effects after switching to a network. If the network is
330
+ * available, updates the network state with the network ID of the network and
331
+ * stores whether the network supports EIP-1559; otherwise clears said
332
+ * information about the network that may have been previously stored.
333
+ *
334
+ * @fires infuraIsBlocked if the network is Infura-supported and is blocking
335
+ * requests.
336
+ * @fires infuraIsUnblocked if the network is Infura-supported and is not
337
+ * blocking requests, or if the network is not Infura-supported.
338
+ */
339
+ lookupNetwork() {
340
+ return __awaiter(this, void 0, void 0, function* () {
341
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
342
+ return;
343
+ }
344
+ const isInfura = isInfuraProviderConfig(this.state.providerConfig);
345
+ let networkChanged = false;
346
+ const listener = () => {
347
+ networkChanged = true;
348
+ this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
349
+ };
350
+ this.messagingSystem.subscribe('NetworkController:networkDidChange', listener);
351
+ let updatedNetworkStatus;
352
+ let updatedNetworkId = null;
353
+ let updatedIsEIP1559Compatible;
354
+ try {
355
+ const [networkId, isEIP1559Compatible] = yield Promise.all([
356
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this),
357
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this),
358
+ ]);
359
+ updatedNetworkStatus = constants_1.NetworkStatus.Available;
360
+ updatedNetworkId = networkId;
361
+ updatedIsEIP1559Compatible = isEIP1559Compatible;
362
+ }
363
+ catch (error) {
364
+ if (isErrorWithCode(error)) {
365
+ let responseBody;
366
+ if (isInfura &&
367
+ (0, utils_1.hasProperty)(error, 'message') &&
368
+ typeof error.message === 'string') {
369
+ try {
370
+ responseBody = JSON.parse(error.message);
371
+ }
372
+ catch (_a) {
373
+ // error.message must not be JSON
374
+ }
375
+ }
376
+ if ((0, utils_1.isPlainObject)(responseBody) &&
377
+ responseBody.error === constants_1.INFURA_BLOCKED_KEY) {
378
+ updatedNetworkStatus = constants_1.NetworkStatus.Blocked;
379
+ }
380
+ else if (error.code === eth_rpc_errors_1.errorCodes.rpc.internal) {
381
+ updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
382
+ }
383
+ else {
384
+ updatedNetworkStatus = constants_1.NetworkStatus.Unavailable;
385
+ }
386
+ }
387
+ else {
388
+ log('NetworkController - could not determine network status', error);
389
+ updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
390
+ }
391
+ }
392
+ if (networkChanged) {
393
+ // If the network has changed, then `lookupNetwork` either has been or is
394
+ // in the process of being called, so we don't need to go further.
395
+ return;
396
+ }
397
+ this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
398
+ this.update((state) => {
399
+ state.networkId = updatedNetworkId;
400
+ const meta = state.networksMetadata[state.selectedNetworkClientId];
401
+ meta.status = updatedNetworkStatus;
402
+ if (updatedIsEIP1559Compatible === undefined) {
403
+ delete meta.EIPS[1559];
404
+ }
405
+ else {
406
+ meta.EIPS[1559] = updatedIsEIP1559Compatible;
407
+ }
408
+ });
409
+ if (isInfura) {
410
+ if (updatedNetworkStatus === constants_1.NetworkStatus.Available) {
411
+ this.messagingSystem.publish('NetworkController:infuraIsUnblocked');
412
+ }
413
+ else if (updatedNetworkStatus === constants_1.NetworkStatus.Blocked) {
414
+ this.messagingSystem.publish('NetworkController:infuraIsBlocked');
415
+ }
416
+ }
417
+ else {
418
+ // Always publish infuraIsUnblocked regardless of network status to
419
+ // prevent consumers from being stuck in a blocked state if they were
420
+ // previously connected to an Infura network that was blocked
421
+ this.messagingSystem.publish('NetworkController:infuraIsUnblocked');
422
+ }
423
+ });
424
+ }
425
+ /**
426
+ * Convenience method to update provider network type settings.
427
+ *
428
+ * @param type - Human readable network name.
429
+ */
430
+ setProviderType(type) {
431
+ return __awaiter(this, void 0, void 0, function* () {
432
+ assert_1.strict.notStrictEqual(type, controller_utils_1.NetworkType.rpc, `NetworkController - cannot call "setProviderType" with type "${controller_utils_1.NetworkType.rpc}". Use "setActiveNetwork"`);
433
+ assert_1.strict.ok(isInfuraProviderType(type), `Unknown Infura provider type "${type}".`);
434
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
435
+ // If testnet the ticker symbol should use a testnet prefix
436
+ const ticker = type in controller_utils_1.NetworksTicker && controller_utils_1.NetworksTicker[type].length > 0
437
+ ? controller_utils_1.NetworksTicker[type]
438
+ : 'ETH';
439
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
440
+ this.update((state) => {
441
+ state.providerConfig.type = type;
442
+ state.providerConfig.ticker = ticker;
443
+ state.providerConfig.chainId = controller_utils_1.ChainId[type];
444
+ state.providerConfig.rpcPrefs = controller_utils_1.BUILT_IN_NETWORKS[type].rpcPrefs;
445
+ state.providerConfig.rpcUrl = undefined;
446
+ state.providerConfig.nickname = undefined;
447
+ state.providerConfig.id = undefined;
448
+ });
449
+ yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
450
+ });
451
+ }
452
+ /**
453
+ * Convenience method to update provider RPC settings.
454
+ *
455
+ * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.
456
+ */
457
+ setActiveNetwork(networkConfigurationId) {
458
+ return __awaiter(this, void 0, void 0, function* () {
459
+ __classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
460
+ const targetNetwork = this.state.networkConfigurations[networkConfigurationId];
461
+ if (!targetNetwork) {
462
+ throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
463
+ }
464
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
465
+ this.update((state) => {
466
+ state.providerConfig.type = controller_utils_1.NetworkType.rpc;
467
+ state.providerConfig.rpcUrl = targetNetwork.rpcUrl;
468
+ state.providerConfig.chainId = targetNetwork.chainId;
469
+ state.providerConfig.ticker = targetNetwork.ticker;
470
+ state.providerConfig.nickname = targetNetwork.nickname;
471
+ state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;
472
+ state.providerConfig.id = targetNetwork.id;
473
+ });
474
+ yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
475
+ });
476
+ }
477
+ /**
478
+ * Determines whether the network supports EIP-1559 by checking whether the
479
+ * latest block has a `baseFeePerGas` property, then updates state
480
+ * appropriately.
481
+ *
482
+ * @returns A promise that resolves to true if the network supports EIP-1559
483
+ * , false otherwise, or `undefined` if unable to determine the compatibility.
484
+ */
485
+ getEIP1559Compatibility() {
486
+ return __awaiter(this, void 0, void 0, function* () {
487
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
488
+ return false;
489
+ }
490
+ const { EIPS } = this.state.networksMetadata[this.state.selectedNetworkClientId];
491
+ if (EIPS[1559] !== undefined) {
492
+ return EIPS[1559];
493
+ }
494
+ const isEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this);
495
+ this.update((state) => {
496
+ if (isEIP1559Compatible !== undefined) {
497
+ state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =
498
+ isEIP1559Compatible;
499
+ }
500
+ });
501
+ return isEIP1559Compatible;
502
+ });
503
+ }
504
+ /**
505
+ * Re-initializes the provider and block tracker for the current network.
506
+ */
507
+ resetConnection() {
508
+ return __awaiter(this, void 0, void 0, function* () {
509
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
510
+ yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
511
+ });
512
+ }
513
+ /**
514
+ * Adds a new custom network or updates the information for an existing
515
+ * network.
516
+ *
517
+ * This may involve updating the `networkConfigurations` property in
518
+ * state as well and/or adding a new network client to the network client
519
+ * registry. The `rpcUrl` and `chainId` of the given object are used to
520
+ * determine which action to take:
521
+ *
522
+ * - If the `rpcUrl` corresponds to an existing network configuration
523
+ * (case-insensitively), then it is overwritten with the object. Furthermore,
524
+ * if the `chainId` is different from the existing network configuration, then
525
+ * the existing network client is replaced with a new one.
526
+ * - If the `rpcUrl` does not correspond to an existing network configuration
527
+ * (case-insensitively), then the object is used to add a new network
528
+ * configuration along with a new network client.
529
+ *
530
+ * @param networkConfiguration - The network configuration to add or update.
531
+ * @param options - Additional configuration options.
532
+ * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.
533
+ * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).
534
+ * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).
535
+ * @returns The ID for the added or updated network configuration.
536
+ */
537
+ upsertNetworkConfiguration(networkConfiguration, { referrer, source, setActive = false, }) {
538
+ return __awaiter(this, void 0, void 0, function* () {
539
+ const sanitizedNetworkConfiguration = pick(networkConfiguration, ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs']);
540
+ const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;
541
+ (0, utils_1.assertIsStrictHexString)(chainId);
542
+ if (!(0, controller_utils_1.isSafeChainId)(chainId)) {
543
+ throw new Error(`Invalid chain ID "${chainId}": numerical value greater than max safe value.`);
544
+ }
545
+ if (!rpcUrl) {
546
+ throw new Error('An rpcUrl is required to add or update network configuration');
547
+ }
548
+ if (!referrer || !source) {
549
+ throw new Error('referrer and source are required arguments for adding or updating a network configuration');
550
+ }
551
+ try {
552
+ new URL(rpcUrl);
553
+ }
554
+ catch (e) {
555
+ if (e.message.includes('Invalid URL')) {
556
+ throw new Error('rpcUrl must be a valid URL');
557
+ }
558
+ }
559
+ if (!ticker) {
560
+ throw new Error('A ticker is required to add or update networkConfiguration');
561
+ }
562
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
563
+ const existingNetworkConfiguration = Object.values(this.state.networkConfigurations).find((networkConfig) => networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase());
564
+ const upsertedNetworkConfigurationId = existingNetworkConfiguration
565
+ ? existingNetworkConfiguration.id
566
+ : (0, uuid_1.v4)();
567
+ const networkClientId = buildCustomNetworkClientId(upsertedNetworkConfigurationId);
568
+ this.update((state) => {
569
+ state.networkConfigurations[upsertedNetworkConfigurationId] = Object.assign({ id: upsertedNetworkConfigurationId }, sanitizedNetworkConfiguration);
570
+ });
571
+ const customNetworkClientRegistry = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom];
572
+ const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
573
+ const shouldDestroyExistingNetworkClient = existingAutoManagedNetworkClient &&
574
+ existingAutoManagedNetworkClient.configuration.chainId !== chainId;
575
+ if (shouldDestroyExistingNetworkClient) {
576
+ existingAutoManagedNetworkClient.destroy();
577
+ }
578
+ if (!existingAutoManagedNetworkClient ||
579
+ shouldDestroyExistingNetworkClient) {
580
+ customNetworkClientRegistry[networkClientId] =
581
+ (0, create_auto_managed_network_client_1.createAutoManagedNetworkClient)({
582
+ type: types_1.NetworkClientType.Custom,
583
+ chainId,
584
+ rpcUrl,
585
+ });
586
+ }
587
+ if (!existingNetworkConfiguration) {
588
+ __classPrivateFieldGet(this, _NetworkController_trackMetaMetricsEvent, "f").call(this, {
589
+ event: 'Custom Network Added',
590
+ category: 'Network',
591
+ referrer: {
592
+ url: referrer,
593
+ },
594
+ properties: {
595
+ chain_id: chainId,
596
+ symbol: ticker,
597
+ source,
598
+ },
599
+ });
600
+ }
601
+ if (setActive) {
602
+ yield this.setActiveNetwork(upsertedNetworkConfigurationId);
603
+ }
604
+ return upsertedNetworkConfigurationId;
605
+ });
606
+ }
607
+ /**
608
+ * Removes a custom network from state.
609
+ *
610
+ * This involves updating the `networkConfigurations` property in state as
611
+ * well and removing the network client that corresponds to the network from
612
+ * the client registry.
613
+ *
614
+ * @param networkConfigurationId - The ID of an existing network
615
+ * configuration.
616
+ */
617
+ removeNetworkConfiguration(networkConfigurationId) {
618
+ if (!this.state.networkConfigurations[networkConfigurationId]) {
619
+ throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
620
+ }
621
+ const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
622
+ const networkClientId = buildCustomNetworkClientId(networkConfigurationId);
623
+ this.update((state) => {
624
+ delete state.networkConfigurations[networkConfigurationId];
625
+ });
626
+ const customNetworkClientRegistry = autoManagedNetworkClientRegistry[types_1.NetworkClientType.Custom];
627
+ const existingAutoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
628
+ existingAutoManagedNetworkClient.destroy();
629
+ delete customNetworkClientRegistry[networkClientId];
630
+ }
631
+ /**
632
+ * Switches to the previously selected network, assuming that there is one
633
+ * (if not and `initializeProvider` has not been previously called, then this
634
+ * method is equivalent to calling `resetConnection`).
635
+ */
636
+ rollbackToPreviousProvider() {
637
+ return __awaiter(this, void 0, void 0, function* () {
638
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
639
+ this.update((state) => {
640
+ state.providerConfig = __classPrivateFieldGet(this, _NetworkController_previousProviderConfig, "f");
641
+ });
642
+ yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
643
+ });
644
+ }
645
+ /**
646
+ * Deactivates the controller, stopping any ongoing polling.
647
+ *
648
+ * In-progress requests will not be aborted.
649
+ */
650
+ destroy() {
651
+ var _a;
652
+ return __awaiter(this, void 0, void 0, function* () {
653
+ yield ((_a = __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) === null || _a === void 0 ? void 0 : _a.destroy());
654
+ });
655
+ }
656
+ /**
657
+ * Updates the controller using the given backup data.
658
+ *
659
+ * @param backup - The data that has been backed up.
660
+ * @param backup.networkConfigurations - Network configurations in the backup.
661
+ */
662
+ loadBackup({ networkConfigurations, }) {
663
+ this.update((state) => {
664
+ state.networkConfigurations = Object.assign(Object.assign({}, state.networkConfigurations), networkConfigurations);
665
+ });
666
+ }
667
+ /**
668
+ * Searches for a network configuration ID with the given ChainID and returns it.
669
+ *
670
+ * @param chainId - ChainId to search for
671
+ * @returns networkClientId of the network configuration with the given chainId
672
+ */
673
+ findNetworkClientIdByChainId(chainId) {
674
+ const networkClients = this.getNetworkClientRegistry();
675
+ const networkClientEntry = Object.entries(networkClients).find(([_, networkClient]) => networkClient.configuration.chainId === chainId);
676
+ if (networkClientEntry === undefined) {
677
+ throw new Error("Couldn't find networkClientId for chainId");
678
+ }
679
+ return networkClientEntry[0];
680
+ }
681
+ }
682
+ exports.NetworkController = NetworkController;
683
+ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_previousProviderConfig = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_autoManagedNetworkClientRegistry = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
684
+ return __awaiter(this, void 0, void 0, function* () {
685
+ this.messagingSystem.publish('NetworkController:networkWillChange');
686
+ this.update((state) => {
687
+ state.networkId = null;
688
+ });
689
+ __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
690
+ this.messagingSystem.publish('NetworkController:networkDidChange');
691
+ yield this.lookupNetwork();
692
+ });
693
+ }, _NetworkController_getNetworkId = function _NetworkController_getNetworkId() {
694
+ return __awaiter(this, void 0, void 0, function* () {
695
+ const possibleNetworkId = yield new Promise((resolve, reject) => {
696
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
697
+ throw new Error('Provider has not been initialized');
698
+ }
699
+ __classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'net_version' }, (error, result) => {
700
+ if (error) {
701
+ reject(error);
702
+ }
703
+ else {
704
+ // TODO: Validate this type
705
+ resolve(result);
706
+ }
707
+ });
708
+ });
709
+ return convertNetworkId(possibleNetworkId);
710
+ });
711
+ }, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock() {
712
+ return new Promise((resolve, reject) => {
713
+ if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
714
+ throw new Error('Provider has not been initialized');
715
+ }
716
+ __classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
717
+ if (error) {
718
+ reject(error);
719
+ }
720
+ else {
721
+ // TODO: Validate this type
722
+ resolve(block);
723
+ }
724
+ });
725
+ });
726
+ }, _NetworkController_determineEIP1559Compatibility = function _NetworkController_determineEIP1559Compatibility() {
727
+ return __awaiter(this, void 0, void 0, function* () {
728
+ const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
729
+ if (!latestBlock) {
730
+ return undefined;
731
+ }
732
+ return latestBlock.baseFeePerGas !== undefined;
733
+ });
734
+ }, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated = function _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated() {
735
+ var _a;
736
+ const autoManagedNetworkClientRegistry = (_a = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_createAutoManagedNetworkClientRegistry).call(this);
737
+ __classPrivateFieldSet(this, _NetworkController_autoManagedNetworkClientRegistry, autoManagedNetworkClientRegistry, "f");
738
+ return autoManagedNetworkClientRegistry;
739
+ }, _NetworkController_createAutoManagedNetworkClientRegistry = function _NetworkController_createAutoManagedNetworkClientRegistry() {
740
+ return [
741
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations).call(this),
742
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedCustomNetworkClientConfigurations).call(this),
743
+ ...__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig).call(this),
744
+ ].reduce((registry, [networkClientType, networkClientId, networkClientConfiguration]) => {
745
+ const autoManagedNetworkClient = (0, create_auto_managed_network_client_1.createAutoManagedNetworkClient)(networkClientConfiguration);
746
+ if (networkClientId in registry[networkClientType]) {
747
+ return registry;
748
+ }
749
+ return Object.assign(Object.assign({}, registry), { [networkClientType]: Object.assign(Object.assign({}, registry[networkClientType]), { [networkClientId]: autoManagedNetworkClient }) });
750
+ }, {
751
+ [types_1.NetworkClientType.Infura]: {},
752
+ [types_1.NetworkClientType.Custom]: {},
753
+ });
754
+ }, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations = function _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations() {
755
+ return knownKeysOf(controller_utils_1.InfuraNetworkType).map((network) => {
756
+ const networkClientId = buildInfuraNetworkClientId(network);
757
+ const networkClientConfiguration = {
758
+ type: types_1.NetworkClientType.Infura,
759
+ network,
760
+ infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
761
+ chainId: controller_utils_1.BUILT_IN_NETWORKS[network].chainId,
762
+ };
763
+ return [
764
+ types_1.NetworkClientType.Infura,
765
+ networkClientId,
766
+ networkClientConfiguration,
767
+ ];
768
+ });
769
+ }, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations = function _NetworkController_buildIdentifiedCustomNetworkClientConfigurations() {
770
+ return Object.entries(this.state.networkConfigurations).map(([networkConfigurationId, networkConfiguration]) => {
771
+ if (networkConfiguration.chainId === undefined) {
772
+ throw new Error('chainId must be provided for custom RPC endpoints');
773
+ }
774
+ if (networkConfiguration.rpcUrl === undefined) {
775
+ throw new Error('rpcUrl must be provided for custom RPC endpoints');
776
+ }
777
+ const networkClientId = buildCustomNetworkClientId(networkConfigurationId);
778
+ const networkClientConfiguration = {
779
+ type: types_1.NetworkClientType.Custom,
780
+ chainId: networkConfiguration.chainId,
781
+ rpcUrl: networkConfiguration.rpcUrl,
782
+ };
783
+ return [
784
+ types_1.NetworkClientType.Custom,
785
+ networkClientId,
786
+ networkClientConfiguration,
787
+ ];
788
+ });
789
+ }, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig = function _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig() {
790
+ const { providerConfig } = this.state;
791
+ if (isCustomProviderConfig(providerConfig)) {
792
+ validateCustomProviderConfig(providerConfig);
793
+ const networkClientId = buildCustomNetworkClientId(providerConfig, this.state.networkConfigurations);
794
+ const networkClientConfiguration = {
795
+ chainId: providerConfig.chainId,
796
+ rpcUrl: providerConfig.rpcUrl,
797
+ type: types_1.NetworkClientType.Custom,
798
+ };
799
+ return [
800
+ [types_1.NetworkClientType.Custom, networkClientId, networkClientConfiguration],
801
+ ];
802
+ }
803
+ if (isInfuraProviderConfig(providerConfig)) {
804
+ return [];
805
+ }
806
+ throw new Error(`Unrecognized network type: '${providerConfig.type}'`);
807
+ }, _NetworkController_applyNetworkSelection = function _NetworkController_applyNetworkSelection() {
808
+ if (!__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")) {
809
+ throw new Error('initializeProvider must be called first in order to switch the network');
810
+ }
811
+ const { providerConfig } = this.state;
812
+ let autoManagedNetworkClient;
813
+ let networkClientId;
814
+ if (isInfuraProviderConfig(providerConfig)) {
815
+ const networkClientType = types_1.NetworkClientType.Infura;
816
+ networkClientId = buildInfuraNetworkClientId(providerConfig);
817
+ const builtInNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")[networkClientType];
818
+ autoManagedNetworkClient =
819
+ builtInNetworkClientRegistry[networkClientId];
820
+ if (!autoManagedNetworkClient) {
821
+ throw new Error(`Could not find custom network matching ${networkClientId}`);
822
+ }
823
+ }
824
+ else if (isCustomProviderConfig(providerConfig)) {
825
+ validateCustomProviderConfig(providerConfig);
826
+ const networkClientType = types_1.NetworkClientType.Custom;
827
+ networkClientId = buildCustomNetworkClientId(providerConfig, this.state.networkConfigurations);
828
+ const customNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f")[networkClientType];
829
+ autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];
830
+ if (!autoManagedNetworkClient) {
831
+ throw new Error(`Could not find built-in network matching ${networkClientId}`);
832
+ }
833
+ }
834
+ else {
835
+ throw new Error('Could not determine type of provider config');
836
+ }
837
+ this.update((state) => {
838
+ state.selectedNetworkClientId = networkClientId;
839
+ if (state.networksMetadata[networkClientId] === undefined) {
840
+ state.networksMetadata[networkClientId] = {
841
+ status: constants_1.NetworkStatus.Unknown,
842
+ EIPS: {},
843
+ };
844
+ }
845
+ });
846
+ const { provider, blockTracker } = autoManagedNetworkClient;
847
+ if (__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")) {
848
+ __classPrivateFieldGet(this, _NetworkController_providerProxy, "f").setTarget(provider);
849
+ }
850
+ else {
851
+ __classPrivateFieldSet(this, _NetworkController_providerProxy, (0, swappable_obj_proxy_1.createEventEmitterProxy)(provider), "f");
852
+ }
853
+ __classPrivateFieldSet(this, _NetworkController_provider, provider, "f");
854
+ if (__classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) {
855
+ __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f").setTarget(blockTracker);
856
+ }
857
+ else {
858
+ __classPrivateFieldSet(this, _NetworkController_blockTrackerProxy, (0, swappable_obj_proxy_1.createEventEmitterProxy)(blockTracker, {
859
+ eventFilter: 'skipInternal',
860
+ }), "f");
861
+ }
862
+ __classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")), "f");
863
+ };
864
+ //# sourceMappingURL=NetworkController.js.map