@metamask-previews/network-controller 12.1.2-preview.f71e42f → 12.2.0-preview.56ca173
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.
- package/CHANGELOG.md +10 -1
- package/dist/NetworkController.d.ts +23 -3
- package/dist/NetworkController.d.ts.map +1 -1
- package/dist/NetworkController.js +162 -12
- package/dist/NetworkController.js.map +1 -1
- package/dist/create-network-client.js +1 -0
- package/dist/create-network-client.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [12.2.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add `NetworkController:getNetworkClientById` action ([#1638](https://github.com/MetaMask/core/pull/1638))
|
|
12
|
+
- Add `lookupNetworkByClientId` and `get1555CompatibilityWithNetworkClientId` methods ([#1557](https://github.com/MetaMask/core/pull/1557))
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- Add optional `networkClientId` argument to methods `lookupNetwork` and `getEIP1559Compatibility` ([#1557](https://github.com/MetaMask/core/pull/1557))
|
|
16
|
+
|
|
9
17
|
## [12.1.2]
|
|
10
18
|
### Changed
|
|
11
19
|
- Bump dependency on `@metamask/base-controller` to ^3.2.1
|
|
@@ -245,7 +253,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
245
253
|
|
|
246
254
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
247
255
|
|
|
248
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.
|
|
256
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.2.0...HEAD
|
|
257
|
+
[12.2.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.1.2...@metamask/network-controller@12.2.0
|
|
249
258
|
[12.1.2]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.1.1...@metamask/network-controller@12.1.2
|
|
250
259
|
[12.1.1]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.1.0...@metamask/network-controller@12.1.1
|
|
251
260
|
[12.1.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@12.0.0...@metamask/network-controller@12.1.0
|
|
@@ -104,6 +104,10 @@ export declare type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClie
|
|
|
104
104
|
export declare type NetworksMetadata = {
|
|
105
105
|
[networkClientId: NetworkClientId]: NetworkMetadata;
|
|
106
106
|
};
|
|
107
|
+
/**
|
|
108
|
+
* The network ID of a network.
|
|
109
|
+
*/
|
|
110
|
+
export declare type NetworkId = `${number}`;
|
|
107
111
|
/**
|
|
108
112
|
* @type NetworkState
|
|
109
113
|
*
|
|
@@ -115,6 +119,7 @@ export declare type NetworksMetadata = {
|
|
|
115
119
|
*/
|
|
116
120
|
export declare type NetworkState = {
|
|
117
121
|
selectedNetworkClientId: NetworkClientId;
|
|
122
|
+
networkId: NetworkId | null;
|
|
118
123
|
providerConfig: ProviderConfig;
|
|
119
124
|
networkConfigurations: NetworkConfigurations;
|
|
120
125
|
networksMetadata: NetworksMetadata;
|
|
@@ -188,7 +193,11 @@ export declare type NetworkControllerGetEthQueryAction = {
|
|
|
188
193
|
type: `NetworkController:getEthQuery`;
|
|
189
194
|
handler: () => EthQuery | undefined;
|
|
190
195
|
};
|
|
191
|
-
export declare type
|
|
196
|
+
export declare type NetworkControllerGetNetworkClientByIdAction = {
|
|
197
|
+
type: `NetworkController:getNetworkClientById`;
|
|
198
|
+
handler: NetworkController['getNetworkClientById'];
|
|
199
|
+
};
|
|
200
|
+
export declare type NetworkControllerActions = NetworkControllerGetStateAction | NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction | NetworkControllerGetNetworkClientByIdAction;
|
|
192
201
|
export declare type NetworkControllerMessenger = RestrictedControllerMessenger<typeof name, NetworkControllerActions, NetworkControllerEvents, string, string>;
|
|
193
202
|
export declare type NetworkControllerOptions = {
|
|
194
203
|
messenger: NetworkControllerMessenger;
|
|
@@ -251,18 +260,27 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
|
|
|
251
260
|
* the provider configuration in state.
|
|
252
261
|
*/
|
|
253
262
|
initializeProvider(): Promise<void>;
|
|
263
|
+
/**
|
|
264
|
+
* Refreshes the network meta with EIP-1559 support and the network status
|
|
265
|
+
* based on the given network client ID.
|
|
266
|
+
*
|
|
267
|
+
* @param networkClientId - The ID of the network client to update.
|
|
268
|
+
*/
|
|
269
|
+
lookupNetworkByClientId(networkClientId: NetworkClientId): Promise<void>;
|
|
254
270
|
/**
|
|
255
271
|
* Performs side effects after switching to a network. If the network is
|
|
256
272
|
* available, updates the network state with the network ID of the network and
|
|
257
273
|
* stores whether the network supports EIP-1559; otherwise clears said
|
|
258
274
|
* information about the network that may have been previously stored.
|
|
259
275
|
*
|
|
276
|
+
* @param networkClientId - (Optional) The ID of the network client to update.
|
|
277
|
+
* If no ID is provided, uses the currently selected network.
|
|
260
278
|
* @fires infuraIsBlocked if the network is Infura-supported and is blocking
|
|
261
279
|
* requests.
|
|
262
280
|
* @fires infuraIsUnblocked if the network is Infura-supported and is not
|
|
263
281
|
* blocking requests, or if the network is not Infura-supported.
|
|
264
282
|
*/
|
|
265
|
-
lookupNetwork(): Promise<void>;
|
|
283
|
+
lookupNetwork(networkClientId?: NetworkClientId): Promise<void>;
|
|
266
284
|
/**
|
|
267
285
|
* Convenience method to update provider network type settings.
|
|
268
286
|
*
|
|
@@ -280,10 +298,12 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
|
|
|
280
298
|
* latest block has a `baseFeePerGas` property, then updates state
|
|
281
299
|
* appropriately.
|
|
282
300
|
*
|
|
301
|
+
* @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.
|
|
283
302
|
* @returns A promise that resolves to true if the network supports EIP-1559
|
|
284
303
|
* , false otherwise, or `undefined` if unable to determine the compatibility.
|
|
285
304
|
*/
|
|
286
|
-
getEIP1559Compatibility(): Promise<boolean | undefined>;
|
|
305
|
+
getEIP1559Compatibility(networkClientId?: NetworkClientId): Promise<boolean | undefined>;
|
|
306
|
+
get1555CompatibilityWithNetworkClientId(networkClientId: NetworkClientId): Promise<boolean>;
|
|
287
307
|
/**
|
|
288
308
|
* Re-initializes the provider and block tracker for the current network.
|
|
289
309
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,
|
|
1
|
+
{"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAKL,iBAAiB,EACjB,WAAW,EAEZ,MAAM,4BAA4B,CAAC;AACpC,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAE3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAS3C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAGnC,OAAO,EAAsB,aAAa,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,sCAAsC,CAAC;AAI9C,OAAO,KAAK,EACV,YAAY,EACZ,QAAQ,EACR,gCAAgC,EAChC,gCAAgC,EAEjC,MAAM,SAAS,CAAC;AAIjB;;;;;;;;;;GAUG;AACH,oBAAY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GAClB,EAAE;QACD,QAAQ,EAAE,MAAM,CAAC;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,OAAO,CAAC;KACrB,GACA,OAAO,CAAC,MAAM,CAAC;IAuGlB;;;;;;;;;OASG;IACH,0BAA0B,CAAC,sBAAsB,EAAE,MAAM;IAuBzD;;;;OAIG;IACG,0BAA0B;IAUhC;;;;OAIG;IACG,OAAO;IAIb;;;;;OAKG;IACH,UAAU,CAAC,EACT,qBAAqB,GACtB,EAAE;QACD,qBAAqB,EAAE,YAAY,CAAC,uBAAuB,CAAC,CAAC;KAC9D,GAAG,IAAI;IASR;;;;;OAKG;IACH,4BAA4B,CAAC,OAAO,EAAE,GAAG,GAAG,eAAe;CA2P5D"}
|
|
@@ -22,7 +22,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
22
22
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
23
23
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
24
24
|
};
|
|
25
|
-
var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_previousProviderConfig, _NetworkController_providerProxy, _NetworkController_provider, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_refreshNetwork, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated, _NetworkController_createAutoManagedNetworkClientRegistry, _NetworkController_buildIdentifiedInfuraNetworkClientConfigurations, _NetworkController_buildIdentifiedCustomNetworkClientConfigurations, _NetworkController_buildIdentifiedNetworkClientConfigurationsFromProviderConfig, _NetworkController_applyNetworkSelection;
|
|
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
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
27
|
exports.NetworkController = exports.defaultState = exports.knownKeysOf = void 0;
|
|
28
28
|
const base_controller_1 = require("@metamask/base-controller");
|
|
@@ -84,6 +84,26 @@ function pick(object, keys) {
|
|
|
84
84
|
assertOfType(pickedObject, () => keys.every((key) => key in pickedObject), 'The reduce did not produce an object with all of the desired keys.');
|
|
85
85
|
return pickedObject;
|
|
86
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
|
+
}
|
|
87
107
|
/**
|
|
88
108
|
* Type guard for determining whether the given value is an error object with a
|
|
89
109
|
* `code` property, such as an instance of Error.
|
|
@@ -190,6 +210,7 @@ function validateCustomProviderConfig(providerConfig) {
|
|
|
190
210
|
const name = 'NetworkController';
|
|
191
211
|
exports.defaultState = {
|
|
192
212
|
selectedNetworkClientId: controller_utils_1.NetworkType.mainnet,
|
|
213
|
+
networkId: null,
|
|
193
214
|
providerConfig: {
|
|
194
215
|
type: controller_utils_1.NetworkType.mainnet,
|
|
195
216
|
chainId: controller_utils_1.ChainId.mainnet,
|
|
@@ -210,6 +231,10 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
210
231
|
persist: true,
|
|
211
232
|
anonymous: false,
|
|
212
233
|
},
|
|
234
|
+
networkId: {
|
|
235
|
+
persist: true,
|
|
236
|
+
anonymous: false,
|
|
237
|
+
},
|
|
213
238
|
networksMetadata: {
|
|
214
239
|
persist: true,
|
|
215
240
|
anonymous: false,
|
|
@@ -246,6 +271,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
246
271
|
this.messagingSystem.registerActionHandler(`${this.name}:getEthQuery`, () => {
|
|
247
272
|
return __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
|
|
248
273
|
});
|
|
274
|
+
this.messagingSystem.registerActionHandler(`${this.name}:getNetworkClientById`, this.getNetworkClientById.bind(this));
|
|
249
275
|
__classPrivateFieldSet(this, _NetworkController_previousProviderConfig, this.state.providerConfig, "f");
|
|
250
276
|
}
|
|
251
277
|
/**
|
|
@@ -300,19 +326,93 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
300
326
|
yield this.lookupNetwork();
|
|
301
327
|
});
|
|
302
328
|
}
|
|
329
|
+
/**
|
|
330
|
+
* Refreshes the network meta with EIP-1559 support and the network status
|
|
331
|
+
* based on the given network client ID.
|
|
332
|
+
*
|
|
333
|
+
* @param networkClientId - The ID of the network client to update.
|
|
334
|
+
*/
|
|
335
|
+
lookupNetworkByClientId(networkClientId) {
|
|
336
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
337
|
+
const isInfura = isInfuraProviderType(networkClientId);
|
|
338
|
+
let updatedNetworkStatus;
|
|
339
|
+
let updatedIsEIP1559Compatible;
|
|
340
|
+
try {
|
|
341
|
+
updatedIsEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this, networkClientId);
|
|
342
|
+
updatedNetworkStatus = constants_1.NetworkStatus.Available;
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (isErrorWithCode(error)) {
|
|
346
|
+
let responseBody;
|
|
347
|
+
if (isInfura &&
|
|
348
|
+
(0, utils_1.hasProperty)(error, 'message') &&
|
|
349
|
+
typeof error.message === 'string') {
|
|
350
|
+
try {
|
|
351
|
+
responseBody = JSON.parse(error.message);
|
|
352
|
+
}
|
|
353
|
+
catch (_a) {
|
|
354
|
+
// error.message must not be JSON
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if ((0, utils_1.isPlainObject)(responseBody) &&
|
|
358
|
+
responseBody.error === constants_1.INFURA_BLOCKED_KEY) {
|
|
359
|
+
updatedNetworkStatus = constants_1.NetworkStatus.Blocked;
|
|
360
|
+
}
|
|
361
|
+
else if (error.code === eth_rpc_errors_1.errorCodes.rpc.internal) {
|
|
362
|
+
updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
updatedNetworkStatus = constants_1.NetworkStatus.Unavailable;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
else if (typeof Error !== 'undefined' &&
|
|
369
|
+
(0, utils_1.hasProperty)(error, 'message') &&
|
|
370
|
+
typeof error.message === 'string' &&
|
|
371
|
+
error.message.includes('No custom network client was found with the ID')) {
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
log('NetworkController - could not determine network status', error);
|
|
376
|
+
updatedNetworkStatus = constants_1.NetworkStatus.Unknown;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
this.update((state) => {
|
|
380
|
+
if (state.networksMetadata[networkClientId] === undefined) {
|
|
381
|
+
state.networksMetadata[networkClientId] = {
|
|
382
|
+
status: constants_1.NetworkStatus.Unknown,
|
|
383
|
+
EIPS: {},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
const meta = state.networksMetadata[networkClientId];
|
|
387
|
+
meta.status = updatedNetworkStatus;
|
|
388
|
+
if (updatedIsEIP1559Compatible === undefined) {
|
|
389
|
+
delete meta.EIPS[1559];
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
meta.EIPS[1559] = updatedIsEIP1559Compatible;
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
}
|
|
303
397
|
/**
|
|
304
398
|
* Performs side effects after switching to a network. If the network is
|
|
305
399
|
* available, updates the network state with the network ID of the network and
|
|
306
400
|
* stores whether the network supports EIP-1559; otherwise clears said
|
|
307
401
|
* information about the network that may have been previously stored.
|
|
308
402
|
*
|
|
403
|
+
* @param networkClientId - (Optional) The ID of the network client to update.
|
|
404
|
+
* If no ID is provided, uses the currently selected network.
|
|
309
405
|
* @fires infuraIsBlocked if the network is Infura-supported and is blocking
|
|
310
406
|
* requests.
|
|
311
407
|
* @fires infuraIsUnblocked if the network is Infura-supported and is not
|
|
312
408
|
* blocking requests, or if the network is not Infura-supported.
|
|
313
409
|
*/
|
|
314
|
-
lookupNetwork() {
|
|
410
|
+
lookupNetwork(networkClientId) {
|
|
315
411
|
return __awaiter(this, void 0, void 0, function* () {
|
|
412
|
+
if (networkClientId) {
|
|
413
|
+
yield this.lookupNetworkByClientId(networkClientId);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
316
416
|
if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
317
417
|
return;
|
|
318
418
|
}
|
|
@@ -324,10 +424,15 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
324
424
|
};
|
|
325
425
|
this.messagingSystem.subscribe('NetworkController:networkDidChange', listener);
|
|
326
426
|
let updatedNetworkStatus;
|
|
427
|
+
let updatedNetworkId = null;
|
|
327
428
|
let updatedIsEIP1559Compatible;
|
|
328
429
|
try {
|
|
329
|
-
const isEIP1559Compatible = yield
|
|
430
|
+
const [networkId, isEIP1559Compatible] = yield Promise.all([
|
|
431
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this, this.state.selectedNetworkClientId),
|
|
432
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this, this.state.selectedNetworkClientId),
|
|
433
|
+
]);
|
|
330
434
|
updatedNetworkStatus = constants_1.NetworkStatus.Available;
|
|
435
|
+
updatedNetworkId = networkId;
|
|
331
436
|
updatedIsEIP1559Compatible = isEIP1559Compatible;
|
|
332
437
|
}
|
|
333
438
|
catch (error) {
|
|
@@ -366,6 +471,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
366
471
|
}
|
|
367
472
|
this.messagingSystem.unsubscribe('NetworkController:networkDidChange', listener);
|
|
368
473
|
this.update((state) => {
|
|
474
|
+
state.networkId = updatedNetworkId;
|
|
369
475
|
const meta = state.networksMetadata[state.selectedNetworkClientId];
|
|
370
476
|
meta.status = updatedNetworkStatus;
|
|
371
477
|
if (updatedIsEIP1559Compatible === undefined) {
|
|
@@ -448,11 +554,15 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
448
554
|
* latest block has a `baseFeePerGas` property, then updates state
|
|
449
555
|
* appropriately.
|
|
450
556
|
*
|
|
557
|
+
* @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.
|
|
451
558
|
* @returns A promise that resolves to true if the network supports EIP-1559
|
|
452
559
|
* , false otherwise, or `undefined` if unable to determine the compatibility.
|
|
453
560
|
*/
|
|
454
|
-
getEIP1559Compatibility() {
|
|
561
|
+
getEIP1559Compatibility(networkClientId) {
|
|
455
562
|
return __awaiter(this, void 0, void 0, function* () {
|
|
563
|
+
if (networkClientId) {
|
|
564
|
+
return this.get1555CompatibilityWithNetworkClientId(networkClientId);
|
|
565
|
+
}
|
|
456
566
|
if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
457
567
|
return false;
|
|
458
568
|
}
|
|
@@ -460,7 +570,7 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
460
570
|
if (EIPS[1559] !== undefined) {
|
|
461
571
|
return EIPS[1559];
|
|
462
572
|
}
|
|
463
|
-
const isEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this);
|
|
573
|
+
const isEIP1559Compatible = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this, this.state.selectedNetworkClientId);
|
|
464
574
|
this.update((state) => {
|
|
465
575
|
if (isEIP1559Compatible !== undefined) {
|
|
466
576
|
state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =
|
|
@@ -470,6 +580,18 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
470
580
|
return isEIP1559Compatible;
|
|
471
581
|
});
|
|
472
582
|
}
|
|
583
|
+
get1555CompatibilityWithNetworkClientId(networkClientId) {
|
|
584
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
585
|
+
let metadata = this.state.networksMetadata[networkClientId];
|
|
586
|
+
if (metadata === undefined) {
|
|
587
|
+
yield this.lookupNetwork(networkClientId);
|
|
588
|
+
metadata = this.state.networksMetadata[networkClientId];
|
|
589
|
+
}
|
|
590
|
+
const { EIPS } = metadata;
|
|
591
|
+
// may want to include some 'freshness' value - something to make sure we refetch this from time to time
|
|
592
|
+
return EIPS[1559];
|
|
593
|
+
});
|
|
594
|
+
}
|
|
473
595
|
/**
|
|
474
596
|
* Re-initializes the provider and block tracker for the current network.
|
|
475
597
|
*/
|
|
@@ -652,16 +774,44 @@ exports.NetworkController = NetworkController;
|
|
|
652
774
|
_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() {
|
|
653
775
|
return __awaiter(this, void 0, void 0, function* () {
|
|
654
776
|
this.messagingSystem.publish('NetworkController:networkWillChange');
|
|
777
|
+
this.update((state) => {
|
|
778
|
+
state.networkId = null;
|
|
779
|
+
});
|
|
655
780
|
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this);
|
|
656
781
|
this.messagingSystem.publish('NetworkController:networkDidChange');
|
|
657
782
|
yield this.lookupNetwork();
|
|
658
783
|
});
|
|
659
|
-
},
|
|
784
|
+
}, _NetworkController_getNetworkId = function _NetworkController_getNetworkId(networkClientId) {
|
|
785
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
786
|
+
const possibleNetworkId = yield new Promise((resolve, reject) => {
|
|
787
|
+
let ethQuery = __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
|
|
788
|
+
if (networkClientId) {
|
|
789
|
+
const networkClient = this.getNetworkClientById(networkClientId);
|
|
790
|
+
ethQuery = new eth_query_1.default(networkClient.provider);
|
|
791
|
+
}
|
|
792
|
+
if (!ethQuery) {
|
|
793
|
+
throw new Error('Provider has not been initialized');
|
|
794
|
+
}
|
|
795
|
+
ethQuery.sendAsync({ method: 'net_version' }, (error, result) => {
|
|
796
|
+
if (error) {
|
|
797
|
+
reject(error);
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
// TODO: Validate this type
|
|
801
|
+
resolve(result);
|
|
802
|
+
}
|
|
803
|
+
});
|
|
804
|
+
});
|
|
805
|
+
return convertNetworkId(possibleNetworkId);
|
|
806
|
+
});
|
|
807
|
+
}, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock(networkClientId) {
|
|
808
|
+
if (networkClientId === undefined) {
|
|
809
|
+
networkClientId = this.state.selectedNetworkClientId;
|
|
810
|
+
}
|
|
811
|
+
const networkClient = this.getNetworkClientById(networkClientId);
|
|
812
|
+
const ethQuery = new eth_query_1.default(networkClient.provider);
|
|
660
813
|
return new Promise((resolve, reject) => {
|
|
661
|
-
|
|
662
|
-
throw new Error('Provider has not been initialized');
|
|
663
|
-
}
|
|
664
|
-
__classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
|
|
814
|
+
ethQuery.sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
|
|
665
815
|
if (error) {
|
|
666
816
|
reject(error);
|
|
667
817
|
}
|
|
@@ -671,9 +821,9 @@ _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId
|
|
|
671
821
|
}
|
|
672
822
|
});
|
|
673
823
|
});
|
|
674
|
-
}, _NetworkController_determineEIP1559Compatibility = function _NetworkController_determineEIP1559Compatibility() {
|
|
824
|
+
}, _NetworkController_determineEIP1559Compatibility = function _NetworkController_determineEIP1559Compatibility(networkClientId) {
|
|
675
825
|
return __awaiter(this, void 0, void 0, function* () {
|
|
676
|
-
const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
|
|
826
|
+
const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this, networkClientId);
|
|
677
827
|
if (!latestBlock) {
|
|
678
828
|
return undefined;
|
|
679
829
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA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SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { errorCodes } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Returns whether the given argument is a type that our Infura middleware\n * recognizes.\n *\n * @param type - A type to compare.\n * @returns True or false, depending on whether the given type is one that our\n * Infura middleware recognizes.\n */\nfunction isInfuraProviderType(type: string): type is InfuraNetworkType {\n return Object.keys(InfuraNetworkType).includes(type);\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraProviderType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = {\n type: `NetworkController:getState`;\n handler: () => NetworkState;\n};\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraProviderType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish('NetworkController:networkWillChange');\n this.#applyNetworkSelection();\n this.messagingSystem.publish('NetworkController:networkDidChange');\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork() {\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility();\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraProviderType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(): Promise<Block> {\n return new Promise((resolve, reject) => {\n if (!this.#ethQuery) {\n throw new Error('Provider has not been initialized');\n }\n\n this.#ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility() {\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility();\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock();\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,+DAA6D;AAC7D,iEAQoC;AACpC,oEAA2C;AA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BAAwB,EAAE;YAC7B,MAAM,IAAI,KAAK,CACb,4CAA4C,eAAe,EAAE,CAC9D,CAAC;SACH;KACF;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAChE;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,uBAAuB,GAAG,eAAe,CAAC;QAChD,IAAI,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE;YACzD,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,GAAG;gBACxC,MAAM,EAAE,yBAAa,CAAC,OAAO;gBAC7B,IAAI,EAAE,EAAE;aACT,CAAC;SACH;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,wBAAwB,CAAC;IAE5D,IAAI,uBAAA,IAAI,wCAAe,EAAE;QACvB,uBAAA,IAAI,wCAAe,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;KACzC;SAAM;QACL,uBAAA,IAAI,oCAAkB,IAAA,6CAAuB,EAAC,QAAQ,CAAC,MAAA,CAAC;KACzD;IACD,uBAAA,IAAI,+BAAa,QAAQ,MAAA,CAAC;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;IAED,uBAAA,IAAI,+BAAa,IAAI,mBAAQ,CAAC,uBAAA,IAAI,wCAAe,CAAC,MAAA,CAAC;AACrD,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n convertHexToDecimal,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n isStrictHexString,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { errorCodes } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Convert the given value into a valid network ID. The ID is accepted\n * as either a number, a decimal string, or a 0x-prefixed hex string.\n *\n * @param value - The network ID to convert, in an unknown format.\n * @returns A valid network ID (as a decimal string)\n * @throws If the given value cannot be safely parsed.\n */\nfunction convertNetworkId(value: unknown): NetworkId {\n if (typeof value === 'number' && !Number.isNaN(value)) {\n return `${value}`;\n } else if (isStrictHexString(value)) {\n return `${convertHexToDecimal(value)}`;\n } else if (typeof value === 'string' && /^\\d+$/u.test(value)) {\n return value as NetworkId;\n }\n throw new Error(`Cannot parse as a valid network ID: '${value}'`);\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Returns whether the given argument is a type that our Infura middleware\n * recognizes.\n *\n * @param type - A type to compare.\n * @returns True or false, depending on whether the given type is one that our\n * Infura middleware recognizes.\n */\nfunction isInfuraProviderType(type: string): type is InfuraNetworkType {\n return Object.keys(InfuraNetworkType).includes(type);\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraProviderType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * The network ID of a network.\n */\nexport type NetworkId = `${number}`;\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n networkId: NetworkId | null;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = {\n type: `NetworkController:getState`;\n handler: () => NetworkState;\n};\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n networkId: null,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #provider: ProxyWithAccessibleTarget<Provider> | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networkId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns The proxy and block tracker proxies.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraProviderType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish('NetworkController:networkWillChange');\n this.update((state) => {\n state.networkId = null;\n });\n this.#applyNetworkSelection();\n this.messagingSystem.publish('NetworkController:networkDidChange');\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Fetches the network ID for the network, ensuring that it is a hex string.\n *\n * @param networkClientId - The ID of the network client to fetch the network\n * @returns A promise that either resolves to the network ID, or rejects with\n * an error.\n * @throws If the network ID of the network is not a valid hex string.\n */\n async #getNetworkId(networkClientId: NetworkClientId): Promise<NetworkId> {\n const possibleNetworkId = await new Promise<string>((resolve, reject) => {\n let ethQuery = this.#ethQuery;\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n ethQuery = new EthQuery(networkClient.provider);\n }\n if (!ethQuery) {\n throw new Error('Provider has not been initialized');\n }\n\n ethQuery.sendAsync(\n { method: 'net_version' },\n (error: unknown, result?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(result as string);\n }\n },\n );\n });\n\n return convertNetworkId(possibleNetworkId);\n }\n\n /**\n * Refreshes the network meta with EIP-1559 support and the network status\n * based on the given network client ID.\n *\n * @param networkClientId - The ID of the network client to update.\n */\n async lookupNetworkByClientId(networkClientId: NetworkClientId) {\n const isInfura = isInfuraProviderType(networkClientId);\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n updatedIsEIP1559Compatible = await this.#determineEIP1559Compatibility(\n networkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else if (\n typeof Error !== 'undefined' &&\n hasProperty(error as unknown as Error, 'message') &&\n typeof (error as unknown as Error).message === 'string' &&\n (error as unknown as Error).message.includes(\n 'No custom network client was found with the ID',\n )\n ) {\n throw error;\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n this.update((state) => {\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n const meta = state.networksMetadata[networkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @param networkClientId - (Optional) The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n await this.lookupNetworkByClientId(networkClientId);\n return;\n }\n\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedNetworkId: NetworkId | null = null;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const [networkId, isEIP1559Compatible] = await Promise.all([\n this.#getNetworkId(this.state.selectedNetworkClientId),\n this.#determineEIP1559Compatibility(this.state.selectedNetworkClientId),\n ]);\n updatedNetworkStatus = NetworkStatus.Available;\n updatedNetworkId = networkId;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n state.networkId = updatedNetworkId;\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraProviderType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = ChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcUrl = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcUrl = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(networkClientId: NetworkClientId): Promise<Block> {\n if (networkClientId === undefined) {\n networkClientId = this.state.selectedNetworkClientId;\n }\n\n const networkClient = this.getNetworkClientById(networkClientId);\n const ethQuery = new EthQuery(networkClient.provider);\n\n return new Promise((resolve, reject) => {\n ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n return this.get1555CompatibilityWithNetworkClientId(networkClientId);\n }\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n async get1555CompatibilityWithNetworkClientId(\n networkClientId: NetworkClientId,\n ) {\n let metadata = this.state.networksMetadata[networkClientId];\n if (metadata === undefined) {\n await this.lookupNetwork(networkClientId);\n metadata = this.state.networksMetadata[networkClientId];\n }\n const { EIPS } = metadata;\n\n // may want to include some 'freshness' value - something to make sure we refetch this from time to time\n return EIPS[1559];\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(\n networkClientId: NetworkClientId,\n ): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock(networkClientId);\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n });\n }\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
|
|
@@ -96,6 +96,7 @@ function createInfuraNetworkMiddleware({ blockTracker, network, rpcProvider, rpc
|
|
|
96
96
|
function createNetworkAndChainIdMiddleware({ network, }) {
|
|
97
97
|
return (0, json_rpc_engine_1.createScaffoldMiddleware)({
|
|
98
98
|
eth_chainId: controller_utils_1.ChainId[network],
|
|
99
|
+
net_version: controller_utils_1.NetworkId[network],
|
|
99
100
|
});
|
|
100
101
|
}
|
|
101
102
|
const createChainIdMiddleware = (chainId) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-network-client.js","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,
|
|
1
|
+
{"version":3,"file":"create-network-client.js","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAAgE;AAChE,uEAAuE;AACvE,+EAQ2C;AAE3C,2EAGyC;AAEzC,yDAAwD;AACxD,qDAKyB;AAQzB,mCAA4C;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,aAAyC;IAEzC,MAAM,gBAAgB,GACpB,aAAa,CAAC,IAAI,KAAK,yBAAiB,CAAC,MAAM;QAC7C,CAAC,CAAC,IAAA,4CAAsB,EAAC;YACrB,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,eAAe;YACxC,WAAW,EAAE,CAAC;YACd,MAAM,EAAE,UAAU;SACnB,CAA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AA,iCAAe,EAAC;QACrB,GAAG,eAAe;QAClB,uBAAuB,CAAC,OAAO,CAAC;QAChC,IAAA,yDAA+B,EAAC,EAAE,YAAY,EAAE,CAAC;QACjD,IAAA,oDAA0B,EAAC,EAAE,YAAY,EAAE,CAAC;QAC5C,IAAA,uDAA6B,GAAE;QAC/B,IAAA,+DAAqC,EAAC,EAAE,YAAY,EAAE,CAAC;QACvD,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,IAAA,uCAAqB,EAAC,CAAO,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;SACjE;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { InfuraNetworkType } from '@metamask/controller-utils';\nimport { ChainId, NetworkId } from '@metamask/controller-utils';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport type { Hex } from '@metamask/utils';\nimport { PollingBlockTracker } from 'eth-block-tracker';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from 'json-rpc-engine';\nimport type { JsonRpcMiddleware } from 'json-rpc-engine';\n\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param networkConfig - The network configuration.\n * @returns The network client.\n */\nexport function createNetworkClient(\n networkConfig: NetworkClientConfiguration,\n): NetworkClient {\n const rpcApiMiddleware =\n networkConfig.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n network: networkConfig.network,\n projectId: networkConfig.infuraProjectId,\n maxAttempts: 5,\n source: 'metamask',\n })\n : createFetchMiddleware({\n btoa: global.btoa,\n fetch: global.fetch,\n rpcUrl: networkConfig.rpcUrl,\n });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTrackerOpts =\n // eslint-disable-next-line n/no-process-env\n process.env.IN_TEST && networkConfig.type === 'custom'\n ? { pollingInterval: SECOND }\n : {};\n const blockTracker = new PollingBlockTracker({\n ...blockTrackerOpts,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n networkConfig.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: networkConfig.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: networkConfig.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider = providerFromEngine(engine);\n\n const destroy = () => {\n blockTracker.destroy();\n };\n\n return { configuration: networkConfig, provider, blockTracker, destroy };\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: SafeEventEmitterProvider;\n rpcApiMiddleware: JsonRpcMiddleware<unknown, unknown>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements eth_chainId & net_version methods.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n net_version: NetworkId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<unknown, unknown> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: any;\n}) {\n // eslint-disable-next-line n/no-process-env\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/network-controller",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.2.0-preview.56ca173",
|
|
4
4
|
"description": "Provides an interface to the currently selected network via a MetaMask-compatible provider object",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"@metamask/base-controller": "^3.2.1",
|
|
32
32
|
"@metamask/controller-utils": "^4.3.2",
|
|
33
33
|
"@metamask/eth-json-rpc-infura": "^8.1.1",
|
|
34
|
-
"@metamask/eth-json-rpc-middleware": "^11.0.
|
|
34
|
+
"@metamask/eth-json-rpc-middleware": "^11.0.2",
|
|
35
35
|
"@metamask/eth-json-rpc-provider": "^1.0.0",
|
|
36
36
|
"@metamask/eth-query": "^3.0.1",
|
|
37
37
|
"@metamask/swappable-obj-proxy": "^2.1.0",
|