@metamask/gas-fee-controller 4.0.1 → 6.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.
Files changed (27) hide show
  1. package/CHANGELOG.md +16 -2
  2. package/dist/GasFeeController.d.ts +7 -5
  3. package/dist/GasFeeController.d.ts.map +1 -0
  4. package/dist/GasFeeController.js +34 -34
  5. package/dist/GasFeeController.js.map +1 -1
  6. package/dist/determineGasFeeCalculations.d.ts +1 -0
  7. package/dist/determineGasFeeCalculations.d.ts.map +1 -0
  8. package/dist/fetchBlockFeeHistory.d.ts +1 -0
  9. package/dist/fetchBlockFeeHistory.d.ts.map +1 -0
  10. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts +1 -0
  11. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts.map +1 -0
  12. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts +3 -1
  13. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts.map +1 -0
  14. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js.map +1 -1
  15. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts +1 -0
  16. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts.map +1 -0
  17. package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts +1 -3
  18. package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts.map +1 -0
  19. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js.map +1 -1
  20. package/dist/fetchGasEstimatesViaEthFeeHistory.d.ts +2 -1
  21. package/dist/fetchGasEstimatesViaEthFeeHistory.d.ts.map +1 -0
  22. package/dist/fetchGasEstimatesViaEthFeeHistory.js.map +1 -1
  23. package/dist/gas-util.d.ts +1 -0
  24. package/dist/gas-util.d.ts.map +1 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/package.json +10 -9
package/CHANGELOG.md CHANGED
@@ -6,6 +6,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [6.0.0]
10
+ ### Changed
11
+ - **BREAKING:** Bump to Node 16 ([#1262](https://github.com/MetaMask/core/pull/1262))
12
+ - **BREAKING:** The `getChainId` constructor parameter now expects a `Hex` return type rather than a decimal string ([#1367](https://github.com/MetaMask/core/pull/1367))
13
+ - Add `@metamask/utils` dependency
14
+ - **BREAKING:** The gas fee controller messenger now requires the `NetworkController:stateChange` event instead of the `NetworkController:providerConfigChange` event ([#1329](https://github.com/MetaMask/core/pull/1329))
15
+ - **BREAKING:** Update `@metamask/network-controller` dependency and peer dependency
16
+
17
+ ## [5.0.0]
18
+ ### Changed
19
+ - **BREAKING**: peerDeps: @metamask/network-controller@6.0.0->8.0.0 ([#1196](https://github.com/MetaMask/core/pull/1196))
20
+
9
21
  ## [4.0.1]
10
22
  ### Changed
11
23
  - Adjust types to align with new version of `NetworkController` ([#1091](https://github.com/MetaMask/core/pull/1091))
@@ -22,7 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
22
34
  ### Changed
23
35
  - **BREAKING:** Update `@metamask/network-controller` peer dependency to v3 ([#1041](https://github.com/MetaMask/controllers/pull/1041))
24
36
  - Rename this repository to `core` ([#1031](https://github.com/MetaMask/controllers/pull/1031))
25
- - Update `@metamask/controller-utils` package ([#1041](https://github.com/MetaMask/controllers/pull/1041))
37
+ - Update `@metamask/controller-utils` package ([#1041](https://github.com/MetaMask/controllers/pull/1041))
26
38
 
27
39
  ## [2.0.1]
28
40
  ### Fixed
@@ -42,7 +54,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
42
54
 
43
55
  All changes listed after this point were applied to this package following the monorepo conversion.
44
56
 
45
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@4.0.1...HEAD
57
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@6.0.0...HEAD
58
+ [6.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@5.0.0...@metamask/gas-fee-controller@6.0.0
59
+ [5.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@4.0.1...@metamask/gas-fee-controller@5.0.0
46
60
  [4.0.1]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@4.0.0...@metamask/gas-fee-controller@4.0.1
47
61
  [4.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@3.0.0...@metamask/gas-fee-controller@4.0.0
48
62
  [3.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@2.0.1...@metamask/gas-fee-controller@3.0.0
@@ -1,6 +1,7 @@
1
1
  import type { Patch } from 'immer';
2
+ import type { Hex } from '@metamask/utils';
2
3
  import { BaseControllerV2, RestrictedControllerMessenger } from '@metamask/base-controller';
3
- import type { NetworkControllerGetEthQueryAction, NetworkControllerGetProviderConfigAction, NetworkControllerProviderConfigChangeEvent, NetworkState, ProviderProxy } from '@metamask/network-controller';
4
+ import type { NetworkControllerGetStateAction, NetworkControllerStateChangeEvent, NetworkState, ProviderProxy } from '@metamask/network-controller';
4
5
  export declare const LEGACY_GAS_PRICES_API_URL = "https://api.metaswap.codefi.network/gasPrices";
5
6
  export declare type unknownString = 'unknown';
6
7
  export declare type FeeMarketEstimateType = 'fee-market';
@@ -141,12 +142,12 @@ export declare type GetGasFeeState = {
141
142
  type: `${typeof name}:getState`;
142
143
  handler: () => GasFeeState;
143
144
  };
144
- declare type GasFeeMessenger = RestrictedControllerMessenger<typeof name, GetGasFeeState | NetworkControllerGetProviderConfigAction | NetworkControllerGetEthQueryAction, GasFeeStateChange | NetworkControllerProviderConfigChangeEvent, NetworkControllerGetProviderConfigAction['type'] | NetworkControllerGetEthQueryAction['type'], NetworkControllerProviderConfigChangeEvent['type']>;
145
- export declare type ChainID = `0x${string}` | `${number}` | number;
145
+ declare type GasFeeMessenger = RestrictedControllerMessenger<typeof name, GetGasFeeState | NetworkControllerGetStateAction, GasFeeStateChange | NetworkControllerStateChangeEvent, NetworkControllerGetStateAction['type'], NetworkControllerStateChangeEvent['type']>;
146
146
  /**
147
147
  * Controller that retrieves gas fee estimate data and polls for updated data on a set interval
148
148
  */
149
149
  export declare class GasFeeController extends BaseControllerV2<typeof name, GasFeeState, GasFeeMessenger> {
150
+ #private;
150
151
  private intervalId?;
151
152
  private intervalDelay;
152
153
  private pollTokens;
@@ -156,7 +157,7 @@ export declare class GasFeeController extends BaseControllerV2<typeof name, GasF
156
157
  private getCurrentNetworkLegacyGasAPICompatibility;
157
158
  private getCurrentAccountEIP1559Compatibility;
158
159
  private currentChainId;
159
- private ethQuery;
160
+ private ethQuery?;
160
161
  private clientId?;
161
162
  /**
162
163
  * Creates a GasFeeController instance.
@@ -188,7 +189,7 @@ export declare class GasFeeController extends BaseControllerV2<typeof name, GasF
188
189
  getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;
189
190
  getCurrentNetworkLegacyGasAPICompatibility: () => boolean;
190
191
  getCurrentAccountEIP1559Compatibility?: () => boolean;
191
- getChainId?: () => `0x${string}` | `${number}` | number;
192
+ getChainId?: () => Hex;
192
193
  getProvider: () => ProviderProxy;
193
194
  onNetworkStateChange?: (listener: (state: NetworkState) => void) => void;
194
195
  legacyAPIEndpoint?: string;
@@ -226,3 +227,4 @@ export declare class GasFeeController extends BaseControllerV2<typeof name, GasF
226
227
  getTimeEstimate(maxPriorityFeePerGas: string, maxFeePerGas: string): EstimatedGasFeeTimeBounds | Record<string, never>;
227
228
  }
228
229
  export default GasFeeController;
230
+ //# sourceMappingURL=GasFeeController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GasFeeController.d.ts","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAA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CAAC;IA+CvB;;;;OAIG;IACH,gBAAgB,CAAC,SAAS,EAAE,MAAM;IAOlC,WAAW;IAQX;;;;OAIG;IACM,OAAO;IAKhB,OAAO,CAAC,KAAK;IAUb,OAAO,CAAC,UAAU;YAMJ,uBAAuB;IAWrC,eAAe,CACb,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,GACnB,yBAAyB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC;CAwBrD;AAED,eAAe,gBAAgB,CAAC"}
@@ -8,14 +8,25 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
11
22
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
23
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
24
  };
25
+ var _GasFeeController_instances, _GasFeeController_getProvider, _GasFeeController_onNetworkControllerStateChange;
14
26
  Object.defineProperty(exports, "__esModule", { value: true });
15
27
  exports.GasFeeController = exports.GAS_ESTIMATE_TYPES = exports.LEGACY_GAS_PRICES_API_URL = void 0;
16
28
  const eth_query_1 = __importDefault(require("eth-query"));
17
29
  const uuid_1 = require("uuid");
18
- const ethereumjs_util_1 = require("ethereumjs-util");
19
30
  const base_controller_1 = require("@metamask/base-controller");
20
31
  const controller_utils_1 = require("@metamask/controller-utils");
21
32
  const gas_util_1 = require("./gas-util");
@@ -79,6 +90,8 @@ class GasFeeController extends base_controller_1.BaseControllerV2 {
79
90
  messenger,
80
91
  state: Object.assign(Object.assign({}, defaultState), state),
81
92
  });
93
+ _GasFeeController_instances.add(this);
94
+ _GasFeeController_getProvider.set(this, void 0);
82
95
  this.intervalDelay = interval;
83
96
  this.pollTokens = new Set();
84
97
  this.getCurrentNetworkEIP1559Compatibility =
@@ -87,33 +100,21 @@ class GasFeeController extends base_controller_1.BaseControllerV2 {
87
100
  getCurrentNetworkLegacyGasAPICompatibility;
88
101
  this.getCurrentAccountEIP1559Compatibility =
89
102
  getCurrentAccountEIP1559Compatibility;
103
+ __classPrivateFieldSet(this, _GasFeeController_getProvider, getProvider, "f");
90
104
  this.EIP1559APIEndpoint = EIP1559APIEndpoint;
91
105
  this.legacyAPIEndpoint = legacyAPIEndpoint;
92
106
  this.clientId = clientId;
107
+ this.ethQuery = new eth_query_1.default(__classPrivateFieldGet(this, _GasFeeController_getProvider, "f").call(this));
93
108
  if (onNetworkStateChange && getChainId) {
94
- const initialProvider = getProvider();
95
- this.ethQuery = new eth_query_1.default(initialProvider);
96
109
  this.currentChainId = getChainId();
97
- onNetworkStateChange(() => __awaiter(this, void 0, void 0, function* () {
98
- const newProvider = getProvider();
99
- const newChainId = getChainId();
100
- this.ethQuery = new eth_query_1.default(newProvider);
101
- if (this.currentChainId !== newChainId) {
102
- this.currentChainId = newChainId;
103
- yield this.resetPolling();
104
- }
110
+ onNetworkStateChange((networkControllerState) => __awaiter(this, void 0, void 0, function* () {
111
+ yield __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerStateChange).call(this, networkControllerState);
105
112
  }));
106
113
  }
107
114
  else {
108
- const providerConfig = this.messagingSystem.call('NetworkController:getProviderConfig');
109
- this.currentChainId = providerConfig.chainId;
110
- this.ethQuery = this.messagingSystem.call('NetworkController:getEthQuery');
111
- this.messagingSystem.subscribe('NetworkController:providerConfigChange', (newProviderConfig) => __awaiter(this, void 0, void 0, function* () {
112
- this.ethQuery = this.messagingSystem.call('NetworkController:getEthQuery');
113
- if (this.currentChainId !== newProviderConfig.chainId) {
114
- this.currentChainId = newProviderConfig.chainId;
115
- yield this.resetPolling();
116
- }
115
+ this.currentChainId = this.messagingSystem.call('NetworkController:getState').providerConfig.chainId;
116
+ this.messagingSystem.subscribe('NetworkController:stateChange', (networkControllerState) => __awaiter(this, void 0, void 0, function* () {
117
+ yield __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerStateChange).call(this, networkControllerState);
117
118
  }));
118
119
  }
119
120
  }
@@ -158,18 +159,7 @@ class GasFeeController extends base_controller_1.BaseControllerV2 {
158
159
  const { shouldUpdateState = true } = options;
159
160
  let isEIP1559Compatible;
160
161
  const isLegacyGasAPICompatible = this.getCurrentNetworkLegacyGasAPICompatibility();
161
- let chainId;
162
- if (typeof this.currentChainId === 'string') {
163
- if ((0, ethereumjs_util_1.isHexString)(this.currentChainId)) {
164
- chainId = parseInt(this.currentChainId, 16);
165
- }
166
- else {
167
- chainId = parseInt(this.currentChainId, 10);
168
- }
169
- }
170
- else {
171
- chainId = this.currentChainId;
172
- }
162
+ const decimalChainId = (0, controller_utils_1.convertHexToDecimal)(this.currentChainId);
173
163
  try {
174
164
  isEIP1559Compatible = yield this.getEIP1559Compatibility();
175
165
  }
@@ -181,10 +171,10 @@ class GasFeeController extends base_controller_1.BaseControllerV2 {
181
171
  isEIP1559Compatible,
182
172
  isLegacyGasAPICompatible,
183
173
  fetchGasEstimates: gas_util_1.fetchGasEstimates,
184
- fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace('<chain_id>', `${chainId}`),
174
+ fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace('<chain_id>', `${decimalChainId}`),
185
175
  fetchGasEstimatesViaEthFeeHistory: fetchGasEstimatesViaEthFeeHistory_1.default,
186
176
  fetchLegacyGasPriceEstimates: gas_util_1.fetchLegacyGasPriceEstimates,
187
- fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace('<chain_id>', `${chainId}`),
177
+ fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace('<chain_id>', `${decimalChainId}`),
188
178
  fetchEthGasPriceEstimate: gas_util_1.fetchEthGasPriceEstimate,
189
179
  calculateTimeEstimate: gas_util_1.calculateTimeEstimate,
190
180
  clientId: this.clientId,
@@ -258,5 +248,15 @@ class GasFeeController extends base_controller_1.BaseControllerV2 {
258
248
  }
259
249
  }
260
250
  exports.GasFeeController = GasFeeController;
251
+ _GasFeeController_getProvider = new WeakMap(), _GasFeeController_instances = new WeakSet(), _GasFeeController_onNetworkControllerStateChange = function _GasFeeController_onNetworkControllerStateChange(networkControllerState) {
252
+ return __awaiter(this, void 0, void 0, function* () {
253
+ const newChainId = networkControllerState.providerConfig.chainId;
254
+ if (newChainId !== this.currentChainId) {
255
+ this.ethQuery = new eth_query_1.default(__classPrivateFieldGet(this, _GasFeeController_getProvider, "f").call(this));
256
+ yield this.resetPolling();
257
+ this.currentChainId = newChainId;
258
+ }
259
+ });
260
+ };
261
261
  exports.default = GasFeeController;
262
262
  //# sourceMappingURL=GasFeeController.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GasFeeController.js","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,0DAAiC;AACjC,+BAAoC;AACpC,qDAA8C;AAC9C,+DAGmC;AACnC,iEAA2D;AAQ3D,yCAKoB;AACpB,gGAAwE;AACxE,4GAAoF;AAEvE,QAAA,yBAAyB,GAAG,+CAA+C,CAAC;AAoBzF;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG;IAChC,UAAU,EAAE,YAAq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AEzD,OAAO,CACL,iCAAiC,IAAI,iCAAiC,CACvE,CAAC;;KACH;IAED,eAAe,CACb,oBAA4B,EAC5B,YAAoB;QAEpB,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe;YAC3B,IAAI,CAAC,KAAK,CAAC,eAAe,KAAK,0BAAkB,CAAC,UAAU,EAC5D;YACA,OAAO,EAAE,CAAC;SACX;QACD,OAAO,IAAA,gCAAqB,EAC1B,oBAAoB,EACpB,YAAY,EACZ,IAAI,CAAC,KAAK,CAAC,eAAe,CAC3B,CAAC;IACJ,CAAC;CACF;AA/SD,4CA+SC;AAED,kBAAe,gBAAgB,CAAC","sourcesContent":["import type { Patch } from 'immer';\nimport EthQuery from 'eth-query';\nimport { v1 as random } from 'uuid';\nimport { isHexString } from 'ethereumjs-util';\nimport {\n BaseControllerV2,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport type {\n NetworkControllerGetEthQueryAction,\n NetworkControllerGetProviderConfigAction,\n NetworkControllerProviderConfigChangeEvent,\n NetworkState,\n ProviderProxy,\n} from '@metamask/network-controller';\nimport {\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n} from './gas-util';\nimport determineGasFeeCalculations from './determineGasFeeCalculations';\nimport fetchGasEstimatesViaEthFeeHistory from './fetchGasEstimatesViaEthFeeHistory';\n\nexport const LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;\n\nexport type unknownString = 'unknown';\n\n// Fee Market describes the way gas is set after the london hardfork, and was\n// defined by EIP-1559.\nexport type FeeMarketEstimateType = 'fee-market';\n// Legacy describes gasPrice estimates from before london hardfork, when the\n// user is connected to mainnet and are presented with fast/average/slow\n// estimate levels to choose from.\nexport type LegacyEstimateType = 'legacy';\n// EthGasPrice describes a gasPrice estimate received from eth_gasPrice. Post\n// london this value should only be used for legacy type transactions when on\n// networks that support EIP-1559. This type of estimate is the most accurate\n// to display on custom networks that don't support EIP-1559.\nexport type EthGasPriceEstimateType = 'eth_gasPrice';\n// NoEstimate describes the state of the controller before receiving its first\n// estimate.\nexport type NoEstimateType = 'none';\n\n/**\n * Indicates which type of gasEstimate the controller is currently returning.\n * This is useful as a way of asserting that the shape of gasEstimates matches\n * expectations. NONE is a special case indicating that no previous gasEstimate\n * has been fetched.\n */\nexport const GAS_ESTIMATE_TYPES = {\n FEE_MARKET: 'fee-market' as FeeMarketEstimateType,\n LEGACY: 'legacy' as LegacyEstimateType,\n ETH_GASPRICE: 'eth_gasPrice' as EthGasPriceEstimateType,\n NONE: 'none' as NoEstimateType,\n};\n\nexport type GasEstimateType =\n | FeeMarketEstimateType\n | EthGasPriceEstimateType\n | LegacyEstimateType\n | NoEstimateType;\n\nexport type EstimatedGasFeeTimeBounds = {\n lowerTimeBound: number | null;\n upperTimeBound: number | unknownString;\n};\n\n/**\n * @type EthGasPriceEstimate\n *\n * A single gas price estimate for networks and accounts that don't support EIP-1559\n * This estimate comes from eth_gasPrice but is converted to dec gwei to match other\n * return values\n * @property gasPrice - A GWEI dec string\n */\n\nexport type EthGasPriceEstimate = {\n gasPrice: string;\n};\n\n/**\n * @type LegacyGasPriceEstimate\n *\n * A set of gas price estimates for networks and accounts that don't support EIP-1559\n * These estimates include low, medium and high all as strings representing gwei in\n * decimal format.\n * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion\n * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion\n * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion\n */\nexport type LegacyGasPriceEstimate = {\n high: string;\n medium: string;\n low: string;\n};\n\n/**\n * @type Eip1559GasFee\n *\n * Data necessary to provide an estimate of a gas fee with a specific tip\n * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds\n * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds\n * @property suggestedMaxPriorityFeePerGas - A suggested \"tip\", a GWEI hex number\n * @property suggestedMaxFeePerGas - A suggested max fee, the most a user will pay. a GWEI hex number\n */\nexport type Eip1559GasFee = {\n minWaitTimeEstimate: number; // a time duration in milliseconds\n maxWaitTimeEstimate: number; // a time duration in milliseconds\n suggestedMaxPriorityFeePerGas: string; // a GWEI decimal number\n suggestedMaxFeePerGas: string; // a GWEI decimal number\n};\n\n/**\n * @type GasFeeEstimates\n *\n * Data necessary to provide multiple GasFee estimates, and supporting information, to the user\n * @property low - A GasFee for a minimum necessary combination of tip and maxFee\n * @property medium - A GasFee for a recommended combination of tip and maxFee\n * @property high - A GasFee for a high combination of tip and maxFee\n * @property estimatedBaseFee - An estimate of what the base fee will be for the pending/next block. A GWEI dec number\n * @property networkCongestion - A normalized number that can be used to gauge the congestion\n * level of the network, with 0 meaning not congested and 1 meaning extremely congested\n */\nexport type GasFeeEstimates = SourcedGasFeeEstimates | FallbackGasFeeEstimates;\n\ntype SourcedGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: [string, string];\n baseFeeTrend: 'up' | 'down' | 'level';\n latestPriorityFeeRange: [string, string];\n historicalPriorityFeeRange: [string, string];\n priorityFeeTrend: 'up' | 'down' | 'level';\n networkCongestion: number;\n};\n\ntype FallbackGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: null;\n baseFeeTrend: null;\n latestPriorityFeeRange: null;\n historicalPriorityFeeRange: null;\n priorityFeeTrend: null;\n networkCongestion: null;\n};\n\nconst metadata = {\n gasFeeEstimates: { persist: true, anonymous: false },\n estimatedGasFeeTimeBounds: { persist: true, anonymous: false },\n gasEstimateType: { persist: true, anonymous: false },\n};\n\nexport type GasFeeStateEthGasPrice = {\n gasFeeEstimates: EthGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: EthGasPriceEstimateType;\n};\n\nexport type GasFeeStateFeeMarket = {\n gasFeeEstimates: GasFeeEstimates;\n estimatedGasFeeTimeBounds: EstimatedGasFeeTimeBounds | Record<string, never>;\n gasEstimateType: FeeMarketEstimateType;\n};\n\nexport type GasFeeStateLegacy = {\n gasFeeEstimates: LegacyGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: LegacyEstimateType;\n};\n\nexport type GasFeeStateNoEstimates = {\n gasFeeEstimates: Record<string, never>;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: NoEstimateType;\n};\n\nexport type FetchGasFeeEstimateOptions = {\n shouldUpdateState?: boolean;\n};\n\n/**\n * @type GasFeeState\n *\n * Gas Fee controller state\n * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties\n * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum\n */\nexport type GasFeeState =\n | GasFeeStateEthGasPrice\n | GasFeeStateFeeMarket\n | GasFeeStateLegacy\n | GasFeeStateNoEstimates;\n\nconst name = 'GasFeeController';\n\nexport type GasFeeStateChange = {\n type: `${typeof name}:stateChange`;\n payload: [GasFeeState, Patch[]];\n};\n\nexport type GetGasFeeState = {\n type: `${typeof name}:getState`;\n handler: () => GasFeeState;\n};\n\ntype GasFeeMessenger = RestrictedControllerMessenger<\n typeof name,\n | GetGasFeeState\n | NetworkControllerGetProviderConfigAction\n | NetworkControllerGetEthQueryAction,\n GasFeeStateChange | NetworkControllerProviderConfigChangeEvent,\n | NetworkControllerGetProviderConfigAction['type']\n | NetworkControllerGetEthQueryAction['type'],\n NetworkControllerProviderConfigChangeEvent['type']\n>;\n\nconst defaultState: GasFeeState = {\n gasFeeEstimates: {},\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.NONE,\n};\n\nexport type ChainID = `0x${string}` | `${number}` | number;\n\n/**\n * Controller that retrieves gas fee estimate data and polls for updated data on a set interval\n */\nexport class GasFeeController extends BaseControllerV2<\n typeof name,\n GasFeeState,\n GasFeeMessenger\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private intervalDelay;\n\n private pollTokens: Set<string>;\n\n private legacyAPIEndpoint: string;\n\n private EIP1559APIEndpoint: string;\n\n private getCurrentNetworkEIP1559Compatibility;\n\n private getCurrentNetworkLegacyGasAPICompatibility;\n\n private getCurrentAccountEIP1559Compatibility;\n\n private currentChainId;\n\n private ethQuery: any;\n\n private clientId?: string;\n\n /**\n * Creates a GasFeeController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The time in milliseconds to wait between polls.\n * @param options.messenger - The controller messenger.\n * @param options.state - The initial state.\n * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current\n * network is EIP-1559 compatible.\n * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the\n * current network is compatible with the legacy gas price API.\n * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current\n * account is EIP-1559 compatible.\n * @param options.getChainId - Returns the current chain ID.\n * @param options.getProvider - Returns a network provider for the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for the\n * network state change event.\n * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for\n * testing purposes.\n * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.\n * @param options.clientId - The client ID used to identify to the gas estimation API who is\n * asking for estimates.\n */\n constructor({\n interval = 15000,\n messenger,\n state,\n getCurrentNetworkEIP1559Compatibility,\n getCurrentAccountEIP1559Compatibility,\n getChainId,\n getCurrentNetworkLegacyGasAPICompatibility,\n getProvider,\n onNetworkStateChange,\n legacyAPIEndpoint = LEGACY_GAS_PRICES_API_URL,\n EIP1559APIEndpoint,\n clientId,\n }: {\n interval?: number;\n messenger: GasFeeMessenger;\n state?: GasFeeState;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkLegacyGasAPICompatibility: () => boolean;\n getCurrentAccountEIP1559Compatibility?: () => boolean;\n getChainId?: () => `0x${string}` | `${number}` | number;\n getProvider: () => ProviderProxy;\n onNetworkStateChange?: (listener: (state: NetworkState) => void) => void;\n legacyAPIEndpoint?: string;\n EIP1559APIEndpoint: string;\n clientId?: string;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.intervalDelay = interval;\n this.pollTokens = new Set();\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n\n this.getCurrentNetworkLegacyGasAPICompatibility =\n getCurrentNetworkLegacyGasAPICompatibility;\n\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.EIP1559APIEndpoint = EIP1559APIEndpoint;\n this.legacyAPIEndpoint = legacyAPIEndpoint;\n this.clientId = clientId;\n if (onNetworkStateChange && getChainId) {\n const initialProvider = getProvider();\n this.ethQuery = new EthQuery(initialProvider);\n this.currentChainId = getChainId();\n onNetworkStateChange(async () => {\n const newProvider = getProvider();\n const newChainId = getChainId();\n this.ethQuery = new EthQuery(newProvider);\n if (this.currentChainId !== newChainId) {\n this.currentChainId = newChainId;\n await this.resetPolling();\n }\n });\n } else {\n const providerConfig = this.messagingSystem.call(\n 'NetworkController:getProviderConfig',\n );\n this.currentChainId = providerConfig.chainId;\n this.ethQuery = this.messagingSystem.call(\n 'NetworkController:getEthQuery',\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:providerConfigChange',\n async (newProviderConfig) => {\n this.ethQuery = this.messagingSystem.call(\n 'NetworkController:getEthQuery',\n );\n\n if (this.currentChainId !== newProviderConfig.chainId) {\n this.currentChainId = newProviderConfig.chainId;\n await this.resetPolling();\n }\n },\n );\n }\n }\n\n async resetPolling() {\n if (this.pollTokens.size !== 0) {\n const tokens = Array.from(this.pollTokens);\n this.stopPolling();\n await this.getGasFeeEstimatesAndStartPolling(tokens[0]);\n tokens.slice(1).forEach((token) => {\n this.pollTokens.add(token);\n });\n }\n }\n\n async fetchGasFeeEstimates(options?: FetchGasFeeEstimateOptions) {\n return await this._fetchGasFeeEstimateData(options);\n }\n\n async getGasFeeEstimatesAndStartPolling(\n pollToken: string | undefined,\n ): Promise<string> {\n const _pollToken = pollToken || random();\n\n this.pollTokens.add(_pollToken);\n\n if (this.pollTokens.size === 1) {\n await this._fetchGasFeeEstimateData();\n this._poll();\n }\n\n return _pollToken;\n }\n\n /**\n * Gets and sets gasFeeEstimates in state.\n *\n * @param options - The gas fee estimate options.\n * @param options.shouldUpdateState - Determines whether the state should be updated with the\n * updated gas estimates.\n * @returns The gas fee estimates.\n */\n async _fetchGasFeeEstimateData(\n options: FetchGasFeeEstimateOptions = {},\n ): Promise<GasFeeState> {\n const { shouldUpdateState = true } = options;\n let isEIP1559Compatible;\n const isLegacyGasAPICompatible =\n this.getCurrentNetworkLegacyGasAPICompatibility();\n\n let chainId: number;\n if (typeof this.currentChainId === 'string') {\n if (isHexString(this.currentChainId)) {\n chainId = parseInt(this.currentChainId, 16);\n } else {\n chainId = parseInt(this.currentChainId, 10);\n }\n } else {\n chainId = this.currentChainId;\n }\n\n try {\n isEIP1559Compatible = await this.getEIP1559Compatibility();\n } catch (e) {\n console.error(e);\n isEIP1559Compatible = false;\n }\n\n const gasFeeCalculations = await determineGasFeeCalculations({\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n fetchGasEstimates,\n fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace(\n '<chain_id>',\n `${chainId}`,\n ),\n fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${chainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery: this.ethQuery,\n });\n\n if (shouldUpdateState) {\n this.update((state) => {\n state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;\n state.estimatedGasFeeTimeBounds =\n gasFeeCalculations.estimatedGasFeeTimeBounds;\n state.gasEstimateType = gasFeeCalculations.gasEstimateType;\n });\n }\n\n return gasFeeCalculations;\n }\n\n /**\n * Remove the poll token, and stop polling if the set of poll tokens is empty.\n *\n * @param pollToken - The poll token to disconnect.\n */\n disconnectPoller(pollToken: string) {\n this.pollTokens.delete(pollToken);\n if (this.pollTokens.size === 0) {\n this.stopPolling();\n }\n }\n\n stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n this.pollTokens.clear();\n this.resetState();\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopPolling();\n }\n\n private _poll() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this._fetchGasFeeEstimateData());\n }, this.intervalDelay);\n }\n\n private resetState() {\n this.update(() => {\n return defaultState;\n });\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n\n getTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n ): EstimatedGasFeeTimeBounds | Record<string, never> {\n if (\n !this.state.gasFeeEstimates ||\n this.state.gasEstimateType !== GAS_ESTIMATE_TYPES.FEE_MARKET\n ) {\n return {};\n }\n return calculateTimeEstimate(\n maxPriorityFeePerGas,\n maxFeePerGas,\n this.state.gasFeeEstimates,\n );\n }\n}\n\nexport default GasFeeController;\n"]}
1
+ {"version":3,"file":"GasFeeController.js","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,0DAAiC;AACjC,+BAAoC;AAEpC,+DAGmC;AACnC,iEAAgF;AAOhF,yCAKoB;AACpB,gGAAwE;AACxE,4GAAoF;AAEvE,QAAA,yBAAyB,GAAG,+CAA+C,CAAC;AAoBzF;;;;;GAKG;A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;IACH,CAAC;;AAGH,kBAAe,gBAAgB,CAAC","sourcesContent":["import type { Patch } from 'immer';\nimport EthQuery from 'eth-query';\nimport { v1 as random } from 'uuid';\nimport type { Hex } from '@metamask/utils';\nimport {\n BaseControllerV2,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { convertHexToDecimal, safelyExecute } from '@metamask/controller-utils';\nimport type {\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n ProviderProxy,\n} from '@metamask/network-controller';\nimport {\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n} from './gas-util';\nimport determineGasFeeCalculations from './determineGasFeeCalculations';\nimport fetchGasEstimatesViaEthFeeHistory from './fetchGasEstimatesViaEthFeeHistory';\n\nexport const LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;\n\nexport type unknownString = 'unknown';\n\n// Fee Market describes the way gas is set after the london hardfork, and was\n// defined by EIP-1559.\nexport type FeeMarketEstimateType = 'fee-market';\n// Legacy describes gasPrice estimates from before london hardfork, when the\n// user is connected to mainnet and are presented with fast/average/slow\n// estimate levels to choose from.\nexport type LegacyEstimateType = 'legacy';\n// EthGasPrice describes a gasPrice estimate received from eth_gasPrice. Post\n// london this value should only be used for legacy type transactions when on\n// networks that support EIP-1559. This type of estimate is the most accurate\n// to display on custom networks that don't support EIP-1559.\nexport type EthGasPriceEstimateType = 'eth_gasPrice';\n// NoEstimate describes the state of the controller before receiving its first\n// estimate.\nexport type NoEstimateType = 'none';\n\n/**\n * Indicates which type of gasEstimate the controller is currently returning.\n * This is useful as a way of asserting that the shape of gasEstimates matches\n * expectations. NONE is a special case indicating that no previous gasEstimate\n * has been fetched.\n */\nexport const GAS_ESTIMATE_TYPES = {\n FEE_MARKET: 'fee-market' as FeeMarketEstimateType,\n LEGACY: 'legacy' as LegacyEstimateType,\n ETH_GASPRICE: 'eth_gasPrice' as EthGasPriceEstimateType,\n NONE: 'none' as NoEstimateType,\n};\n\nexport type GasEstimateType =\n | FeeMarketEstimateType\n | EthGasPriceEstimateType\n | LegacyEstimateType\n | NoEstimateType;\n\nexport type EstimatedGasFeeTimeBounds = {\n lowerTimeBound: number | null;\n upperTimeBound: number | unknownString;\n};\n\n/**\n * @type EthGasPriceEstimate\n *\n * A single gas price estimate for networks and accounts that don't support EIP-1559\n * This estimate comes from eth_gasPrice but is converted to dec gwei to match other\n * return values\n * @property gasPrice - A GWEI dec string\n */\n\nexport type EthGasPriceEstimate = {\n gasPrice: string;\n};\n\n/**\n * @type LegacyGasPriceEstimate\n *\n * A set of gas price estimates for networks and accounts that don't support EIP-1559\n * These estimates include low, medium and high all as strings representing gwei in\n * decimal format.\n * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion\n * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion\n * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion\n */\nexport type LegacyGasPriceEstimate = {\n high: string;\n medium: string;\n low: string;\n};\n\n/**\n * @type Eip1559GasFee\n *\n * Data necessary to provide an estimate of a gas fee with a specific tip\n * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds\n * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds\n * @property suggestedMaxPriorityFeePerGas - A suggested \"tip\", a GWEI hex number\n * @property suggestedMaxFeePerGas - A suggested max fee, the most a user will pay. a GWEI hex number\n */\nexport type Eip1559GasFee = {\n minWaitTimeEstimate: number; // a time duration in milliseconds\n maxWaitTimeEstimate: number; // a time duration in milliseconds\n suggestedMaxPriorityFeePerGas: string; // a GWEI decimal number\n suggestedMaxFeePerGas: string; // a GWEI decimal number\n};\n\n/**\n * @type GasFeeEstimates\n *\n * Data necessary to provide multiple GasFee estimates, and supporting information, to the user\n * @property low - A GasFee for a minimum necessary combination of tip and maxFee\n * @property medium - A GasFee for a recommended combination of tip and maxFee\n * @property high - A GasFee for a high combination of tip and maxFee\n * @property estimatedBaseFee - An estimate of what the base fee will be for the pending/next block. A GWEI dec number\n * @property networkCongestion - A normalized number that can be used to gauge the congestion\n * level of the network, with 0 meaning not congested and 1 meaning extremely congested\n */\nexport type GasFeeEstimates = SourcedGasFeeEstimates | FallbackGasFeeEstimates;\n\ntype SourcedGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: [string, string];\n baseFeeTrend: 'up' | 'down' | 'level';\n latestPriorityFeeRange: [string, string];\n historicalPriorityFeeRange: [string, string];\n priorityFeeTrend: 'up' | 'down' | 'level';\n networkCongestion: number;\n};\n\ntype FallbackGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: null;\n baseFeeTrend: null;\n latestPriorityFeeRange: null;\n historicalPriorityFeeRange: null;\n priorityFeeTrend: null;\n networkCongestion: null;\n};\n\nconst metadata = {\n gasFeeEstimates: { persist: true, anonymous: false },\n estimatedGasFeeTimeBounds: { persist: true, anonymous: false },\n gasEstimateType: { persist: true, anonymous: false },\n};\n\nexport type GasFeeStateEthGasPrice = {\n gasFeeEstimates: EthGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: EthGasPriceEstimateType;\n};\n\nexport type GasFeeStateFeeMarket = {\n gasFeeEstimates: GasFeeEstimates;\n estimatedGasFeeTimeBounds: EstimatedGasFeeTimeBounds | Record<string, never>;\n gasEstimateType: FeeMarketEstimateType;\n};\n\nexport type GasFeeStateLegacy = {\n gasFeeEstimates: LegacyGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: LegacyEstimateType;\n};\n\nexport type GasFeeStateNoEstimates = {\n gasFeeEstimates: Record<string, never>;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: NoEstimateType;\n};\n\nexport type FetchGasFeeEstimateOptions = {\n shouldUpdateState?: boolean;\n};\n\n/**\n * @type GasFeeState\n *\n * Gas Fee controller state\n * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties\n * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum\n */\nexport type GasFeeState =\n | GasFeeStateEthGasPrice\n | GasFeeStateFeeMarket\n | GasFeeStateLegacy\n | GasFeeStateNoEstimates;\n\nconst name = 'GasFeeController';\n\nexport type GasFeeStateChange = {\n type: `${typeof name}:stateChange`;\n payload: [GasFeeState, Patch[]];\n};\n\nexport type GetGasFeeState = {\n type: `${typeof name}:getState`;\n handler: () => GasFeeState;\n};\n\ntype GasFeeMessenger = RestrictedControllerMessenger<\n typeof name,\n GetGasFeeState | NetworkControllerGetStateAction,\n GasFeeStateChange | NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction['type'],\n NetworkControllerStateChangeEvent['type']\n>;\n\nconst defaultState: GasFeeState = {\n gasFeeEstimates: {},\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.NONE,\n};\n\n/**\n * Controller that retrieves gas fee estimate data and polls for updated data on a set interval\n */\nexport class GasFeeController extends BaseControllerV2<\n typeof name,\n GasFeeState,\n GasFeeMessenger\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private intervalDelay;\n\n private pollTokens: Set<string>;\n\n private legacyAPIEndpoint: string;\n\n private EIP1559APIEndpoint: string;\n\n private getCurrentNetworkEIP1559Compatibility;\n\n private getCurrentNetworkLegacyGasAPICompatibility;\n\n private getCurrentAccountEIP1559Compatibility;\n\n private currentChainId;\n\n private ethQuery?: EthQuery;\n\n private clientId?: string;\n\n #getProvider: () => ProviderProxy;\n\n /**\n * Creates a GasFeeController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The time in milliseconds to wait between polls.\n * @param options.messenger - The controller messenger.\n * @param options.state - The initial state.\n * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current\n * network is EIP-1559 compatible.\n * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the\n * current network is compatible with the legacy gas price API.\n * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current\n * account is EIP-1559 compatible.\n * @param options.getChainId - Returns the current chain ID.\n * @param options.getProvider - Returns a network provider for the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for the\n * network state change event.\n * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for\n * testing purposes.\n * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.\n * @param options.clientId - The client ID used to identify to the gas estimation API who is\n * asking for estimates.\n */\n constructor({\n interval = 15000,\n messenger,\n state,\n getCurrentNetworkEIP1559Compatibility,\n getCurrentAccountEIP1559Compatibility,\n getChainId,\n getCurrentNetworkLegacyGasAPICompatibility,\n getProvider,\n onNetworkStateChange,\n legacyAPIEndpoint = LEGACY_GAS_PRICES_API_URL,\n EIP1559APIEndpoint,\n clientId,\n }: {\n interval?: number;\n messenger: GasFeeMessenger;\n state?: GasFeeState;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkLegacyGasAPICompatibility: () => boolean;\n getCurrentAccountEIP1559Compatibility?: () => boolean;\n getChainId?: () => Hex;\n getProvider: () => ProviderProxy;\n onNetworkStateChange?: (listener: (state: NetworkState) => void) => void;\n legacyAPIEndpoint?: string;\n EIP1559APIEndpoint: string;\n clientId?: string;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.intervalDelay = interval;\n this.pollTokens = new Set();\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n this.getCurrentNetworkLegacyGasAPICompatibility =\n getCurrentNetworkLegacyGasAPICompatibility;\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.#getProvider = getProvider;\n this.EIP1559APIEndpoint = EIP1559APIEndpoint;\n this.legacyAPIEndpoint = legacyAPIEndpoint;\n this.clientId = clientId;\n\n this.ethQuery = new EthQuery(this.#getProvider());\n\n if (onNetworkStateChange && getChainId) {\n this.currentChainId = getChainId();\n onNetworkStateChange(async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n });\n } else {\n this.currentChainId = this.messagingSystem.call(\n 'NetworkController:getState',\n ).providerConfig.chainId;\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n },\n );\n }\n }\n\n async resetPolling() {\n if (this.pollTokens.size !== 0) {\n const tokens = Array.from(this.pollTokens);\n this.stopPolling();\n await this.getGasFeeEstimatesAndStartPolling(tokens[0]);\n tokens.slice(1).forEach((token) => {\n this.pollTokens.add(token);\n });\n }\n }\n\n async fetchGasFeeEstimates(options?: FetchGasFeeEstimateOptions) {\n return await this._fetchGasFeeEstimateData(options);\n }\n\n async getGasFeeEstimatesAndStartPolling(\n pollToken: string | undefined,\n ): Promise<string> {\n const _pollToken = pollToken || random();\n\n this.pollTokens.add(_pollToken);\n\n if (this.pollTokens.size === 1) {\n await this._fetchGasFeeEstimateData();\n this._poll();\n }\n\n return _pollToken;\n }\n\n /**\n * Gets and sets gasFeeEstimates in state.\n *\n * @param options - The gas fee estimate options.\n * @param options.shouldUpdateState - Determines whether the state should be updated with the\n * updated gas estimates.\n * @returns The gas fee estimates.\n */\n async _fetchGasFeeEstimateData(\n options: FetchGasFeeEstimateOptions = {},\n ): Promise<GasFeeState> {\n const { shouldUpdateState = true } = options;\n let isEIP1559Compatible;\n const isLegacyGasAPICompatible =\n this.getCurrentNetworkLegacyGasAPICompatibility();\n\n const decimalChainId = convertHexToDecimal(this.currentChainId);\n\n try {\n isEIP1559Compatible = await this.getEIP1559Compatibility();\n } catch (e) {\n console.error(e);\n isEIP1559Compatible = false;\n }\n\n const gasFeeCalculations = await determineGasFeeCalculations({\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n fetchGasEstimates,\n fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery: this.ethQuery,\n });\n\n if (shouldUpdateState) {\n this.update((state) => {\n state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;\n state.estimatedGasFeeTimeBounds =\n gasFeeCalculations.estimatedGasFeeTimeBounds;\n state.gasEstimateType = gasFeeCalculations.gasEstimateType;\n });\n }\n\n return gasFeeCalculations;\n }\n\n /**\n * Remove the poll token, and stop polling if the set of poll tokens is empty.\n *\n * @param pollToken - The poll token to disconnect.\n */\n disconnectPoller(pollToken: string) {\n this.pollTokens.delete(pollToken);\n if (this.pollTokens.size === 0) {\n this.stopPolling();\n }\n }\n\n stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n this.pollTokens.clear();\n this.resetState();\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopPolling();\n }\n\n private _poll() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this._fetchGasFeeEstimateData());\n }, this.intervalDelay);\n }\n\n private resetState() {\n this.update(() => {\n return defaultState;\n });\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n\n getTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n ): EstimatedGasFeeTimeBounds | Record<string, never> {\n if (\n !this.state.gasFeeEstimates ||\n this.state.gasEstimateType !== GAS_ESTIMATE_TYPES.FEE_MARKET\n ) {\n return {};\n }\n return calculateTimeEstimate(\n maxPriorityFeePerGas,\n maxFeePerGas,\n this.state.gasFeeEstimates,\n );\n }\n\n async #onNetworkControllerStateChange(networkControllerState: NetworkState) {\n const newChainId = networkControllerState.providerConfig.chainId;\n\n if (newChainId !== this.currentChainId) {\n this.ethQuery = new EthQuery(this.#getProvider());\n await this.resetPolling();\n\n this.currentChainId = newChainId;\n }\n }\n}\n\nexport default GasFeeController;\n"]}
@@ -38,3 +38,4 @@ export default function determineGasFeeCalculations({ isEIP1559Compatible, isLeg
38
38
  clientId: string | undefined;
39
39
  ethQuery: any;
40
40
  }): Promise<GasFeeCalculations>;
41
+ //# sourceMappingURL=determineGasFeeCalculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"determineGasFeeCalculations.d.ts","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,yBAAyB,EACzB,mBAAmB,EACnB,eAAe,EACf,WAAW,IAAI,kBAAkB,EACjC,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAA8B,2BAA2B,CAAC,EACxD,mBAAmB,EACnB,wBAAwB,EACxB,iBAAiB,EACjB,oBAAoB,EACpB,iCAAiC,EACjC,4BAA4B,EAC5B,+BAA+B,EAC/B,wBAAwB,EACxB,qBAAqB,EACrB,QAAQ,EACR,QAAQ,GACT,EAAE;IACD,mBAAmB,EAAE,OAAO,CAAC;IAC7B,wBAAwB,EAAE,OAAO,CAAC;IAClC,iBAAiB,EAAE,CACjB,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,KACd,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,iCAAiC,EAAE,CACjC,QAAQ,EAAE,GAAG,KACV,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,4BAA4B,EAAE,CAC5B,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,KACd,OAAO,CAAC,sBAAsB,CAAC,CAAC;IACrC,+BAA+B,EAAE,MAAM,CAAC;IACxC,wBAAwB,EAAE,CAAC,QAAQ,EAAE,GAAG,KAAK,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAC1E,qBAAqB,EAAE,CACrB,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,eAAe,KAC7B,yBAAyB,CAAC;IAC/B,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,QAAQ,EAAE,GAAG,CAAC;CACf,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAkD9B"}
@@ -113,3 +113,4 @@ export default function fetchBlockFeeHistory<Percentile extends number>({ ethQue
113
113
  includeNextBlock?: boolean;
114
114
  }): Promise<FeeHistoryBlock<Percentile>[]>;
115
115
  export {};
116
+ //# sourceMappingURL=fetchBlockFeeHistory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchBlockFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAGrC,aAAK,QAAQ,GAAG,GAAG,CAAC;AAcpB;;;;;;;;;;;;;GAaG;AAEH,oBAAY,qBAAqB,GAAG;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,aAAK,uBAAuB,CAAC,UAAU,SAAS,MAAM,IAAI;IACxD,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,wBAAwB,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;;GAMG;AACH,aAAK,mBAAmB,GAAG;IACzB,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,oBAAY,eAAe,CAAC,UAAU,SAAS,MAAM,IACjD,uBAAuB,CAAC,UAAU,CAAC,GACnC,mBAAmB,CAAC;AAExB;;;;;GAKG;AACH,oBAAY,qBAAqB,CAAC,CAAC,IAAI,CAAC,SAAS,eAAe,CAAC,MAAM,CAAC,CAAC,EAAE,GACvE,CAAC,GACD,KAAK,CAAC;AAIV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAA8B,oBAAoB,CAAC,UAAU,SAAS,MAAM,EAAE,EAC5E,QAAQ,EACR,cAAc,EAAE,mBAAmB,EACnC,QAAQ,EAAE,aAAwB,EAClC,WAAW,EAAE,gBAAqB,EAClC,gBAAwB,GACzB,EAAE;IACD,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,QAAQ,GAAG,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IACpC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,GAAG,OAAO,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,CAAC,CAwCzC"}
@@ -14,3 +14,4 @@ declare const PRIORITY_LEVEL_PERCENTILES: readonly [10, 20, 30];
14
14
  */
15
15
  export default function calculateGasFeeEstimatesForPriorityLevels(blocks: FeeHistoryBlock<Percentile>[]): Pick<GasFeeEstimates, PriorityLevel>;
16
16
  export {};
17
+ //# sourceMappingURL=calculateGasFeeEstimatesForPriorityLevels.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculateGasFeeEstimatesForPriorityLevels.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":"AAGA,OAAO,EAAiB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,oBAAY,aAAa,GAAG,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC;AAC3D,oBAAY,UAAU,GAAG,OAAO,0BAA0B,CAAC,MAAM,CAAC,CAAC;AAEnE,QAAA,MAAM,eAAe,oCAAqC,CAAC;AAC3D,QAAA,MAAM,0BAA0B,uBAAwB,CAAC;AAiFzD;;;;;;;GAOG;AACH,MAAM,CAAC,OAAO,UAAU,yCAAyC,CAC/D,MAAM,EAAE,eAAe,CAAC,UAAU,CAAC,EAAE,GACpC,IAAI,CAAC,eAAe,EAAE,aAAa,CAAC,CAQtC"}
@@ -1,4 +1,5 @@
1
- import { EthBlock, EthQuery } from './types';
1
+ import type EthQuery from 'eth-query';
2
+ import { EthBlock } from './types';
2
3
  /**
3
4
  * Returns information about the latest completed block.
4
5
  *
@@ -8,3 +9,4 @@ import { EthBlock, EthQuery } from './types';
8
9
  * @returns The block.
9
10
  */
10
11
  export default function fetchLatestBlock(ethQuery: EthQuery, includeFullTransactionData?: boolean): Promise<EthBlock>;
12
+ //# sourceMappingURL=fetchLatestBlock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchLatestBlock.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEnC;;;;;;;GAOG;AACH,wBAA8B,gBAAgB,CAC5C,QAAQ,EAAE,QAAQ,EAClB,0BAA0B,UAAQ,GACjC,OAAO,CAAC,QAAQ,CAAC,CAWnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetchLatestBlock.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iEAA4D;AAG5D;;;;;;;GAOG;AACH,SAA8B,gBAAgB,CAC5C,QAAkB,EAClB,0BAA0B,GAAG,KAAK;;QAElC,MAAM,WAAW,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;QACzD,MAAM,KAAK,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,kBAAkB,EAAE;YACtD,WAAW;YACX,0BAA0B;SAC3B,CAAC,CAAC;QACH,uCACK,KAAK,KACR,MAAM,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,MAAM,CAAC,EAC7B,aAAa,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,aAAa,CAAC,IAC3C;IACJ,CAAC;CAAA;AAdD,mCAcC","sourcesContent":["import { query, fromHex } from '@metamask/controller-utils';\nimport { EthBlock, EthQuery } from './types';\n\n/**\n * Returns information about the latest completed block.\n *\n * @param ethQuery - An EthQuery instance\n * @param includeFullTransactionData - Whether or not to include all data for transactions as\n * opposed to merely hashes. False by default.\n * @returns The block.\n */\nexport default async function fetchLatestBlock(\n ethQuery: EthQuery,\n includeFullTransactionData = false,\n): Promise<EthBlock> {\n const blockNumber = await query(ethQuery, 'blockNumber');\n const block = await query(ethQuery, 'getBlockByNumber', [\n blockNumber,\n includeFullTransactionData,\n ]);\n return {\n ...block,\n number: fromHex(block.number),\n baseFeePerGas: fromHex(block.baseFeePerGas),\n };\n}\n"]}
1
+ {"version":3,"file":"fetchLatestBlock.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iEAA4D;AAI5D;;;;;;;GAOG;AACH,SAA8B,gBAAgB,CAC5C,QAAkB,EAClB,0BAA0B,GAAG,KAAK;;QAElC,MAAM,WAAW,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;QACzD,MAAM,KAAK,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,kBAAkB,EAAE;YACtD,WAAW;YACX,0BAA0B;SAC3B,CAAC,CAAC;QACH,uCACK,KAAK,KACR,MAAM,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,MAAM,CAAC,EAC7B,aAAa,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,aAAa,CAAC,IAC3C;IACJ,CAAC;CAAA;AAdD,mCAcC","sourcesContent":["import { query, fromHex } from '@metamask/controller-utils';\nimport type EthQuery from 'eth-query';\nimport { EthBlock } from './types';\n\n/**\n * Returns information about the latest completed block.\n *\n * @param ethQuery - An EthQuery instance\n * @param includeFullTransactionData - Whether or not to include all data for transactions as\n * opposed to merely hashes. False by default.\n * @returns The block.\n */\nexport default async function fetchLatestBlock(\n ethQuery: EthQuery,\n includeFullTransactionData = false,\n): Promise<EthBlock> {\n const blockNumber = await query(ethQuery, 'blockNumber');\n const block = await query(ethQuery, 'getBlockByNumber', [\n blockNumber,\n includeFullTransactionData,\n ]);\n return {\n ...block,\n number: fromHex(block.number),\n baseFeePerGas: fromHex(block.baseFeePerGas),\n };\n}\n"]}
@@ -8,3 +8,4 @@ import { BN } from 'ethereumjs-util';
8
8
  * @returns The median number.
9
9
  */
10
10
  export default function medianOf(numbers: BN[]): BN;
11
+ //# sourceMappingURL=medianOf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"medianOf.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,CAKlD"}
@@ -4,7 +4,5 @@ export declare type EthBlock = {
4
4
  number: BN;
5
5
  baseFeePerGas: BN;
6
6
  };
7
- export declare type EthQuery = {
8
- getBlockByNumber: (blockNumber: BN | 'latest' | 'earliest' | 'pending') => Promise<EthBlock>;
9
- };
10
7
  export declare type FeeRange = [string, string];
8
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAErC,oBAAY,QAAQ,GAAG;IACrB,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;CACnB,CAAC;AAEF,oBAAY,QAAQ,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"","sourcesContent":["import { BN } from 'ethereumjs-util';\n\nexport type EthBlock = {\n number: BN;\n baseFeePerGas: BN;\n};\n\nexport type EthQuery = {\n getBlockByNumber: (\n blockNumber: BN | 'latest' | 'earliest' | 'pending',\n ) => Promise<EthBlock>;\n};\n\nexport type FeeRange = [string, string];\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"","sourcesContent":["import { BN } from 'ethereumjs-util';\n\nexport type EthBlock = {\n number: BN;\n baseFeePerGas: BN;\n};\n\nexport type FeeRange = [string, string];\n"]}
@@ -1,5 +1,5 @@
1
+ import type EthQuery from 'eth-query';
1
2
  import { GasFeeEstimates } from './GasFeeController';
2
- import { EthQuery } from './fetchGasEstimatesViaEthFeeHistory/types';
3
3
  /**
4
4
  * Generates gas fee estimates based on gas fees that have been used in the recent past so that
5
5
  * those estimates can be displayed to users.
@@ -19,3 +19,4 @@ import { EthQuery } from './fetchGasEstimatesViaEthFeeHistory/types';
19
19
  * for the next block's base fee.
20
20
  */
21
21
  export default function fetchGasEstimatesViaEthFeeHistory(ethQuery: EthQuery): Promise<GasFeeEstimates>;
22
+ //# sourceMappingURL=fetchGasEstimatesViaEthFeeHistory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchGasEstimatesViaEthFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAKrD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAA8B,iCAAiC,CAC7D,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,eAAe,CAAC,CAuB1B"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetchGasEstimatesViaEthFeeHistory.js","sourceRoot":"","sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,2CAAqC;AACrC,iEAAkD;AAGlD,kFAA0D;AAC1D,4GAAoF;AACpF,8JAAsI;AAEtI;;;;;;;;;;;;;;;;;GAiBG;AACH,SAA8B,iCAAiC,CAC7D,QAAkB;;QAElB,MAAM,WAAW,GAAG,MAAM,IAAA,0BAAgB,EAAC,QAAQ,CAAC,CAAC;QACrD,MAAM,MAAM,GAAG,MAAM,IAAA,8BAAoB,EAAC;YACxC,QAAQ;YACR,QAAQ,EAAE,WAAW,CAAC,MAAM;YAC5B,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;SAC1B,CAAC,CAAC;QACH,MAAM,gBAAgB,GAAG,IAAA,oBAAO,EAAC,WAAW,CAAC,aAAa,EAAE,uBAAI,CAAC,CAAC;QAElE,MAAM,sBAAsB,GAC1B,IAAA,mDAAyC,EAAC,MAAM,CAAC,CAAC;QAEpD,uCACK,sBAAsB,KACzB,gBAAgB,EAChB,sBAAsB,EAAE,IAAI,EAC5B,YAAY,EAAE,IAAI,EAClB,sBAAsB,EAAE,IAAI,EAC5B,0BAA0B,EAAE,IAAI,EAChC,gBAAgB,EAAE,IAAI,EACtB,iBAAiB,EAAE,IAAI,IACvB;IACJ,CAAC;CAAA;AAzBD,oDAyBC","sourcesContent":["import { fromWei } from 'ethjs-unit';\nimport { GWEI } from '@metamask/controller-utils';\nimport { GasFeeEstimates } from './GasFeeController';\nimport { EthQuery } from './fetchGasEstimatesViaEthFeeHistory/types';\nimport fetchBlockFeeHistory from './fetchBlockFeeHistory';\nimport fetchLatestBlock from './fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock';\nimport calculateGasFeeEstimatesForPriorityLevels from './fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels';\n\n/**\n * Generates gas fee estimates based on gas fees that have been used in the recent past so that\n * those estimates can be displayed to users.\n *\n * To produce the estimates, the last 5 blocks are read from the network, and for each block, the\n * priority fees for transactions at the 10th, 20th, and 30th percentiles are also read (here\n * \"percentile\" signifies the level at which those transactions contribute to the overall gas used\n * for the block, where higher percentiles correspond to higher fees). This information is used to\n * calculate reasonable max priority and max fees for three different priority levels (higher\n * priority = higher fee).\n *\n * Note that properties are returned for other data that are normally obtained via the API; however,\n * to prevent extra requests to Infura, these properties are empty.\n *\n * @param ethQuery - An EthQuery instance.\n * @returns Base and priority fee estimates, categorized by priority level, as well as an estimate\n * for the next block's base fee.\n */\nexport default async function fetchGasEstimatesViaEthFeeHistory(\n ethQuery: EthQuery,\n): Promise<GasFeeEstimates> {\n const latestBlock = await fetchLatestBlock(ethQuery);\n const blocks = await fetchBlockFeeHistory({\n ethQuery,\n endBlock: latestBlock.number,\n numberOfBlocks: 5,\n percentiles: [10, 20, 30],\n });\n const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);\n\n const levelSpecificEstimates =\n calculateGasFeeEstimatesForPriorityLevels(blocks);\n\n return {\n ...levelSpecificEstimates,\n estimatedBaseFee,\n historicalBaseFeeRange: null,\n baseFeeTrend: null,\n latestPriorityFeeRange: null,\n historicalPriorityFeeRange: null,\n priorityFeeTrend: null,\n networkCongestion: null,\n };\n}\n"]}
1
+ {"version":3,"file":"fetchGasEstimatesViaEthFeeHistory.js","sourceRoot":"","sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,2CAAqC;AAErC,iEAAkD;AAElD,kFAA0D;AAC1D,4GAAoF;AACpF,8JAAsI;AAEtI;;;;;;;;;;;;;;;;;GAiBG;AACH,SAA8B,iCAAiC,CAC7D,QAAkB;;QAElB,MAAM,WAAW,GAAG,MAAM,IAAA,0BAAgB,EAAC,QAAQ,CAAC,CAAC;QACrD,MAAM,MAAM,GAAG,MAAM,IAAA,8BAAoB,EAAC;YACxC,QAAQ;YACR,QAAQ,EAAE,WAAW,CAAC,MAAM;YAC5B,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;SAC1B,CAAC,CAAC;QACH,MAAM,gBAAgB,GAAG,IAAA,oBAAO,EAAC,WAAW,CAAC,aAAa,EAAE,uBAAI,CAAC,CAAC;QAElE,MAAM,sBAAsB,GAC1B,IAAA,mDAAyC,EAAC,MAAM,CAAC,CAAC;QAEpD,uCACK,sBAAsB,KACzB,gBAAgB,EAChB,sBAAsB,EAAE,IAAI,EAC5B,YAAY,EAAE,IAAI,EAClB,sBAAsB,EAAE,IAAI,EAC5B,0BAA0B,EAAE,IAAI,EAChC,gBAAgB,EAAE,IAAI,EACtB,iBAAiB,EAAE,IAAI,IACvB;IACJ,CAAC;CAAA;AAzBD,oDAyBC","sourcesContent":["import { fromWei } from 'ethjs-unit';\nimport type EthQuery from 'eth-query';\nimport { GWEI } from '@metamask/controller-utils';\nimport { GasFeeEstimates } from './GasFeeController';\nimport fetchBlockFeeHistory from './fetchBlockFeeHistory';\nimport fetchLatestBlock from './fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock';\nimport calculateGasFeeEstimatesForPriorityLevels from './fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels';\n\n/**\n * Generates gas fee estimates based on gas fees that have been used in the recent past so that\n * those estimates can be displayed to users.\n *\n * To produce the estimates, the last 5 blocks are read from the network, and for each block, the\n * priority fees for transactions at the 10th, 20th, and 30th percentiles are also read (here\n * \"percentile\" signifies the level at which those transactions contribute to the overall gas used\n * for the block, where higher percentiles correspond to higher fees). This information is used to\n * calculate reasonable max priority and max fees for three different priority levels (higher\n * priority = higher fee).\n *\n * Note that properties are returned for other data that are normally obtained via the API; however,\n * to prevent extra requests to Infura, these properties are empty.\n *\n * @param ethQuery - An EthQuery instance.\n * @returns Base and priority fee estimates, categorized by priority level, as well as an estimate\n * for the next block's base fee.\n */\nexport default async function fetchGasEstimatesViaEthFeeHistory(\n ethQuery: EthQuery,\n): Promise<GasFeeEstimates> {\n const latestBlock = await fetchLatestBlock(ethQuery);\n const blocks = await fetchBlockFeeHistory({\n ethQuery,\n endBlock: latestBlock.number,\n numberOfBlocks: 5,\n percentiles: [10, 20, 30],\n });\n const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);\n\n const levelSpecificEstimates =\n calculateGasFeeEstimatesForPriorityLevels(blocks);\n\n return {\n ...levelSpecificEstimates,\n estimatedBaseFee,\n historicalBaseFeeRange: null,\n baseFeeTrend: null,\n latestPriorityFeeRange: null,\n historicalPriorityFeeRange: null,\n priorityFeeTrend: null,\n networkCongestion: null,\n };\n}\n"]}
@@ -39,3 +39,4 @@ export declare function fetchEthGasPriceEstimate(ethQuery: any): Promise<EthGasP
39
39
  * @returns The estimated lower and upper bounds for when this transaction will be confirmed.
40
40
  */
41
41
  export declare function calculateTimeEstimate(maxPriorityFeePerGas: string, maxFeePerGas: string, gasFeeEstimates: GasFeeEstimates): EstimatedGasFeeTimeBounds;
42
+ //# sourceMappingURL=gas-util.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas-util.d.ts","sourceRoot":"","sources":["../src/gas-util.ts"],"names":[],"mappings":"AAOA,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,yBAAyB,EAEzB,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAI5B;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,OAI7D;AAED;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,eAAe,CAAC,CAyC1B;AAED;;;;;;;GAOG;AACH,wBAAsB,4BAA4B,CAChD,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,sBAAsB,CAAC,CAgBjC;AAED;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,QAAQ,EAAE,GAAG,GACZ,OAAO,CAAC,mBAAmB,CAAC,CAK9B;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,eAAe,GAC/B,yBAAyB,CAoD3B"}
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './GasFeeController';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/gas-fee-controller",
3
- "version": "4.0.1",
3
+ "version": "6.0.0",
4
4
  "description": "Periodically calculates gas fee estimates based on various gas limits as well as other data displayed on transaction confirm screens",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -29,9 +29,10 @@
29
29
  "test:watch": "jest --watch"
30
30
  },
31
31
  "dependencies": {
32
- "@metamask/base-controller": "^2.0.0",
33
- "@metamask/controller-utils": "^3.1.0",
34
- "@metamask/network-controller": "^6.0.0",
32
+ "@metamask/base-controller": "^3.0.0",
33
+ "@metamask/controller-utils": "^4.0.0",
34
+ "@metamask/network-controller": "^9.0.0",
35
+ "@metamask/utils": "^5.0.2",
35
36
  "@types/uuid": "^8.3.0",
36
37
  "babel-runtime": "^6.26.0",
37
38
  "eth-query": "^2.1.2",
@@ -42,23 +43,23 @@
42
43
  },
43
44
  "devDependencies": {
44
45
  "@metamask/auto-changelog": "^3.1.0",
45
- "@types/jest": "^26.0.22",
46
+ "@types/jest": "^27.4.1",
46
47
  "@types/jest-when": "^2.7.3",
47
48
  "deepmerge": "^4.2.2",
48
- "jest": "^26.4.2",
49
+ "jest": "^27.5.1",
49
50
  "jest-when": "^3.4.2",
50
51
  "nock": "^13.0.7",
51
52
  "sinon": "^9.2.4",
52
- "ts-jest": "^26.5.2",
53
+ "ts-jest": "^27.1.4",
53
54
  "typedoc": "^0.22.15",
54
55
  "typedoc-plugin-missing-exports": "^0.22.6",
55
56
  "typescript": "~4.6.3"
56
57
  },
57
58
  "peerDependencies": {
58
- "@metamask/network-controller": "^6.0.0"
59
+ "@metamask/network-controller": "^9.0.0"
59
60
  },
60
61
  "engines": {
61
- "node": ">=14.0.0"
62
+ "node": ">=16.0.0"
62
63
  },
63
64
  "publishConfig": {
64
65
  "access": "public",