@metamask-previews/network-controller 18.0.1-preview-a8ffe8e → 18.0.1-preview-eec1f90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NetworkController.js +2 -2
- package/dist/NetworkController.mjs +1 -1
- package/dist/{chunk-XWP6GXMK.mjs → chunk-AJED3H6M.mjs} +20 -2
- package/dist/chunk-AJED3H6M.mjs.map +1 -0
- package/dist/{chunk-VNCJZRDU.js → chunk-UEWIYOS6.js} +20 -2
- package/dist/chunk-UEWIYOS6.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/NetworkController.d.ts +15 -2
- package/dist/types/NetworkController.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-VNCJZRDU.js.map +0 -1
- package/dist/chunk-XWP6GXMK.mjs.map +0 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var
|
|
5
|
+
var _chunkUEWIYOS6js = require('./chunk-UEWIYOS6.js');
|
|
6
6
|
require('./chunk-ZKNI7MD3.js');
|
|
7
7
|
require('./chunk-LTT6WJXC.js');
|
|
8
8
|
require('./chunk-NFRLCZQI.js');
|
|
@@ -13,5 +13,5 @@ require('./chunk-Z4BLTVTB.js');
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
exports.NetworkController =
|
|
16
|
+
exports.NetworkController = _chunkUEWIYOS6js.NetworkController; exports.defaultState = _chunkUEWIYOS6js.defaultState; exports.knownKeysOf = _chunkUEWIYOS6js.knownKeysOf;
|
|
17
17
|
//# sourceMappingURL=NetworkController.js.map
|
|
@@ -265,12 +265,16 @@ var NetworkController = class extends BaseController {
|
|
|
265
265
|
`${this.name}:getNetworkConfigurationByNetworkClientId`,
|
|
266
266
|
this.getNetworkConfigurationByNetworkClientId.bind(this)
|
|
267
267
|
);
|
|
268
|
+
this.messagingSystem.registerActionHandler(
|
|
269
|
+
`${this.name}:getSelectedNetworkClient`,
|
|
270
|
+
this.getSelectedNetworkClient.bind(this)
|
|
271
|
+
);
|
|
268
272
|
__privateSet(this, _previousProviderConfig, this.state.providerConfig);
|
|
269
273
|
}
|
|
270
274
|
/**
|
|
271
275
|
* Accesses the provider and block tracker for the currently selected network.
|
|
272
|
-
*
|
|
273
276
|
* @returns The proxy and block tracker proxies.
|
|
277
|
+
* @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.
|
|
274
278
|
*/
|
|
275
279
|
getProviderAndBlockTracker() {
|
|
276
280
|
return {
|
|
@@ -278,6 +282,20 @@ var NetworkController = class extends BaseController {
|
|
|
278
282
|
blockTracker: __privateGet(this, _blockTrackerProxy)
|
|
279
283
|
};
|
|
280
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* Accesses the provider and block tracker for the currently selected network.
|
|
287
|
+
*
|
|
288
|
+
* @returns an object with the provider and block tracker proxies for the currently selected network.
|
|
289
|
+
*/
|
|
290
|
+
getSelectedNetworkClient() {
|
|
291
|
+
if (__privateGet(this, _providerProxy) && __privateGet(this, _blockTrackerProxy)) {
|
|
292
|
+
return {
|
|
293
|
+
provider: __privateGet(this, _providerProxy),
|
|
294
|
+
blockTracker: __privateGet(this, _blockTrackerProxy)
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
return void 0;
|
|
298
|
+
}
|
|
281
299
|
/**
|
|
282
300
|
* Returns all of the network clients that have been created so far, keyed by
|
|
283
301
|
* their identifier in the network client registry. This collection represents
|
|
@@ -996,4 +1014,4 @@ export {
|
|
|
996
1014
|
defaultState,
|
|
997
1015
|
NetworkController
|
|
998
1016
|
};
|
|
999
|
-
//# sourceMappingURL=chunk-
|
|
1017
|
+
//# sourceMappingURL=chunk-AJED3H6M.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NetworkController.ts"],"sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n isInfuraNetworkType,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { errorCodes } from '@metamask/rpc-errors';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraNetworkType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof name,\n NetworkState\n>;\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [NetworkState];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [NetworkState];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = ControllerGetStateAction<\n typeof name,\n NetworkState\n>;\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\n};\n\nexport type NetworkControllerGetSelectedNetworkClientAction = {\n type: `NetworkController:getSelectedNetworkClient`;\n handler: NetworkController['getSelectedNetworkClient'];\n};\n\nexport type NetworkControllerGetEIP1559CompatibilityAction = {\n type: `NetworkController:getEIP1559Compatibility`;\n handler: NetworkController['getEIP1559Compatibility'];\n};\n\nexport type NetworkControllerFindNetworkClientIdByChainIdAction = {\n type: `NetworkController:findNetworkClientIdByChainId`;\n handler: NetworkController['findNetworkClientIdByChainId'];\n};\n\n/**\n * Change the currently selected network to the given built-in network type.\n *\n * @deprecated This action has been replaced by `setActiveNetwork`, and will be\n * removed in a future release.\n */\nexport type NetworkControllerSetProviderTypeAction = {\n type: `NetworkController:setProviderType`;\n handler: NetworkController['setProviderType'];\n};\n\nexport type NetworkControllerSetActiveNetworkAction = {\n type: `NetworkController:setActiveNetwork`;\n handler: NetworkController['setActiveNetwork'];\n};\n\nexport type NetworkControllerGetNetworkConfigurationByNetworkClientId = {\n type: `NetworkController:getNetworkConfigurationByNetworkClientId`;\n handler: NetworkController['getNetworkConfigurationByNetworkClientId'];\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n never,\n never\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseController<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkConfigurationByNetworkClientId`,\n this.getNetworkConfigurationByNetworkClientId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getSelectedNetworkClient`,\n this.getSelectedNetworkClient.bind(this),\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n * @returns The proxy and block tracker proxies.\n * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns an object with the provider and block tracker proxies for the currently selected network.\n */\n getSelectedNetworkClient():\n | {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n blockTracker: SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>;\n }\n | undefined {\n if (this.#providerProxy && this.#blockTrackerProxy) {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n return undefined;\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraNetworkType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish(\n 'NetworkController:networkWillChange',\n this.state,\n );\n this.#applyNetworkSelection();\n this.messagingSystem.publish(\n 'NetworkController:networkDidChange',\n this.state,\n );\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Refreshes the network meta with EIP-1559 support and the network status\n * based on the given network client ID.\n *\n * @param networkClientId - The ID of the network client to update.\n */\n async lookupNetworkByClientId(networkClientId: NetworkClientId) {\n const isInfura = isInfuraNetworkType(networkClientId);\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n updatedIsEIP1559Compatible = await this.#determineEIP1559Compatibility(\n networkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else if (\n typeof Error !== 'undefined' &&\n hasProperty(error as unknown as Error, 'message') &&\n typeof (error as unknown as Error).message === 'string' &&\n (error as unknown as Error).message.includes(\n 'No custom network client was found with the ID',\n )\n ) {\n throw error;\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n this.update((state) => {\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n const meta = state.networksMetadata[networkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @param networkClientId - (Optional) The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n await this.lookupNetworkByClientId(networkClientId);\n return;\n }\n\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n * @deprecated This has been replaced by `setActiveNetwork`, and will be\n * removed in a future release\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraNetworkType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n await this.setActiveNetwork(type);\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationIdOrType - The unique id for the network configuration to set as the active provider,\n * or the type of a built-in network.\n */\n async setActiveNetwork(networkConfigurationIdOrType: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n let targetNetwork: ProviderConfig;\n if (isInfuraNetworkType(networkConfigurationIdOrType)) {\n const ticker = NetworksTicker[networkConfigurationIdOrType];\n\n targetNetwork = {\n chainId: ChainId[networkConfigurationIdOrType],\n id: undefined,\n rpcPrefs: BUILT_IN_NETWORKS[networkConfigurationIdOrType].rpcPrefs,\n rpcUrl: undefined,\n nickname: undefined,\n ticker,\n type: networkConfigurationIdOrType,\n };\n } else {\n if (\n !Object.keys(this.state.networkConfigurations).includes(\n networkConfigurationIdOrType,\n )\n ) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationIdOrType} does not match a configured networkConfiguration or built-in network type`,\n );\n }\n targetNetwork = {\n ...this.state.networkConfigurations[networkConfigurationIdOrType],\n type: NetworkType.rpc,\n };\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = targetNetwork;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(networkClientId: NetworkClientId): Promise<Block> {\n if (networkClientId === undefined) {\n networkClientId = this.state.selectedNetworkClientId;\n }\n\n const networkClient = this.getNetworkClientById(networkClientId);\n const ethQuery = new EthQuery(networkClient.provider);\n\n return new Promise((resolve, reject) => {\n ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n return this.get1559CompatibilityWithNetworkClientId(networkClientId);\n }\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n async get1559CompatibilityWithNetworkClientId(\n networkClientId: NetworkClientId,\n ) {\n let metadata = this.state.networksMetadata[networkClientId];\n if (metadata === undefined) {\n await this.lookupNetwork(networkClientId);\n metadata = this.state.networksMetadata[networkClientId];\n }\n const { EIPS } = metadata;\n\n // may want to include some 'freshness' value - something to make sure we refetch this from time to time\n return EIPS[1559];\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(\n networkClientId: NetworkClientId,\n ): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock(networkClientId);\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Returns a configuration object for the network identified by the given\n * network client ID. If given an Infura network type, constructs one based on\n * what we know about the network; otherwise attempts locates a network\n * configuration in state that corresponds to the network client ID.\n *\n * @param networkClientId - The network client ID.\n * @returns The configuration for the referenced network if one exists, or\n * undefined otherwise.\n */\n getNetworkConfigurationByNetworkClientId(\n networkClientId: NetworkClientId,\n ): NetworkConfiguration | undefined {\n if (isInfuraNetworkType(networkClientId)) {\n const rpcUrl = `https://${networkClientId}.infura.io/v3/${\n this.#infuraProjectId\n }`;\n return {\n rpcUrl,\n ...BUILT_IN_NETWORKS[networkClientId],\n };\n }\n\n return this.state.networkConfigurations[networkClientId];\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n ticker,\n });\n }\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n ticker: providerConfig.ticker,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#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AM,CAAC;AAAA,MACT;AAAA,IACF;AAAA,EACF,CAAC;AAED,QAAM,EAAE,UAAU,aAAa,IAAI;AAEnC,MAAI,mBAAK,iBAAgB;AACvB,uBAAK,gBAAe,UAAU,QAAQ;AAAA,EACxC,OAAO;AACL,uBAAK,gBAAiB,wBAAwB,QAAQ;AAAA,EACxD;AAEA,MAAI,mBAAK,qBAAoB;AAC3B,uBAAK,oBAAmB,UAAU,YAAY;AAAA,EAChD,OAAO;AACL,uBAAK,oBAAqB,wBAAwB,cAAc;AAAA,MAC9D,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,qBAAK,WAAY,IAAI,SAAS,mBAAK,eAAc;AACnD;","names":[]}
|
|
@@ -265,12 +265,16 @@ var NetworkController = class extends _basecontroller.BaseController {
|
|
|
265
265
|
`${this.name}:getNetworkConfigurationByNetworkClientId`,
|
|
266
266
|
this.getNetworkConfigurationByNetworkClientId.bind(this)
|
|
267
267
|
);
|
|
268
|
+
this.messagingSystem.registerActionHandler(
|
|
269
|
+
`${this.name}:getSelectedNetworkClient`,
|
|
270
|
+
this.getSelectedNetworkClient.bind(this)
|
|
271
|
+
);
|
|
268
272
|
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _previousProviderConfig, this.state.providerConfig);
|
|
269
273
|
}
|
|
270
274
|
/**
|
|
271
275
|
* Accesses the provider and block tracker for the currently selected network.
|
|
272
|
-
*
|
|
273
276
|
* @returns The proxy and block tracker proxies.
|
|
277
|
+
* @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.
|
|
274
278
|
*/
|
|
275
279
|
getProviderAndBlockTracker() {
|
|
276
280
|
return {
|
|
@@ -278,6 +282,20 @@ var NetworkController = class extends _basecontroller.BaseController {
|
|
|
278
282
|
blockTracker: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _blockTrackerProxy)
|
|
279
283
|
};
|
|
280
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* Accesses the provider and block tracker for the currently selected network.
|
|
287
|
+
*
|
|
288
|
+
* @returns an object with the provider and block tracker proxies for the currently selected network.
|
|
289
|
+
*/
|
|
290
|
+
getSelectedNetworkClient() {
|
|
291
|
+
if (_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _providerProxy) && _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _blockTrackerProxy)) {
|
|
292
|
+
return {
|
|
293
|
+
provider: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _providerProxy),
|
|
294
|
+
blockTracker: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _blockTrackerProxy)
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
return void 0;
|
|
298
|
+
}
|
|
281
299
|
/**
|
|
282
300
|
* Returns all of the network clients that have been created so far, keyed by
|
|
283
301
|
* their identifier in the network client registry. This collection represents
|
|
@@ -996,4 +1014,4 @@ applyNetworkSelection_fn = function() {
|
|
|
996
1014
|
|
|
997
1015
|
|
|
998
1016
|
exports.knownKeysOf = knownKeysOf; exports.defaultState = defaultState; exports.NetworkController = NetworkController;
|
|
999
|
-
//# sourceMappingURL=chunk-
|
|
1017
|
+
//# sourceMappingURL=chunk-UEWIYOS6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AACrB,SAAS,kBAAkB;AAC3B,SAAS,+BAA+B;AAGxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,cAAc;AACjC,SAAS,MAAM,cAAc;AAkB7B,IAAM,MAAM,mBAAmB,eAAe,mBAAmB;AAmF1D,SAAS,YAGd,QACA;AACA,SAAO,OAAO,KAAK,MAAM;AAC3B;AAcA,SAA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Action,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BUILT_IN_NETWORKS,\n NetworksTicker,\n ChainId,\n InfuraNetworkType,\n NetworkType,\n isSafeChainId,\n isInfuraNetworkType,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport { errorCodes } from '@metamask/rpc-errors';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertIsStrictHexString,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { strict as assert } from 'assert';\nimport { v4 as random } from 'uuid';\n\nimport { INFURA_BLOCKED_KEY, NetworkStatus } from './constants';\nimport type {\n AutoManagedNetworkClient,\n ProxyWithAccessibleTarget,\n} from './create-auto-managed-network-client';\nimport { createAutoManagedNetworkClient } from './create-auto-managed-network-client';\nimport { projectLogger, createModuleLogger } from './logger';\nimport { NetworkClientType } from './types';\nimport type {\n BlockTracker,\n Provider,\n CustomNetworkClientConfiguration,\n InfuraNetworkClientConfiguration,\n NetworkClientConfiguration,\n} from './types';\n\nconst log = createModuleLogger(projectLogger, 'NetworkController');\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcUrl - RPC target URL.\n * @property type - Human-readable network name.\n * @property chainId - Network ID as per EIP-155.\n * @property ticker - Currency ticker.\n * @property nickname - Personalized network name.\n * @property id - Network Configuration Id.\n */\nexport type ProviderConfig = {\n rpcUrl?: string;\n type: NetworkType;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\n/**\n * Information about a network not held by any other part of state.\n */\nexport type NetworkMetadata = {\n /**\n * EIPs supported by the network.\n */\n EIPS: {\n [eipNumber: number]: boolean;\n };\n /**\n * Indicates the availability of the network\n */\n status: NetworkStatus;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcUrl - RPC target URL.\n * @property chainId - Network ID as per EIP-155\n * @property nickname - Personalized network name.\n * @property ticker - Currency ticker.\n * @property rpcPrefs - Personalized preferences.\n */\nexport type NetworkConfiguration = {\n rpcUrl: string;\n chainId: Hex;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * The collection of network configurations in state.\n */\ntype NetworkConfigurations = Record<\n NetworkConfigurationId,\n NetworkConfiguration & { id: NetworkConfigurationId }\n>;\n\n/**\n * `Object.keys()` is intentionally generic: it returns the keys of an object,\n * but it cannot make guarantees about the contents of that object, so the type\n * of the keys is merely `string[]`. While this is technically accurate, it is\n * also unnecessary if we have an object that we own and whose contents are\n * known exactly.\n *\n * TODO: Move to @metamask/utils.\n *\n * @param object - The object.\n * @returns The keys of an object, typed according to the type of the object\n * itself.\n */\nexport function knownKeysOf<K extends PropertyKey>(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: Partial<Record<K, any>>,\n) {\n return Object.keys(object) as K[];\n}\n\n/**\n * Asserts that the given value is of the given type if the given validation\n * function returns a truthy result.\n *\n * @param value - The value to validate.\n * @param validate - A function used to validate that the value is of the given\n * type. Takes the `value` as an argument and is expected to return true or\n * false.\n * @param message - The message to throw if the function does not return a\n * truthy result.\n * @throws if the function does not return a truthy result.\n */\nfunction assertOfType<Type>(\n value: unknown,\n validate: (value: unknown) => boolean,\n message: string,\n): asserts value is Type {\n assert.ok(validate(value), message);\n}\n\n/**\n * Returns a portion of the given object with only the given keys.\n *\n * @param object - An object.\n * @param keys - The keys to pick from the object.\n * @returns the portion of the object.\n */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction pick<Obj extends Record<any, any>, Keys extends keyof Obj>(\n object: Obj,\n keys: Keys[],\n): Pick<Obj, Keys> {\n const pickedObject = keys.reduce<Partial<Pick<Obj, Keys>>>(\n (finalObject, key) => {\n return { ...finalObject, [key]: object[key] };\n },\n {},\n );\n assertOfType<Pick<Obj, Keys>>(\n pickedObject,\n () => keys.every((key) => key in pickedObject),\n 'The reduce did not produce an object with all of the desired keys.',\n );\n return pickedObject;\n}\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `code` property, such as an instance of Error.\n *\n * TODO: Move this to @metamask/utils.\n *\n * @param error - The object to check.\n * @returns True if `error` has a `code`, false otherwise.\n */\nfunction isErrorWithCode(error: unknown): error is { code: string | number } {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Builds an identifier for an Infura network client for lookup purposes.\n *\n * @param infuraNetworkOrProviderConfig - The name of an Infura network or a\n * provider config.\n * @returns The built identifier.\n */\nfunction buildInfuraNetworkClientId(\n infuraNetworkOrProviderConfig:\n | InfuraNetworkType\n | (ProviderConfig & { type: InfuraNetworkType }),\n): BuiltInNetworkClientId {\n if (typeof infuraNetworkOrProviderConfig === 'string') {\n return infuraNetworkOrProviderConfig;\n }\n return infuraNetworkOrProviderConfig.type;\n}\n\n/**\n * Builds an identifier for a custom network client for lookup purposes.\n *\n * @param args - This function can be called two ways:\n * 1. The ID of a network configuration.\n * 2. A provider config and a set of network configurations.\n * @returns The built identifier.\n */\nfunction buildCustomNetworkClientId(\n ...args:\n | [NetworkConfigurationId]\n | [\n ProviderConfig & { type: typeof NetworkType.rpc; rpcUrl: string },\n NetworkConfigurations,\n ]\n): CustomNetworkClientId {\n if (args.length === 1) {\n return args[0];\n }\n const [{ id, rpcUrl }, networkConfigurations] = args;\n if (id === undefined) {\n const matchingNetworkConfiguration = Object.values(\n networkConfigurations,\n ).find((networkConfiguration) => {\n return networkConfiguration.rpcUrl === rpcUrl.toLowerCase();\n });\n if (matchingNetworkConfiguration) {\n return matchingNetworkConfiguration.id;\n }\n return rpcUrl.toLowerCase();\n }\n return id;\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isInfuraProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: InfuraNetworkType } {\n return isInfuraNetworkType(providerConfig.type);\n}\n\n/**\n * Returns whether the given provider config refers to an Infura network.\n *\n * @param providerConfig - The provider config.\n * @returns True if the provider config refers to an Infura network, false\n * otherwise.\n */\nfunction isCustomProviderConfig(\n providerConfig: ProviderConfig,\n): providerConfig is ProviderConfig & { type: typeof NetworkType.rpc } {\n return providerConfig.type === NetworkType.rpc;\n}\n\n/**\n * As a provider config represents the settings that are used to interface with\n * an RPC endpoint, it must have both a chain ID and an RPC URL if it represents\n * a custom network. These properties _should_ be set as they are validated in\n * the UI when a user adds a custom network, but just to be safe we validate\n * them here.\n *\n * In addition, historically the `rpcUrl` property on the ProviderConfig type\n * has been optional, even though it should not be. Making this non-optional\n * would be a breaking change, so this function types the provider config\n * correctly so that we don't have to check `rpcUrl` in other places.\n *\n * @param providerConfig - A provider config.\n * @throws if the provider config does not have a chain ID or an RPC URL.\n */\nfunction validateCustomProviderConfig(\n providerConfig: ProviderConfig & { type: typeof NetworkType.rpc },\n): asserts providerConfig is typeof providerConfig & { rpcUrl: string } {\n if (providerConfig.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (providerConfig.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n}\n/**\n * The string that uniquely identifies an Infura network client.\n */\ntype BuiltInNetworkClientId = InfuraNetworkType;\n\n/**\n * The string that uniquely identifies a custom network client.\n */\ntype CustomNetworkClientId = string;\n\n/**\n * The string that uniquely identifies a network client.\n */\nexport type NetworkClientId = BuiltInNetworkClientId | CustomNetworkClientId;\n\n/**\n * Information about networks not held by any other part of state.\n */\nexport type NetworksMetadata = {\n [networkClientId: NetworkClientId]: NetworkMetadata;\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n selectedNetworkClientId: NetworkClientId;\n providerConfig: ProviderConfig;\n networkConfigurations: NetworkConfigurations;\n networksMetadata: NetworksMetadata;\n};\n\nconst name = 'NetworkController';\n\n/**\n * Represents the block tracker for the currently selected network. (Note that\n * this is a proxy around a proxy: the inner one exists so that the block\n * tracker doesn't have to exist until it's used, and the outer one exists so\n * that the currently selected network can change without consumers needing to\n * refresh the object reference to that network.)\n */\nexport type BlockTrackerProxy = SwappableProxy<\n ProxyWithAccessibleTarget<BlockTracker>\n>;\n\n/**\n * Represents the provider for the currently selected network. (Note that this\n * is a proxy around a proxy: the inner one exists so that the provider doesn't\n * have to exist until it's used, and the outer one exists so that the currently\n * selected network can change without consumers needing to refresh the object\n * reference to that network.)\n */\nexport type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n\nexport type NetworkControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof name,\n NetworkState\n>;\n\n/**\n * `networkWillChange` is published when the current network is about to be\n * switched, but the new provider has not been created and no state changes have\n * occurred yet.\n */\nexport type NetworkControllerNetworkWillChangeEvent = {\n type: 'NetworkController:networkWillChange';\n payload: [NetworkState];\n};\n\n/**\n * `networkDidChange` is published after a provider has been created for a newly\n * switched network (but before the network has been confirmed to be available).\n */\nexport type NetworkControllerNetworkDidChangeEvent = {\n type: 'NetworkController:networkDidChange';\n payload: [NetworkState];\n};\n\n/**\n * `infuraIsBlocked` is published after the network is switched to an Infura\n * network, but when Infura returns an error blocking the user based on their\n * location.\n */\nexport type NetworkControllerInfuraIsBlockedEvent = {\n type: 'NetworkController:infuraIsBlocked';\n payload: [];\n};\n\n/**\n * `infuraIsBlocked` is published either after the network is switched to an\n * Infura network and Infura does not return an error blocking the user based on\n * their location, or the network is switched to a non-Infura network.\n */\nexport type NetworkControllerInfuraIsUnblockedEvent = {\n type: 'NetworkController:infuraIsUnblocked';\n payload: [];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerNetworkWillChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | NetworkControllerInfuraIsBlockedEvent\n | NetworkControllerInfuraIsUnblockedEvent;\n\nexport type NetworkControllerGetStateAction = ControllerGetStateAction<\n typeof name,\n NetworkState\n>;\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery | undefined;\n};\n\nexport type NetworkControllerGetNetworkClientByIdAction = {\n type: `NetworkController:getNetworkClientById`;\n handler: NetworkController['getNetworkClientById'];\n};\n\nexport type NetworkControllerGetSelectedNetworkClientAction = {\n type: `NetworkController:getSelectedNetworkClient`;\n handler: NetworkController['getSelectedNetworkClient'];\n};\n\nexport type NetworkControllerGetEIP1559CompatibilityAction = {\n type: `NetworkController:getEIP1559Compatibility`;\n handler: NetworkController['getEIP1559Compatibility'];\n};\n\nexport type NetworkControllerFindNetworkClientIdByChainIdAction = {\n type: `NetworkController:findNetworkClientIdByChainId`;\n handler: NetworkController['findNetworkClientIdByChainId'];\n};\n\n/**\n * Change the currently selected network to the given built-in network type.\n *\n * @deprecated This action has been replaced by `setActiveNetwork`, and will be\n * removed in a future release.\n */\nexport type NetworkControllerSetProviderTypeAction = {\n type: `NetworkController:setProviderType`;\n handler: NetworkController['setProviderType'];\n};\n\nexport type NetworkControllerSetActiveNetworkAction = {\n type: `NetworkController:setActiveNetwork`;\n handler: NetworkController['setActiveNetwork'];\n};\n\nexport type NetworkControllerGetNetworkConfigurationByNetworkClientId = {\n type: `NetworkController:getNetworkConfigurationByNetworkClientId`;\n handler: NetworkController['getNetworkConfigurationByNetworkClientId'];\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetEIP1559CompatibilityAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerSetActiveNetworkAction\n | NetworkControllerSetProviderTypeAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerActions,\n NetworkControllerEvents,\n never,\n never\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n selectedNetworkClientId: NetworkType.mainnet,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: ChainId.mainnet,\n ticker: NetworksTicker.mainnet,\n },\n networksMetadata: {},\n networkConfigurations: {},\n};\n\ntype MetaMetricsEventPayload = {\n event: string;\n category: string;\n referrer?: { url: string };\n actionId?: number;\n environmentType?: string;\n properties?: unknown;\n sensitiveProperties?: unknown;\n revenue?: number;\n currency?: string;\n value?: number;\n};\n\ntype NetworkConfigurationId = string;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedBuiltInNetworkClientRegistry = Record<\n BuiltInNetworkClientId,\n AutoManagedNetworkClient<InfuraNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks.\n */\ntype AutoManagedCustomNetworkClientRegistry = Record<\n CustomNetworkClientId,\n AutoManagedNetworkClient<CustomNetworkClientConfiguration>\n>;\n\n/**\n * The collection of auto-managed network clients that map to Infura networks\n * as well as custom networks that users have added.\n */\ntype AutoManagedNetworkClientRegistry = {\n [NetworkClientType.Infura]: AutoManagedBuiltInNetworkClientRegistry;\n [NetworkClientType.Custom]: AutoManagedCustomNetworkClientRegistry;\n};\n\n/**\n * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseController<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery?: EthQuery;\n\n #infuraProjectId: string;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #previousProviderConfig: ProviderConfig;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n #autoManagedNetworkClientRegistry?: AutoManagedNetworkClientRegistry;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n selectedNetworkClientId: {\n persist: true,\n anonymous: false,\n },\n networksMetadata: {\n persist: true,\n anonymous: false,\n },\n providerConfig: {\n persist: true,\n anonymous: false,\n },\n networkConfigurations: {\n persist: true,\n anonymous: false,\n },\n },\n messenger,\n state: { ...defaultState, ...state },\n });\n if (!infuraProjectId || typeof infuraProjectId !== 'string') {\n throw new Error('Invalid Infura project ID');\n }\n this.#infuraProjectId = infuraProjectId;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.messagingSystem.registerActionHandler(\n `${this.name}:getProviderConfig`,\n () => {\n return this.state.providerConfig;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEthQuery`,\n () => {\n return this.#ethQuery;\n },\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkClientById`,\n this.getNetworkClientById.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getEIP1559Compatibility`,\n this.getEIP1559Compatibility.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setActiveNetwork`,\n this.setActiveNetwork.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:setProviderType`,\n this.setProviderType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:findNetworkClientIdByChainId`,\n this.findNetworkClientIdByChainId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getNetworkConfigurationByNetworkClientId`,\n this.getNetworkConfigurationByNetworkClientId.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${this.name}:getSelectedNetworkClient`,\n this.getSelectedNetworkClient.bind(this),\n );\n\n this.#previousProviderConfig = this.state.providerConfig;\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n * @returns The proxy and block tracker proxies.\n * @deprecated This method has been replaced by `getSelectedNetworkClient` (which has a more easily used return type) and will be removed in a future release.\n */\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>> | undefined;\n blockTracker:\n | SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>\n | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n /**\n * Accesses the provider and block tracker for the currently selected network.\n *\n * @returns an object with the provider and block tracker proxies for the currently selected network.\n */\n getSelectedNetworkClient():\n | {\n provider: SwappableProxy<ProxyWithAccessibleTarget<Provider>>;\n blockTracker: SwappableProxy<ProxyWithAccessibleTarget<BlockTracker>>;\n }\n | undefined {\n if (this.#providerProxy && this.#blockTrackerProxy) {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n return undefined;\n }\n\n /**\n * Returns all of the network clients that have been created so far, keyed by\n * their identifier in the network client registry. This collection represents\n * not only built-in networks but also any custom networks that consumers have\n * added.\n *\n * @returns The list of known network clients.\n */\n getNetworkClientRegistry(): AutoManagedBuiltInNetworkClientRegistry &\n AutoManagedCustomNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n return Object.assign(\n {},\n autoManagedNetworkClientRegistry[NetworkClientType.Infura],\n autoManagedNetworkClientRegistry[NetworkClientType.Custom],\n );\n }\n\n /**\n * Returns the Infura network client with the given ID.\n *\n * @param infuraNetworkClientId - An Infura network client ID.\n * @returns The Infura network client.\n * @throws If an Infura network client does not exist with the given ID.\n */\n getNetworkClientById(\n infuraNetworkClientId: BuiltInNetworkClientId,\n ): AutoManagedNetworkClient<InfuraNetworkClientConfiguration>;\n\n /**\n * Returns the custom network client with the given ID.\n *\n * @param customNetworkClientId - A custom network client ID.\n * @returns The custom network client.\n * @throws If a custom network client does not exist with the given ID.\n */\n getNetworkClientById(\n customNetworkClientId: CustomNetworkClientId,\n ): AutoManagedNetworkClient<CustomNetworkClientConfiguration>;\n\n getNetworkClientById(\n networkClientId: NetworkClientId,\n ): AutoManagedNetworkClient<NetworkClientConfiguration> {\n if (!networkClientId) {\n throw new Error('No network client ID was provided.');\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n if (isInfuraNetworkType(networkClientId)) {\n const infuraNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Infura][\n networkClientId\n ];\n if (!infuraNetworkClient) {\n throw new Error(\n `No Infura network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return infuraNetworkClient;\n }\n\n const customNetworkClient =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom][\n networkClientId\n ];\n if (!customNetworkClient) {\n throw new Error(\n `No custom network client was found with the ID \"${networkClientId}\".`,\n );\n }\n return customNetworkClient;\n }\n\n /**\n * Executes a series of steps to apply the changes to the provider config:\n *\n * 1. Notifies subscribers that the network is about to change.\n * 2. Looks up a known and preinitialized network client matching the provider\n * config and re-points the provider and block tracker proxy to it.\n * 3. Notifies subscribers that the network has changed.\n */\n async #refreshNetwork() {\n this.messagingSystem.publish(\n 'NetworkController:networkWillChange',\n this.state,\n );\n this.#applyNetworkSelection();\n this.messagingSystem.publish(\n 'NetworkController:networkDidChange',\n this.state,\n );\n await this.lookupNetwork();\n }\n\n /**\n * Populates the network clients and establishes the initial network based on\n * the provider configuration in state.\n */\n async initializeProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.#applyNetworkSelection();\n await this.lookupNetwork();\n }\n\n /**\n * Refreshes the network meta with EIP-1559 support and the network status\n * based on the given network client ID.\n *\n * @param networkClientId - The ID of the network client to update.\n */\n async lookupNetworkByClientId(networkClientId: NetworkClientId) {\n const isInfura = isInfuraNetworkType(networkClientId);\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n updatedIsEIP1559Compatible = await this.#determineEIP1559Compatibility(\n networkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else if (\n typeof Error !== 'undefined' &&\n hasProperty(error as unknown as Error, 'message') &&\n typeof (error as unknown as Error).message === 'string' &&\n (error as unknown as Error).message.includes(\n 'No custom network client was found with the ID',\n )\n ) {\n throw error;\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n this.update((state) => {\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n const meta = state.networksMetadata[networkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n }\n\n /**\n * Performs side effects after switching to a network. If the network is\n * available, updates the network state with the network ID of the network and\n * stores whether the network supports EIP-1559; otherwise clears said\n * information about the network that may have been previously stored.\n *\n * @param networkClientId - (Optional) The ID of the network client to update.\n * If no ID is provided, uses the currently selected network.\n * @fires infuraIsBlocked if the network is Infura-supported and is blocking\n * requests.\n * @fires infuraIsUnblocked if the network is Infura-supported and is not\n * blocking requests, or if the network is not Infura-supported.\n */\n async lookupNetwork(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n await this.lookupNetworkByClientId(networkClientId);\n return;\n }\n\n if (!this.#ethQuery) {\n return;\n }\n\n const isInfura = isInfuraProviderConfig(this.state.providerConfig);\n\n let networkChanged = false;\n const listener = () => {\n networkChanged = true;\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n };\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n let updatedNetworkStatus: NetworkStatus;\n let updatedIsEIP1559Compatible: boolean | undefined;\n\n try {\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n updatedNetworkStatus = NetworkStatus.Available;\n updatedIsEIP1559Compatible = isEIP1559Compatible;\n } catch (error) {\n if (isErrorWithCode(error)) {\n let responseBody;\n if (\n isInfura &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n try {\n responseBody = JSON.parse(error.message);\n } catch {\n // error.message must not be JSON\n }\n }\n\n if (\n isPlainObject(responseBody) &&\n responseBody.error === INFURA_BLOCKED_KEY\n ) {\n updatedNetworkStatus = NetworkStatus.Blocked;\n } else if (error.code === errorCodes.rpc.internal) {\n updatedNetworkStatus = NetworkStatus.Unknown;\n } else {\n updatedNetworkStatus = NetworkStatus.Unavailable;\n }\n } else {\n log('NetworkController - could not determine network status', error);\n updatedNetworkStatus = NetworkStatus.Unknown;\n }\n }\n\n if (networkChanged) {\n // If the network has changed, then `lookupNetwork` either has been or is\n // in the process of being called, so we don't need to go further.\n return;\n }\n this.messagingSystem.unsubscribe(\n 'NetworkController:networkDidChange',\n listener,\n );\n\n this.update((state) => {\n const meta = state.networksMetadata[state.selectedNetworkClientId];\n meta.status = updatedNetworkStatus;\n if (updatedIsEIP1559Compatible === undefined) {\n delete meta.EIPS[1559];\n } else {\n meta.EIPS[1559] = updatedIsEIP1559Compatible;\n }\n });\n\n if (isInfura) {\n if (updatedNetworkStatus === NetworkStatus.Available) {\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n } else if (updatedNetworkStatus === NetworkStatus.Blocked) {\n this.messagingSystem.publish('NetworkController:infuraIsBlocked');\n }\n } else {\n // Always publish infuraIsUnblocked regardless of network status to\n // prevent consumers from being stuck in a blocked state if they were\n // previously connected to an Infura network that was blocked\n this.messagingSystem.publish('NetworkController:infuraIsUnblocked');\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n * @deprecated This has been replaced by `setActiveNetwork`, and will be\n * removed in a future release\n */\n async setProviderType(type: InfuraNetworkType) {\n assert.notStrictEqual(\n type,\n NetworkType.rpc,\n `NetworkController - cannot call \"setProviderType\" with type \"${NetworkType.rpc}\". Use \"setActiveNetwork\"`,\n );\n assert.ok(\n isInfuraNetworkType(type),\n `Unknown Infura provider type \"${type}\".`,\n );\n\n await this.setActiveNetwork(type);\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationIdOrType - The unique id for the network configuration to set as the active provider,\n * or the type of a built-in network.\n */\n async setActiveNetwork(networkConfigurationIdOrType: string) {\n this.#previousProviderConfig = this.state.providerConfig;\n\n let targetNetwork: ProviderConfig;\n if (isInfuraNetworkType(networkConfigurationIdOrType)) {\n const ticker = NetworksTicker[networkConfigurationIdOrType];\n\n targetNetwork = {\n chainId: ChainId[networkConfigurationIdOrType],\n id: undefined,\n rpcPrefs: BUILT_IN_NETWORKS[networkConfigurationIdOrType].rpcPrefs,\n rpcUrl: undefined,\n nickname: undefined,\n ticker,\n type: networkConfigurationIdOrType,\n };\n } else {\n if (\n !Object.keys(this.state.networkConfigurations).includes(\n networkConfigurationIdOrType,\n )\n ) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationIdOrType} does not match a configured networkConfiguration or built-in network type`,\n );\n }\n targetNetwork = {\n ...this.state.networkConfigurations[networkConfigurationIdOrType],\n type: NetworkType.rpc,\n };\n }\n\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = targetNetwork;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Fetches the latest block for the network.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check the latest block. Defaults to the selectedNetworkClientId.\n * @returns A promise that either resolves to the block header or null if\n * there is no latest block, or rejects with an error.\n */\n #getLatestBlock(networkClientId: NetworkClientId): Promise<Block> {\n if (networkClientId === undefined) {\n networkClientId = this.state.selectedNetworkClientId;\n }\n\n const networkClient = this.getNetworkClientById(networkClientId);\n const ethQuery = new EthQuery(networkClient.provider);\n\n return new Promise((resolve, reject) => {\n ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: unknown, block?: unknown) => {\n if (error) {\n reject(error);\n } else {\n // TODO: Validate this type\n resolve(block as Block);\n }\n },\n );\n });\n }\n\n /**\n * Determines whether the network supports EIP-1559 by checking whether the\n * latest block has a `baseFeePerGas` property, then updates state\n * appropriately.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility.\n * @returns A promise that resolves to true if the network supports EIP-1559\n * , false otherwise, or `undefined` if unable to determine the compatibility.\n */\n async getEIP1559Compatibility(networkClientId?: NetworkClientId) {\n if (networkClientId) {\n return this.get1559CompatibilityWithNetworkClientId(networkClientId);\n }\n if (!this.#ethQuery) {\n return false;\n }\n\n const { EIPS } =\n this.state.networksMetadata[this.state.selectedNetworkClientId];\n\n if (EIPS[1559] !== undefined) {\n return EIPS[1559];\n }\n\n const isEIP1559Compatible = await this.#determineEIP1559Compatibility(\n this.state.selectedNetworkClientId,\n );\n this.update((state) => {\n if (isEIP1559Compatible !== undefined) {\n state.networksMetadata[state.selectedNetworkClientId].EIPS[1559] =\n isEIP1559Compatible;\n }\n });\n return isEIP1559Compatible;\n }\n\n async get1559CompatibilityWithNetworkClientId(\n networkClientId: NetworkClientId,\n ) {\n let metadata = this.state.networksMetadata[networkClientId];\n if (metadata === undefined) {\n await this.lookupNetwork(networkClientId);\n metadata = this.state.networksMetadata[networkClientId];\n }\n const { EIPS } = metadata;\n\n // may want to include some 'freshness' value - something to make sure we refetch this from time to time\n return EIPS[1559];\n }\n\n /**\n * Retrieves and checks the latest block from the currently selected\n * network; if the block has a `baseFeePerGas` property, then we know\n * that the network supports EIP-1559; otherwise it doesn't.\n *\n * @param networkClientId - The networkClientId to fetch the correct provider against which to check 1559 compatibility\n * @returns A promise that resolves to `true` if the network supports EIP-1559,\n * `false` otherwise, or `undefined` if unable to retrieve the last block.\n */\n async #determineEIP1559Compatibility(\n networkClientId: NetworkClientId,\n ): Promise<boolean | undefined> {\n const latestBlock = await this.#getLatestBlock(networkClientId);\n\n if (!latestBlock) {\n return undefined;\n }\n\n return latestBlock.baseFeePerGas !== undefined;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n await this.#refreshNetwork();\n }\n\n /**\n * Returns a configuration object for the network identified by the given\n * network client ID. If given an Infura network type, constructs one based on\n * what we know about the network; otherwise attempts locates a network\n * configuration in state that corresponds to the network client ID.\n *\n * @param networkClientId - The network client ID.\n * @returns The configuration for the referenced network if one exists, or\n * undefined otherwise.\n */\n getNetworkConfigurationByNetworkClientId(\n networkClientId: NetworkClientId,\n ): NetworkConfiguration | undefined {\n if (isInfuraNetworkType(networkClientId)) {\n const rpcUrl = `https://${networkClientId}.infura.io/v3/${\n this.#infuraProjectId\n }`;\n return {\n rpcUrl,\n ...BUILT_IN_NETWORKS[networkClientId],\n };\n }\n\n return this.state.networkConfigurations[networkClientId];\n }\n\n /**\n * Adds a new custom network or updates the information for an existing\n * network.\n *\n * This may involve updating the `networkConfigurations` property in\n * state as well and/or adding a new network client to the network client\n * registry. The `rpcUrl` and `chainId` of the given object are used to\n * determine which action to take:\n *\n * - If the `rpcUrl` corresponds to an existing network configuration\n * (case-insensitively), then it is overwritten with the object. Furthermore,\n * if the `chainId` is different from the existing network configuration, then\n * the existing network client is replaced with a new one.\n * - If the `rpcUrl` does not correspond to an existing network configuration\n * (case-insensitively), then the object is used to add a new network\n * configuration along with a new network client.\n *\n * @param networkConfiguration - The network configuration to add or update.\n * @param options - Additional configuration options.\n * @param options.referrer - Used to create a metrics event; the site from which the call originated, or 'metamask' for internal calls.\n * @param options.source - Used to create a metrics event; where the event originated (i.e. from a dapp or from the network form).\n * @param options.setActive - If true, switches to the network upon adding or updating it (default: false).\n * @returns The ID for the added or updated network configuration.\n */\n async upsertNetworkConfiguration(\n networkConfiguration: NetworkConfiguration,\n {\n referrer,\n source,\n setActive = false,\n }: {\n referrer: string;\n source: string;\n setActive?: boolean;\n },\n ): Promise<string> {\n const sanitizedNetworkConfiguration: NetworkConfiguration = pick(\n networkConfiguration,\n ['rpcUrl', 'chainId', 'ticker', 'nickname', 'rpcPrefs'],\n );\n const { rpcUrl, chainId, ticker } = sanitizedNetworkConfiguration;\n\n assertIsStrictHexString(chainId);\n if (!isSafeChainId(chainId)) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\n }\n if (!referrer || !source) {\n throw new Error(\n 'referrer and source are required arguments for adding or updating a network configuration',\n );\n }\n try {\n new URL(rpcUrl);\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n const existingNetworkConfiguration = Object.values(\n this.state.networkConfigurations,\n ).find(\n (networkConfig) =>\n networkConfig.rpcUrl.toLowerCase() === rpcUrl.toLowerCase(),\n );\n const upsertedNetworkConfigurationId = existingNetworkConfiguration\n ? existingNetworkConfiguration.id\n : random();\n const networkClientId = buildCustomNetworkClientId(\n upsertedNetworkConfigurationId,\n );\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n const shouldDestroyExistingNetworkClient =\n existingAutoManagedNetworkClient &&\n existingAutoManagedNetworkClient.configuration.chainId !== chainId;\n if (shouldDestroyExistingNetworkClient) {\n existingAutoManagedNetworkClient.destroy();\n }\n if (\n !existingAutoManagedNetworkClient ||\n shouldDestroyExistingNetworkClient\n ) {\n customNetworkClientRegistry[networkClientId] =\n createAutoManagedNetworkClient({\n type: NetworkClientType.Custom,\n chainId,\n rpcUrl,\n ticker,\n });\n }\n\n this.update((state) => {\n state.networkConfigurations[upsertedNetworkConfigurationId] = {\n id: upsertedNetworkConfigurationId,\n ...sanitizedNetworkConfiguration,\n };\n });\n\n if (!existingNetworkConfiguration) {\n this.#trackMetaMetricsEvent({\n event: 'Custom Network Added',\n category: 'Network',\n referrer: {\n url: referrer,\n },\n properties: {\n chain_id: chainId,\n symbol: ticker,\n source,\n },\n });\n }\n\n if (setActive) {\n await this.setActiveNetwork(upsertedNetworkConfigurationId);\n }\n\n return upsertedNetworkConfigurationId;\n }\n\n /**\n * Removes a custom network from state.\n *\n * This involves updating the `networkConfigurations` property in state as\n * well and removing the network client that corresponds to the network from\n * the client registry.\n *\n * @param networkConfigurationId - The ID of an existing network\n * configuration.\n */\n removeNetworkConfiguration(networkConfigurationId: string) {\n if (!this.state.networkConfigurations[networkConfigurationId]) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n const autoManagedNetworkClientRegistry =\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n const networkClientId = buildCustomNetworkClientId(networkConfigurationId);\n\n this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n\n const customNetworkClientRegistry =\n autoManagedNetworkClientRegistry[NetworkClientType.Custom];\n const existingAutoManagedNetworkClient =\n customNetworkClientRegistry[networkClientId];\n existingAutoManagedNetworkClient.destroy();\n delete customNetworkClientRegistry[networkClientId];\n }\n\n /**\n * Switches to the previously selected network, assuming that there is one\n * (if not and `initializeProvider` has not been previously called, then this\n * method is equivalent to calling `resetConnection`).\n */\n async rollbackToPreviousProvider() {\n this.#ensureAutoManagedNetworkClientRegistryPopulated();\n\n this.update((state) => {\n state.providerConfig = this.#previousProviderConfig;\n });\n\n await this.#refreshNetwork();\n }\n\n /**\n * Deactivates the controller, stopping any ongoing polling.\n *\n * In-progress requests will not be aborted.\n */\n async destroy() {\n await this.#blockTrackerProxy?.destroy();\n }\n\n /**\n * Updates the controller using the given backup data.\n *\n * @param backup - The data that has been backed up.\n * @param backup.networkConfigurations - Network configurations in the backup.\n */\n loadBackup({\n networkConfigurations,\n }: {\n networkConfigurations: NetworkState['networkConfigurations'];\n }): void {\n this.update((state) => {\n state.networkConfigurations = {\n ...state.networkConfigurations,\n ...networkConfigurations,\n };\n });\n }\n\n /**\n * Searches for a network configuration ID with the given ChainID and returns it.\n *\n * @param chainId - ChainId to search for\n * @returns networkClientId of the network configuration with the given chainId\n */\n findNetworkClientIdByChainId(chainId: Hex): NetworkClientId {\n const networkClients = this.getNetworkClientRegistry();\n const networkClientEntry = Object.entries(networkClients).find(\n ([_, networkClient]) => networkClient.configuration.chainId === chainId,\n );\n if (networkClientEntry === undefined) {\n throw new Error(\"Couldn't find networkClientId for chainId\");\n }\n return networkClientEntry[0];\n }\n\n /**\n * Before accessing or switching the network, the registry of network clients\n * needs to be populated. Otherwise, `#applyNetworkSelection` and\n * `getNetworkClientRegistry` will throw an error. This method checks to see if the\n * population step has happened yet, and if not, makes it happen.\n *\n * @returns The populated network client registry.\n */\n #ensureAutoManagedNetworkClientRegistryPopulated(): AutoManagedNetworkClientRegistry {\n const autoManagedNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry ??\n this.#createAutoManagedNetworkClientRegistry();\n this.#autoManagedNetworkClientRegistry = autoManagedNetworkClientRegistry;\n return autoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the registry of network clients based on the set of built-in\n * networks as well as the custom networks in state.\n *\n * @returns The network clients keyed by ID.\n */\n #createAutoManagedNetworkClientRegistry(): AutoManagedNetworkClientRegistry {\n return [\n ...this.#buildIdentifiedInfuraNetworkClientConfigurations(),\n ...this.#buildIdentifiedCustomNetworkClientConfigurations(),\n ...this.#buildIdentifiedNetworkClientConfigurationsFromProviderConfig(),\n ].reduce(\n (\n registry,\n [networkClientType, networkClientId, networkClientConfiguration],\n ) => {\n const autoManagedNetworkClient = createAutoManagedNetworkClient(\n networkClientConfiguration,\n );\n if (networkClientId in registry[networkClientType]) {\n return registry;\n }\n return {\n ...registry,\n [networkClientType]: {\n ...registry[networkClientType],\n [networkClientId]: autoManagedNetworkClient,\n },\n };\n },\n {\n [NetworkClientType.Infura]: {},\n [NetworkClientType.Custom]: {},\n },\n ) as AutoManagedNetworkClientRegistry;\n }\n\n /**\n * Constructs the list of network clients for built-in networks (that is,\n * the subset of the networks we know Infura supports that consumers do not\n * need to explicitly add).\n *\n * @returns The network clients.\n */\n #buildIdentifiedInfuraNetworkClientConfigurations(): [\n NetworkClientType.Infura,\n BuiltInNetworkClientId,\n InfuraNetworkClientConfiguration,\n ][] {\n return knownKeysOf(InfuraNetworkType).map((network) => {\n const networkClientId = buildInfuraNetworkClientId(network);\n const networkClientConfiguration: InfuraNetworkClientConfiguration = {\n type: NetworkClientType.Infura,\n network,\n infuraProjectId: this.#infuraProjectId,\n chainId: BUILT_IN_NETWORKS[network].chainId,\n ticker: BUILT_IN_NETWORKS[network].ticker,\n };\n return [\n NetworkClientType.Infura,\n networkClientId,\n networkClientConfiguration,\n ];\n });\n }\n\n /**\n * Constructs the list of network clients for custom networks (that is, those\n * which consumers have added via `networkConfigurations`).\n *\n * @returns The network clients.\n */\n #buildIdentifiedCustomNetworkClientConfigurations(): [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ][] {\n return Object.entries(this.state.networkConfigurations).map(\n ([networkConfigurationId, networkConfiguration]) => {\n if (networkConfiguration.chainId === undefined) {\n throw new Error('chainId must be provided for custom RPC endpoints');\n }\n if (networkConfiguration.rpcUrl === undefined) {\n throw new Error('rpcUrl must be provided for custom RPC endpoints');\n }\n const networkClientId = buildCustomNetworkClientId(\n networkConfigurationId,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n type: NetworkClientType.Custom,\n chainId: networkConfiguration.chainId,\n rpcUrl: networkConfiguration.rpcUrl,\n ticker: networkConfiguration.ticker,\n };\n return [\n NetworkClientType.Custom,\n networkClientId,\n networkClientConfiguration,\n ];\n },\n );\n }\n\n /**\n * Converts the provider config object in state to a network client\n * configuration object.\n *\n * @returns The network client config.\n * @throws If the provider config is of type \"rpc\" and lacks either a\n * `chainId` or an `rpcUrl`.\n */\n #buildIdentifiedNetworkClientConfigurationsFromProviderConfig():\n | [\n [\n NetworkClientType.Custom,\n CustomNetworkClientId,\n CustomNetworkClientConfiguration,\n ],\n ]\n | [] {\n const { providerConfig } = this.state;\n\n if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const networkClientConfiguration: CustomNetworkClientConfiguration = {\n chainId: providerConfig.chainId,\n rpcUrl: providerConfig.rpcUrl,\n type: NetworkClientType.Custom,\n ticker: providerConfig.ticker,\n };\n return [\n [NetworkClientType.Custom, networkClientId, networkClientConfiguration],\n ];\n }\n\n if (isInfuraProviderConfig(providerConfig)) {\n return [];\n }\n\n throw new Error(`Unrecognized network type: '${providerConfig.type}'`);\n }\n\n /**\n * Uses the information in the provider config object to look up a known and\n * preinitialized network client. Once a network client is found, updates the\n * provider and block tracker proxy to point to those from the network client,\n * then finally creates an EthQuery that points to the provider proxy.\n *\n * @throws If no network client could be found matching the current provider\n * config.\n */\n #applyNetworkSelection() {\n if (!this.#autoManagedNetworkClientRegistry) {\n throw new Error(\n 'initializeProvider must be called first in order to switch the network',\n );\n }\n\n const { providerConfig } = this.state;\n\n let autoManagedNetworkClient: AutoManagedNetworkClient<NetworkClientConfiguration>;\n\n let networkClientId: NetworkClientId;\n if (isInfuraProviderConfig(providerConfig)) {\n const networkClientType = NetworkClientType.Infura;\n networkClientId = buildInfuraNetworkClientId(providerConfig);\n const builtInNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient =\n builtInNetworkClientRegistry[networkClientId as BuiltInNetworkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find custom network matching ${networkClientId}`,\n );\n }\n } else if (isCustomProviderConfig(providerConfig)) {\n validateCustomProviderConfig(providerConfig);\n const networkClientType = NetworkClientType.Custom;\n networkClientId = buildCustomNetworkClientId(\n providerConfig,\n this.state.networkConfigurations,\n );\n const customNetworkClientRegistry =\n this.#autoManagedNetworkClientRegistry[networkClientType];\n autoManagedNetworkClient = customNetworkClientRegistry[networkClientId];\n if (!autoManagedNetworkClient) {\n throw new Error(\n `Could not find built-in network matching ${networkClientId}`,\n );\n }\n } else {\n throw new Error('Could not determine type of provider config');\n }\n\n this.update((state) => {\n state.selectedNetworkClientId = networkClientId;\n if (state.networksMetadata[networkClientId] === undefined) {\n state.networksMetadata[networkClientId] = {\n status: NetworkStatus.Unknown,\n EIPS: {},\n };\n }\n });\n\n const { provider, blockTracker } = autoManagedNetworkClient;\n\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n\n this.#ethQuery = new EthQuery(this.#providerProxy);\n }\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var
|
|
5
|
+
var _chunkUEWIYOS6js = require('./chunk-UEWIYOS6.js');
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
@@ -21,5 +21,5 @@ require('./chunk-Z4BLTVTB.js');
|
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
|
|
24
|
-
exports.INFURA_BLOCKED_KEY = _chunkZKNI7MD3js.INFURA_BLOCKED_KEY; exports.NetworkClientType = _chunkDMJYDN4Qjs.NetworkClientType; exports.NetworkController =
|
|
24
|
+
exports.INFURA_BLOCKED_KEY = _chunkZKNI7MD3js.INFURA_BLOCKED_KEY; exports.NetworkClientType = _chunkDMJYDN4Qjs.NetworkClientType; exports.NetworkController = _chunkUEWIYOS6js.NetworkController; exports.NetworkStatus = _chunkZKNI7MD3js.NetworkStatus; exports.defaultState = _chunkUEWIYOS6js.defaultState; exports.knownKeysOf = _chunkUEWIYOS6js.knownKeysOf;
|
|
25
25
|
//# sourceMappingURL=index.js.map
|