@metamask-previews/network-controller 36.0.0-preview-abca9bcea → 37.0.0-preview-0a30e47

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 (158) hide show
  1. package/CHANGELOG.md +24 -4
  2. package/dist/{NetworkController-method-action-types.d.mts → NetworkController-method-action-types.d.ts} +2 -2
  3. package/dist/NetworkController-method-action-types.d.ts.map +1 -0
  4. package/dist/{NetworkController-method-action-types.mjs → NetworkController-method-action-types.js} +1 -1
  5. package/dist/NetworkController-method-action-types.js.map +1 -0
  6. package/dist/{NetworkController.d.cts → NetworkController.d.ts} +37 -29
  7. package/dist/NetworkController.d.ts.map +1 -0
  8. package/dist/{NetworkController.mjs → NetworkController.js} +716 -612
  9. package/dist/NetworkController.js.map +1 -0
  10. package/dist/{constants.d.cts → constants.d.ts} +1 -1
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/{constants.mjs → constants.js} +1 -1
  13. package/dist/constants.js.map +1 -0
  14. package/dist/{create-auto-managed-network-client.d.cts → create-auto-managed-network-client.d.ts} +7 -7
  15. package/dist/create-auto-managed-network-client.d.ts.map +1 -0
  16. package/dist/{create-auto-managed-network-client.mjs → create-auto-managed-network-client.js} +4 -4
  17. package/dist/create-auto-managed-network-client.js.map +1 -0
  18. package/dist/{create-network-client.d.cts → create-network-client.d.ts} +7 -7
  19. package/dist/create-network-client.d.ts.map +1 -0
  20. package/dist/{create-network-client.mjs → create-network-client.js} +17 -14
  21. package/dist/create-network-client.js.map +1 -0
  22. package/dist/{index.d.cts → index.d.ts} +16 -16
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +6 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/logger.d.ts +4 -0
  27. package/dist/logger.d.ts.map +1 -0
  28. package/dist/logger.js +4 -0
  29. package/dist/logger.js.map +1 -0
  30. package/dist/rpc-service/{abstract-rpc-service.d.cts → abstract-rpc-service.d.ts} +2 -2
  31. package/dist/rpc-service/abstract-rpc-service.d.ts.map +1 -0
  32. package/dist/rpc-service/abstract-rpc-service.js +2 -0
  33. package/dist/rpc-service/abstract-rpc-service.js.map +1 -0
  34. package/dist/rpc-service/{rpc-service-chain.d.cts → rpc-service-chain.d.ts} +6 -6
  35. package/dist/rpc-service/rpc-service-chain.d.ts.map +1 -0
  36. package/dist/rpc-service/{rpc-service-chain.mjs → rpc-service-chain.js} +57 -70
  37. package/dist/rpc-service/rpc-service-chain.js.map +1 -0
  38. package/dist/rpc-service/{rpc-service-requestable.d.cts → rpc-service-requestable.d.ts} +4 -4
  39. package/dist/rpc-service/rpc-service-requestable.d.ts.map +1 -0
  40. package/dist/rpc-service/rpc-service-requestable.js +2 -0
  41. package/dist/rpc-service/rpc-service-requestable.js.map +1 -0
  42. package/dist/rpc-service/{rpc-service.d.mts → rpc-service.d.ts} +6 -6
  43. package/dist/rpc-service/rpc-service.d.ts.map +1 -0
  44. package/dist/rpc-service/{rpc-service.mjs → rpc-service.js} +206 -197
  45. package/dist/rpc-service/rpc-service.js.map +1 -0
  46. package/dist/rpc-service/{shared.d.cts → shared.d.ts} +2 -2
  47. package/dist/rpc-service/shared.d.ts.map +1 -0
  48. package/dist/rpc-service/shared.js +2 -0
  49. package/dist/rpc-service/shared.js.map +1 -0
  50. package/dist/{rpc-service-analytics.d.mts → rpc-service-analytics.d.ts} +3 -3
  51. package/dist/rpc-service-analytics.d.ts.map +1 -0
  52. package/dist/{rpc-service-analytics.mjs → rpc-service-analytics.js} +4 -4
  53. package/dist/rpc-service-analytics.js.map +1 -0
  54. package/dist/{selectors.d.mts → selectors.d.ts} +2 -2
  55. package/dist/selectors.d.ts.map +1 -0
  56. package/dist/{selectors.mjs → selectors.js} +1 -1
  57. package/dist/selectors.js.map +1 -0
  58. package/dist/{types.d.cts → types.d.ts} +5 -5
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/{types.mjs → types.js} +1 -1
  61. package/dist/types.js.map +1 -0
  62. package/package.json +26 -30
  63. package/dist/NetworkController-method-action-types.cjs +0 -7
  64. package/dist/NetworkController-method-action-types.cjs.map +0 -1
  65. package/dist/NetworkController-method-action-types.d.cts +0 -268
  66. package/dist/NetworkController-method-action-types.d.cts.map +0 -1
  67. package/dist/NetworkController-method-action-types.d.mts.map +0 -1
  68. package/dist/NetworkController-method-action-types.mjs.map +0 -1
  69. package/dist/NetworkController.cjs +0 -1597
  70. package/dist/NetworkController.cjs.map +0 -1
  71. package/dist/NetworkController.d.cts.map +0 -1
  72. package/dist/NetworkController.d.mts +0 -956
  73. package/dist/NetworkController.d.mts.map +0 -1
  74. package/dist/NetworkController.mjs.map +0 -1
  75. package/dist/constants.cjs +0 -46
  76. package/dist/constants.cjs.map +0 -1
  77. package/dist/constants.d.cts.map +0 -1
  78. package/dist/constants.d.mts +0 -42
  79. package/dist/constants.d.mts.map +0 -1
  80. package/dist/constants.mjs.map +0 -1
  81. package/dist/create-auto-managed-network-client.cjs +0 -149
  82. package/dist/create-auto-managed-network-client.cjs.map +0 -1
  83. package/dist/create-auto-managed-network-client.d.cts.map +0 -1
  84. package/dist/create-auto-managed-network-client.d.mts +0 -74
  85. package/dist/create-auto-managed-network-client.d.mts.map +0 -1
  86. package/dist/create-auto-managed-network-client.mjs.map +0 -1
  87. package/dist/create-network-client.cjs +0 -439
  88. package/dist/create-network-client.cjs.map +0 -1
  89. package/dist/create-network-client.d.cts.map +0 -1
  90. package/dist/create-network-client.d.mts +0 -60
  91. package/dist/create-network-client.d.mts.map +0 -1
  92. package/dist/create-network-client.mjs.map +0 -1
  93. package/dist/index.cjs +0 -31
  94. package/dist/index.cjs.map +0 -1
  95. package/dist/index.d.cts.map +0 -1
  96. package/dist/index.d.mts +0 -16
  97. package/dist/index.d.mts.map +0 -1
  98. package/dist/index.mjs +0 -6
  99. package/dist/index.mjs.map +0 -1
  100. package/dist/logger.cjs +0 -7
  101. package/dist/logger.cjs.map +0 -1
  102. package/dist/logger.d.cts +0 -5
  103. package/dist/logger.d.cts.map +0 -1
  104. package/dist/logger.d.mts +0 -5
  105. package/dist/logger.d.mts.map +0 -1
  106. package/dist/logger.mjs +0 -4
  107. package/dist/logger.mjs.map +0 -1
  108. package/dist/rpc-service/abstract-rpc-service.cjs +0 -3
  109. package/dist/rpc-service/abstract-rpc-service.cjs.map +0 -1
  110. package/dist/rpc-service/abstract-rpc-service.d.cts.map +0 -1
  111. package/dist/rpc-service/abstract-rpc-service.d.mts +0 -17
  112. package/dist/rpc-service/abstract-rpc-service.d.mts.map +0 -1
  113. package/dist/rpc-service/abstract-rpc-service.mjs +0 -2
  114. package/dist/rpc-service/abstract-rpc-service.mjs.map +0 -1
  115. package/dist/rpc-service/rpc-service-chain.cjs +0 -304
  116. package/dist/rpc-service/rpc-service-chain.cjs.map +0 -1
  117. package/dist/rpc-service/rpc-service-chain.d.cts.map +0 -1
  118. package/dist/rpc-service/rpc-service-chain.d.mts +0 -169
  119. package/dist/rpc-service/rpc-service-chain.d.mts.map +0 -1
  120. package/dist/rpc-service/rpc-service-chain.mjs.map +0 -1
  121. package/dist/rpc-service/rpc-service-requestable.cjs +0 -3
  122. package/dist/rpc-service/rpc-service-requestable.cjs.map +0 -1
  123. package/dist/rpc-service/rpc-service-requestable.d.cts.map +0 -1
  124. package/dist/rpc-service/rpc-service-requestable.d.mts +0 -63
  125. package/dist/rpc-service/rpc-service-requestable.d.mts.map +0 -1
  126. package/dist/rpc-service/rpc-service-requestable.mjs +0 -2
  127. package/dist/rpc-service/rpc-service-requestable.mjs.map +0 -1
  128. package/dist/rpc-service/rpc-service.cjs +0 -540
  129. package/dist/rpc-service/rpc-service.cjs.map +0 -1
  130. package/dist/rpc-service/rpc-service.d.cts +0 -247
  131. package/dist/rpc-service/rpc-service.d.cts.map +0 -1
  132. package/dist/rpc-service/rpc-service.d.mts.map +0 -1
  133. package/dist/rpc-service/rpc-service.mjs.map +0 -1
  134. package/dist/rpc-service/shared.cjs +0 -3
  135. package/dist/rpc-service/shared.cjs.map +0 -1
  136. package/dist/rpc-service/shared.d.cts.map +0 -1
  137. package/dist/rpc-service/shared.d.mts +0 -32
  138. package/dist/rpc-service/shared.d.mts.map +0 -1
  139. package/dist/rpc-service/shared.mjs +0 -2
  140. package/dist/rpc-service/shared.mjs.map +0 -1
  141. package/dist/rpc-service-analytics.cjs +0 -180
  142. package/dist/rpc-service-analytics.cjs.map +0 -1
  143. package/dist/rpc-service-analytics.d.cts +0 -85
  144. package/dist/rpc-service-analytics.d.cts.map +0 -1
  145. package/dist/rpc-service-analytics.d.mts.map +0 -1
  146. package/dist/rpc-service-analytics.mjs.map +0 -1
  147. package/dist/selectors.cjs +0 -16
  148. package/dist/selectors.cjs.map +0 -1
  149. package/dist/selectors.d.cts +0 -22
  150. package/dist/selectors.d.cts.map +0 -1
  151. package/dist/selectors.d.mts.map +0 -1
  152. package/dist/selectors.mjs.map +0 -1
  153. package/dist/types.cjs +0 -12
  154. package/dist/types.cjs.map +0 -1
  155. package/dist/types.d.cts.map +0 -1
  156. package/dist/types.d.mts +0 -49
  157. package/dist/types.d.mts.map +0 -1
  158. package/dist/types.mjs.map +0 -1
@@ -1,1597 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
26
- if (kind === "m") throw new TypeError("Private method is not writable");
27
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
28
- 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");
29
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
30
- };
31
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
32
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
33
- 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");
34
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
35
- };
36
- var __importDefault = (this && this.__importDefault) || function (mod) {
37
- return (mod && mod.__esModule) ? mod : { "default": mod };
38
- };
39
- var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_failoverUrls, _NetworkController_previouslySelectedNetworkClientId, _NetworkController_providerProxy, _NetworkController_blockTrackerProxy, _NetworkController_autoManagedNetworkClientRegistry, _NetworkController_autoManagedNetworkClient, _NetworkController_log, _NetworkController_getRpcServiceOptions, _NetworkController_getBlockTrackerOptions, _NetworkController_analyticsOptions, _NetworkController_networkConfigurationsByNetworkClientId, _NetworkController_rpcFailoverMode, _NetworkController_updateRpcFailover, _NetworkController_refreshNetwork, _NetworkController_determineNetworkMetadata, _NetworkController_lookupGivenNetwork, _NetworkController_lookupSelectedNetwork, _NetworkController_updateMetadataForNetwork, _NetworkController_getLatestBlock, _NetworkController_determineEIP1559Compatibility, _NetworkController_validateNetworkFields, _NetworkController_determineNetworkConfigurationToPersist, _NetworkController_registerNetworkClientsAsNeeded, _NetworkController_unregisterNetworkClientsAsNeeded, _NetworkController_updateNetworkConfigurations, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated, _NetworkController_createAutoManagedNetworkClientRegistry, _NetworkController_applyNetworkSelection, _NetworkController_autoAddNetworksFromConfigRegistry;
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.NetworkController = exports.selectAvailableNetworkClientIds = exports.getAvailableNetworkClientIds = exports.selectNetworkConfigurations = exports.getNetworkConfigurations = exports.getDefaultNetworkControllerState = exports.knownKeysOf = exports.RpcEndpointType = void 0;
42
- const base_controller_1 = require("@metamask/base-controller");
43
- const config_registry_controller_1 = require("@metamask/config-registry-controller");
44
- const controller_utils_1 = require("@metamask/controller-utils");
45
- const eth_query_1 = __importDefault(require("@metamask/eth-query"));
46
- const rpc_errors_1 = require("@metamask/rpc-errors");
47
- const swappable_obj_proxy_1 = require("@metamask/swappable-obj-proxy");
48
- const utils_1 = require("@metamask/utils");
49
- const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
50
- const immer_1 = require("immer");
51
- const lodash_1 = require("lodash");
52
- const reselect_1 = require("reselect");
53
- const URI = __importStar(require("uri-js"));
54
- const uuid_1 = require("uuid");
55
- const constants_js_1 = require("./constants.cjs");
56
- const create_auto_managed_network_client_js_1 = require("./create-auto-managed-network-client.cjs");
57
- const logger_js_1 = require("./logger.cjs");
58
- const rpc_service_analytics_js_1 = require("./rpc-service-analytics.cjs");
59
- const selectors_js_1 = require("./selectors.cjs");
60
- const types_js_1 = require("./types.cjs");
61
- const debugLog = (0, logger_js_1.createModuleLogger)(logger_js_1.projectLogger, 'NetworkController');
62
- const INFURA_URL_REGEX = /^https:\/\/(?<networkName>[^.]+)\.infura\.io\/v\d+\/(?<apiKey>.+)$/u;
63
- /**
64
- * The type of an RPC endpoint.
65
- *
66
- * @see {@link CustomRpcEndpoint}
67
- * @see {@link InfuraRpcEndpoint}
68
- */
69
- var RpcEndpointType;
70
- (function (RpcEndpointType) {
71
- RpcEndpointType["Custom"] = "custom";
72
- RpcEndpointType["Infura"] = "infura";
73
- })(RpcEndpointType || (exports.RpcEndpointType = RpcEndpointType = {}));
74
- /**
75
- * `Object.keys()` is intentionally generic: it returns the keys of an object,
76
- * but it cannot make guarantees about the contents of that object, so the type
77
- * of the keys is merely `string[]`. While this is technically accurate, it is
78
- * also unnecessary if we have an object that we own and whose contents are
79
- * known exactly.
80
- *
81
- * TODO: Move to @metamask/utils.
82
- *
83
- * @param object - The object.
84
- * @returns The keys of an object, typed according to the type of the object
85
- * itself.
86
- */
87
- function knownKeysOf(
88
- // TODO: Replace `any` with type
89
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
90
- object) {
91
- return Object.keys(object);
92
- }
93
- exports.knownKeysOf = knownKeysOf;
94
- /**
95
- * Type guard for determining whether the given value is an error object with a
96
- * `code` property, such as an instance of Error.
97
- *
98
- * TODO: Move this to @metamask/utils.
99
- *
100
- * @param error - The object to check.
101
- * @returns True if `error` has a `code`, false otherwise.
102
- */
103
- function isErrorWithCode(error) {
104
- return typeof error === 'object' && error !== null && 'code' in error;
105
- }
106
- const controllerName = 'NetworkController';
107
- const MESSENGER_EXPOSED_METHODS = [
108
- 'addNetwork',
109
- 'findNetworkClientIdByChainId',
110
- 'get1559CompatibilityWithNetworkClientId',
111
- 'getEIP1559Compatibility',
112
- 'getEthQuery',
113
- 'getNetworkClientById',
114
- 'getNetworkClientRegistry',
115
- 'getNetworkConfigurationByChainId',
116
- 'getNetworkConfigurationByNetworkClientId',
117
- 'getProviderAndBlockTracker',
118
- 'getSelectedChainId',
119
- 'getSelectedNetworkClient',
120
- 'loadBackup',
121
- 'lookupNetwork',
122
- 'lookupNetworkByClientId',
123
- 'removeNetwork',
124
- 'resetConnection',
125
- 'rollbackToPreviousProvider',
126
- 'setActiveNetwork',
127
- 'setProviderType',
128
- 'updateNetwork',
129
- ];
130
- /**
131
- * Constructs a value for the state property `networkConfigurationsByChainId`
132
- * which will be used if it has not been provided to the constructor.
133
- *
134
- * @returns The default value for `networkConfigurationsByChainId`.
135
- */
136
- function getDefaultNetworkConfigurationsByChainId() {
137
- const infuraNetworks = getDefaultInfuraNetworkConfigurationsByChainId();
138
- const customNetworks = getDefaultCustomNetworkConfigurationsByChainId();
139
- return { ...customNetworks, ...infuraNetworks };
140
- }
141
- /**
142
- * Constructs a `networkConfigurationsByChainId` object for all default Infura networks.
143
- *
144
- * @returns The `networkConfigurationsByChainId` object of all Infura networks.
145
- */
146
- function getDefaultInfuraNetworkConfigurationsByChainId() {
147
- return controller_utils_1.DEFAULT_INFURA_NETWORKS.reduce((obj, infuraNetworkType) => {
148
- const chainId = controller_utils_1.ChainId[infuraNetworkType];
149
- // Skip deprecated network as default network.
150
- if (constants_js_1.DEPRECATED_NETWORKS.has(chainId)) {
151
- return obj;
152
- }
153
- const rpcEndpointUrl = `https://${infuraNetworkType}.infura.io/v3/{infuraProjectId}`;
154
- const { rpcPrefs } = controller_utils_1.BUILT_IN_NETWORKS[infuraNetworkType];
155
- const networkConfiguration = {
156
- blockExplorerUrls: [rpcPrefs.blockExplorerUrl],
157
- defaultBlockExplorerUrlIndex: 0,
158
- chainId,
159
- defaultRpcEndpointIndex: 0,
160
- name: controller_utils_1.NetworkNickname[infuraNetworkType],
161
- nativeCurrency: controller_utils_1.NetworksTicker[infuraNetworkType],
162
- rpcEndpoints: [
163
- {
164
- failoverUrls: [],
165
- networkClientId: infuraNetworkType,
166
- type: RpcEndpointType.Infura,
167
- url: rpcEndpointUrl,
168
- },
169
- ],
170
- };
171
- return { ...obj, [chainId]: networkConfiguration };
172
- }, {});
173
- }
174
- /**
175
- * Constructs a `networkConfigurationsByChainId` object for all default custom networks.
176
- *
177
- * @returns The `networkConfigurationsByChainId` object of all custom networks.
178
- */
179
- function getDefaultCustomNetworkConfigurationsByChainId() {
180
- // Create the `networkConfigurationsByChainId` objects explicitly,
181
- // Because it is not always guaranteed that the custom networks are included in the
182
- // default networks.
183
- return {
184
- [controller_utils_1.ChainId['megaeth-testnet-v2']]: getCustomNetworkConfiguration(controller_utils_1.CustomNetworkType['megaeth-testnet-v2']),
185
- [controller_utils_1.ChainId['monad-testnet']]: getCustomNetworkConfiguration(controller_utils_1.CustomNetworkType['monad-testnet']),
186
- };
187
- }
188
- /**
189
- * Constructs a `NetworkConfiguration` object by `CustomNetworkType`.
190
- *
191
- * @param customNetworkType - The type of the custom network.
192
- * @returns The `NetworkConfiguration` object.
193
- */
194
- function getCustomNetworkConfiguration(customNetworkType) {
195
- const { ticker, rpcPrefs } = controller_utils_1.BUILT_IN_NETWORKS[customNetworkType];
196
- const rpcEndpointUrl = controller_utils_1.BUILT_IN_CUSTOM_NETWORKS_RPC[customNetworkType];
197
- return {
198
- blockExplorerUrls: [rpcPrefs.blockExplorerUrl],
199
- chainId: controller_utils_1.ChainId[customNetworkType],
200
- defaultRpcEndpointIndex: 0,
201
- defaultBlockExplorerUrlIndex: 0,
202
- name: controller_utils_1.NetworkNickname[customNetworkType],
203
- nativeCurrency: ticker,
204
- rpcEndpoints: [
205
- {
206
- failoverUrls: [],
207
- networkClientId: customNetworkType,
208
- type: RpcEndpointType.Custom,
209
- url: rpcEndpointUrl,
210
- },
211
- ],
212
- };
213
- }
214
- /**
215
- * Constructs properties for the NetworkController state whose values will be
216
- * used if not provided to the constructor.
217
- *
218
- * @returns The default NetworkController state.
219
- */
220
- function getDefaultNetworkControllerState() {
221
- const networksMetadata = {};
222
- const networkConfigurationsByChainId = getDefaultNetworkConfigurationsByChainId();
223
- return {
224
- selectedNetworkClientId: controller_utils_1.InfuraNetworkType.mainnet,
225
- networksMetadata,
226
- networkConfigurationsByChainId,
227
- };
228
- }
229
- exports.getDefaultNetworkControllerState = getDefaultNetworkControllerState;
230
- /**
231
- * Redux selector for getting all network configurations from NetworkController
232
- * state, keyed by chain ID.
233
- *
234
- * @param state - NetworkController state
235
- * @returns All registered network configurations, keyed by chain ID.
236
- */
237
- const selectNetworkConfigurationsByChainId = (state) => state.networkConfigurationsByChainId;
238
- /**
239
- * Get a list of all network configurations.
240
- *
241
- * @param state - NetworkController state
242
- * @returns A list of all available network configurations
243
- */
244
- function getNetworkConfigurations(state) {
245
- return Object.values(state.networkConfigurationsByChainId);
246
- }
247
- exports.getNetworkConfigurations = getNetworkConfigurations;
248
- /**
249
- * Redux selector for getting a list of all network configurations from
250
- * NetworkController state.
251
- *
252
- * @param state - NetworkController state
253
- * @returns A list of all available network configurations
254
- */
255
- exports.selectNetworkConfigurations = (0, reselect_1.createSelector)(selectNetworkConfigurationsByChainId, (networkConfigurationsByChainId) => Object.values(networkConfigurationsByChainId));
256
- /**
257
- * Get a list of all available network client IDs from a list of network
258
- * configurations.
259
- *
260
- * @param networkConfigurations - The array of network configurations
261
- * @returns A list of all available client IDs
262
- */
263
- function getAvailableNetworkClientIds(networkConfigurations) {
264
- return networkConfigurations.flatMap((networkConfiguration) => networkConfiguration.rpcEndpoints.map((rpcEndpoint) => rpcEndpoint.networkClientId));
265
- }
266
- exports.getAvailableNetworkClientIds = getAvailableNetworkClientIds;
267
- /**
268
- * Redux selector for getting a list of all available network client IDs
269
- * from NetworkController state.
270
- *
271
- * @param state - NetworkController state
272
- * @returns A list of all available network client IDs.
273
- */
274
- exports.selectAvailableNetworkClientIds = (0, reselect_1.createSelector)(exports.selectNetworkConfigurations, getAvailableNetworkClientIds);
275
- /**
276
- * Determines whether the given URL is valid by attempting to parse it.
277
- *
278
- * @param url - The URL to test.
279
- * @returns True if the URL is valid, false otherwise.
280
- */
281
- function isValidUrl(url) {
282
- const uri = URI.parse(url);
283
- return (uri.error === undefined && (uri.scheme === 'http' || uri.scheme === 'https'));
284
- }
285
- /**
286
- * Given an Infura API URL, extracts the subdomain that identifies the Infura
287
- * network.
288
- *
289
- * @param rpcEndpointUrl - The URL to operate on.
290
- * @returns The Infura network name that the URL references.
291
- * @throws if no Infura network is present in the URL.
292
- */
293
- function deriveInfuraNetworkNameFromRpcEndpointUrl(rpcEndpointUrl) {
294
- const match = INFURA_URL_REGEX.exec(rpcEndpointUrl);
295
- if (match?.groups) {
296
- return match.groups.networkName;
297
- }
298
- throw new Error('Could not derive Infura network from RPC endpoint URL');
299
- }
300
- /**
301
- * Performs a series of checks that the given NetworkController state is
302
- * internally consistent — that all parts of state that are supposed to match in
303
- * fact do — so that working with the state later on doesn't cause unexpected
304
- * errors.
305
- *
306
- * In the case of NetworkController, there are several parts of state that need
307
- * to match. For instance, `defaultRpcEndpointIndex` needs to match an entry
308
- * within `rpcEndpoints`, and `selectedNetworkClientId` needs to point to an RPC
309
- * endpoint within a network configuration.
310
- *
311
- * @param state - The NetworkController state to verify.
312
- * @throws if the state is invalid in some way.
313
- */
314
- function validateInitialState(state) {
315
- const networkConfigurationEntries = Object.entries(state.networkConfigurationsByChainId);
316
- const networkClientIds = getAvailableNetworkClientIds(getNetworkConfigurations(state));
317
- if (networkConfigurationEntries.length === 0) {
318
- throw new Error('NetworkController state is invalid: `networkConfigurationsByChainId` cannot be empty');
319
- }
320
- for (const [chainId, networkConfiguration] of networkConfigurationEntries) {
321
- if (chainId !== networkConfiguration.chainId) {
322
- 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}'`);
323
- }
324
- const isInvalidDefaultBlockExplorerUrlIndex = networkConfiguration.blockExplorerUrls.length > 0
325
- ? networkConfiguration.defaultBlockExplorerUrlIndex === undefined ||
326
- networkConfiguration.blockExplorerUrls[networkConfiguration.defaultBlockExplorerUrlIndex] === undefined
327
- : networkConfiguration.defaultBlockExplorerUrlIndex !== undefined;
328
- if (isInvalidDefaultBlockExplorerUrlIndex) {
329
- throw new Error(`NetworkController state has invalid \`networkConfigurationsByChainId\`: Network configuration '${networkConfiguration.name}' has a \`defaultBlockExplorerUrlIndex\` that does not refer to an entry in \`blockExplorerUrls\``);
330
- }
331
- if (networkConfiguration.rpcEndpoints[networkConfiguration.defaultRpcEndpointIndex] === undefined) {
332
- throw new Error(`NetworkController state has invalid \`networkConfigurationsByChainId\`: Network configuration '${networkConfiguration.name}' has a \`defaultRpcEndpointIndex\` that does not refer to an entry in \`rpcEndpoints\``);
333
- }
334
- }
335
- if ([...new Set(networkClientIds)].length < networkClientIds.length) {
336
- throw new Error('NetworkController state has invalid `networkConfigurationsByChainId`: Every RPC endpoint across all network configurations must have a unique `networkClientId`');
337
- }
338
- }
339
- /**
340
- * Checks that the given initial NetworkController state is internally
341
- * consistent similar to `validateInitialState`, but if an anomaly is detected,
342
- * it does its best to correct the state and logs an error to Sentry.
343
- *
344
- * @param state - The NetworkController state to verify.
345
- * @param messenger - The NetworkController messenger.
346
- * @returns The corrected state.
347
- */
348
- function correctInitialState(state, messenger) {
349
- const networkConfigurationsSortedByChainId = getNetworkConfigurations(state).sort((a, b) => a.chainId.localeCompare(b.chainId));
350
- const availableNetworkClientIds = getAvailableNetworkClientIds(networkConfigurationsSortedByChainId);
351
- const invalidNetworkClientIdsWithMetadata = Object.keys(state.networksMetadata).filter((networkClientId) => !availableNetworkClientIds.includes(networkClientId));
352
- return (0, immer_1.produce)(state, (newState) => {
353
- if (!availableNetworkClientIds.includes(state.selectedNetworkClientId)) {
354
- const firstNetworkConfiguration = networkConfigurationsSortedByChainId[0];
355
- const newSelectedNetworkClientId = firstNetworkConfiguration.rpcEndpoints[firstNetworkConfiguration.defaultRpcEndpointIndex].networkClientId;
356
- messenger.captureException?.(new Error(`\`selectedNetworkClientId\` '${state.selectedNetworkClientId}' does not refer to an RPC endpoint within a network configuration; correcting to '${newSelectedNetworkClientId}'`));
357
- newState.selectedNetworkClientId = newSelectedNetworkClientId;
358
- }
359
- if (invalidNetworkClientIdsWithMetadata.length > 0) {
360
- for (const invalidNetworkClientId of invalidNetworkClientIdsWithMetadata) {
361
- delete newState.networksMetadata[invalidNetworkClientId];
362
- }
363
- messenger.captureException?.(new Error('`networksMetadata` had invalid network client IDs, which have been removed'));
364
- }
365
- });
366
- }
367
- /**
368
- * Transforms a map of chain ID to network configuration to a map of network
369
- * client ID to network configuration.
370
- *
371
- * @param networkConfigurationsByChainId - The network configurations, keyed by
372
- * chain ID.
373
- * @returns The network configurations, keyed by network client ID.
374
- */
375
- function buildNetworkConfigurationsByNetworkClientId(networkConfigurationsByChainId) {
376
- return new Map(Object.values(networkConfigurationsByChainId).flatMap((networkConfiguration) => {
377
- return networkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
378
- return [rpcEndpoint.networkClientId, networkConfiguration];
379
- });
380
- }));
381
- }
382
- /**
383
- * Controller that creates and manages an Ethereum network provider.
384
- */
385
- class NetworkController extends base_controller_1.BaseController {
386
- /**
387
- * Constructs a NetworkController.
388
- *
389
- * @param options - The options; see {@link NetworkControllerOptions}.
390
- */
391
- constructor(options) {
392
- const { messenger, state, infuraProjectId, failoverUrls, log, getRpcServiceOptions, getBlockTrackerOptions, analyticsOptions, } = options;
393
- const initialState = {
394
- ...getDefaultNetworkControllerState(),
395
- ...state,
396
- };
397
- validateInitialState(initialState);
398
- const correctedInitialState = correctInitialState(initialState, messenger);
399
- if (!infuraProjectId || typeof infuraProjectId !== 'string') {
400
- throw new Error('Invalid Infura project ID');
401
- }
402
- super({
403
- name: controllerName,
404
- metadata: {
405
- selectedNetworkClientId: {
406
- includeInStateLogs: true,
407
- persist: true,
408
- includeInDebugSnapshot: false,
409
- usedInUi: true,
410
- },
411
- networksMetadata: {
412
- includeInStateLogs: true,
413
- persist: true,
414
- includeInDebugSnapshot: false,
415
- usedInUi: true,
416
- },
417
- networkConfigurationsByChainId: {
418
- includeInStateLogs: true,
419
- persist: true,
420
- includeInDebugSnapshot: false,
421
- usedInUi: true,
422
- },
423
- },
424
- messenger,
425
- state: correctedInitialState,
426
- });
427
- _NetworkController_instances.add(this);
428
- _NetworkController_ethQuery.set(this, void 0);
429
- _NetworkController_infuraProjectId.set(this, void 0);
430
- _NetworkController_failoverUrls.set(this, void 0);
431
- _NetworkController_previouslySelectedNetworkClientId.set(this, void 0);
432
- _NetworkController_providerProxy.set(this, void 0);
433
- _NetworkController_blockTrackerProxy.set(this, void 0);
434
- _NetworkController_autoManagedNetworkClientRegistry.set(this, void 0);
435
- _NetworkController_autoManagedNetworkClient.set(this, void 0);
436
- _NetworkController_log.set(this, void 0);
437
- _NetworkController_getRpcServiceOptions.set(this, void 0);
438
- _NetworkController_getBlockTrackerOptions.set(this, void 0);
439
- _NetworkController_analyticsOptions.set(this, void 0);
440
- _NetworkController_networkConfigurationsByNetworkClientId.set(this, void 0);
441
- _NetworkController_rpcFailoverMode.set(this, 'disabled');
442
- __classPrivateFieldSet(this, _NetworkController_infuraProjectId, infuraProjectId, "f");
443
- __classPrivateFieldSet(this, _NetworkController_failoverUrls, failoverUrls, "f");
444
- __classPrivateFieldSet(this, _NetworkController_log, log, "f");
445
- __classPrivateFieldSet(this, _NetworkController_getRpcServiceOptions, getRpcServiceOptions, "f");
446
- __classPrivateFieldSet(this, _NetworkController_getBlockTrackerOptions, getBlockTrackerOptions, "f");
447
- __classPrivateFieldSet(this, _NetworkController_analyticsOptions, {
448
- isRpcEndpointUrlPublic: () => false,
449
- rpcServiceEventsSampleRate: 0,
450
- ...analyticsOptions,
451
- }, "f");
452
- __classPrivateFieldSet(this, _NetworkController_previouslySelectedNetworkClientId, this.state.selectedNetworkClientId, "f");
453
- __classPrivateFieldSet(this, _NetworkController_networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId(this.state.networkConfigurationsByChainId), "f");
454
- this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
455
- this.messenger.subscribe(`${this.name}:rpcEndpointChainUnavailable`, ({ networkClientId }) => {
456
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateMetadataForNetwork).call(this, networkClientId, {
457
- networkStatus: constants_js_1.NetworkStatus.Unavailable,
458
- });
459
- });
460
- this.messenger.subscribe(`${this.name}:rpcEndpointChainDegraded`, ({ networkClientId }) => {
461
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateMetadataForNetwork).call(this, networkClientId, {
462
- networkStatus: constants_js_1.NetworkStatus.Degraded,
463
- });
464
- });
465
- this.messenger.subscribe(`${this.name}:rpcEndpointChainAvailable`, ({ networkClientId }) => {
466
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateMetadataForNetwork).call(this, networkClientId, {
467
- networkStatus: constants_js_1.NetworkStatus.Available,
468
- });
469
- });
470
- this.messenger.subscribe(`${this.name}:rpcEndpointUnavailable`, (payload) => (0, rpc_service_analytics_js_1.trackRpcServiceUnavailable)(this.messenger, __classPrivateFieldGet(this, _NetworkController_analyticsOptions, "f"), payload));
471
- this.messenger.subscribe(`${this.name}:rpcEndpointDegraded`, (payload) => (0, rpc_service_analytics_js_1.trackRpcServiceDegraded)(this.messenger, __classPrivateFieldGet(this, _NetworkController_analyticsOptions, "f"), payload));
472
- this.messenger.subscribe('RemoteFeatureFlagController:stateChange', (rpcFailoverMode) => {
473
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateRpcFailover).call(this, rpcFailoverMode);
474
- }, selectors_js_1.getRpcFailoverMode);
475
- this.messenger.subscribe('ConfigRegistryController:stateChanged', (caipChainIds) => __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_autoAddNetworksFromConfigRegistry).call(this, caipChainIds), config_registry_controller_1.selectEvmAutoEnabledNetworksChainIds);
476
- }
477
- /**
478
- * Returns the EthQuery instance for the currently selected network.
479
- *
480
- * @returns The EthQuery instance, or undefined if the provider has not been
481
- * initialized.
482
- */
483
- getEthQuery() {
484
- return __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
485
- }
486
- /**
487
- * Accesses the provider and block tracker for the currently selected network.
488
- *
489
- * @returns The proxy and block tracker proxies.
490
- * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.
491
- */
492
- getProviderAndBlockTracker() {
493
- return {
494
- provider: __classPrivateFieldGet(this, _NetworkController_providerProxy, "f"),
495
- blockTracker: __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f"),
496
- };
497
- }
498
- /**
499
- * Accesses the provider and block tracker for the currently selected network.
500
- *
501
- * @returns an object with the provider and block tracker proxies for the currently selected network.
502
- */
503
- getSelectedNetworkClient() {
504
- if (__classPrivateFieldGet(this, _NetworkController_providerProxy, "f") && __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) {
505
- return {
506
- provider: __classPrivateFieldGet(this, _NetworkController_providerProxy, "f"),
507
- blockTracker: __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f"),
508
- };
509
- }
510
- return undefined;
511
- }
512
- /**
513
- * Accesses the chain ID from the selected network client.
514
- *
515
- * @returns The chain ID of the selected network client in hex format or undefined if there is no network client.
516
- */
517
- getSelectedChainId() {
518
- const networkConfiguration = this.getNetworkConfigurationByNetworkClientId(this.state.selectedNetworkClientId);
519
- return networkConfiguration?.chainId;
520
- }
521
- /**
522
- * Internally, the Infura and custom network clients are categorized by type
523
- * so that when accessing either kind of network client, TypeScript knows
524
- * which type to assign to the network client. For some cases it's more useful
525
- * to be able to access network clients by ID instead of by type and then ID,
526
- * so this function makes that possible.
527
- *
528
- * @returns The network clients registered so far, keyed by ID.
529
- */
530
- getNetworkClientRegistry() {
531
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
532
- return Object.assign({}, autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Infura], autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Custom]);
533
- }
534
- getNetworkClientById(networkClientId) {
535
- if (!networkClientId) {
536
- throw new Error('No network client ID was provided.');
537
- }
538
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
539
- const infuraNetworkClient = autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Infura][networkClientId];
540
- if (infuraNetworkClient) {
541
- return infuraNetworkClient;
542
- }
543
- const customNetworkClient = autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Custom][networkClientId];
544
- if (!customNetworkClient) {
545
- throw new Error(`No network client was found with ID "${networkClientId}".`);
546
- }
547
- return customNetworkClient;
548
- }
549
- /**
550
- * Initialize the NetworkController:
551
- * - Apply the RPC failover mode from the `corePlatformRpcFailoverMode` remote feature flag;
552
- * - Apply the network selection.
553
- * - Auto-add networks for any chains that are configured to be auto-enabled in ConfigRegistryController.
554
- */
555
- init() {
556
- const state = this.messenger.call('RemoteFeatureFlagController:getState');
557
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateRpcFailover).call(this, (0, selectors_js_1.getRpcFailoverMode)(state));
558
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this, this.state.selectedNetworkClientId);
559
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_autoAddNetworksFromConfigRegistry).call(this, (0, config_registry_controller_1.selectEvmAutoEnabledNetworksChainIds)(this.messenger.call('ConfigRegistryController:getState')));
560
- }
561
- /**
562
- * Uses a request for the latest block to gather the following information on
563
- * the given or selected network, persisting it to state:
564
- *
565
- * - The connectivity status: whether it is available, geo-blocked (Infura
566
- * only), unavailable, or unknown
567
- * - The capabilities status: whether it supports EIP-1559, whether it does
568
- * not, or whether it is unknown
569
- *
570
- * @param networkClientId - The ID of the network client to inspect.
571
- * If no ID is provided, uses the currently selected network.
572
- */
573
- async lookupNetwork(networkClientId) {
574
- if (networkClientId) {
575
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_lookupGivenNetwork).call(this, networkClientId);
576
- }
577
- else {
578
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_lookupSelectedNetwork).call(this);
579
- }
580
- }
581
- /**
582
- * Uses a request for the latest block to gather the following information on
583
- * the given network, persisting it to state:
584
- *
585
- * - The connectivity status: whether the network is available, geo-blocked
586
- * (Infura only), unavailable, or unknown
587
- * - The feature compatibility status: whether the network supports EIP-1559,
588
- * whether it does not, or whether it is unknown
589
- *
590
- * @param networkClientId - The ID of the network client to inspect.
591
- * @deprecated Please use `lookupNetwork` and pass a network client ID
592
- * instead. This method will be removed in a future major version.
593
- */
594
- // We are planning on removing this so we aren't interested in testing this
595
- // right now.
596
- /* istanbul ignore next */
597
- async lookupNetworkByClientId(networkClientId) {
598
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_lookupGivenNetwork).call(this, networkClientId);
599
- }
600
- /**
601
- * Convenience method to update provider network type settings.
602
- *
603
- * @param type - Human readable network name.
604
- * @deprecated This has been replaced by `setActiveNetwork`, and will be
605
- * removed in a future release
606
- */
607
- async setProviderType(type) {
608
- if (type === controller_utils_1.NetworkType.rpc) {
609
- throw new Error(`NetworkController - cannot call "setProviderType" with type "${controller_utils_1.NetworkType.rpc}". Use "setActiveNetwork"`);
610
- }
611
- if (!(0, controller_utils_1.isInfuraNetworkType)(type)) {
612
- throw new Error(`Unknown Infura provider type "${String(type)}".`);
613
- }
614
- await this.setActiveNetwork(type);
615
- }
616
- /**
617
- * Changes the selected network.
618
- *
619
- * @param networkClientId - The ID of a network client that will be used to
620
- * make requests.
621
- * @param options - Options for this method.
622
- * @param options.updateState - Allows for updating state.
623
- * @throws if no network client is associated with the given
624
- * network client ID.
625
- */
626
- async setActiveNetwork(networkClientId, options = {}) {
627
- __classPrivateFieldSet(this, _NetworkController_previouslySelectedNetworkClientId, this.state.selectedNetworkClientId, "f");
628
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this, networkClientId, options);
629
- }
630
- /**
631
- * Determines whether the network supports EIP-1559 by checking whether the
632
- * latest block has a `baseFeePerGas` property, then updates state
633
- * appropriately.
634
- *
635
- * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.
636
- * @returns A promise that resolves to true if the network supports EIP-1559
637
- * , false otherwise, or `undefined` if unable to determine the compatibility.
638
- */
639
- async getEIP1559Compatibility(networkClientId) {
640
- if (networkClientId) {
641
- return this.get1559CompatibilityWithNetworkClientId(networkClientId);
642
- }
643
- if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
644
- return false;
645
- }
646
- const { EIPS } = this.state.networksMetadata[this.state.selectedNetworkClientId];
647
- if (EIPS[1559] !== undefined) {
648
- return EIPS[1559];
649
- }
650
- const isEIP1559Compatible = await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this, this.state.selectedNetworkClientId);
651
- this.update((state) => {
652
- if (isEIP1559Compatible !== undefined) {
653
- state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =
654
- isEIP1559Compatible;
655
- }
656
- });
657
- return isEIP1559Compatible;
658
- }
659
- async get1559CompatibilityWithNetworkClientId(networkClientId) {
660
- let metadata = this.state.networksMetadata[networkClientId];
661
- if (metadata?.EIPS[1559] === undefined) {
662
- await this.lookupNetwork(networkClientId);
663
- metadata = this.state.networksMetadata[networkClientId];
664
- }
665
- const { EIPS } = metadata;
666
- // may want to include some 'freshness' value - something to make sure we refetch this from time to time
667
- return EIPS[1559];
668
- }
669
- /**
670
- * Ensures that the provider and block tracker proxies are pointed to the
671
- * currently selected network and refreshes the metadata for the
672
- */
673
- async resetConnection() {
674
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this, this.state.selectedNetworkClientId);
675
- }
676
- /**
677
- * Returns the network configuration that has been filed under the given chain
678
- * ID.
679
- *
680
- * @param chainId - The chain ID to use as a key.
681
- * @returns The network configuration if one exists, or undefined.
682
- */
683
- getNetworkConfigurationByChainId(chainId) {
684
- return this.state.networkConfigurationsByChainId[chainId];
685
- }
686
- /**
687
- * Returns the network configuration that contains an RPC endpoint with the
688
- * given network client ID.
689
- *
690
- * @param networkClientId - The network client ID to use as a key.
691
- * @returns The network configuration if one exists, or undefined.
692
- */
693
- getNetworkConfigurationByNetworkClientId(networkClientId) {
694
- return __classPrivateFieldGet(this, _NetworkController_networkConfigurationsByNetworkClientId, "f").get(networkClientId);
695
- }
696
- /**
697
- * Creates and registers network clients for the collection of Infura and
698
- * custom RPC endpoints that can be used to make requests for a particular
699
- * chain, storing the given configuration object in state for later reference.
700
- *
701
- * @param fields - The object that describes the new network/chain and lists
702
- * the RPC endpoints which front that chain.
703
- * @returns The newly added network configuration.
704
- * @throws if any part of `fields` would produce invalid state.
705
- * @see {@link NetworkConfiguration}
706
- */
707
- addNetwork(fields) {
708
- const { rpcEndpoints: setOfRpcEndpointFields } = fields;
709
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
710
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_validateNetworkFields).call(this, {
711
- mode: 'add',
712
- networkFields: fields,
713
- autoManagedNetworkClientRegistry,
714
- });
715
- const networkClientOperations = setOfRpcEndpointFields.map((defaultOrCustomRpcEndpointFields) => {
716
- const rpcEndpoint = defaultOrCustomRpcEndpointFields.type === RpcEndpointType.Custom
717
- ? {
718
- ...defaultOrCustomRpcEndpointFields,
719
- networkClientId: (0, uuid_1.v4)(),
720
- }
721
- : defaultOrCustomRpcEndpointFields;
722
- return {
723
- type: 'add',
724
- rpcEndpoint,
725
- };
726
- });
727
- const newNetworkConfiguration = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineNetworkConfigurationToPersist).call(this, {
728
- networkFields: fields,
729
- networkClientOperations,
730
- });
731
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerNetworkClientsAsNeeded).call(this, {
732
- networkFields: fields,
733
- networkClientOperations,
734
- autoManagedNetworkClientRegistry,
735
- });
736
- this.update((state) => {
737
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateNetworkConfigurations).call(this, {
738
- state,
739
- mode: 'add',
740
- networkFields: fields,
741
- networkConfigurationToPersist: newNetworkConfiguration,
742
- });
743
- });
744
- this.messenger.publish(`${controllerName}:networkAdded`, newNetworkConfiguration);
745
- return newNetworkConfiguration;
746
- }
747
- /**
748
- * Updates the configuration for a previously stored network filed under the
749
- * given chain ID, creating + registering new network clients to represent RPC
750
- * endpoints that have been added and destroying + unregistering existing
751
- * network clients for RPC endpoints that have been removed.
752
- *
753
- * Note that if `chainId` is changed, then all network clients associated with
754
- * that chain will be removed and re-added, even if none of the RPC endpoints
755
- * have changed.
756
- *
757
- * @param chainId - The chain ID associated with an existing network.
758
- * @param fields - The object that describes the updates to the network/chain,
759
- * including the new set of RPC endpoints which should front that chain.
760
- * @param options - Options to provide.
761
- * @param options.replacementSelectedRpcEndpointIndex - Usually you cannot
762
- * remove an RPC endpoint that is being represented by the currently selected
763
- * network client. This option allows you to specify another RPC endpoint
764
- * (either an existing one or a new one) that should be used to select a new
765
- * network instead.
766
- * @returns The updated network configuration.
767
- * @throws if `chainId` does not refer to an existing network configuration,
768
- * if any part of `fields` would produce invalid state, etc.
769
- * @see {@link NetworkConfiguration}
770
- */
771
- async updateNetwork(chainId, fields, { replacementSelectedRpcEndpointIndex, } = {}) {
772
- const existingNetworkConfiguration = this.state.networkConfigurationsByChainId[chainId];
773
- if (existingNetworkConfiguration === undefined) {
774
- throw new Error(`Could not update network: Cannot find network configuration for chain '${chainId}'`);
775
- }
776
- const existingChainId = chainId;
777
- const { chainId: newChainId, rpcEndpoints: setOfNewRpcEndpointFields } = fields;
778
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
779
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_validateNetworkFields).call(this, {
780
- mode: 'update',
781
- networkFields: fields,
782
- existingNetworkConfiguration,
783
- autoManagedNetworkClientRegistry,
784
- });
785
- const networkClientOperations = [];
786
- for (const newRpcEndpointFields of setOfNewRpcEndpointFields) {
787
- const existingRpcEndpointForNoop = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
788
- return (rpcEndpoint.type === newRpcEndpointFields.type &&
789
- rpcEndpoint.url === newRpcEndpointFields.url &&
790
- (rpcEndpoint.networkClientId ===
791
- newRpcEndpointFields.networkClientId ||
792
- newRpcEndpointFields.networkClientId === undefined));
793
- });
794
- const existingRpcEndpointForReplaceWhenChainChanged = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
795
- return ((rpcEndpoint.type === RpcEndpointType.Infura &&
796
- newRpcEndpointFields.type === RpcEndpointType.Infura) ||
797
- (rpcEndpoint.type === newRpcEndpointFields.type &&
798
- rpcEndpoint.networkClientId ===
799
- newRpcEndpointFields.networkClientId &&
800
- rpcEndpoint.url === newRpcEndpointFields.url));
801
- });
802
- const existingRpcEndpointForReplaceWhenChainNotChanged = existingNetworkConfiguration.rpcEndpoints.find((rpcEndpoint) => {
803
- return (rpcEndpoint.type === newRpcEndpointFields.type &&
804
- (rpcEndpoint.url === newRpcEndpointFields.url ||
805
- rpcEndpoint.networkClientId ===
806
- newRpcEndpointFields.networkClientId));
807
- });
808
- if (newChainId !== existingChainId &&
809
- existingRpcEndpointForReplaceWhenChainChanged !== undefined) {
810
- const newRpcEndpoint = newRpcEndpointFields.type === RpcEndpointType.Infura
811
- ? newRpcEndpointFields
812
- : { ...newRpcEndpointFields, networkClientId: (0, uuid_1.v4)() };
813
- networkClientOperations.push({
814
- type: 'replace',
815
- oldRpcEndpoint: existingRpcEndpointForReplaceWhenChainChanged,
816
- newRpcEndpoint,
817
- });
818
- }
819
- else if (existingRpcEndpointForNoop !== undefined) {
820
- let newRpcEndpoint;
821
- if (existingRpcEndpointForNoop.type === RpcEndpointType.Infura) {
822
- newRpcEndpoint = existingRpcEndpointForNoop;
823
- }
824
- else {
825
- // `networkClientId` shouldn't be missing at this point; if it is,
826
- // that's a mistake, so fill it back in
827
- newRpcEndpoint = Object.assign({}, newRpcEndpointFields, {
828
- networkClientId: existingRpcEndpointForNoop.networkClientId,
829
- });
830
- }
831
- networkClientOperations.push({
832
- type: 'noop',
833
- rpcEndpoint: newRpcEndpoint,
834
- });
835
- }
836
- else if (existingRpcEndpointForReplaceWhenChainNotChanged === undefined) {
837
- const newRpcEndpoint = newRpcEndpointFields.type === RpcEndpointType.Infura
838
- ? newRpcEndpointFields
839
- : { ...newRpcEndpointFields, networkClientId: (0, uuid_1.v4)() };
840
- const networkClientOperation = {
841
- type: 'add',
842
- rpcEndpoint: newRpcEndpoint,
843
- };
844
- networkClientOperations.push(networkClientOperation);
845
- }
846
- else {
847
- let newRpcEndpoint;
848
- /* istanbul ignore if */
849
- if (newRpcEndpointFields.type === RpcEndpointType.Infura) {
850
- // This case can't actually happen. If we're here, it means that some
851
- // part of the RPC endpoint changed. But there is no part of an Infura
852
- // RPC endpoint that can be changed (as it would immediately make that
853
- // RPC endpoint self-inconsistent). This is just here to appease
854
- // TypeScript.
855
- newRpcEndpoint = newRpcEndpointFields;
856
- }
857
- else {
858
- newRpcEndpoint = {
859
- ...newRpcEndpointFields,
860
- networkClientId: (0, uuid_1.v4)(),
861
- };
862
- }
863
- networkClientOperations.push({
864
- type: 'replace',
865
- oldRpcEndpoint: existingRpcEndpointForReplaceWhenChainNotChanged,
866
- newRpcEndpoint,
867
- });
868
- }
869
- }
870
- for (const existingRpcEndpoint of existingNetworkConfiguration.rpcEndpoints) {
871
- if (!networkClientOperations.some((networkClientOperation) => {
872
- const otherRpcEndpoint = networkClientOperation.type === 'replace'
873
- ? networkClientOperation.oldRpcEndpoint
874
- : networkClientOperation.rpcEndpoint;
875
- return (otherRpcEndpoint.type === existingRpcEndpoint.type &&
876
- otherRpcEndpoint.networkClientId ===
877
- existingRpcEndpoint.networkClientId &&
878
- otherRpcEndpoint.url === existingRpcEndpoint.url);
879
- })) {
880
- const networkClientOperation = {
881
- type: 'remove',
882
- rpcEndpoint: existingRpcEndpoint,
883
- };
884
- networkClientOperations.push(networkClientOperation);
885
- }
886
- }
887
- const updatedNetworkConfiguration = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineNetworkConfigurationToPersist).call(this, {
888
- networkFields: fields,
889
- networkClientOperations,
890
- });
891
- if (replacementSelectedRpcEndpointIndex === undefined &&
892
- networkClientOperations.some((networkClientOperation) => {
893
- return (networkClientOperation.type === 'remove' &&
894
- networkClientOperation.rpcEndpoint.networkClientId ===
895
- this.state.selectedNetworkClientId);
896
- }) &&
897
- !networkClientOperations.some((networkClientOperation) => {
898
- return (networkClientOperation.type === 'replace' &&
899
- networkClientOperation.oldRpcEndpoint.networkClientId ===
900
- this.state.selectedNetworkClientId);
901
- })) {
902
- throw new Error(`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.`);
903
- }
904
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerNetworkClientsAsNeeded).call(this, {
905
- networkFields: fields,
906
- networkClientOperations,
907
- autoManagedNetworkClientRegistry,
908
- });
909
- const replacementSelectedRpcEndpointWithIndex = networkClientOperations
910
- .map((networkClientOperation, index) => [networkClientOperation, index])
911
- .find(([networkClientOperation, _index]) => {
912
- return (networkClientOperation.type === 'replace' &&
913
- networkClientOperation.oldRpcEndpoint.networkClientId ===
914
- this.state.selectedNetworkClientId);
915
- });
916
- const correctedReplacementSelectedRpcEndpointIndex = replacementSelectedRpcEndpointIndex ??
917
- replacementSelectedRpcEndpointWithIndex?.[1];
918
- let rpcEndpointToSelect;
919
- if (correctedReplacementSelectedRpcEndpointIndex !== undefined) {
920
- rpcEndpointToSelect =
921
- updatedNetworkConfiguration.rpcEndpoints[correctedReplacementSelectedRpcEndpointIndex];
922
- if (rpcEndpointToSelect === undefined) {
923
- throw new Error(`Could not update network: \`replacementSelectedRpcEndpointIndex\` ${correctedReplacementSelectedRpcEndpointIndex} does not refer to an entry in \`rpcEndpoints\``);
924
- }
925
- }
926
- if (rpcEndpointToSelect &&
927
- rpcEndpointToSelect.networkClientId !== this.state.selectedNetworkClientId) {
928
- await this.setActiveNetwork(rpcEndpointToSelect.networkClientId, {
929
- updateState: (state) => {
930
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateNetworkConfigurations).call(this, {
931
- state,
932
- mode: 'update',
933
- networkFields: fields,
934
- networkConfigurationToPersist: updatedNetworkConfiguration,
935
- existingNetworkConfiguration,
936
- });
937
- },
938
- });
939
- }
940
- else {
941
- this.update((state) => {
942
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateNetworkConfigurations).call(this, {
943
- state,
944
- mode: 'update',
945
- networkFields: fields,
946
- networkConfigurationToPersist: updatedNetworkConfiguration,
947
- existingNetworkConfiguration,
948
- });
949
- });
950
- }
951
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_unregisterNetworkClientsAsNeeded).call(this, {
952
- networkClientOperations,
953
- autoManagedNetworkClientRegistry,
954
- });
955
- return updatedNetworkConfiguration;
956
- }
957
- /**
958
- * Destroys and unregisters the network identified by the given chain ID, also
959
- * removing the associated network configuration from state.
960
- *
961
- * @param chainId - The chain ID associated with an existing network.
962
- * @throws if `chainId` does not refer to an existing network configuration,
963
- * or if the currently selected network is being removed.
964
- * @see {@link NetworkConfiguration}
965
- */
966
- removeNetwork(chainId) {
967
- const existingNetworkConfiguration = this.state.networkConfigurationsByChainId[chainId];
968
- if (existingNetworkConfiguration === undefined) {
969
- throw new Error(`Cannot find network configuration for chain '${chainId}'`);
970
- }
971
- if (existingNetworkConfiguration.rpcEndpoints.some((rpcEndpoint) => rpcEndpoint.networkClientId === this.state.selectedNetworkClientId)) {
972
- throw new Error(`Cannot remove the currently selected network`);
973
- }
974
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
975
- const networkClientOperations = existingNetworkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
976
- return {
977
- type: 'remove',
978
- rpcEndpoint,
979
- };
980
- });
981
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_unregisterNetworkClientsAsNeeded).call(this, {
982
- networkClientOperations,
983
- autoManagedNetworkClientRegistry,
984
- });
985
- this.update((state) => {
986
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateNetworkConfigurations).call(this, {
987
- state,
988
- mode: 'remove',
989
- existingNetworkConfiguration,
990
- });
991
- for (const rpcEndpoint of existingNetworkConfiguration.rpcEndpoints) {
992
- delete state.networksMetadata[rpcEndpoint.networkClientId];
993
- }
994
- });
995
- this.messenger.publish('NetworkController:networkRemoved', existingNetworkConfiguration);
996
- }
997
- /**
998
- * Assuming that the network has been previously switched, switches to this
999
- * new network.
1000
- *
1001
- * If the network has not been previously switched, this method is equivalent
1002
- * to {@link resetConnection}.
1003
- */
1004
- async rollbackToPreviousProvider() {
1005
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this, __classPrivateFieldGet(this, _NetworkController_previouslySelectedNetworkClientId, "f"));
1006
- }
1007
- /**
1008
- * Deactivates the controller, stopping any ongoing polling.
1009
- *
1010
- * In-progress requests will not be aborted.
1011
- */
1012
- // We're intentionally changing the signature of an extended method.
1013
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
1014
- async destroy() {
1015
- await __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")?.destroy();
1016
- }
1017
- /**
1018
- * Merges the given backup data into controller state.
1019
- *
1020
- * @param backup - The data that has been backed up.
1021
- * @param backup.networkConfigurationsByChainId - Network configurations,
1022
- * keyed by chain ID.
1023
- */
1024
- loadBackup({ networkConfigurationsByChainId, }) {
1025
- this.update((state) => {
1026
- state.networkConfigurationsByChainId = {
1027
- ...state.networkConfigurationsByChainId,
1028
- ...networkConfigurationsByChainId,
1029
- };
1030
- });
1031
- }
1032
- /**
1033
- * Searches for the default RPC endpoint configured for the given chain and
1034
- * returns its network client ID. This can then be passed to
1035
- * {@link getNetworkClientById} to retrieve the network client.
1036
- *
1037
- * @param chainId - Chain ID to search for.
1038
- * @returns The ID of the network client created for the chain's default RPC
1039
- * endpoint.
1040
- */
1041
- findNetworkClientIdByChainId(chainId) {
1042
- const networkConfiguration = this.state.networkConfigurationsByChainId[chainId];
1043
- if (!networkConfiguration) {
1044
- throw new Error(`Invalid chain ID "${chainId}"`);
1045
- }
1046
- const { networkClientId } = networkConfiguration.rpcEndpoints[networkConfiguration.defaultRpcEndpointIndex];
1047
- return networkClientId;
1048
- }
1049
- }
1050
- exports.NetworkController = NetworkController;
1051
- _NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_failoverUrls = 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_getRpcServiceOptions = new WeakMap(), _NetworkController_getBlockTrackerOptions = new WeakMap(), _NetworkController_analyticsOptions = new WeakMap(), _NetworkController_networkConfigurationsByNetworkClientId = new WeakMap(), _NetworkController_rpcFailoverMode = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_updateRpcFailover = function _NetworkController_updateRpcFailover(newMode) {
1052
- if (__classPrivateFieldGet(this, _NetworkController_rpcFailoverMode, "f") === newMode) {
1053
- return;
1054
- }
1055
- const autoManagedNetworkClientRegistry = __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated).call(this);
1056
- for (const networkClientsById of Object.values(autoManagedNetworkClientRegistry)) {
1057
- for (const networkClientId of Object.keys(networkClientsById)) {
1058
- const networkClient = networkClientsById[networkClientId];
1059
- if (networkClient.configuration.failoverRpcUrls &&
1060
- networkClient.configuration.failoverRpcUrls.length > 0) {
1061
- networkClient.setRpcFailoverMode(newMode);
1062
- }
1063
- }
1064
- }
1065
- __classPrivateFieldSet(this, _NetworkController_rpcFailoverMode, newMode, "f");
1066
- }, _NetworkController_refreshNetwork =
1067
- /**
1068
- * Executes a series of steps to switch the network:
1069
- *
1070
- * 1. Notifies subscribers via the messenger that the network is about to be
1071
- * switched (and, really, that the global provider and block tracker proxies
1072
- * will be re-pointed to a new network).
1073
- * 2. Looks up a known and preinitialized network client matching the given
1074
- * ID and uses it to re-point the aforementioned provider and block tracker
1075
- * proxies.
1076
- * 3. Notifies subscribers via the messenger that the network has switched.
1077
- * 4. Captures metadata for the newly switched network in state.
1078
- *
1079
- * @param networkClientId - The ID of a network client that requests will be
1080
- * routed through (either the name of an Infura network or the ID of a custom
1081
- * network configuration).
1082
- * @param options - Options for this method.
1083
- * @param options.updateState - Allows for updating state.
1084
- */
1085
- async function _NetworkController_refreshNetwork(networkClientId, options = {}) {
1086
- this.messenger.publish('NetworkController:networkWillChange', this.state);
1087
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_applyNetworkSelection).call(this, networkClientId, options);
1088
- this.messenger.publish('NetworkController:networkDidChange', this.state);
1089
- await this.lookupNetwork();
1090
- }, _NetworkController_determineNetworkMetadata =
1091
- /**
1092
- * Uses a request for the latest block to gather the following information on
1093
- * the given network:
1094
- *
1095
- * - The connectivity status: whether it is available, geo-blocked (Infura
1096
- * only), unavailable, or unknown
1097
- * - The capabilities status: whether it supports EIP-1559, whether it does
1098
- * not, or whether it is unknown
1099
- *
1100
- * @param networkClientId - The ID of the network client to inspect.
1101
- * If no ID is provided, uses the currently selected network.
1102
- * @returns The resulting metadata for the network.
1103
- */
1104
- async function _NetworkController_determineNetworkMetadata(networkClientId) {
1105
- const networkClient = this.getNetworkClientById(networkClientId);
1106
- const isInfura = networkClient.configuration.type === types_js_1.NetworkClientType.Infura;
1107
- let networkStatus;
1108
- let isEIP1559Compatible;
1109
- try {
1110
- isEIP1559Compatible =
1111
- await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineEIP1559Compatibility).call(this, networkClientId);
1112
- networkStatus = constants_js_1.NetworkStatus.Available;
1113
- }
1114
- catch (error) {
1115
- debugLog('NetworkController: lookupNetwork: ', error);
1116
- if (isErrorWithCode(error)) {
1117
- let responseBody;
1118
- if (isInfura &&
1119
- (0, utils_1.hasProperty)(error, 'message') &&
1120
- typeof error.message === 'string') {
1121
- try {
1122
- responseBody = JSON.parse(error.message);
1123
- }
1124
- catch {
1125
- // error.message must not be JSON
1126
- __classPrivateFieldGet(this, _NetworkController_log, "f")?.warn('NetworkController: lookupNetwork: json parse error: ', error);
1127
- }
1128
- }
1129
- if ((0, utils_1.isPlainObject)(responseBody) &&
1130
- responseBody.error === constants_js_1.INFURA_BLOCKED_KEY) {
1131
- networkStatus = constants_js_1.NetworkStatus.Blocked;
1132
- }
1133
- else if (error.code === rpc_errors_1.errorCodes.rpc.internal) {
1134
- networkStatus = constants_js_1.NetworkStatus.Unknown;
1135
- __classPrivateFieldGet(this, _NetworkController_log, "f")?.warn('NetworkController: lookupNetwork: rpc internal error: ', error);
1136
- }
1137
- else {
1138
- networkStatus = constants_js_1.NetworkStatus.Unavailable;
1139
- __classPrivateFieldGet(this, _NetworkController_log, "f")?.warn('NetworkController: lookupNetwork: ', error);
1140
- }
1141
- }
1142
- else {
1143
- debugLog('NetworkController - could not determine network status', error);
1144
- networkStatus = constants_js_1.NetworkStatus.Unknown;
1145
- __classPrivateFieldGet(this, _NetworkController_log, "f")?.warn('NetworkController: lookupNetwork: ', error);
1146
- }
1147
- }
1148
- return { isInfura, networkStatus, isEIP1559Compatible };
1149
- }, _NetworkController_lookupGivenNetwork =
1150
- /**
1151
- * Uses a request for the latest block to gather the following information on
1152
- * the given network, persisting it to state:
1153
- *
1154
- * - The connectivity status: whether the network is available, geo-blocked
1155
- * (Infura only), unavailable, or unknown
1156
- * - The feature compatibility status: whether the network supports EIP-1559,
1157
- * whether it does not, or whether it is unknown
1158
- *
1159
- * @param networkClientId - The ID of the network client to inspect.
1160
- */
1161
- async function _NetworkController_lookupGivenNetwork(networkClientId) {
1162
- const { networkStatus, isEIP1559Compatible } = await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineNetworkMetadata).call(this, networkClientId);
1163
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateMetadataForNetwork).call(this, networkClientId, {
1164
- networkStatus,
1165
- isEIP1559Compatible,
1166
- });
1167
- }, _NetworkController_lookupSelectedNetwork =
1168
- /**
1169
- * Uses a request for the latest block to gather the following information on
1170
- * the currently selected network, persisting it to state:
1171
- *
1172
- * - The connectivity status: whether the network is available, geo-blocked
1173
- * (Infura only), unavailable, or unknown
1174
- * - The feature compatibility status: whether the network supports EIP-1559,
1175
- * whether it does not, or whether it is unknown
1176
- *
1177
- * Note that it is possible for the current network to be switched while this
1178
- * method is running. If that is the case, it will exit early (as this method
1179
- * will also run for the new network).
1180
- */
1181
- async function _NetworkController_lookupSelectedNetwork() {
1182
- if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
1183
- return;
1184
- }
1185
- let networkChanged = false;
1186
- const listener = () => {
1187
- networkChanged = true;
1188
- try {
1189
- this.messenger.unsubscribe('NetworkController:networkDidChange', listener);
1190
- }
1191
- catch (error) {
1192
- // In theory, this `catch` should not be necessary given that this error
1193
- // would occur "inside" of the call to `#determineEIP1559Compatibility`
1194
- // below and so it should be caught by the `try`/`catch` below (it is
1195
- // impossible to reproduce in tests for that reason). However, somehow
1196
- // it occurs within Mobile and so we have to add our own `try`/`catch`
1197
- // here.
1198
- /* istanbul ignore next */
1199
- if (!(error instanceof Error) ||
1200
- error.message !==
1201
- 'Subscription not found for event: NetworkController:networkDidChange') {
1202
- // Again, this error should not happen and is impossible to reproduce
1203
- // in tests.
1204
- /* istanbul ignore next */
1205
- throw error;
1206
- }
1207
- }
1208
- };
1209
- this.messenger.subscribe('NetworkController:networkDidChange', listener);
1210
- const { isInfura, networkStatus, isEIP1559Compatible } = await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_determineNetworkMetadata).call(this, this.state.selectedNetworkClientId);
1211
- if (networkChanged) {
1212
- // If the network has changed, then `lookupNetwork` either has been or is
1213
- // in the process of being called, so we don't need to go further.
1214
- return;
1215
- }
1216
- try {
1217
- this.messenger.unsubscribe('NetworkController:networkDidChange', listener);
1218
- }
1219
- catch (error) {
1220
- if (!(error instanceof Error) ||
1221
- error.message !==
1222
- 'Subscription not found for event: NetworkController:networkDidChange') {
1223
- throw error;
1224
- }
1225
- }
1226
- __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateMetadataForNetwork).call(this, this.state.selectedNetworkClientId, {
1227
- networkStatus,
1228
- isEIP1559Compatible,
1229
- });
1230
- if (isInfura) {
1231
- if (networkStatus === constants_js_1.NetworkStatus.Available) {
1232
- this.messenger.publish('NetworkController:infuraIsUnblocked');
1233
- }
1234
- else if (networkStatus === constants_js_1.NetworkStatus.Blocked) {
1235
- this.messenger.publish('NetworkController:infuraIsBlocked');
1236
- }
1237
- }
1238
- else {
1239
- // Always publish infuraIsUnblocked regardless of network status to
1240
- // prevent consumers from being stuck in a blocked state if they were
1241
- // previously connected to an Infura network that was blocked
1242
- this.messenger.publish('NetworkController:infuraIsUnblocked');
1243
- }
1244
- }, _NetworkController_updateMetadataForNetwork = function _NetworkController_updateMetadataForNetwork(networkClientId, metadata) {
1245
- this.update((state) => {
1246
- var _a;
1247
- (_a = state.networksMetadata)[networkClientId] ?? (_a[networkClientId] = {
1248
- status: constants_js_1.NetworkStatus.Unknown,
1249
- EIPS: {},
1250
- });
1251
- const newMetadata = state.networksMetadata[networkClientId];
1252
- newMetadata.status = metadata.networkStatus;
1253
- if ('isEIP1559Compatible' in metadata) {
1254
- if (metadata.isEIP1559Compatible === undefined) {
1255
- delete newMetadata.EIPS[1559];
1256
- }
1257
- else {
1258
- newMetadata.EIPS[1559] = metadata.isEIP1559Compatible;
1259
- }
1260
- }
1261
- });
1262
- }, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock(networkClientId = this.state.selectedNetworkClientId) {
1263
- const networkClient = this.getNetworkClientById(networkClientId);
1264
- const ethQuery = new eth_query_1.default(networkClient.provider);
1265
- return new Promise((resolve, reject) => {
1266
- ethQuery.sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
1267
- if (error) {
1268
- // This error comes from JsonRpcEngine, we don't control it.
1269
- // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
1270
- reject(error);
1271
- }
1272
- else {
1273
- // TODO: Validate this type
1274
- resolve(block);
1275
- }
1276
- });
1277
- });
1278
- }, _NetworkController_determineEIP1559Compatibility =
1279
- /**
1280
- * Retrieves and checks the latest block from the currently selected
1281
- * network; if the block has a `baseFeePerGas` property, then we know
1282
- * that the network supports EIP-1559; otherwise it doesn't.
1283
- *
1284
- * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility
1285
- * @returns A promise that resolves to `true` if the network supports EIP-1559,
1286
- * `false` otherwise, or `undefined` if unable to retrieve the last block.
1287
- */
1288
- async function _NetworkController_determineEIP1559Compatibility(networkClientId) {
1289
- const latestBlock = await __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this, networkClientId);
1290
- if (!latestBlock) {
1291
- return undefined;
1292
- }
1293
- return latestBlock.baseFeePerGas !== undefined;
1294
- }, _NetworkController_validateNetworkFields = function _NetworkController_validateNetworkFields(args) {
1295
- const { mode, networkFields, autoManagedNetworkClientRegistry } = args;
1296
- const existingNetworkConfiguration = 'existingNetworkConfiguration' in args
1297
- ? args.existingNetworkConfiguration
1298
- : null;
1299
- const errorMessagePrefix = mode === 'update' ? 'Could not update network' : 'Could not add network';
1300
- if (!(0, utils_1.isStrictHexString)(networkFields.chainId) ||
1301
- !(0, controller_utils_1.isSafeChainId)(networkFields.chainId)) {
1302
- throw new Error(`${errorMessagePrefix}: Invalid \`chainId\` '${networkFields.chainId}' (must start with "0x" and not exceed the maximum)`);
1303
- }
1304
- if (networkFields.chainId !== existingNetworkConfiguration?.chainId) {
1305
- const existingNetworkConfigurationViaChainId = this.state.networkConfigurationsByChainId[networkFields.chainId];
1306
- if (existingNetworkConfigurationViaChainId !== undefined) {
1307
- if (existingNetworkConfiguration === null) {
1308
- throw new Error(`Could not add network for chain ${args.networkFields.chainId} as another network for that chain already exists ('${existingNetworkConfigurationViaChainId.name}')`);
1309
- }
1310
- else {
1311
- throw new Error(`Cannot move network from chain ${existingNetworkConfiguration.chainId} to ${networkFields.chainId} as another network for that chain already exists ('${existingNetworkConfigurationViaChainId.name}')`);
1312
- }
1313
- }
1314
- }
1315
- const isInvalidDefaultBlockExplorerUrlIndex = networkFields.blockExplorerUrls.length > 0
1316
- ? networkFields.defaultBlockExplorerUrlIndex === undefined ||
1317
- networkFields.blockExplorerUrls[networkFields.defaultBlockExplorerUrlIndex] === undefined
1318
- : networkFields.defaultBlockExplorerUrlIndex !== undefined;
1319
- if (isInvalidDefaultBlockExplorerUrlIndex) {
1320
- throw new Error(`${errorMessagePrefix}: \`defaultBlockExplorerUrlIndex\` must refer to an entry in \`blockExplorerUrls\``);
1321
- }
1322
- if (networkFields.rpcEndpoints.length === 0) {
1323
- throw new Error(`${errorMessagePrefix}: \`rpcEndpoints\` must be a non-empty array`);
1324
- }
1325
- for (const rpcEndpointFields of networkFields.rpcEndpoints) {
1326
- if (!isValidUrl(rpcEndpointFields.url)) {
1327
- throw new Error(`${errorMessagePrefix}: An entry in \`rpcEndpoints\` has invalid URL '${rpcEndpointFields.url}'`);
1328
- }
1329
- const networkClientId = 'networkClientId' in rpcEndpointFields
1330
- ? rpcEndpointFields.networkClientId
1331
- : undefined;
1332
- if (mode === 'update' &&
1333
- networkClientId !== undefined &&
1334
- rpcEndpointFields.type === RpcEndpointType.Custom &&
1335
- !Object.values(autoManagedNetworkClientRegistry).some((networkClientsById) => networkClientId in networkClientsById)) {
1336
- throw new Error(`${errorMessagePrefix}: RPC endpoint '${rpcEndpointFields.url}' refers to network client '${networkClientId}' that does not exist`);
1337
- }
1338
- if (networkFields.rpcEndpoints.some((otherRpcEndpointFields) => otherRpcEndpointFields !== rpcEndpointFields &&
1339
- URI.equal(otherRpcEndpointFields.url, rpcEndpointFields.url))) {
1340
- throw new Error(`${errorMessagePrefix}: Each entry in rpcEndpoints must have a unique URL`);
1341
- }
1342
- const networkConfigurationsForOtherChains = Object.values(this.state.networkConfigurationsByChainId).filter((networkConfiguration) => existingNetworkConfiguration
1343
- ? networkConfiguration.chainId !==
1344
- existingNetworkConfiguration.chainId
1345
- : true);
1346
- for (const networkConfiguration of networkConfigurationsForOtherChains) {
1347
- const rpcEndpoint = networkConfiguration.rpcEndpoints.find((existingRpcEndpoint) => URI.equal(rpcEndpointFields.url, existingRpcEndpoint.url));
1348
- if (rpcEndpoint) {
1349
- if (mode === 'update') {
1350
- throw new Error(`Could not update network to point to same RPC endpoint as existing network for chain ${networkConfiguration.chainId} ('${networkConfiguration.name}')`);
1351
- }
1352
- else {
1353
- throw new Error(`Could not add network that points to same RPC endpoint as existing network for chain ${networkConfiguration.chainId} ('${networkConfiguration.name}')`);
1354
- }
1355
- }
1356
- }
1357
- }
1358
- if ([...new Set(networkFields.rpcEndpoints)].length <
1359
- networkFields.rpcEndpoints.length) {
1360
- throw new Error(`${errorMessagePrefix}: Each entry in rpcEndpoints must be unique`);
1361
- }
1362
- const networkClientIds = networkFields.rpcEndpoints
1363
- .map((rpcEndpoint) => 'networkClientId' in rpcEndpoint
1364
- ? rpcEndpoint.networkClientId
1365
- : undefined)
1366
- .filter((networkClientId) => networkClientId !== undefined);
1367
- if ([...new Set(networkClientIds)].length < networkClientIds.length) {
1368
- throw new Error(`${errorMessagePrefix}: Each entry in rpcEndpoints must have a unique networkClientId`);
1369
- }
1370
- const infuraRpcEndpoints = networkFields.rpcEndpoints.filter((rpcEndpointFields) => rpcEndpointFields.type === RpcEndpointType.Infura);
1371
- if (infuraRpcEndpoints.length > 1) {
1372
- throw new Error(`${errorMessagePrefix}: There cannot be more than one Infura RPC endpoint`);
1373
- }
1374
- if (networkFields.rpcEndpoints[networkFields.defaultRpcEndpointIndex] ===
1375
- undefined) {
1376
- throw new Error(`${errorMessagePrefix}: \`defaultRpcEndpointIndex\` must refer to an entry in \`rpcEndpoints\``);
1377
- }
1378
- }, _NetworkController_determineNetworkConfigurationToPersist = function _NetworkController_determineNetworkConfigurationToPersist({ networkFields, networkClientOperations, }) {
1379
- const rpcEndpointsToPersist = networkClientOperations
1380
- .filter((networkClientOperation) => {
1381
- return (networkClientOperation.type === 'add' ||
1382
- networkClientOperation.type === 'noop');
1383
- })
1384
- .map((networkClientOperation) => networkClientOperation.rpcEndpoint)
1385
- .concat(networkClientOperations
1386
- .filter((networkClientOperation) => {
1387
- return networkClientOperation.type === 'replace';
1388
- })
1389
- .map((networkClientOperation) => networkClientOperation.newRpcEndpoint));
1390
- return { ...networkFields, rpcEndpoints: rpcEndpointsToPersist };
1391
- }, _NetworkController_registerNetworkClientsAsNeeded = function _NetworkController_registerNetworkClientsAsNeeded({ networkFields, networkClientOperations, autoManagedNetworkClientRegistry, }) {
1392
- const addedRpcEndpoints = networkClientOperations
1393
- .filter((networkClientOperation) => {
1394
- return networkClientOperation.type === 'add';
1395
- })
1396
- .map((networkClientOperation) => networkClientOperation.rpcEndpoint)
1397
- .concat(networkClientOperations
1398
- .filter((networkClientOperation) => {
1399
- return networkClientOperation.type === 'replace';
1400
- })
1401
- .map((networkClientOperation) => networkClientOperation.newRpcEndpoint));
1402
- const defaultFailoverUrls = __classPrivateFieldGet(this, _NetworkController_failoverUrls, "f")?.[networkFields.chainId];
1403
- for (const addedRpcEndpoint of addedRpcEndpoints) {
1404
- if (addedRpcEndpoint.type === RpcEndpointType.Infura) {
1405
- autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Infura][addedRpcEndpoint.networkClientId] = (0, create_auto_managed_network_client_js_1.createAutoManagedNetworkClient)({
1406
- networkClientId: addedRpcEndpoint.networkClientId,
1407
- networkClientConfiguration: {
1408
- type: types_js_1.NetworkClientType.Infura,
1409
- chainId: networkFields.chainId,
1410
- network: addedRpcEndpoint.networkClientId,
1411
- failoverRpcUrls: defaultFailoverUrls ?? addedRpcEndpoint.failoverUrls,
1412
- infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
1413
- ticker: networkFields.nativeCurrency,
1414
- },
1415
- getRpcServiceOptions: __classPrivateFieldGet(this, _NetworkController_getRpcServiceOptions, "f"),
1416
- getBlockTrackerOptions: __classPrivateFieldGet(this, _NetworkController_getBlockTrackerOptions, "f"),
1417
- messenger: this.messenger,
1418
- rpcFailoverMode: __classPrivateFieldGet(this, _NetworkController_rpcFailoverMode, "f"),
1419
- logger: __classPrivateFieldGet(this, _NetworkController_log, "f"),
1420
- });
1421
- }
1422
- else {
1423
- autoManagedNetworkClientRegistry[types_js_1.NetworkClientType.Custom][addedRpcEndpoint.networkClientId] = (0, create_auto_managed_network_client_js_1.createAutoManagedNetworkClient)({
1424
- networkClientId: addedRpcEndpoint.networkClientId,
1425
- networkClientConfiguration: {
1426
- type: types_js_1.NetworkClientType.Custom,
1427
- chainId: networkFields.chainId,
1428
- failoverRpcUrls: defaultFailoverUrls ?? addedRpcEndpoint.failoverUrls,
1429
- rpcUrl: addedRpcEndpoint.url,
1430
- ticker: networkFields.nativeCurrency,
1431
- },
1432
- getRpcServiceOptions: __classPrivateFieldGet(this, _NetworkController_getRpcServiceOptions, "f"),
1433
- getBlockTrackerOptions: __classPrivateFieldGet(this, _NetworkController_getBlockTrackerOptions, "f"),
1434
- messenger: this.messenger,
1435
- rpcFailoverMode: __classPrivateFieldGet(this, _NetworkController_rpcFailoverMode, "f"),
1436
- logger: __classPrivateFieldGet(this, _NetworkController_log, "f"),
1437
- });
1438
- }
1439
- }
1440
- }, _NetworkController_unregisterNetworkClientsAsNeeded = function _NetworkController_unregisterNetworkClientsAsNeeded({ networkClientOperations, autoManagedNetworkClientRegistry, }) {
1441
- const removedRpcEndpoints = networkClientOperations
1442
- .filter((networkClientOperation) => {
1443
- return networkClientOperation.type === 'remove';
1444
- })
1445
- .map((networkClientOperation) => networkClientOperation.rpcEndpoint)
1446
- .concat(networkClientOperations
1447
- .filter((networkClientOperation) => {
1448
- return networkClientOperation.type === 'replace';
1449
- })
1450
- .map((networkClientOperation) => networkClientOperation.oldRpcEndpoint));
1451
- for (const rpcEndpoint of removedRpcEndpoints) {
1452
- const networkClient = this.getNetworkClientById(rpcEndpoint.networkClientId);
1453
- networkClient.destroy();
1454
- delete autoManagedNetworkClientRegistry[networkClient.configuration.type][rpcEndpoint.networkClientId];
1455
- }
1456
- }, _NetworkController_updateNetworkConfigurations = function _NetworkController_updateNetworkConfigurations(args) {
1457
- const { state, mode } = args;
1458
- if (mode === 'remove' ||
1459
- (mode === 'update' &&
1460
- args.networkFields.chainId !==
1461
- args.existingNetworkConfiguration.chainId)) {
1462
- delete state.networkConfigurationsByChainId[args.existingNetworkConfiguration.chainId];
1463
- }
1464
- if (mode === 'add' || mode === 'update') {
1465
- if (!(0, fast_deep_equal_1.default)(state.networkConfigurationsByChainId[args.networkFields.chainId], args.networkConfigurationToPersist)) {
1466
- args.networkConfigurationToPersist.lastUpdatedAt = Date.now();
1467
- }
1468
- state.networkConfigurationsByChainId[args.networkFields.chainId] =
1469
- args.networkConfigurationToPersist;
1470
- }
1471
- __classPrivateFieldSet(this, _NetworkController_networkConfigurationsByNetworkClientId, buildNetworkConfigurationsByNetworkClientId((0, lodash_1.cloneDeep)(state.networkConfigurationsByChainId)), "f");
1472
- }, _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated = function _NetworkController_ensureAutoManagedNetworkClientRegistryPopulated() {
1473
- return (__classPrivateFieldSet(this, _NetworkController_autoManagedNetworkClientRegistry, __classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClientRegistry, "f") ?? __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_createAutoManagedNetworkClientRegistry).call(this), "f"));
1474
- }, _NetworkController_createAutoManagedNetworkClientRegistry = function _NetworkController_createAutoManagedNetworkClientRegistry() {
1475
- const chainIds = knownKeysOf(this.state.networkConfigurationsByChainId);
1476
- const networkClientsWithIds = chainIds.flatMap((chainId) => {
1477
- const networkConfiguration = this.state.networkConfigurationsByChainId[chainId];
1478
- const defaultFailoverUrls = __classPrivateFieldGet(this, _NetworkController_failoverUrls, "f")?.[chainId];
1479
- return networkConfiguration.rpcEndpoints.map((rpcEndpoint) => {
1480
- if (rpcEndpoint.type === RpcEndpointType.Infura) {
1481
- const infuraNetworkName = deriveInfuraNetworkNameFromRpcEndpointUrl(rpcEndpoint.url);
1482
- return [
1483
- rpcEndpoint.networkClientId,
1484
- (0, create_auto_managed_network_client_js_1.createAutoManagedNetworkClient)({
1485
- networkClientId: rpcEndpoint.networkClientId,
1486
- networkClientConfiguration: {
1487
- type: types_js_1.NetworkClientType.Infura,
1488
- network: infuraNetworkName,
1489
- failoverRpcUrls: defaultFailoverUrls ?? rpcEndpoint.failoverUrls,
1490
- infuraProjectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
1491
- chainId: networkConfiguration.chainId,
1492
- ticker: networkConfiguration.nativeCurrency,
1493
- },
1494
- getRpcServiceOptions: __classPrivateFieldGet(this, _NetworkController_getRpcServiceOptions, "f"),
1495
- getBlockTrackerOptions: __classPrivateFieldGet(this, _NetworkController_getBlockTrackerOptions, "f"),
1496
- messenger: this.messenger,
1497
- rpcFailoverMode: __classPrivateFieldGet(this, _NetworkController_rpcFailoverMode, "f"),
1498
- logger: __classPrivateFieldGet(this, _NetworkController_log, "f"),
1499
- }),
1500
- ];
1501
- }
1502
- return [
1503
- rpcEndpoint.networkClientId,
1504
- (0, create_auto_managed_network_client_js_1.createAutoManagedNetworkClient)({
1505
- networkClientId: rpcEndpoint.networkClientId,
1506
- networkClientConfiguration: {
1507
- type: types_js_1.NetworkClientType.Custom,
1508
- chainId: networkConfiguration.chainId,
1509
- failoverRpcUrls: defaultFailoverUrls ?? rpcEndpoint.failoverUrls,
1510
- rpcUrl: rpcEndpoint.url,
1511
- ticker: networkConfiguration.nativeCurrency,
1512
- },
1513
- getRpcServiceOptions: __classPrivateFieldGet(this, _NetworkController_getRpcServiceOptions, "f"),
1514
- getBlockTrackerOptions: __classPrivateFieldGet(this, _NetworkController_getBlockTrackerOptions, "f"),
1515
- messenger: this.messenger,
1516
- rpcFailoverMode: __classPrivateFieldGet(this, _NetworkController_rpcFailoverMode, "f"),
1517
- logger: __classPrivateFieldGet(this, _NetworkController_log, "f"),
1518
- }),
1519
- ];
1520
- });
1521
- });
1522
- return networkClientsWithIds.reduce((obj, [networkClientId, networkClient]) => {
1523
- return {
1524
- ...obj,
1525
- [networkClient.configuration.type]: {
1526
- ...obj[networkClient.configuration.type],
1527
- [networkClientId]: networkClient,
1528
- },
1529
- };
1530
- }, {
1531
- [types_js_1.NetworkClientType.Custom]: {},
1532
- [types_js_1.NetworkClientType.Infura]: {},
1533
- });
1534
- }, _NetworkController_applyNetworkSelection = function _NetworkController_applyNetworkSelection(networkClientId, { updateState, } = {}) {
1535
- __classPrivateFieldSet(this, _NetworkController_autoManagedNetworkClient, this.getNetworkClientById(networkClientId), "f");
1536
- this.update((state) => {
1537
- var _a;
1538
- state.selectedNetworkClientId = networkClientId;
1539
- (_a = state.networksMetadata)[networkClientId] ?? (_a[networkClientId] = {
1540
- status: constants_js_1.NetworkStatus.Unknown,
1541
- EIPS: {},
1542
- });
1543
- updateState?.(state);
1544
- });
1545
- if (__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")) {
1546
- __classPrivateFieldGet(this, _NetworkController_providerProxy, "f").setTarget(__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClient, "f").provider);
1547
- }
1548
- else {
1549
- __classPrivateFieldSet(this, _NetworkController_providerProxy, (0, swappable_obj_proxy_1.createSwappableProxy)(__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClient, "f").provider), "f");
1550
- }
1551
- if (__classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f")) {
1552
- __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f").setTarget(__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClient, "f").blockTracker);
1553
- }
1554
- else {
1555
- __classPrivateFieldSet(this, _NetworkController_blockTrackerProxy, (0, swappable_obj_proxy_1.createEventEmitterProxy)(__classPrivateFieldGet(this, _NetworkController_autoManagedNetworkClient, "f").blockTracker, {
1556
- eventFilter: 'skipInternal',
1557
- }), "f");
1558
- }
1559
- __classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(__classPrivateFieldGet(this, _NetworkController_providerProxy, "f")), "f");
1560
- }, _NetworkController_autoAddNetworksFromConfigRegistry = function _NetworkController_autoAddNetworksFromConfigRegistry(caipChainIds) {
1561
- for (const caipChainId of caipChainIds) {
1562
- try {
1563
- const registryNetworkConfig = this.messenger.call('ConfigRegistryController:getNetworkConfigByCaip2ChainId', caipChainId);
1564
- const hexChainId = (0, utils_1.numberToHex)(Number((0, utils_1.parseCaipChainId)(caipChainId).reference));
1565
- if (!registryNetworkConfig ||
1566
- this.state.networkConfigurationsByChainId[hexChainId]) {
1567
- continue;
1568
- }
1569
- const rpcEndpoint = registryNetworkConfig.rpcProviders.default.type === 'infura'
1570
- ? {
1571
- type: RpcEndpointType.Infura,
1572
- networkClientId: registryNetworkConfig.rpcProviders.default.networkClientId,
1573
- url: registryNetworkConfig.rpcProviders.default
1574
- .url,
1575
- }
1576
- : {
1577
- type: RpcEndpointType.Custom,
1578
- url: registryNetworkConfig.rpcProviders.default.url,
1579
- };
1580
- this.addNetwork({
1581
- chainId: hexChainId,
1582
- name: registryNetworkConfig.name,
1583
- nativeCurrency: registryNetworkConfig.assets.native.symbol,
1584
- rpcEndpoints: [rpcEndpoint],
1585
- defaultRpcEndpointIndex: 0,
1586
- blockExplorerUrls: [registryNetworkConfig.blockExplorerUrls.default],
1587
- defaultBlockExplorerUrlIndex: 0,
1588
- });
1589
- }
1590
- catch (error) {
1591
- const capturedError = error instanceof Error ? error : new Error(String(error));
1592
- __classPrivateFieldGet(this, _NetworkController_log, "f")?.error(`Failed to auto-enable network for chain ID ${caipChainId}: ${capturedError}`);
1593
- this.messenger.captureException?.(capturedError);
1594
- }
1595
- }
1596
- };
1597
- //# sourceMappingURL=NetworkController.cjs.map