@metamask/network-controller 7.0.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -2
- package/dist/NetworkController.d.ts +21 -22
- package/dist/NetworkController.d.ts.map +1 -1
- package/dist/NetworkController.js +245 -197
- package/dist/NetworkController.js.map +1 -1
- package/dist/constants.d.ts +21 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +25 -0
- package/dist/constants.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [8.0.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Implement `resetConnection` method ([#1131](https://github.com/MetaMask/core/pull/1131), [#1235](https://github.com/MetaMask/core/pull/1235), [#1239](https://github.com/MetaMask/core/pull/1239))
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
- Update EIP-1559 compatibility during network lookup ([#1236](https://github.com/MetaMask/core/pull/1236))
|
|
15
|
+
- EIP-1559 compatibility check is still performed on initialization and after switching networks, like before. This change only impacts direct calls to `lookupNetwork`.
|
|
16
|
+
- `lookupNetwork` is now making two network calls instead of one, ensuring that the `networkDetails` state is up-to-date.
|
|
17
|
+
- **BREAKING:** Replace `network` state with `networkId` and `networkStatus` ([#1196](https://github.com/MetaMask/core/pull/1196))
|
|
18
|
+
- If you were using `network` to access the network ID, use `networkId` instead. It will be set to `null` rather than `loading` if the network is not currently available.
|
|
19
|
+
- If you were using `network` to see if the network was currently available, use `networkStatus` instead. It will be set to `NetworkStatus.Available` if the network is available.
|
|
20
|
+
- When the network is unavailable, we now have two different states to represent that: `unknown` and `unavailable`. `unavailable` means that the network was detected as not available, whereas `unknown` is used for unknown errors and cases where the network status is yet to be determined (e.g. before initialization, or while the network is loading).
|
|
21
|
+
- Use JavaScript private fields rather than `private` TypeScript keyword for internal methods/fields ([#1189](https://github.com/MetaMask/core/pull/1189))
|
|
22
|
+
- Export `BlockTrackerProxy` type ([#1147](https://github.com/MetaMask/core/pull/1147))
|
|
23
|
+
- This is the type of the block tracker returned from the `getProviderAndBlockTracker` method
|
|
24
|
+
- **BREAKING:** Async refactor
|
|
25
|
+
- Make `rollbackToPreviousProvider` async ([#1237](https://github.com/MetaMask/core/pull/1237))
|
|
26
|
+
- Make `upsertNetworkConfiguration` async ([#1192](https://github.com/MetaMask/core/pull/1192))
|
|
27
|
+
- Make `setActiveNetwork` async ([#1190](https://github.com/MetaMask/core/pull/1190))
|
|
28
|
+
- Make `setProviderType` async ([#1191](https://github.com/MetaMask/core/pull/1191))
|
|
29
|
+
- Make `refreshNetwork` async ([#1182](https://github.com/MetaMask/core/pull/1182))
|
|
30
|
+
- Make `initializeProvider` async ([#1180](https://github.com/MetaMask/core/pull/1180))
|
|
31
|
+
- Make `verifyNetwork` async ([#1181](https://github.com/MetaMask/core/pull/1181))
|
|
32
|
+
- Dependency updates
|
|
33
|
+
- deps: bump web3-provider-engine@16.0.3->16.0.5 ([#1212](https://github.com/MetaMask/core/pull/1212))
|
|
34
|
+
- deps: eth-rpc-errors@4.0.0->4.0.2 ([#1215](https://github.com/MetaMask/core/pull/1215))
|
|
35
|
+
- deps: bump @metamask/utils to 5.0.1 ([#1211](https://github.com/MetaMask/core/pull/1211))
|
|
36
|
+
|
|
37
|
+
### Removed
|
|
38
|
+
- **BREAKING:** Remove `isCustomNetwork` state ([#1199](https://github.com/MetaMask/core/pull/1199))
|
|
39
|
+
- The `providerConfig.type` state will be set to `'rpc'` if the current network is a custom network. Replace all references to the `isCustomNetwork` state by checking the provider config state instead.
|
|
40
|
+
|
|
9
41
|
## [7.0.0]
|
|
10
42
|
### Changed
|
|
11
43
|
- **BREAKING:** Replace `providerConfig` setter with a public `initializeProvider` method ([#1133](https://github.com/MetaMask/core/pull/1133))
|
|
@@ -50,7 +82,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
50
82
|
- **BREAKING:** Make `lookupNetwork` block on completing the lookup ([#1063](https://github.com/MetaMask/controllers/pull/1063))
|
|
51
83
|
- This function was always `async`, but it would return before completing any async work. Now it will not return until after the network lookup has been completed.
|
|
52
84
|
- Rename this repository to `core` ([#1031](https://github.com/MetaMask/controllers/pull/1031))
|
|
53
|
-
- Update `@metamask/controller-utils` package ([#1041](https://github.com/MetaMask/controllers/pull/1041))
|
|
85
|
+
- Update `@metamask/controller-utils` package ([#1041](https://github.com/MetaMask/controllers/pull/1041))
|
|
54
86
|
|
|
55
87
|
### Removed
|
|
56
88
|
- **BREAKING:**: Drop support for Ropsten, Rinkeby, and Kovan as built-in Infura networks ([#1041](https://github.com/MetaMask/controllers/pull/1041))
|
|
@@ -70,7 +102,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
70
102
|
|
|
71
103
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
72
104
|
|
|
73
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@
|
|
105
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/network-controller@8.0.0...HEAD
|
|
106
|
+
[8.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@7.0.0...@metamask/network-controller@8.0.0
|
|
74
107
|
[7.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@6.0.0...@metamask/network-controller@7.0.0
|
|
75
108
|
[6.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@5.0.0...@metamask/network-controller@6.0.0
|
|
76
109
|
[5.0.0]: https://github.com/MetaMask/core/compare/@metamask/network-controller@4.0.0...@metamask/network-controller@5.0.0
|
|
@@ -2,6 +2,7 @@ import type { SwappableProxy } from '@metamask/swappable-obj-proxy';
|
|
|
2
2
|
import type { Patch } from 'immer';
|
|
3
3
|
import { BaseControllerV2, RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
4
4
|
import { NetworkType } from '@metamask/controller-utils';
|
|
5
|
+
import { NetworkStatus } from './constants';
|
|
5
6
|
/**
|
|
6
7
|
* @type ProviderConfig
|
|
7
8
|
*
|
|
@@ -48,19 +49,22 @@ export declare type NetworkConfiguration = {
|
|
|
48
49
|
blockExplorerUrl: string;
|
|
49
50
|
};
|
|
50
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* The network ID of a network.
|
|
54
|
+
*/
|
|
55
|
+
export declare type NetworkId = `${number}`;
|
|
51
56
|
/**
|
|
52
57
|
* @type NetworkState
|
|
53
58
|
*
|
|
54
59
|
* Network controller state
|
|
55
60
|
* @property network - Network ID as per net_version of the currently connected network
|
|
56
|
-
* @property isCustomNetwork - Identifies if the currently connected network is a custom network
|
|
57
61
|
* @property providerConfig - RPC URL and network name provider settings of the currently connected network
|
|
58
62
|
* @property properties - an additional set of network properties for the currently connected network
|
|
59
63
|
* @property networkConfigurations - the full list of configured networks either preloaded or added by the user.
|
|
60
64
|
*/
|
|
61
65
|
export declare type NetworkState = {
|
|
62
|
-
|
|
63
|
-
|
|
66
|
+
networkId: NetworkId | null;
|
|
67
|
+
networkStatus: NetworkStatus;
|
|
64
68
|
providerConfig: ProviderConfig;
|
|
65
69
|
networkDetails: NetworkDetails;
|
|
66
70
|
networkConfigurations: Record<string, NetworkConfiguration & {
|
|
@@ -72,6 +76,7 @@ export declare type EthQuery = any;
|
|
|
72
76
|
declare type Provider = any;
|
|
73
77
|
export declare type ProviderProxy = SwappableProxy<Provider>;
|
|
74
78
|
declare type BlockTracker = any;
|
|
79
|
+
export declare type BlockTrackerProxy = SwappableProxy<BlockTracker>;
|
|
75
80
|
export declare type NetworkControllerStateChangeEvent = {
|
|
76
81
|
type: `NetworkController:stateChange`;
|
|
77
82
|
payload: [NetworkState, Patch[]];
|
|
@@ -104,33 +109,23 @@ declare type NetworkConfigurationId = string;
|
|
|
104
109
|
*/
|
|
105
110
|
export declare class NetworkController extends BaseControllerV2<typeof name, NetworkState, NetworkControllerMessenger> {
|
|
106
111
|
#private;
|
|
107
|
-
private ethQuery;
|
|
108
|
-
private infuraProjectId;
|
|
109
|
-
private trackMetaMetricsEvent;
|
|
110
|
-
private mutex;
|
|
111
112
|
constructor({ messenger, state, infuraProjectId, trackMetaMetricsEvent, }: NetworkControllerOptions);
|
|
112
|
-
private configureProvider;
|
|
113
113
|
getProviderAndBlockTracker(): {
|
|
114
114
|
provider: SwappableProxy<Provider> | undefined;
|
|
115
115
|
blockTracker: SwappableProxy<BlockTracker> | undefined;
|
|
116
116
|
};
|
|
117
|
-
private refreshNetwork;
|
|
118
|
-
private registerProvider;
|
|
119
|
-
private setupInfuraProvider;
|
|
120
|
-
private getIsCustomNetwork;
|
|
121
|
-
private setupStandardProvider;
|
|
122
|
-
private updateProvider;
|
|
123
|
-
private safelyStopProvider;
|
|
124
|
-
private verifyNetwork;
|
|
125
117
|
/**
|
|
126
118
|
* Method to inilialize the provider,
|
|
127
119
|
* Creates the provider and block tracker for the configured network,
|
|
128
120
|
* using the provider to gather details about the network.
|
|
129
121
|
*
|
|
130
122
|
*/
|
|
131
|
-
initializeProvider(): void
|
|
123
|
+
initializeProvider(): Promise<void>;
|
|
132
124
|
/**
|
|
133
|
-
*
|
|
125
|
+
* Performs side effects after switching to a network. If the network is
|
|
126
|
+
* available, updates the network state with the network ID of the network and
|
|
127
|
+
* stores whether the network supports EIP-1559; otherwise clears said
|
|
128
|
+
* information about the network that may have been previously stored.
|
|
134
129
|
*/
|
|
135
130
|
lookupNetwork(): Promise<void>;
|
|
136
131
|
/**
|
|
@@ -138,14 +133,18 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
|
|
|
138
133
|
*
|
|
139
134
|
* @param type - Human readable network name.
|
|
140
135
|
*/
|
|
141
|
-
setProviderType(type: NetworkType): void
|
|
136
|
+
setProviderType(type: NetworkType): Promise<void>;
|
|
142
137
|
/**
|
|
143
138
|
* Convenience method to update provider RPC settings.
|
|
144
139
|
*
|
|
145
140
|
* @param networkConfigurationId - The unique id for the network configuration to set as the active provider.
|
|
146
141
|
*/
|
|
147
|
-
setActiveNetwork(networkConfigurationId: string): void
|
|
142
|
+
setActiveNetwork(networkConfigurationId: string): Promise<void>;
|
|
148
143
|
getEIP1559Compatibility(): Promise<boolean>;
|
|
144
|
+
/**
|
|
145
|
+
* Re-initializes the provider and block tracker for the current network.
|
|
146
|
+
*/
|
|
147
|
+
resetConnection(): Promise<void>;
|
|
149
148
|
/**
|
|
150
149
|
* Adds a network configuration if the rpcUrl is not already present on an
|
|
151
150
|
* existing network configuration. Otherwise updates the entry with the matching rpcUrl.
|
|
@@ -166,7 +165,7 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
|
|
|
166
165
|
setActive?: boolean;
|
|
167
166
|
referrer: string;
|
|
168
167
|
source: string;
|
|
169
|
-
}): string
|
|
168
|
+
}): Promise<string>;
|
|
170
169
|
/**
|
|
171
170
|
* Removes network configuration from state.
|
|
172
171
|
*
|
|
@@ -176,7 +175,7 @@ export declare class NetworkController extends BaseControllerV2<typeof name, Net
|
|
|
176
175
|
/**
|
|
177
176
|
* Rolls back provider config to the previous provider in case of errors or inability to connect during network switch.
|
|
178
177
|
*/
|
|
179
|
-
rollbackToPreviousProvider(): void
|
|
178
|
+
rollbackToPreviousProvider(): Promise<void>;
|
|
180
179
|
}
|
|
181
180
|
export default NetworkController;
|
|
182
181
|
//# sourceMappingURL=NetworkController.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.d.ts","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAGpE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"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A0B;CAQjC;AAED,eAAe,iBAAiB,CAAC"}
|
|
@@ -22,7 +22,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
22
22
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
23
23
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
24
24
|
};
|
|
25
|
-
var _NetworkController_instances, _NetworkController_previousNetworkSpecifier, _NetworkController_provider, _NetworkController_providerProxy, _NetworkController_blockTrackerProxy, _NetworkController_getNetworkId, _NetworkController_setCurrentAsPreviousProvider, _NetworkController_getLatestBlock, _NetworkController_setProviderAndBlockTracker;
|
|
25
|
+
var _NetworkController_instances, _NetworkController_ethQuery, _NetworkController_infuraProjectId, _NetworkController_trackMetaMetricsEvent, _NetworkController_mutex, _NetworkController_previousNetworkSpecifier, _NetworkController_provider, _NetworkController_providerProxy, _NetworkController_blockTrackerProxy, _NetworkController_configureProvider, _NetworkController_refreshNetwork, _NetworkController_registerProvider, _NetworkController_setupInfuraProvider, _NetworkController_setupStandardProvider, _NetworkController_updateProvider, _NetworkController_safelyStopProvider, _NetworkController_verifyNetwork, _NetworkController_getNetworkId, _NetworkController_setCurrentAsPreviousProvider, _NetworkController_getLatestBlock, _NetworkController_setProviderAndBlockTracker;
|
|
26
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
27
|
exports.NetworkController = exports.defaultState = void 0;
|
|
28
28
|
const eth_query_1 = __importDefault(require("eth-query"));
|
|
@@ -32,14 +32,39 @@ const zero_1 = __importDefault(require("web3-provider-engine/zero"));
|
|
|
32
32
|
const swappable_obj_proxy_1 = require("@metamask/swappable-obj-proxy");
|
|
33
33
|
const async_mutex_1 = require("async-mutex");
|
|
34
34
|
const uuid_1 = require("uuid");
|
|
35
|
+
const eth_rpc_errors_1 = require("eth-rpc-errors");
|
|
35
36
|
const base_controller_1 = require("@metamask/base-controller");
|
|
36
37
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
37
38
|
const utils_1 = require("@metamask/utils");
|
|
39
|
+
const constants_1 = require("./constants");
|
|
40
|
+
/**
|
|
41
|
+
* Asserts that the given value is a network ID, i.e., that it is a decimal
|
|
42
|
+
* number represented as a string.
|
|
43
|
+
*
|
|
44
|
+
* @param value - The value to check.
|
|
45
|
+
*/
|
|
46
|
+
function assertNetworkId(value) {
|
|
47
|
+
if (!/^\d+$/u.test(value) || Number.isNaN(Number(value))) {
|
|
48
|
+
throw new Error('value is not a number');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Type guard for determining whether the given value is an error object with a
|
|
53
|
+
* `code` property, such as an instance of Error.
|
|
54
|
+
*
|
|
55
|
+
* TODO: Move this to @metamask/utils.
|
|
56
|
+
*
|
|
57
|
+
* @param error - The object to check.
|
|
58
|
+
* @returns True if `error` has a `code`, false otherwise.
|
|
59
|
+
*/
|
|
60
|
+
function isErrorWithCode(error) {
|
|
61
|
+
return typeof error === 'object' && error !== null && 'code' in error;
|
|
62
|
+
}
|
|
38
63
|
const LOCALHOST_RPC_URL = 'http://localhost:8545';
|
|
39
64
|
const name = 'NetworkController';
|
|
40
65
|
exports.defaultState = {
|
|
41
|
-
|
|
42
|
-
|
|
66
|
+
networkId: null,
|
|
67
|
+
networkStatus: constants_1.NetworkStatus.Unknown,
|
|
43
68
|
providerConfig: {
|
|
44
69
|
type: controller_utils_1.NetworkType.mainnet,
|
|
45
70
|
chainId: controller_utils_1.NetworksChainId.mainnet,
|
|
@@ -55,11 +80,11 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
55
80
|
super({
|
|
56
81
|
name,
|
|
57
82
|
metadata: {
|
|
58
|
-
|
|
83
|
+
networkId: {
|
|
59
84
|
persist: true,
|
|
60
85
|
anonymous: false,
|
|
61
86
|
},
|
|
62
|
-
|
|
87
|
+
networkStatus: {
|
|
63
88
|
persist: true,
|
|
64
89
|
anonymous: false,
|
|
65
90
|
},
|
|
@@ -80,112 +105,30 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
80
105
|
state: Object.assign(Object.assign({}, exports.defaultState), state),
|
|
81
106
|
});
|
|
82
107
|
_NetworkController_instances.add(this);
|
|
83
|
-
this
|
|
108
|
+
_NetworkController_ethQuery.set(this, void 0);
|
|
109
|
+
_NetworkController_infuraProjectId.set(this, void 0);
|
|
110
|
+
_NetworkController_trackMetaMetricsEvent.set(this, void 0);
|
|
111
|
+
_NetworkController_mutex.set(this, new async_mutex_1.Mutex());
|
|
84
112
|
_NetworkController_previousNetworkSpecifier.set(this, void 0);
|
|
85
113
|
_NetworkController_provider.set(this, void 0);
|
|
86
114
|
_NetworkController_providerProxy.set(this, void 0);
|
|
87
115
|
_NetworkController_blockTrackerProxy.set(this, void 0);
|
|
88
|
-
this
|
|
89
|
-
this
|
|
116
|
+
__classPrivateFieldSet(this, _NetworkController_infuraProjectId, infuraProjectId, "f");
|
|
117
|
+
__classPrivateFieldSet(this, _NetworkController_trackMetaMetricsEvent, trackMetaMetricsEvent, "f");
|
|
90
118
|
this.messagingSystem.registerActionHandler(`${this.name}:getProviderConfig`, () => {
|
|
91
119
|
return this.state.providerConfig;
|
|
92
120
|
});
|
|
93
121
|
this.messagingSystem.registerActionHandler(`${this.name}:getEthQuery`, () => {
|
|
94
|
-
return this
|
|
122
|
+
return __classPrivateFieldGet(this, _NetworkController_ethQuery, "f");
|
|
95
123
|
});
|
|
96
124
|
__classPrivateFieldSet(this, _NetworkController_previousNetworkSpecifier, this.state.providerConfig.type, "f");
|
|
97
125
|
}
|
|
98
|
-
configureProvider(type, rpcTarget, chainId, ticker, nickname) {
|
|
99
|
-
this.update((state) => {
|
|
100
|
-
state.isCustomNetwork = this.getIsCustomNetwork(chainId);
|
|
101
|
-
});
|
|
102
|
-
switch (type) {
|
|
103
|
-
case controller_utils_1.NetworkType.mainnet:
|
|
104
|
-
case controller_utils_1.NetworkType.goerli:
|
|
105
|
-
case controller_utils_1.NetworkType.sepolia:
|
|
106
|
-
this.setupInfuraProvider(type);
|
|
107
|
-
break;
|
|
108
|
-
case controller_utils_1.NetworkType.localhost:
|
|
109
|
-
this.setupStandardProvider(LOCALHOST_RPC_URL);
|
|
110
|
-
break;
|
|
111
|
-
case controller_utils_1.NetworkType.rpc:
|
|
112
|
-
rpcTarget &&
|
|
113
|
-
this.setupStandardProvider(rpcTarget, chainId, ticker, nickname);
|
|
114
|
-
break;
|
|
115
|
-
default:
|
|
116
|
-
throw new Error(`Unrecognized network type: '${type}'`);
|
|
117
|
-
}
|
|
118
|
-
this.getEIP1559Compatibility();
|
|
119
|
-
}
|
|
120
126
|
getProviderAndBlockTracker() {
|
|
121
127
|
return {
|
|
122
128
|
provider: __classPrivateFieldGet(this, _NetworkController_providerProxy, "f"),
|
|
123
129
|
blockTracker: __classPrivateFieldGet(this, _NetworkController_blockTrackerProxy, "f"),
|
|
124
130
|
};
|
|
125
131
|
}
|
|
126
|
-
refreshNetwork() {
|
|
127
|
-
this.update((state) => {
|
|
128
|
-
state.network = 'loading';
|
|
129
|
-
state.networkDetails = {};
|
|
130
|
-
});
|
|
131
|
-
const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;
|
|
132
|
-
this.configureProvider(type, rpcTarget, chainId, ticker);
|
|
133
|
-
this.lookupNetwork();
|
|
134
|
-
}
|
|
135
|
-
registerProvider() {
|
|
136
|
-
const { provider } = this.getProviderAndBlockTracker();
|
|
137
|
-
if (provider) {
|
|
138
|
-
provider.on('error', this.verifyNetwork.bind(this));
|
|
139
|
-
this.ethQuery = new eth_query_1.default(provider);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
setupInfuraProvider(type) {
|
|
143
|
-
const infuraProvider = (0, createProvider_1.default)({
|
|
144
|
-
network: type,
|
|
145
|
-
projectId: this.infuraProjectId,
|
|
146
|
-
});
|
|
147
|
-
const infuraSubprovider = new provider_1.default(infuraProvider);
|
|
148
|
-
const config = {
|
|
149
|
-
dataSubprovider: infuraSubprovider,
|
|
150
|
-
engineParams: {
|
|
151
|
-
blockTrackerProvider: infuraProvider,
|
|
152
|
-
pollingInterval: 12000,
|
|
153
|
-
},
|
|
154
|
-
};
|
|
155
|
-
this.updateProvider((0, zero_1.default)(config));
|
|
156
|
-
}
|
|
157
|
-
getIsCustomNetwork(chainId) {
|
|
158
|
-
return (chainId !== controller_utils_1.NetworksChainId.mainnet &&
|
|
159
|
-
chainId !== controller_utils_1.NetworksChainId.goerli &&
|
|
160
|
-
chainId !== controller_utils_1.NetworksChainId.sepolia &&
|
|
161
|
-
chainId !== controller_utils_1.NetworksChainId.localhost);
|
|
162
|
-
}
|
|
163
|
-
setupStandardProvider(rpcTarget, chainId, ticker, nickname) {
|
|
164
|
-
const config = {
|
|
165
|
-
chainId,
|
|
166
|
-
engineParams: { pollingInterval: 12000 },
|
|
167
|
-
nickname,
|
|
168
|
-
rpcUrl: rpcTarget,
|
|
169
|
-
ticker,
|
|
170
|
-
};
|
|
171
|
-
this.updateProvider((0, zero_1.default)(config));
|
|
172
|
-
}
|
|
173
|
-
updateProvider(provider) {
|
|
174
|
-
this.safelyStopProvider(__classPrivateFieldGet(this, _NetworkController_provider, "f"));
|
|
175
|
-
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setProviderAndBlockTracker).call(this, {
|
|
176
|
-
provider,
|
|
177
|
-
blockTracker: provider._blockTracker,
|
|
178
|
-
});
|
|
179
|
-
this.registerProvider();
|
|
180
|
-
}
|
|
181
|
-
safelyStopProvider(provider) {
|
|
182
|
-
setTimeout(() => {
|
|
183
|
-
provider === null || provider === void 0 ? void 0 : provider.stop();
|
|
184
|
-
}, 500);
|
|
185
|
-
}
|
|
186
|
-
verifyNetwork() {
|
|
187
|
-
this.state.network === 'loading' && this.lookupNetwork();
|
|
188
|
-
}
|
|
189
132
|
/**
|
|
190
133
|
* Method to inilialize the provider,
|
|
191
134
|
* Creates the provider and block tracker for the configured network,
|
|
@@ -193,33 +136,46 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
193
136
|
*
|
|
194
137
|
*/
|
|
195
138
|
initializeProvider() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
139
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
140
|
+
const { type, rpcTarget, chainId, ticker, nickname } = this.state.providerConfig;
|
|
141
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcTarget, chainId, ticker, nickname);
|
|
142
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
|
|
143
|
+
yield this.lookupNetwork();
|
|
144
|
+
});
|
|
200
145
|
}
|
|
201
146
|
/**
|
|
202
|
-
*
|
|
147
|
+
* Performs side effects after switching to a network. If the network is
|
|
148
|
+
* available, updates the network state with the network ID of the network and
|
|
149
|
+
* stores whether the network supports EIP-1559; otherwise clears said
|
|
150
|
+
* information about the network that may have been previously stored.
|
|
203
151
|
*/
|
|
204
152
|
lookupNetwork() {
|
|
205
153
|
return __awaiter(this, void 0, void 0, function* () {
|
|
206
|
-
if (!this
|
|
154
|
+
if (!__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
207
155
|
return;
|
|
208
156
|
}
|
|
209
|
-
const releaseLock = yield this.
|
|
157
|
+
const releaseLock = yield __classPrivateFieldGet(this, _NetworkController_mutex, "f").acquire();
|
|
210
158
|
try {
|
|
211
159
|
try {
|
|
212
|
-
const networkId = yield
|
|
213
|
-
|
|
160
|
+
const [networkId] = yield Promise.all([
|
|
161
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getNetworkId).call(this),
|
|
162
|
+
this.getEIP1559Compatibility(),
|
|
163
|
+
]);
|
|
164
|
+
if (this.state.networkId === networkId) {
|
|
214
165
|
return;
|
|
215
166
|
}
|
|
216
167
|
this.update((state) => {
|
|
217
|
-
state.
|
|
168
|
+
state.networkId = networkId;
|
|
169
|
+
state.networkStatus = constants_1.NetworkStatus.Available;
|
|
218
170
|
});
|
|
219
171
|
}
|
|
220
|
-
catch (
|
|
172
|
+
catch (error) {
|
|
173
|
+
const networkStatus = isErrorWithCode(error) && error.code !== eth_rpc_errors_1.errorCodes.rpc.internal
|
|
174
|
+
? constants_1.NetworkStatus.Unavailable
|
|
175
|
+
: constants_1.NetworkStatus.Unknown;
|
|
221
176
|
this.update((state) => {
|
|
222
|
-
state.
|
|
177
|
+
state.networkId = null;
|
|
178
|
+
state.networkStatus = networkStatus;
|
|
223
179
|
});
|
|
224
180
|
}
|
|
225
181
|
this.messagingSystem.publish(`NetworkController:providerConfigChange`, this.state.providerConfig);
|
|
@@ -235,21 +191,23 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
235
191
|
* @param type - Human readable network name.
|
|
236
192
|
*/
|
|
237
193
|
setProviderType(type) {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
state
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
194
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
195
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setCurrentAsPreviousProvider).call(this);
|
|
196
|
+
// If testnet the ticker symbol should use a testnet prefix
|
|
197
|
+
const ticker = type in controller_utils_1.NetworksTicker && controller_utils_1.NetworksTicker[type].length > 0
|
|
198
|
+
? controller_utils_1.NetworksTicker[type]
|
|
199
|
+
: 'ETH';
|
|
200
|
+
this.update((state) => {
|
|
201
|
+
state.providerConfig.type = type;
|
|
202
|
+
state.providerConfig.ticker = ticker;
|
|
203
|
+
state.providerConfig.chainId = controller_utils_1.NetworksChainId[type];
|
|
204
|
+
state.providerConfig.rpcPrefs = controller_utils_1.BUILT_IN_NETWORKS[type].rpcPrefs;
|
|
205
|
+
state.providerConfig.rpcTarget = undefined;
|
|
206
|
+
state.providerConfig.nickname = undefined;
|
|
207
|
+
state.providerConfig.id = undefined;
|
|
208
|
+
});
|
|
209
|
+
yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
|
|
251
210
|
});
|
|
252
|
-
this.refreshNetwork();
|
|
253
211
|
}
|
|
254
212
|
/**
|
|
255
213
|
* Convenience method to update provider RPC settings.
|
|
@@ -257,26 +215,28 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
257
215
|
* @param networkConfigurationId - The unique id for the network configuration to set as the active provider.
|
|
258
216
|
*/
|
|
259
217
|
setActiveNetwork(networkConfigurationId) {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
state
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
218
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
219
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setCurrentAsPreviousProvider).call(this);
|
|
220
|
+
const targetNetwork = this.state.networkConfigurations[networkConfigurationId];
|
|
221
|
+
if (!targetNetwork) {
|
|
222
|
+
throw new Error(`networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`);
|
|
223
|
+
}
|
|
224
|
+
this.update((state) => {
|
|
225
|
+
state.providerConfig.type = controller_utils_1.NetworkType.rpc;
|
|
226
|
+
state.providerConfig.rpcTarget = targetNetwork.rpcUrl;
|
|
227
|
+
state.providerConfig.chainId = targetNetwork.chainId;
|
|
228
|
+
state.providerConfig.ticker = targetNetwork.ticker;
|
|
229
|
+
state.providerConfig.nickname = targetNetwork.nickname;
|
|
230
|
+
state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;
|
|
231
|
+
state.providerConfig.id = targetNetwork.id;
|
|
232
|
+
});
|
|
233
|
+
yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
|
|
273
234
|
});
|
|
274
|
-
this.refreshNetwork();
|
|
275
235
|
}
|
|
276
236
|
getEIP1559Compatibility() {
|
|
277
237
|
return __awaiter(this, void 0, void 0, function* () {
|
|
278
238
|
const { networkDetails = {} } = this.state;
|
|
279
|
-
if (networkDetails.isEIP1559Compatible || !this
|
|
239
|
+
if (networkDetails.isEIP1559Compatible || !__classPrivateFieldGet(this, _NetworkController_ethQuery, "f")) {
|
|
280
240
|
return true;
|
|
281
241
|
}
|
|
282
242
|
const latestBlock = yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_getLatestBlock).call(this);
|
|
@@ -289,6 +249,14 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
289
249
|
return isEIP1559Compatible;
|
|
290
250
|
});
|
|
291
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Re-initializes the provider and block tracker for the current network.
|
|
254
|
+
*/
|
|
255
|
+
resetConnection() {
|
|
256
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
257
|
+
yield __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_refreshNetwork).call(this);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
292
260
|
/**
|
|
293
261
|
* Adds a network configuration if the rpcUrl is not already present on an
|
|
294
262
|
* existing network configuration. Otherwise updates the entry with the matching rpcUrl.
|
|
@@ -307,59 +275,61 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
307
275
|
*/
|
|
308
276
|
upsertNetworkConfiguration({ rpcUrl, chainId, ticker, nickname, rpcPrefs }, { setActive = false, referrer, source, }) {
|
|
309
277
|
var _a;
|
|
310
|
-
(0,
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if (!rpcUrl) {
|
|
315
|
-
throw new Error('An rpcUrl is required to add or update network configuration');
|
|
316
|
-
}
|
|
317
|
-
if (!referrer || !source) {
|
|
318
|
-
throw new Error('referrer and source are required arguments for adding or updating a network configuration');
|
|
319
|
-
}
|
|
320
|
-
try {
|
|
321
|
-
// eslint-disable-next-line no-new
|
|
322
|
-
new URL(rpcUrl);
|
|
323
|
-
}
|
|
324
|
-
catch (e) {
|
|
325
|
-
if (e.message.includes('Invalid URL')) {
|
|
326
|
-
throw new Error('rpcUrl must be a valid URL');
|
|
278
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
279
|
+
(0, utils_1.assertIsStrictHexString)(chainId);
|
|
280
|
+
if (!(0, controller_utils_1.isSafeChainId)(parseInt(chainId, 16))) {
|
|
281
|
+
throw new Error(`Invalid chain ID "${chainId}": numerical value greater than max safe value.`);
|
|
327
282
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
283
|
+
if (!rpcUrl) {
|
|
284
|
+
throw new Error('An rpcUrl is required to add or update network configuration');
|
|
285
|
+
}
|
|
286
|
+
if (!referrer || !source) {
|
|
287
|
+
throw new Error('referrer and source are required arguments for adding or updating a network configuration');
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
// eslint-disable-next-line no-new
|
|
291
|
+
new URL(rpcUrl);
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
if (e.message.includes('Invalid URL')) {
|
|
295
|
+
throw new Error('rpcUrl must be a valid URL');
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (!ticker) {
|
|
299
|
+
throw new Error('A ticker is required to add or update networkConfiguration');
|
|
300
|
+
}
|
|
301
|
+
const newNetworkConfiguration = {
|
|
302
|
+
rpcUrl,
|
|
303
|
+
chainId,
|
|
304
|
+
ticker,
|
|
305
|
+
nickname,
|
|
306
|
+
rpcPrefs,
|
|
307
|
+
};
|
|
308
|
+
const oldNetworkConfigurations = this.state.networkConfigurations;
|
|
309
|
+
const oldNetworkConfigurationId = (_a = Object.values(oldNetworkConfigurations).find((networkConfiguration) => { var _a; return ((_a = networkConfiguration.rpcUrl) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === (rpcUrl === null || rpcUrl === void 0 ? void 0 : rpcUrl.toLowerCase()); })) === null || _a === void 0 ? void 0 : _a.id;
|
|
310
|
+
const newNetworkConfigurationId = oldNetworkConfigurationId || (0, uuid_1.v4)();
|
|
311
|
+
this.update((state) => {
|
|
312
|
+
state.networkConfigurations = Object.assign(Object.assign({}, oldNetworkConfigurations), { [newNetworkConfigurationId]: Object.assign(Object.assign({}, newNetworkConfiguration), { id: newNetworkConfigurationId }) });
|
|
357
313
|
});
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
314
|
+
if (!oldNetworkConfigurationId) {
|
|
315
|
+
__classPrivateFieldGet(this, _NetworkController_trackMetaMetricsEvent, "f").call(this, {
|
|
316
|
+
event: 'Custom Network Added',
|
|
317
|
+
category: 'Network',
|
|
318
|
+
referrer: {
|
|
319
|
+
url: referrer,
|
|
320
|
+
},
|
|
321
|
+
properties: {
|
|
322
|
+
chain_id: chainId,
|
|
323
|
+
symbol: ticker,
|
|
324
|
+
source,
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
if (setActive) {
|
|
329
|
+
yield this.setActiveNetwork(newNetworkConfigurationId);
|
|
330
|
+
}
|
|
331
|
+
return newNetworkConfigurationId;
|
|
332
|
+
});
|
|
363
333
|
}
|
|
364
334
|
/**
|
|
365
335
|
* Removes network configuration from state.
|
|
@@ -378,20 +348,96 @@ class NetworkController extends base_controller_1.BaseControllerV2 {
|
|
|
378
348
|
* Rolls back provider config to the previous provider in case of errors or inability to connect during network switch.
|
|
379
349
|
*/
|
|
380
350
|
rollbackToPreviousProvider() {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
351
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
352
|
+
const specifier = __classPrivateFieldGet(this, _NetworkController_previousNetworkSpecifier, "f");
|
|
353
|
+
if ((0, controller_utils_1.isNetworkType)(specifier)) {
|
|
354
|
+
yield this.setProviderType(specifier);
|
|
355
|
+
}
|
|
356
|
+
else if (typeof specifier === 'string') {
|
|
357
|
+
yield this.setActiveNetwork(specifier);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
388
360
|
}
|
|
389
361
|
}
|
|
390
362
|
exports.NetworkController = NetworkController;
|
|
391
|
-
_NetworkController_previousNetworkSpecifier = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_instances = new WeakSet(),
|
|
363
|
+
_NetworkController_ethQuery = new WeakMap(), _NetworkController_infuraProjectId = new WeakMap(), _NetworkController_trackMetaMetricsEvent = new WeakMap(), _NetworkController_mutex = new WeakMap(), _NetworkController_previousNetworkSpecifier = new WeakMap(), _NetworkController_provider = new WeakMap(), _NetworkController_providerProxy = new WeakMap(), _NetworkController_blockTrackerProxy = new WeakMap(), _NetworkController_instances = new WeakSet(), _NetworkController_configureProvider = function _NetworkController_configureProvider(type, rpcTarget, chainId, ticker, nickname) {
|
|
364
|
+
switch (type) {
|
|
365
|
+
case controller_utils_1.NetworkType.mainnet:
|
|
366
|
+
case controller_utils_1.NetworkType.goerli:
|
|
367
|
+
case controller_utils_1.NetworkType.sepolia:
|
|
368
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupInfuraProvider).call(this, type);
|
|
369
|
+
break;
|
|
370
|
+
case controller_utils_1.NetworkType.localhost:
|
|
371
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, LOCALHOST_RPC_URL);
|
|
372
|
+
break;
|
|
373
|
+
case controller_utils_1.NetworkType.rpc:
|
|
374
|
+
rpcTarget &&
|
|
375
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setupStandardProvider).call(this, rpcTarget, chainId, ticker, nickname);
|
|
376
|
+
break;
|
|
377
|
+
default:
|
|
378
|
+
throw new Error(`Unrecognized network type: '${type}'`);
|
|
379
|
+
}
|
|
380
|
+
}, _NetworkController_refreshNetwork = function _NetworkController_refreshNetwork() {
|
|
381
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
382
|
+
this.update((state) => {
|
|
383
|
+
state.networkId = null;
|
|
384
|
+
state.networkStatus = constants_1.NetworkStatus.Unknown;
|
|
385
|
+
state.networkDetails = {};
|
|
386
|
+
});
|
|
387
|
+
const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;
|
|
388
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_configureProvider).call(this, type, rpcTarget, chainId, ticker);
|
|
389
|
+
yield this.lookupNetwork();
|
|
390
|
+
});
|
|
391
|
+
}, _NetworkController_registerProvider = function _NetworkController_registerProvider() {
|
|
392
|
+
const { provider } = this.getProviderAndBlockTracker();
|
|
393
|
+
if (provider) {
|
|
394
|
+
provider.on('error', __classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_verifyNetwork).bind(this));
|
|
395
|
+
__classPrivateFieldSet(this, _NetworkController_ethQuery, new eth_query_1.default(provider), "f");
|
|
396
|
+
}
|
|
397
|
+
}, _NetworkController_setupInfuraProvider = function _NetworkController_setupInfuraProvider(type) {
|
|
398
|
+
const infuraProvider = (0, createProvider_1.default)({
|
|
399
|
+
network: type,
|
|
400
|
+
projectId: __classPrivateFieldGet(this, _NetworkController_infuraProjectId, "f"),
|
|
401
|
+
});
|
|
402
|
+
const infuraSubprovider = new provider_1.default(infuraProvider);
|
|
403
|
+
const config = {
|
|
404
|
+
dataSubprovider: infuraSubprovider,
|
|
405
|
+
engineParams: {
|
|
406
|
+
blockTrackerProvider: infuraProvider,
|
|
407
|
+
pollingInterval: 12000,
|
|
408
|
+
},
|
|
409
|
+
};
|
|
410
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, (0, zero_1.default)(config));
|
|
411
|
+
}, _NetworkController_setupStandardProvider = function _NetworkController_setupStandardProvider(rpcTarget, chainId, ticker, nickname) {
|
|
412
|
+
const config = {
|
|
413
|
+
chainId,
|
|
414
|
+
engineParams: { pollingInterval: 12000 },
|
|
415
|
+
nickname,
|
|
416
|
+
rpcUrl: rpcTarget,
|
|
417
|
+
ticker,
|
|
418
|
+
};
|
|
419
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_updateProvider).call(this, (0, zero_1.default)(config));
|
|
420
|
+
}, _NetworkController_updateProvider = function _NetworkController_updateProvider(provider) {
|
|
421
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_safelyStopProvider).call(this, __classPrivateFieldGet(this, _NetworkController_provider, "f"));
|
|
422
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_setProviderAndBlockTracker).call(this, {
|
|
423
|
+
provider,
|
|
424
|
+
blockTracker: provider._blockTracker,
|
|
425
|
+
});
|
|
426
|
+
__classPrivateFieldGet(this, _NetworkController_instances, "m", _NetworkController_registerProvider).call(this);
|
|
427
|
+
}, _NetworkController_safelyStopProvider = function _NetworkController_safelyStopProvider(provider) {
|
|
428
|
+
setTimeout(() => {
|
|
429
|
+
provider === null || provider === void 0 ? void 0 : provider.stop();
|
|
430
|
+
}, 500);
|
|
431
|
+
}, _NetworkController_verifyNetwork = function _NetworkController_verifyNetwork() {
|
|
432
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
433
|
+
if (this.state.networkStatus !== constants_1.NetworkStatus.Available) {
|
|
434
|
+
yield this.lookupNetwork();
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
}, _NetworkController_getNetworkId = function _NetworkController_getNetworkId() {
|
|
392
438
|
return __awaiter(this, void 0, void 0, function* () {
|
|
393
|
-
|
|
394
|
-
this.
|
|
439
|
+
const possibleNetworkId = yield new Promise((resolve, reject) => {
|
|
440
|
+
__classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'net_version' }, (error, result) => {
|
|
395
441
|
if (error) {
|
|
396
442
|
reject(error);
|
|
397
443
|
}
|
|
@@ -400,6 +446,8 @@ _NetworkController_previousNetworkSpecifier = new WeakMap(), _NetworkController_
|
|
|
400
446
|
}
|
|
401
447
|
});
|
|
402
448
|
});
|
|
449
|
+
assertNetworkId(possibleNetworkId);
|
|
450
|
+
return possibleNetworkId;
|
|
403
451
|
});
|
|
404
452
|
}, _NetworkController_setCurrentAsPreviousProvider = function _NetworkController_setCurrentAsPreviousProvider() {
|
|
405
453
|
const { type, id } = this.state.providerConfig;
|
|
@@ -411,7 +459,7 @@ _NetworkController_previousNetworkSpecifier = new WeakMap(), _NetworkController_
|
|
|
411
459
|
}
|
|
412
460
|
}, _NetworkController_getLatestBlock = function _NetworkController_getLatestBlock() {
|
|
413
461
|
return new Promise((resolve, reject) => {
|
|
414
|
-
this.
|
|
462
|
+
__classPrivateFieldGet(this, _NetworkController_ethQuery, "f").sendAsync({ method: 'eth_getBlockByNumber', params: ['latest', false] }, (error, block) => {
|
|
415
463
|
if (error) {
|
|
416
464
|
reject(error);
|
|
417
465
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAAiC;AACjC,0FAAqE;AACrE,4FAA0E;AAC1E,qEAA+D;AAC/D,uEAAwE;AAExE,6CAAoC;AACpC,+BAAoC;AAEpC,+DAGmC;AACnC,iEAOoC;AAEpC,2CAA0D;AAoE1D,MAAM,iBAAiB,GAAG,uBAAuB,CAAC;AAElD,MAAM,IAAI,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query';\nimport Subprovider from 'web3-provider-engine/subproviders/provider';\nimport createInfuraProvider from 'eth-json-rpc-infura/src/createProvider';\nimport createMetamaskProvider from 'web3-provider-engine/zero';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport { Mutex } from 'async-mutex';\nimport { v4 as random } from 'uuid';\nimport type { Patch } from 'immer';\nimport {\n BaseControllerV2,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n NetworksChainId,\n NetworkType,\n isSafeChainId,\n NetworksTicker,\n isNetworkType,\n BUILT_IN_NETWORKS,\n} from '@metamask/controller-utils';\n\nimport { assertIsStrictHexString } from '@metamask/utils';\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcTarget - 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 rpcTarget?: string;\n type: NetworkType;\n chainId: string;\n ticker?: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\nexport type NetworkDetails = {\n isEIP1559Compatible?: boolean;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcTarget - 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: string;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property isCustomNetwork - Identifies if the currently connected network is a custom network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n network: string;\n isCustomNetwork: boolean;\n providerConfig: ProviderConfig;\n networkDetails: NetworkDetails;\n networkConfigurations: Record<string, NetworkConfiguration & { id: string }>;\n};\n\nconst LOCALHOST_RPC_URL = 'http://localhost:8545';\n\nconst name = 'NetworkController';\n\nexport type EthQuery = any;\n\ntype Provider = any;\n\nexport type ProviderProxy = SwappableProxy<Provider>;\n\ntype BlockTracker = any;\n\ntype BlockTrackerProxy = SwappableProxy<BlockTracker>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\nexport type NetworkControllerProviderConfigChangeEvent = {\n type: `NetworkController:providerConfigChange`;\n payload: [ProviderConfig];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerProviderConfigChangeEvent;\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery;\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction,\n | NetworkControllerStateChangeEvent\n | NetworkControllerProviderConfigChangeEvent,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId?: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n network: 'loading',\n isCustomNetwork: false,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: NetworksChainId.mainnet,\n },\n networkDetails: { isEIP1559Compatible: false },\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 * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n private ethQuery: EthQuery;\n\n private infuraProjectId: string | undefined;\n\n private trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n private mutex = new Mutex();\n\n #previousNetworkSpecifier: NetworkType | NetworkConfigurationId | null;\n\n #provider: Provider | undefined;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n network: {\n persist: true,\n anonymous: false,\n },\n isCustomNetwork: {\n persist: true,\n anonymous: false,\n },\n networkDetails: {\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 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.#previousNetworkSpecifier = this.state.providerConfig.type;\n }\n\n private configureProvider(\n type: NetworkType,\n rpcTarget?: string,\n chainId?: string,\n ticker?: string,\n nickname?: string,\n ) {\n this.update((state) => {\n state.isCustomNetwork = this.getIsCustomNetwork(chainId);\n });\n\n switch (type) {\n case NetworkType.mainnet:\n case NetworkType.goerli:\n case NetworkType.sepolia:\n this.setupInfuraProvider(type);\n break;\n case NetworkType.localhost:\n this.setupStandardProvider(LOCALHOST_RPC_URL);\n break;\n case NetworkType.rpc:\n rpcTarget &&\n this.setupStandardProvider(rpcTarget, chainId, ticker, nickname);\n break;\n default:\n throw new Error(`Unrecognized network type: '${type}'`);\n }\n this.getEIP1559Compatibility();\n }\n\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<Provider> | undefined;\n blockTracker: SwappableProxy<BlockTracker> | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n private refreshNetwork() {\n this.update((state) => {\n state.network = 'loading';\n state.networkDetails = {};\n });\n const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;\n this.configureProvider(type, rpcTarget, chainId, ticker);\n this.lookupNetwork();\n }\n\n private registerProvider() {\n const { provider } = this.getProviderAndBlockTracker();\n\n if (provider) {\n provider.on('error', this.verifyNetwork.bind(this));\n this.ethQuery = new EthQuery(provider);\n }\n }\n\n private setupInfuraProvider(type: NetworkType) {\n const infuraProvider = createInfuraProvider({\n network: type,\n projectId: this.infuraProjectId,\n });\n const infuraSubprovider = new Subprovider(infuraProvider);\n const config = {\n dataSubprovider: infuraSubprovider,\n engineParams: {\n blockTrackerProvider: infuraProvider,\n pollingInterval: 12000,\n },\n };\n this.updateProvider(createMetamaskProvider(config));\n }\n\n private getIsCustomNetwork(chainId?: string) {\n return (\n chainId !== NetworksChainId.mainnet &&\n chainId !== NetworksChainId.goerli &&\n chainId !== NetworksChainId.sepolia &&\n chainId !== NetworksChainId.localhost\n );\n }\n\n private setupStandardProvider(\n rpcTarget: string,\n chainId?: string,\n ticker?: string,\n nickname?: string,\n ) {\n const config = {\n chainId,\n engineParams: { pollingInterval: 12000 },\n nickname,\n rpcUrl: rpcTarget,\n ticker,\n };\n this.updateProvider(createMetamaskProvider(config));\n }\n\n private updateProvider(provider: Provider) {\n this.safelyStopProvider(this.#provider);\n this.#setProviderAndBlockTracker({\n provider,\n blockTracker: provider._blockTracker,\n });\n this.registerProvider();\n }\n\n private safelyStopProvider(provider: Provider | undefined) {\n setTimeout(() => {\n provider?.stop();\n }, 500);\n }\n\n private verifyNetwork() {\n this.state.network === 'loading' && this.lookupNetwork();\n }\n\n /**\n * Method to inilialize the provider,\n * Creates the provider and block tracker for the configured network,\n * using the provider to gather details about the network.\n *\n */\n initializeProvider() {\n const { type, rpcTarget, chainId, ticker, nickname } =\n this.state.providerConfig;\n this.configureProvider(type, rpcTarget, chainId, ticker, nickname);\n this.registerProvider();\n this.lookupNetwork();\n }\n\n async #getNetworkId(): Promise<string> {\n return await new Promise((resolve, reject) => {\n this.ethQuery.sendAsync(\n { method: 'net_version' },\n (error: Error, result: string) => {\n if (error) {\n reject(error);\n } else {\n resolve(result);\n }\n },\n );\n });\n }\n\n /**\n * Refreshes the current network code.\n */\n async lookupNetwork() {\n if (!this.ethQuery) {\n return;\n }\n const releaseLock = await this.mutex.acquire();\n\n try {\n try {\n const networkId = await this.#getNetworkId();\n if (this.state.network === networkId) {\n return;\n }\n\n this.update((state) => {\n state.network = networkId;\n });\n } catch (_error) {\n this.update((state) => {\n state.network = 'loading';\n });\n }\n\n this.messagingSystem.publish(\n `NetworkController:providerConfigChange`,\n this.state.providerConfig,\n );\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Convenience method to set the current provider config to the private providerConfig class variable.\n */\n #setCurrentAsPreviousProvider() {\n const { type, id } = this.state.providerConfig;\n if (type === NetworkType.rpc && id) {\n this.#previousNetworkSpecifier = id;\n } else {\n this.#previousNetworkSpecifier = type;\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n setProviderType(type: NetworkType) {\n this.#setCurrentAsPreviousProvider();\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = NetworksChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcTarget = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n this.refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n setActiveNetwork(networkConfigurationId: string) {\n this.#setCurrentAsPreviousProvider();\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcTarget = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n this.refreshNetwork();\n }\n\n #getLatestBlock(): Promise<Block> {\n return new Promise((resolve, reject) => {\n this.ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: Error, block: Block) => {\n if (error) {\n reject(error);\n } else {\n resolve(block);\n }\n },\n );\n });\n }\n\n async getEIP1559Compatibility() {\n const { networkDetails = {} } = this.state;\n\n if (networkDetails.isEIP1559Compatible || !this.ethQuery) {\n return true;\n }\n\n const latestBlock = await this.#getLatestBlock();\n const isEIP1559Compatible =\n typeof latestBlock.baseFeePerGas !== 'undefined';\n if (networkDetails.isEIP1559Compatible !== isEIP1559Compatible) {\n this.update((state) => {\n state.networkDetails.isEIP1559Compatible = isEIP1559Compatible;\n });\n }\n return isEIP1559Compatible;\n }\n\n #setProviderAndBlockTracker({\n provider,\n blockTracker,\n }: {\n provider: Provider;\n blockTracker: BlockTracker;\n }) {\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n }\n\n /**\n * Adds a network configuration if the rpcUrl is not already present on an\n * existing network configuration. Otherwise updates the entry with the matching rpcUrl.\n *\n * @param networkConfiguration - The network configuration to add or, if rpcUrl matches an existing entry, to modify.\n * @param networkConfiguration.rpcUrl - RPC provider url.\n * @param networkConfiguration.chainId - Network ID as per EIP-155.\n * @param networkConfiguration.ticker - Currency ticker.\n * @param networkConfiguration.nickname - Personalized network name.\n * @param networkConfiguration.rpcPrefs - Personalized preferences (i.e. preferred blockExplorer)\n * @param options - additional configuration options.\n * @param options.setActive - An option to set the newly added networkConfiguration as the active provider.\n * @param options.referrer - The site from which the call originated, or 'metamask' for internal calls - used for event metrics.\n * @param options.source - Where the upsertNetwork event originated (i.e. from a dapp or from the network form) - used for event metrics.\n * @returns id for the added or updated network configuration\n */\n upsertNetworkConfiguration(\n { rpcUrl, chainId, ticker, nickname, rpcPrefs }: NetworkConfiguration,\n {\n setActive = false,\n referrer,\n source,\n }: { setActive?: boolean; referrer: string; source: string },\n ): string {\n assertIsStrictHexString(chainId);\n\n if (!isSafeChainId(parseInt(chainId, 16))) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\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\n try {\n // eslint-disable-next-line no-new\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const newNetworkConfiguration = {\n rpcUrl,\n chainId,\n ticker,\n nickname,\n rpcPrefs,\n };\n\n const oldNetworkConfigurations = this.state.networkConfigurations;\n\n const oldNetworkConfigurationId = Object.values(\n oldNetworkConfigurations,\n ).find(\n (networkConfiguration) =>\n networkConfiguration.rpcUrl?.toLowerCase() === rpcUrl?.toLowerCase(),\n )?.id;\n\n const newNetworkConfigurationId = oldNetworkConfigurationId || random();\n this.update((state) => {\n state.networkConfigurations = {\n ...oldNetworkConfigurations,\n [newNetworkConfigurationId]: {\n ...newNetworkConfiguration,\n id: newNetworkConfigurationId,\n },\n };\n });\n\n if (!oldNetworkConfigurationId) {\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 this.setActiveNetwork(newNetworkConfigurationId);\n }\n\n return newNetworkConfigurationId;\n }\n\n /**\n * Removes network configuration from state.\n *\n * @param networkConfigurationId - The networkConfigurationId of an existing network 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 this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n }\n\n /**\n * Rolls back provider config to the previous provider in case of errors or inability to connect during network switch.\n */\n rollbackToPreviousProvider() {\n const specifier = this.#previousNetworkSpecifier;\n if (isNetworkType(specifier)) {\n this.setProviderType(specifier);\n } else if (typeof specifier === 'string') {\n this.setActiveNetwork(specifier);\n }\n }\n}\n\nexport default NetworkController;\n"]}
|
|
1
|
+
{"version":3,"file":"NetworkController.js","sourceRoot":"","sources":["../src/NetworkController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAAiC;AACjC,0FAAqE;AACrE,4FAA0E;AAC1E,qEAA+D;AAC/D,uEAAwE;AAExE,6CAAoC;AACpC,+BAAoC;AAEpC,mDAA4C;AAC5C,+DAGmC;AAC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M;QACL,uBAAA,IAAI,+CAA6B,IAAI,MAAA,CAAC;KACvC;AACH,CAAC;IA0DC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,uBAAA,IAAI,mCAAU,CAAC,SAAS,CACtB,EAAE,MAAM,EAAE,sBAAsB,EAAE,MAAM,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAC7D,CAAC,KAAY,EAAE,KAAY,EAAE,EAAE;YAC7B,IAAI,KAAK,EAAE;gBACT,MAAM,CAAC,KAAK,CAAC,CAAC;aACf;iBAAM;gBACL,OAAO,CAAC,KAAK,CAAC,CAAC;aAChB;QACH,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,yGA2B2B,EAC1B,QAAQ,EACR,YAAY,GAIb;IACC,IAAI,uBAAA,IAAI,wCAAe,EAAE;QACvB,uBAAA,IAAI,wCAAe,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;KACzC;SAAM;QACL,uBAAA,IAAI,oCAAkB,IAAA,6CAAuB,EAAC,QAAQ,CAAC,MAAA,CAAC;KACzD;IACD,uBAAA,IAAI,+BAAa,QAAQ,MAAA,CAAC;IAE1B,IAAI,uBAAA,IAAI,4CAAmB,EAAE;QAC3B,uBAAA,IAAI,4CAAmB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;KACjD;SAAM;QACL,uBAAA,IAAI,wCAAsB,IAAA,6CAAuB,EAAC,YAAY,EAAE;YAC9D,WAAW,EAAE,cAAc;SAC5B,CAAC,MAAA,CAAC;KACJ;AACH,CAAC;AA4IH,kBAAe,iBAAiB,CAAC","sourcesContent":["import EthQuery from 'eth-query';\nimport Subprovider from 'web3-provider-engine/subproviders/provider';\nimport createInfuraProvider from 'eth-json-rpc-infura/src/createProvider';\nimport createMetamaskProvider from 'web3-provider-engine/zero';\nimport { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';\nimport type { SwappableProxy } from '@metamask/swappable-obj-proxy';\nimport { Mutex } from 'async-mutex';\nimport { v4 as random } from 'uuid';\nimport type { Patch } from 'immer';\nimport { errorCodes } from 'eth-rpc-errors';\nimport {\n BaseControllerV2,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n NetworksChainId,\n NetworkType,\n isSafeChainId,\n NetworksTicker,\n isNetworkType,\n BUILT_IN_NETWORKS,\n} from '@metamask/controller-utils';\nimport { assertIsStrictHexString } from '@metamask/utils';\n\nimport { NetworkStatus } from './constants';\n\n/**\n * @type ProviderConfig\n *\n * Configuration passed to web3-provider-engine\n * @property rpcTarget - 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 rpcTarget?: string;\n type: NetworkType;\n chainId: string;\n ticker?: string;\n nickname?: string;\n rpcPrefs?: { blockExplorerUrl?: string };\n id?: NetworkConfigurationId;\n};\n\nexport type Block = {\n baseFeePerGas?: string;\n};\n\nexport type NetworkDetails = {\n isEIP1559Compatible?: boolean;\n};\n\n/**\n * Custom RPC network information\n *\n * @property rpcTarget - 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: string;\n ticker: string;\n nickname?: string;\n rpcPrefs?: {\n blockExplorerUrl: string;\n };\n};\n\n/**\n * Asserts that the given value is a network ID, i.e., that it is a decimal\n * number represented as a string.\n *\n * @param value - The value to check.\n */\nfunction assertNetworkId(value: string): asserts value is NetworkId {\n if (!/^\\d+$/u.test(value) || Number.isNaN(Number(value))) {\n throw new Error('value is not a number');\n }\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 * The network ID of a network.\n */\nexport type NetworkId = `${number}`;\n\n/**\n * @type NetworkState\n *\n * Network controller state\n * @property network - Network ID as per net_version of the currently connected network\n * @property providerConfig - RPC URL and network name provider settings of the currently connected network\n * @property properties - an additional set of network properties for the currently connected network\n * @property networkConfigurations - the full list of configured networks either preloaded or added by the user.\n */\nexport type NetworkState = {\n networkId: NetworkId | null;\n networkStatus: NetworkStatus;\n providerConfig: ProviderConfig;\n networkDetails: NetworkDetails;\n networkConfigurations: Record<string, NetworkConfiguration & { id: string }>;\n};\n\nconst LOCALHOST_RPC_URL = 'http://localhost:8545';\n\nconst name = 'NetworkController';\n\nexport type EthQuery = any;\n\ntype Provider = any;\n\nexport type ProviderProxy = SwappableProxy<Provider>;\n\ntype BlockTracker = any;\n\nexport type BlockTrackerProxy = SwappableProxy<BlockTracker>;\n\nexport type NetworkControllerStateChangeEvent = {\n type: `NetworkController:stateChange`;\n payload: [NetworkState, Patch[]];\n};\n\nexport type NetworkControllerProviderConfigChangeEvent = {\n type: `NetworkController:providerConfigChange`;\n payload: [ProviderConfig];\n};\n\nexport type NetworkControllerEvents =\n | NetworkControllerStateChangeEvent\n | NetworkControllerProviderConfigChangeEvent;\n\nexport type NetworkControllerGetProviderConfigAction = {\n type: `NetworkController:getProviderConfig`;\n handler: () => ProviderConfig;\n};\n\nexport type NetworkControllerGetEthQueryAction = {\n type: `NetworkController:getEthQuery`;\n handler: () => EthQuery;\n};\n\nexport type NetworkControllerActions =\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction;\n\nexport type NetworkControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction,\n | NetworkControllerStateChangeEvent\n | NetworkControllerProviderConfigChangeEvent,\n string,\n string\n>;\n\nexport type NetworkControllerOptions = {\n messenger: NetworkControllerMessenger;\n trackMetaMetricsEvent: () => void;\n infuraProjectId?: string;\n state?: Partial<NetworkState>;\n};\n\nexport const defaultState: NetworkState = {\n networkId: null,\n networkStatus: NetworkStatus.Unknown,\n providerConfig: {\n type: NetworkType.mainnet,\n chainId: NetworksChainId.mainnet,\n },\n networkDetails: { isEIP1559Compatible: false },\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 * Controller that creates and manages an Ethereum network provider.\n */\nexport class NetworkController extends BaseControllerV2<\n typeof name,\n NetworkState,\n NetworkControllerMessenger\n> {\n #ethQuery: EthQuery;\n\n #infuraProjectId: string | undefined;\n\n #trackMetaMetricsEvent: (event: MetaMetricsEventPayload) => void;\n\n #mutex = new Mutex();\n\n #previousNetworkSpecifier: NetworkType | NetworkConfigurationId | null;\n\n #provider: Provider | undefined;\n\n #providerProxy: ProviderProxy | undefined;\n\n #blockTrackerProxy: BlockTrackerProxy | undefined;\n\n constructor({\n messenger,\n state,\n infuraProjectId,\n trackMetaMetricsEvent,\n }: NetworkControllerOptions) {\n super({\n name,\n metadata: {\n networkId: {\n persist: true,\n anonymous: false,\n },\n networkStatus: {\n persist: true,\n anonymous: false,\n },\n networkDetails: {\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 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.#previousNetworkSpecifier = this.state.providerConfig.type;\n }\n\n #configureProvider(\n type: NetworkType,\n rpcTarget?: string,\n chainId?: string,\n ticker?: string,\n nickname?: string,\n ) {\n switch (type) {\n case NetworkType.mainnet:\n case NetworkType.goerli:\n case NetworkType.sepolia:\n this.#setupInfuraProvider(type);\n break;\n case NetworkType.localhost:\n this.#setupStandardProvider(LOCALHOST_RPC_URL);\n break;\n case NetworkType.rpc:\n rpcTarget &&\n this.#setupStandardProvider(rpcTarget, chainId, ticker, nickname);\n break;\n default:\n throw new Error(`Unrecognized network type: '${type}'`);\n }\n }\n\n getProviderAndBlockTracker(): {\n provider: SwappableProxy<Provider> | undefined;\n blockTracker: SwappableProxy<BlockTracker> | undefined;\n } {\n return {\n provider: this.#providerProxy,\n blockTracker: this.#blockTrackerProxy,\n };\n }\n\n async #refreshNetwork() {\n this.update((state) => {\n state.networkId = null;\n state.networkStatus = NetworkStatus.Unknown;\n state.networkDetails = {};\n });\n const { rpcTarget, type, chainId, ticker } = this.state.providerConfig;\n this.#configureProvider(type, rpcTarget, chainId, ticker);\n await this.lookupNetwork();\n }\n\n #registerProvider() {\n const { provider } = this.getProviderAndBlockTracker();\n\n if (provider) {\n provider.on('error', this.#verifyNetwork.bind(this));\n this.#ethQuery = new EthQuery(provider);\n }\n }\n\n #setupInfuraProvider(type: NetworkType) {\n const infuraProvider = createInfuraProvider({\n network: type,\n projectId: this.#infuraProjectId,\n });\n const infuraSubprovider = new Subprovider(infuraProvider);\n const config = {\n dataSubprovider: infuraSubprovider,\n engineParams: {\n blockTrackerProvider: infuraProvider,\n pollingInterval: 12000,\n },\n };\n this.#updateProvider(createMetamaskProvider(config));\n }\n\n #setupStandardProvider(\n rpcTarget: string,\n chainId?: string,\n ticker?: string,\n nickname?: string,\n ) {\n const config = {\n chainId,\n engineParams: { pollingInterval: 12000 },\n nickname,\n rpcUrl: rpcTarget,\n ticker,\n };\n this.#updateProvider(createMetamaskProvider(config));\n }\n\n #updateProvider(provider: Provider) {\n this.#safelyStopProvider(this.#provider);\n this.#setProviderAndBlockTracker({\n provider,\n blockTracker: provider._blockTracker,\n });\n this.#registerProvider();\n }\n\n #safelyStopProvider(provider: Provider | undefined) {\n setTimeout(() => {\n provider?.stop();\n }, 500);\n }\n\n async #verifyNetwork() {\n if (this.state.networkStatus !== NetworkStatus.Available) {\n await this.lookupNetwork();\n }\n }\n\n /**\n * Method to inilialize the provider,\n * Creates the provider and block tracker for the configured network,\n * using the provider to gather details about the network.\n *\n */\n async initializeProvider() {\n const { type, rpcTarget, chainId, ticker, nickname } =\n this.state.providerConfig;\n this.#configureProvider(type, rpcTarget, chainId, ticker, nickname);\n this.#registerProvider();\n await this.lookupNetwork();\n }\n\n async #getNetworkId(): Promise<NetworkId> {\n const possibleNetworkId = await new Promise<string>((resolve, reject) => {\n this.#ethQuery.sendAsync(\n { method: 'net_version' },\n (error: Error, result: string) => {\n if (error) {\n reject(error);\n } else {\n resolve(result);\n }\n },\n );\n });\n\n assertNetworkId(possibleNetworkId);\n return possibleNetworkId;\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 async lookupNetwork() {\n if (!this.#ethQuery) {\n return;\n }\n const releaseLock = await this.#mutex.acquire();\n\n try {\n try {\n const [networkId] = await Promise.all([\n this.#getNetworkId(),\n this.getEIP1559Compatibility(),\n ]);\n if (this.state.networkId === networkId) {\n return;\n }\n\n this.update((state) => {\n state.networkId = networkId;\n state.networkStatus = NetworkStatus.Available;\n });\n } catch (error) {\n const networkStatus =\n isErrorWithCode(error) && error.code !== errorCodes.rpc.internal\n ? NetworkStatus.Unavailable\n : NetworkStatus.Unknown;\n this.update((state) => {\n state.networkId = null;\n state.networkStatus = networkStatus;\n });\n }\n\n this.messagingSystem.publish(\n `NetworkController:providerConfigChange`,\n this.state.providerConfig,\n );\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Convenience method to set the current provider config to the private providerConfig class variable.\n */\n #setCurrentAsPreviousProvider() {\n const { type, id } = this.state.providerConfig;\n if (type === NetworkType.rpc && id) {\n this.#previousNetworkSpecifier = id;\n } else {\n this.#previousNetworkSpecifier = type;\n }\n }\n\n /**\n * Convenience method to update provider network type settings.\n *\n * @param type - Human readable network name.\n */\n async setProviderType(type: NetworkType) {\n this.#setCurrentAsPreviousProvider();\n // If testnet the ticker symbol should use a testnet prefix\n const ticker =\n type in NetworksTicker && NetworksTicker[type].length > 0\n ? NetworksTicker[type]\n : 'ETH';\n\n this.update((state) => {\n state.providerConfig.type = type;\n state.providerConfig.ticker = ticker;\n state.providerConfig.chainId = NetworksChainId[type];\n state.providerConfig.rpcPrefs = BUILT_IN_NETWORKS[type].rpcPrefs;\n state.providerConfig.rpcTarget = undefined;\n state.providerConfig.nickname = undefined;\n state.providerConfig.id = undefined;\n });\n await this.#refreshNetwork();\n }\n\n /**\n * Convenience method to update provider RPC settings.\n *\n * @param networkConfigurationId - The unique id for the network configuration to set as the active provider.\n */\n async setActiveNetwork(networkConfigurationId: string) {\n this.#setCurrentAsPreviousProvider();\n\n const targetNetwork =\n this.state.networkConfigurations[networkConfigurationId];\n\n if (!targetNetwork) {\n throw new Error(\n `networkConfigurationId ${networkConfigurationId} does not match a configured networkConfiguration`,\n );\n }\n\n this.update((state) => {\n state.providerConfig.type = NetworkType.rpc;\n state.providerConfig.rpcTarget = targetNetwork.rpcUrl;\n state.providerConfig.chainId = targetNetwork.chainId;\n state.providerConfig.ticker = targetNetwork.ticker;\n state.providerConfig.nickname = targetNetwork.nickname;\n state.providerConfig.rpcPrefs = targetNetwork.rpcPrefs;\n state.providerConfig.id = targetNetwork.id;\n });\n\n await this.#refreshNetwork();\n }\n\n #getLatestBlock(): Promise<Block> {\n return new Promise((resolve, reject) => {\n this.#ethQuery.sendAsync(\n { method: 'eth_getBlockByNumber', params: ['latest', false] },\n (error: Error, block: Block) => {\n if (error) {\n reject(error);\n } else {\n resolve(block);\n }\n },\n );\n });\n }\n\n async getEIP1559Compatibility() {\n const { networkDetails = {} } = this.state;\n\n if (networkDetails.isEIP1559Compatible || !this.#ethQuery) {\n return true;\n }\n\n const latestBlock = await this.#getLatestBlock();\n const isEIP1559Compatible =\n typeof latestBlock.baseFeePerGas !== 'undefined';\n if (networkDetails.isEIP1559Compatible !== isEIP1559Compatible) {\n this.update((state) => {\n state.networkDetails.isEIP1559Compatible = isEIP1559Compatible;\n });\n }\n return isEIP1559Compatible;\n }\n\n /**\n * Re-initializes the provider and block tracker for the current network.\n */\n async resetConnection() {\n await this.#refreshNetwork();\n }\n\n #setProviderAndBlockTracker({\n provider,\n blockTracker,\n }: {\n provider: Provider;\n blockTracker: BlockTracker;\n }) {\n if (this.#providerProxy) {\n this.#providerProxy.setTarget(provider);\n } else {\n this.#providerProxy = createEventEmitterProxy(provider);\n }\n this.#provider = provider;\n\n if (this.#blockTrackerProxy) {\n this.#blockTrackerProxy.setTarget(blockTracker);\n } else {\n this.#blockTrackerProxy = createEventEmitterProxy(blockTracker, {\n eventFilter: 'skipInternal',\n });\n }\n }\n\n /**\n * Adds a network configuration if the rpcUrl is not already present on an\n * existing network configuration. Otherwise updates the entry with the matching rpcUrl.\n *\n * @param networkConfiguration - The network configuration to add or, if rpcUrl matches an existing entry, to modify.\n * @param networkConfiguration.rpcUrl - RPC provider url.\n * @param networkConfiguration.chainId - Network ID as per EIP-155.\n * @param networkConfiguration.ticker - Currency ticker.\n * @param networkConfiguration.nickname - Personalized network name.\n * @param networkConfiguration.rpcPrefs - Personalized preferences (i.e. preferred blockExplorer)\n * @param options - additional configuration options.\n * @param options.setActive - An option to set the newly added networkConfiguration as the active provider.\n * @param options.referrer - The site from which the call originated, or 'metamask' for internal calls - used for event metrics.\n * @param options.source - Where the upsertNetwork event originated (i.e. from a dapp or from the network form) - used for event metrics.\n * @returns id for the added or updated network configuration\n */\n async upsertNetworkConfiguration(\n { rpcUrl, chainId, ticker, nickname, rpcPrefs }: NetworkConfiguration,\n {\n setActive = false,\n referrer,\n source,\n }: { setActive?: boolean; referrer: string; source: string },\n ): Promise<string> {\n assertIsStrictHexString(chainId);\n\n if (!isSafeChainId(parseInt(chainId, 16))) {\n throw new Error(\n `Invalid chain ID \"${chainId}\": numerical value greater than max safe value.`,\n );\n }\n\n if (!rpcUrl) {\n throw new Error(\n 'An rpcUrl is required to add or update network configuration',\n );\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\n try {\n // eslint-disable-next-line no-new\n new URL(rpcUrl);\n } catch (e: any) {\n if (e.message.includes('Invalid URL')) {\n throw new Error('rpcUrl must be a valid URL');\n }\n }\n\n if (!ticker) {\n throw new Error(\n 'A ticker is required to add or update networkConfiguration',\n );\n }\n\n const newNetworkConfiguration = {\n rpcUrl,\n chainId,\n ticker,\n nickname,\n rpcPrefs,\n };\n\n const oldNetworkConfigurations = this.state.networkConfigurations;\n\n const oldNetworkConfigurationId = Object.values(\n oldNetworkConfigurations,\n ).find(\n (networkConfiguration) =>\n networkConfiguration.rpcUrl?.toLowerCase() === rpcUrl?.toLowerCase(),\n )?.id;\n\n const newNetworkConfigurationId = oldNetworkConfigurationId || random();\n this.update((state) => {\n state.networkConfigurations = {\n ...oldNetworkConfigurations,\n [newNetworkConfigurationId]: {\n ...newNetworkConfiguration,\n id: newNetworkConfigurationId,\n },\n };\n });\n\n if (!oldNetworkConfigurationId) {\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(newNetworkConfigurationId);\n }\n\n return newNetworkConfigurationId;\n }\n\n /**\n * Removes network configuration from state.\n *\n * @param networkConfigurationId - The networkConfigurationId of an existing network 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 this.update((state) => {\n delete state.networkConfigurations[networkConfigurationId];\n });\n }\n\n /**\n * Rolls back provider config to the previous provider in case of errors or inability to connect during network switch.\n */\n async rollbackToPreviousProvider() {\n const specifier = this.#previousNetworkSpecifier;\n if (isNetworkType(specifier)) {\n await this.setProviderType(specifier);\n } else if (typeof specifier === 'string') {\n await this.setActiveNetwork(specifier);\n }\n }\n}\n\nexport default NetworkController;\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the availability state of the currently selected network.
|
|
3
|
+
*/
|
|
4
|
+
export declare enum NetworkStatus {
|
|
5
|
+
/**
|
|
6
|
+
* The network may or may not be able to receive requests, but either no
|
|
7
|
+
* attempt has been made to determine this, or an attempt was made but was
|
|
8
|
+
* unsuccessful.
|
|
9
|
+
*/
|
|
10
|
+
Unknown = "unknown",
|
|
11
|
+
/**
|
|
12
|
+
* The network is able to receive and respond to requests.
|
|
13
|
+
*/
|
|
14
|
+
Available = "available",
|
|
15
|
+
/**
|
|
16
|
+
* The network was unable to receive and respond to requests for unknown
|
|
17
|
+
* reasons.
|
|
18
|
+
*/
|
|
19
|
+
Unavailable = "unavailable"
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,aAAa;IACvB;;;;OAIG;IACH,OAAO,YAAY;IACnB;;OAEG;IACH,SAAS,cAAc;IACvB;;;OAGG;IACH,WAAW,gBAAgB;CAC5B"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NetworkStatus = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Represents the availability state of the currently selected network.
|
|
6
|
+
*/
|
|
7
|
+
var NetworkStatus;
|
|
8
|
+
(function (NetworkStatus) {
|
|
9
|
+
/**
|
|
10
|
+
* The network may or may not be able to receive requests, but either no
|
|
11
|
+
* attempt has been made to determine this, or an attempt was made but was
|
|
12
|
+
* unsuccessful.
|
|
13
|
+
*/
|
|
14
|
+
NetworkStatus["Unknown"] = "unknown";
|
|
15
|
+
/**
|
|
16
|
+
* The network is able to receive and respond to requests.
|
|
17
|
+
*/
|
|
18
|
+
NetworkStatus["Available"] = "available";
|
|
19
|
+
/**
|
|
20
|
+
* The network was unable to receive and respond to requests for unknown
|
|
21
|
+
* reasons.
|
|
22
|
+
*/
|
|
23
|
+
NetworkStatus["Unavailable"] = "unavailable";
|
|
24
|
+
})(NetworkStatus = exports.NetworkStatus || (exports.NetworkStatus = {}));
|
|
25
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,IAAY,aAgBX;AAhBD,WAAY,aAAa;IACvB;;;;OAIG;IACH,oCAAmB,CAAA;IACnB;;OAEG;IACH,wCAAuB,CAAA;IACvB;;;OAGG;IACH,4CAA2B,CAAA;AAC7B,CAAC,EAhBW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAgBxB","sourcesContent":["/**\n * Represents the availability state of the currently selected network.\n */\nexport enum NetworkStatus {\n /**\n * The network may or may not be able to receive requests, but either no\n * attempt has been made to determine this, or an attempt was made but was\n * unsuccessful.\n */\n Unknown = 'unknown',\n /**\n * The network is able to receive and respond to requests.\n */\n Available = 'available',\n /**\n * The network was unable to receive and respond to requests for unknown\n * reasons.\n */\n Unavailable = 'unavailable',\n}\n"]}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -15,4 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./NetworkController"), exports);
|
|
18
|
+
__exportStar(require("./constants"), exports);
|
|
18
19
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC","sourcesContent":["export * from './NetworkController';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC;AACpC,8CAA4B","sourcesContent":["export * from './NetworkController';\nexport * from './constants';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/network-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0",
|
|
4
4
|
"description": "Provides an interface to the currently selected network via a MetaMask-compatible provider object",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -30,28 +30,29 @@
|
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@metamask/base-controller": "^2.0.0",
|
|
33
|
-
"@metamask/controller-utils": "^3.
|
|
33
|
+
"@metamask/controller-utils": "^3.4.0",
|
|
34
34
|
"@metamask/swappable-obj-proxy": "^2.1.0",
|
|
35
|
-
"@metamask/utils": "^
|
|
35
|
+
"@metamask/utils": "^5.0.1",
|
|
36
36
|
"async-mutex": "^0.2.6",
|
|
37
37
|
"babel-runtime": "^6.26.0",
|
|
38
38
|
"eth-json-rpc-infura": "^5.1.0",
|
|
39
39
|
"eth-query": "^2.1.2",
|
|
40
|
+
"eth-rpc-errors": "^4.0.2",
|
|
40
41
|
"immer": "^9.0.6",
|
|
41
42
|
"uuid": "^8.3.2",
|
|
42
|
-
"web3-provider-engine": "^16.0.
|
|
43
|
+
"web3-provider-engine": "^16.0.5"
|
|
43
44
|
},
|
|
44
45
|
"devDependencies": {
|
|
45
46
|
"@json-rpc-specification/meta-schema": "^1.0.6",
|
|
46
47
|
"@metamask/auto-changelog": "^3.1.0",
|
|
47
|
-
"@types/jest": "^
|
|
48
|
+
"@types/jest": "^27.4.1",
|
|
48
49
|
"@types/lodash": "^4.14.191",
|
|
49
50
|
"deepmerge": "^4.2.2",
|
|
50
|
-
"jest": "^
|
|
51
|
+
"jest": "^27.5.1",
|
|
51
52
|
"lodash": "^4.17.21",
|
|
52
53
|
"nock": "^13.0.7",
|
|
53
54
|
"sinon": "^9.2.4",
|
|
54
|
-
"ts-jest": "^
|
|
55
|
+
"ts-jest": "^27.1.4",
|
|
55
56
|
"typedoc": "^0.22.15",
|
|
56
57
|
"typedoc-plugin-missing-exports": "^0.22.6",
|
|
57
58
|
"typescript": "~4.6.3"
|