@metamask/network-controller 21.0.0 → 21.0.1

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