@metamask-previews/gas-fee-controller 20.0.0-preview-9edcf0e0 → 20.0.0-preview-9d310688

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 (55) hide show
  1. package/dist/GasFeeController.cjs +298 -0
  2. package/dist/GasFeeController.cjs.map +1 -0
  3. package/dist/{types/GasFeeController.d.ts → GasFeeController.d.cts} +5 -5
  4. package/dist/GasFeeController.d.cts.map +1 -0
  5. package/dist/GasFeeController.d.mts +244 -0
  6. package/dist/GasFeeController.d.mts.map +1 -0
  7. package/dist/GasFeeController.mjs +296 -12
  8. package/dist/GasFeeController.mjs.map +1 -1
  9. package/dist/determineGasFeeCalculations.cjs +105 -0
  10. package/dist/determineGasFeeCalculations.cjs.map +1 -0
  11. package/dist/{types/determineGasFeeCalculations.d.ts → determineGasFeeCalculations.d.cts} +2 -2
  12. package/dist/determineGasFeeCalculations.d.cts.map +1 -0
  13. package/dist/determineGasFeeCalculations.d.mts +42 -0
  14. package/dist/determineGasFeeCalculations.d.mts.map +1 -0
  15. package/dist/determineGasFeeCalculations.mjs +101 -7
  16. package/dist/determineGasFeeCalculations.mjs.map +1 -1
  17. package/dist/gas-util.cjs +143 -0
  18. package/dist/gas-util.cjs.map +1 -0
  19. package/dist/{types/gas-util.d.ts → gas-util.d.cts} +3 -3
  20. package/dist/gas-util.d.cts.map +1 -0
  21. package/dist/gas-util.d.mts +43 -0
  22. package/dist/gas-util.d.mts.map +1 -0
  23. package/dist/gas-util.mjs +138 -14
  24. package/dist/gas-util.mjs.map +1 -1
  25. package/dist/index.cjs +18 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.cts +2 -0
  28. package/dist/index.d.cts.map +1 -0
  29. package/dist/index.d.mts +2 -0
  30. package/dist/index.d.mts.map +1 -0
  31. package/dist/index.mjs +1 -11
  32. package/dist/index.mjs.map +1 -1
  33. package/package.json +12 -7
  34. package/dist/GasFeeController.js +0 -14
  35. package/dist/GasFeeController.js.map +0 -1
  36. package/dist/chunk-2MFVV2BX.js +0 -156
  37. package/dist/chunk-2MFVV2BX.js.map +0 -1
  38. package/dist/chunk-R3IOI7AK.mjs +0 -156
  39. package/dist/chunk-R3IOI7AK.mjs.map +0 -1
  40. package/dist/chunk-S5H5NUEH.js +0 -401
  41. package/dist/chunk-S5H5NUEH.js.map +0 -1
  42. package/dist/chunk-WXXOCPNT.mjs +0 -401
  43. package/dist/chunk-WXXOCPNT.mjs.map +0 -1
  44. package/dist/determineGasFeeCalculations.js +0 -8
  45. package/dist/determineGasFeeCalculations.js.map +0 -1
  46. package/dist/gas-util.js +0 -15
  47. package/dist/gas-util.js.map +0 -1
  48. package/dist/index.js +0 -12
  49. package/dist/index.js.map +0 -1
  50. package/dist/tsconfig.build.tsbuildinfo +0 -1
  51. package/dist/types/GasFeeController.d.ts.map +0 -1
  52. package/dist/types/determineGasFeeCalculations.d.ts.map +0 -1
  53. package/dist/types/gas-util.d.ts.map +0 -1
  54. package/dist/types/index.d.ts +0 -2
  55. package/dist/types/index.d.ts.map +0 -1
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ 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");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ 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");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ var _GasFeeController_instances, _GasFeeController_getProvider, _GasFeeController_onNetworkControllerDidChange;
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.GasFeeController = exports.GAS_ESTIMATE_TYPES = exports.LEGACY_GAS_PRICES_API_URL = void 0;
19
+ const controller_utils_1 = require("@metamask/controller-utils");
20
+ const eth_query_1 = __importDefault(require("@metamask/eth-query"));
21
+ const polling_controller_1 = require("@metamask/polling-controller");
22
+ const uuid_1 = require("uuid");
23
+ const determineGasFeeCalculations_1 = __importDefault(require("./determineGasFeeCalculations.cjs"));
24
+ const gas_util_1 = require("./gas-util.cjs");
25
+ exports.LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;
26
+ /**
27
+ * Indicates which type of gasEstimate the controller is currently returning.
28
+ * This is useful as a way of asserting that the shape of gasEstimates matches
29
+ * expectations. NONE is a special case indicating that no previous gasEstimate
30
+ * has been fetched.
31
+ */
32
+ exports.GAS_ESTIMATE_TYPES = {
33
+ FEE_MARKET: 'fee-market',
34
+ LEGACY: 'legacy',
35
+ ETH_GASPRICE: 'eth_gasPrice',
36
+ NONE: 'none',
37
+ };
38
+ const metadata = {
39
+ gasFeeEstimatesByChainId: {
40
+ persist: true,
41
+ anonymous: false,
42
+ },
43
+ gasFeeEstimates: { persist: true, anonymous: false },
44
+ estimatedGasFeeTimeBounds: { persist: true, anonymous: false },
45
+ gasEstimateType: { persist: true, anonymous: false },
46
+ nonRPCGasFeeApisDisabled: { persist: true, anonymous: false },
47
+ };
48
+ const name = 'GasFeeController';
49
+ const defaultState = {
50
+ gasFeeEstimatesByChainId: {},
51
+ gasFeeEstimates: {},
52
+ estimatedGasFeeTimeBounds: {},
53
+ gasEstimateType: exports.GAS_ESTIMATE_TYPES.NONE,
54
+ nonRPCGasFeeApisDisabled: false,
55
+ };
56
+ /**
57
+ * Controller that retrieves gas fee estimate data and polls for updated data on a set interval
58
+ */
59
+ class GasFeeController extends polling_controller_1.StaticIntervalPollingController {
60
+ /**
61
+ * Creates a GasFeeController instance.
62
+ *
63
+ * @param options - The controller options.
64
+ * @param options.interval - The time in milliseconds to wait between polls.
65
+ * @param options.messenger - The controller messenger.
66
+ * @param options.state - The initial state.
67
+ * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current
68
+ * network is EIP-1559 compatible.
69
+ * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the
70
+ * current network is compatible with the legacy gas price API.
71
+ * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current
72
+ * account is EIP-1559 compatible.
73
+ * @param options.getChainId - Returns the current chain ID.
74
+ * @param options.getProvider - Returns a network provider for the current network.
75
+ * @param options.onNetworkDidChange - A function for registering an event handler for the
76
+ * network state change event.
77
+ * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for
78
+ * testing purposes.
79
+ * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.
80
+ * @param options.clientId - The client ID used to identify to the gas estimation API who is
81
+ * asking for estimates.
82
+ */
83
+ constructor({ interval = 15000, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider, onNetworkDidChange, legacyAPIEndpoint = exports.LEGACY_GAS_PRICES_API_URL, EIP1559APIEndpoint, clientId, }) {
84
+ super({
85
+ name,
86
+ metadata,
87
+ messenger,
88
+ state: { ...defaultState, ...state },
89
+ });
90
+ _GasFeeController_instances.add(this);
91
+ _GasFeeController_getProvider.set(this, void 0);
92
+ this.intervalDelay = interval;
93
+ this.setIntervalLength(interval);
94
+ this.pollTokens = new Set();
95
+ this.getCurrentNetworkEIP1559Compatibility =
96
+ getCurrentNetworkEIP1559Compatibility;
97
+ this.getCurrentNetworkLegacyGasAPICompatibility =
98
+ getCurrentNetworkLegacyGasAPICompatibility;
99
+ this.getCurrentAccountEIP1559Compatibility =
100
+ getCurrentAccountEIP1559Compatibility;
101
+ __classPrivateFieldSet(this, _GasFeeController_getProvider, getProvider, "f");
102
+ this.EIP1559APIEndpoint = EIP1559APIEndpoint;
103
+ this.legacyAPIEndpoint = legacyAPIEndpoint;
104
+ this.clientId = clientId;
105
+ this.ethQuery = new eth_query_1.default(__classPrivateFieldGet(this, _GasFeeController_getProvider, "f").call(this));
106
+ if (onNetworkDidChange && getChainId) {
107
+ this.currentChainId = getChainId();
108
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
109
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
110
+ onNetworkDidChange(async (networkControllerState) => {
111
+ await __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerDidChange).call(this, networkControllerState);
112
+ });
113
+ }
114
+ else {
115
+ const { selectedNetworkClientId } = this.messagingSystem.call('NetworkController:getState');
116
+ this.currentChainId = this.messagingSystem.call('NetworkController:getNetworkClientById', selectedNetworkClientId).configuration.chainId;
117
+ this.messagingSystem.subscribe('NetworkController:networkDidChange',
118
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
119
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
120
+ async (networkControllerState) => {
121
+ await __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerDidChange).call(this, networkControllerState);
122
+ });
123
+ }
124
+ }
125
+ async resetPolling() {
126
+ if (this.pollTokens.size !== 0) {
127
+ const tokens = Array.from(this.pollTokens);
128
+ this.stopPolling();
129
+ await this.getGasFeeEstimatesAndStartPolling(tokens[0]);
130
+ tokens.slice(1).forEach((token) => {
131
+ this.pollTokens.add(token);
132
+ });
133
+ }
134
+ }
135
+ async fetchGasFeeEstimates(options) {
136
+ return await this._fetchGasFeeEstimateData(options);
137
+ }
138
+ async getGasFeeEstimatesAndStartPolling(pollToken) {
139
+ const _pollToken = pollToken || (0, uuid_1.v1)();
140
+ this.pollTokens.add(_pollToken);
141
+ if (this.pollTokens.size === 1) {
142
+ await this._fetchGasFeeEstimateData();
143
+ this._poll();
144
+ }
145
+ return _pollToken;
146
+ }
147
+ /**
148
+ * Gets and sets gasFeeEstimates in state.
149
+ *
150
+ * @param options - The gas fee estimate options.
151
+ * @param options.shouldUpdateState - Determines whether the state should be updated with the
152
+ * updated gas estimates.
153
+ * @returns The gas fee estimates.
154
+ */
155
+ async _fetchGasFeeEstimateData(options = {}) {
156
+ const { shouldUpdateState = true, networkClientId } = options;
157
+ let ethQuery, isEIP1559Compatible, isLegacyGasAPICompatible, decimalChainId;
158
+ if (networkClientId !== undefined) {
159
+ const networkClient = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
160
+ isLegacyGasAPICompatible = networkClient.configuration.chainId === '0x38';
161
+ decimalChainId = (0, controller_utils_1.convertHexToDecimal)(networkClient.configuration.chainId);
162
+ try {
163
+ const result = await this.messagingSystem.call('NetworkController:getEIP1559Compatibility', networkClientId);
164
+ isEIP1559Compatible = result || false;
165
+ }
166
+ catch {
167
+ isEIP1559Compatible = false;
168
+ }
169
+ ethQuery = new eth_query_1.default(networkClient.provider);
170
+ }
171
+ ethQuery ?? (ethQuery = this.ethQuery);
172
+ isLegacyGasAPICompatible ?? (isLegacyGasAPICompatible = this.getCurrentNetworkLegacyGasAPICompatibility());
173
+ decimalChainId ?? (decimalChainId = (0, controller_utils_1.convertHexToDecimal)(this.currentChainId));
174
+ try {
175
+ isEIP1559Compatible ?? (isEIP1559Compatible = await this.getEIP1559Compatibility());
176
+ }
177
+ catch (e) {
178
+ console.error(e);
179
+ isEIP1559Compatible ?? (isEIP1559Compatible = false);
180
+ }
181
+ const gasFeeCalculations = await (0, determineGasFeeCalculations_1.default)({
182
+ isEIP1559Compatible,
183
+ isLegacyGasAPICompatible,
184
+ fetchGasEstimates: gas_util_1.fetchGasEstimates,
185
+ fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace('<chain_id>', `${decimalChainId}`),
186
+ fetchLegacyGasPriceEstimates: gas_util_1.fetchLegacyGasPriceEstimates,
187
+ fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace('<chain_id>', `${decimalChainId}`),
188
+ fetchEthGasPriceEstimate: gas_util_1.fetchEthGasPriceEstimate,
189
+ calculateTimeEstimate: gas_util_1.calculateTimeEstimate,
190
+ clientId: this.clientId,
191
+ ethQuery,
192
+ nonRPCGasFeeApisDisabled: this.state.nonRPCGasFeeApisDisabled,
193
+ });
194
+ if (shouldUpdateState) {
195
+ const chainId = (0, controller_utils_1.toHex)(decimalChainId);
196
+ this.update((state) => {
197
+ if (this.currentChainId === chainId) {
198
+ state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;
199
+ state.estimatedGasFeeTimeBounds =
200
+ gasFeeCalculations.estimatedGasFeeTimeBounds;
201
+ state.gasEstimateType = gasFeeCalculations.gasEstimateType;
202
+ }
203
+ state.gasFeeEstimatesByChainId ?? (state.gasFeeEstimatesByChainId = {});
204
+ state.gasFeeEstimatesByChainId[chainId] = {
205
+ gasFeeEstimates: gasFeeCalculations.gasFeeEstimates,
206
+ estimatedGasFeeTimeBounds: gasFeeCalculations.estimatedGasFeeTimeBounds,
207
+ gasEstimateType: gasFeeCalculations.gasEstimateType,
208
+ };
209
+ });
210
+ }
211
+ return gasFeeCalculations;
212
+ }
213
+ /**
214
+ * Remove the poll token, and stop polling if the set of poll tokens is empty.
215
+ *
216
+ * @param pollToken - The poll token to disconnect.
217
+ */
218
+ disconnectPoller(pollToken) {
219
+ this.pollTokens.delete(pollToken);
220
+ if (this.pollTokens.size === 0) {
221
+ this.stopPolling();
222
+ }
223
+ }
224
+ stopPolling() {
225
+ if (this.intervalId) {
226
+ clearInterval(this.intervalId);
227
+ }
228
+ this.pollTokens.clear();
229
+ this.resetState();
230
+ }
231
+ /**
232
+ * Prepare to discard this controller.
233
+ *
234
+ * This stops any active polling.
235
+ */
236
+ destroy() {
237
+ super.destroy();
238
+ this.stopPolling();
239
+ }
240
+ _poll() {
241
+ if (this.intervalId) {
242
+ clearInterval(this.intervalId);
243
+ }
244
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
245
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
246
+ this.intervalId = setInterval(async () => {
247
+ await (0, controller_utils_1.safelyExecute)(() => this._fetchGasFeeEstimateData());
248
+ }, this.intervalDelay);
249
+ }
250
+ /**
251
+ * Fetching token list from the Token Service API.
252
+ *
253
+ * @private
254
+ * @param networkClientId - The ID of the network client triggering the fetch.
255
+ * @returns A promise that resolves when this operation completes.
256
+ */
257
+ async _executePoll(networkClientId) {
258
+ await this._fetchGasFeeEstimateData({ networkClientId });
259
+ }
260
+ resetState() {
261
+ this.update(() => {
262
+ return defaultState;
263
+ });
264
+ }
265
+ async getEIP1559Compatibility() {
266
+ const currentNetworkIsEIP1559Compatible = await this.getCurrentNetworkEIP1559Compatibility();
267
+ const currentAccountIsEIP1559Compatible = this.getCurrentAccountEIP1559Compatibility?.() ?? true;
268
+ return (currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible);
269
+ }
270
+ getTimeEstimate(maxPriorityFeePerGas, maxFeePerGas) {
271
+ if (!this.state.gasFeeEstimates ||
272
+ this.state.gasEstimateType !== exports.GAS_ESTIMATE_TYPES.FEE_MARKET) {
273
+ return {};
274
+ }
275
+ return (0, gas_util_1.calculateTimeEstimate)(maxPriorityFeePerGas, maxFeePerGas, this.state.gasFeeEstimates);
276
+ }
277
+ enableNonRPCGasFeeApis() {
278
+ this.update((state) => {
279
+ state.nonRPCGasFeeApisDisabled = false;
280
+ });
281
+ }
282
+ disableNonRPCGasFeeApis() {
283
+ this.update((state) => {
284
+ state.nonRPCGasFeeApisDisabled = true;
285
+ });
286
+ }
287
+ }
288
+ exports.GasFeeController = GasFeeController;
289
+ _GasFeeController_getProvider = new WeakMap(), _GasFeeController_instances = new WeakSet(), _GasFeeController_onNetworkControllerDidChange = async function _GasFeeController_onNetworkControllerDidChange({ selectedNetworkClientId, }) {
290
+ const newChainId = this.messagingSystem.call('NetworkController:getNetworkClientById', selectedNetworkClientId).configuration.chainId;
291
+ if (newChainId !== this.currentChainId) {
292
+ this.ethQuery = new eth_query_1.default(__classPrivateFieldGet(this, _GasFeeController_getProvider, "f").call(this));
293
+ await this.resetPolling();
294
+ this.currentChainId = newChainId;
295
+ }
296
+ };
297
+ exports.default = GasFeeController;
298
+ //# sourceMappingURL=GasFeeController.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GasFeeController.cjs","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA,iEAIoC;AACpC,oEAA2C;AAU3C,qEAA+E;AAE/E,+BAAoC;AAEpC,oGAAwE;AACxE,6CAKoB;AAEP,QAAA,yBAAyB,GAAG,+CAA+C,CAAC;AAsBzF;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG;IAChC,UAAU,EAAE,YAAqC;IACjD,MAAM,EAAE,QAA8B;IACtC,YAAY,EAAE,cAAyC;IACvD,IAAI,EAAE,MAAwB;CAC/B,CAAC;AAiGF,MAAM,QAAQ,GAAG;IACf,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IACpD,yBAAyB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IAC9D,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IACpD,wBAAwB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CAC9D,CAAC;AAqDF,MAAM,IAAI,GAAG,kBAAkB,CAAC;AA0BhC,MAAM,YAAY,GAAgB;IAChC,wBAAwB,EAAE,EAAE;IAC5B,eAAe,EAAE,EAAE;IACnB,yBAAyB,EAAE,EAAE;IAC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BAAQ,CAAC,uBAAA,IAAI,qCAAa,MAAjB,IAAI,CAAe,CAAC,CAAC;QAClD,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QAE1B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC;KAClC;AACH,CAAC;AAeH,kBAAe,gBAAgB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n convertHexToDecimal,\n safelyExecute,\n toHex,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkControllerGetEIP1559CompatibilityAction,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n NetworkState,\n ProviderProxy,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { v1 as random } from 'uuid';\n\nimport determineGasFeeCalculations from './determineGasFeeCalculations';\nimport {\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n} from './gas-util';\n\nexport const LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;\n\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 gasFeeEstimatesByChainId: {\n persist: true,\n anonymous: false,\n },\n gasFeeEstimates: { persist: true, anonymous: false },\n estimatedGasFeeTimeBounds: { persist: true, anonymous: false },\n gasEstimateType: { persist: true, anonymous: false },\n nonRPCGasFeeApisDisabled: { 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 networkClientId?: NetworkClientId;\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 SingleChainGasFeeState =\n | GasFeeStateEthGasPrice\n | GasFeeStateFeeMarket\n | GasFeeStateLegacy\n | GasFeeStateNoEstimates;\n\nexport type GasFeeEstimatesByChainId = {\n gasFeeEstimatesByChainId?: Record<string, SingleChainGasFeeState>;\n};\n\nexport type GasFeeState = GasFeeEstimatesByChainId &\n SingleChainGasFeeState & {\n nonRPCGasFeeApisDisabled?: boolean;\n };\n\nconst name = 'GasFeeController';\n\nexport type GasFeeStateChange = ControllerStateChangeEvent<\n typeof name,\n GasFeeState\n>;\n\nexport type GetGasFeeState = ControllerGetStateAction<typeof name, GasFeeState>;\n\nexport type GasFeeControllerActions = GetGasFeeState;\n\nexport type GasFeeControllerEvents = GasFeeStateChange;\n\ntype AllowedActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetEIP1559CompatibilityAction;\n\ntype GasFeeMessenger = RestrictedControllerMessenger<\n typeof name,\n GasFeeControllerActions | AllowedActions,\n GasFeeControllerEvents | NetworkControllerNetworkDidChangeEvent,\n AllowedActions['type'],\n NetworkControllerNetworkDidChangeEvent['type']\n>;\n\nconst defaultState: GasFeeState = {\n gasFeeEstimatesByChainId: {},\n gasFeeEstimates: {},\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.NONE,\n nonRPCGasFeeApisDisabled: false,\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 StaticIntervalPollingController<\n typeof name,\n GasFeeState,\n GasFeeMessenger\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay;\n\n private readonly pollTokens: Set<string>;\n\n private readonly legacyAPIEndpoint: string;\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private readonly EIP1559APIEndpoint: string;\n\n private readonly getCurrentNetworkEIP1559Compatibility;\n\n private readonly getCurrentNetworkLegacyGasAPICompatibility;\n\n private readonly getCurrentAccountEIP1559Compatibility;\n\n private currentChainId;\n\n private ethQuery?: EthQuery;\n\n private readonly 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.onNetworkDidChange - 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 onNetworkDidChange,\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 onNetworkDidChange?: (listener: (state: NetworkState) => void) => void;\n legacyAPIEndpoint?: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\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.setIntervalLength(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 (onNetworkDidChange && getChainId) {\n this.currentChainId = getChainId();\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onNetworkDidChange(async (networkControllerState) => {\n await this.#onNetworkControllerDidChange(networkControllerState);\n });\n } else {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n this.currentChainId = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n ).configuration.chainId;\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (networkControllerState) => {\n await this.#onNetworkControllerDidChange(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, networkClientId } = options;\n\n let ethQuery,\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n decimalChainId: number;\n\n if (networkClientId !== undefined) {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n isLegacyGasAPICompatible = networkClient.configuration.chainId === '0x38';\n\n decimalChainId = convertHexToDecimal(networkClient.configuration.chainId);\n\n try {\n const result = await this.messagingSystem.call(\n 'NetworkController:getEIP1559Compatibility',\n networkClientId,\n );\n isEIP1559Compatible = result || false;\n } catch {\n isEIP1559Compatible = false;\n }\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n ethQuery ??= this.ethQuery;\n\n isLegacyGasAPICompatible ??=\n this.getCurrentNetworkLegacyGasAPICompatibility();\n\n 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 fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery,\n nonRPCGasFeeApisDisabled: this.state.nonRPCGasFeeApisDisabled,\n });\n\n if (shouldUpdateState) {\n const chainId = toHex(decimalChainId);\n this.update((state) => {\n if (this.currentChainId === chainId) {\n state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;\n state.estimatedGasFeeTimeBounds =\n gasFeeCalculations.estimatedGasFeeTimeBounds;\n state.gasEstimateType = gasFeeCalculations.gasEstimateType;\n }\n state.gasFeeEstimatesByChainId ??= {};\n state.gasFeeEstimatesByChainId[chainId] = {\n gasFeeEstimates: gasFeeCalculations.gasFeeEstimates,\n estimatedGasFeeTimeBounds:\n gasFeeCalculations.estimatedGasFeeTimeBounds,\n gasEstimateType: gasFeeCalculations.gasEstimateType,\n } as SingleChainGasFeeState;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this._fetchGasFeeEstimateData());\n }, this.intervalDelay);\n }\n\n /**\n * Fetching token list from the Token Service API.\n *\n * @private\n * @param networkClientId - The ID of the network client triggering the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n await this._fetchGasFeeEstimateData({ networkClientId });\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 #onNetworkControllerDidChange({\n selectedNetworkClientId,\n }: NetworkState) {\n const newChainId = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n ).configuration.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 enableNonRPCGasFeeApis() {\n this.update((state) => {\n state.nonRPCGasFeeApisDisabled = false;\n });\n }\n\n disableNonRPCGasFeeApis() {\n this.update((state) => {\n state.nonRPCGasFeeApisDisabled = true;\n });\n }\n}\n\nexport default GasFeeController;\n"]}
@@ -1,7 +1,7 @@
1
- import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
2
- import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerNetworkDidChangeEvent, NetworkState, ProviderProxy } from '@metamask/network-controller';
3
- import { StaticIntervalPollingController } from '@metamask/polling-controller';
4
- import type { Hex } from '@metamask/utils';
1
+ import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from "@metamask/base-controller";
2
+ import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerNetworkDidChangeEvent, NetworkState, ProviderProxy } from "@metamask/network-controller";
3
+ import { StaticIntervalPollingController } from "@metamask/polling-controller";
4
+ import type { Hex } from "@metamask/utils";
5
5
  export declare const LEGACY_GAS_PRICES_API_URL = "https://api.metaswap.codefi.network/gasPrices";
6
6
  export type unknownString = 'unknown';
7
7
  export type FeeMarketEstimateType = 'fee-market';
@@ -241,4 +241,4 @@ export declare class GasFeeController extends StaticIntervalPollingController<ty
241
241
  disableNonRPCGasFeeApis(): void;
242
242
  }
243
243
  export default GasFeeController;
244
- //# sourceMappingURL=GasFeeController.d.ts.map
244
+ //# sourceMappingURL=GasFeeController.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GasFeeController.d.cts","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAC9B,kCAAkC;AAOnC,OAAO,KAAK,EACV,eAAe,EACf,8CAA8C,EAC9C,2CAA2C,EAC3C,+BAA+B,EAC/B,sCAAsC,EACtC,YAAY,EACZ,aAAa,EACd,qCAAqC;AACtC,OAAO,EAAE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AAiB,CAAC,EAAE,MAAM,CAAC;QAE3B,kBAAkB,EAAE,MAAM,CAAC;QAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB;IAiDK,YAAY;IAWZ,oBAAoB,CAAC,OAAO,CAAC,EAAE,0BAA0B;IAIzD,iCAAiC,CACrC,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,OAAO,CAAC,MAAM,CAAC;IAalB;;;;;;;OAOG;IACG,wBAAwB,CAC5B,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,WAAW,CAAC;IAqFvB;;;;OAIG;IACH,gBAAgB,CAAC,SAAS,EAAE,MAAM;IAOlC,WAAW;IAQX;;;;OAIG;IACM,OAAO;IAKhB,OAAO,CAAC,KAAK;IAYb;;;;;;OAMG;IACG,YAAY,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1D,OAAO,CAAC,UAAU;YAMJ,uBAAuB;IAWrC,eAAe,CACb,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,GACnB,yBAAyB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC;IA8BpD,sBAAsB;IAMtB,uBAAuB;CAKxB;AAED,eAAe,gBAAgB,CAAC"}
@@ -0,0 +1,244 @@
1
+ import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from "@metamask/base-controller";
2
+ import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerNetworkDidChangeEvent, NetworkState, ProviderProxy } from "@metamask/network-controller";
3
+ import { StaticIntervalPollingController } from "@metamask/polling-controller";
4
+ import type { Hex } from "@metamask/utils";
5
+ export declare const LEGACY_GAS_PRICES_API_URL = "https://api.metaswap.codefi.network/gasPrices";
6
+ export type unknownString = 'unknown';
7
+ export type FeeMarketEstimateType = 'fee-market';
8
+ export type LegacyEstimateType = 'legacy';
9
+ export type EthGasPriceEstimateType = 'eth_gasPrice';
10
+ export type NoEstimateType = 'none';
11
+ /**
12
+ * Indicates which type of gasEstimate the controller is currently returning.
13
+ * This is useful as a way of asserting that the shape of gasEstimates matches
14
+ * expectations. NONE is a special case indicating that no previous gasEstimate
15
+ * has been fetched.
16
+ */
17
+ export declare const GAS_ESTIMATE_TYPES: {
18
+ FEE_MARKET: "fee-market";
19
+ LEGACY: "legacy";
20
+ ETH_GASPRICE: "eth_gasPrice";
21
+ NONE: "none";
22
+ };
23
+ export type GasEstimateType = FeeMarketEstimateType | EthGasPriceEstimateType | LegacyEstimateType | NoEstimateType;
24
+ export type EstimatedGasFeeTimeBounds = {
25
+ lowerTimeBound: number | null;
26
+ upperTimeBound: number | unknownString;
27
+ };
28
+ /**
29
+ * @type EthGasPriceEstimate
30
+ *
31
+ * A single gas price estimate for networks and accounts that don't support EIP-1559
32
+ * This estimate comes from eth_gasPrice but is converted to dec gwei to match other
33
+ * return values
34
+ * @property gasPrice - A GWEI dec string
35
+ */
36
+ export type EthGasPriceEstimate = {
37
+ gasPrice: string;
38
+ };
39
+ /**
40
+ * @type LegacyGasPriceEstimate
41
+ *
42
+ * A set of gas price estimates for networks and accounts that don't support EIP-1559
43
+ * These estimates include low, medium and high all as strings representing gwei in
44
+ * decimal format.
45
+ * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion
46
+ * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion
47
+ * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion
48
+ */
49
+ export type LegacyGasPriceEstimate = {
50
+ high: string;
51
+ medium: string;
52
+ low: string;
53
+ };
54
+ /**
55
+ * @type Eip1559GasFee
56
+ *
57
+ * Data necessary to provide an estimate of a gas fee with a specific tip
58
+ * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds
59
+ * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds
60
+ * @property suggestedMaxPriorityFeePerGas - A suggested "tip", a GWEI hex number
61
+ * @property suggestedMaxFeePerGas - A suggested max fee, the most a user will pay. a GWEI hex number
62
+ */
63
+ export type Eip1559GasFee = {
64
+ minWaitTimeEstimate: number;
65
+ maxWaitTimeEstimate: number;
66
+ suggestedMaxPriorityFeePerGas: string;
67
+ suggestedMaxFeePerGas: string;
68
+ };
69
+ /**
70
+ * @type GasFeeEstimates
71
+ *
72
+ * Data necessary to provide multiple GasFee estimates, and supporting information, to the user
73
+ * @property low - A GasFee for a minimum necessary combination of tip and maxFee
74
+ * @property medium - A GasFee for a recommended combination of tip and maxFee
75
+ * @property high - A GasFee for a high combination of tip and maxFee
76
+ * @property estimatedBaseFee - An estimate of what the base fee will be for the pending/next block. A GWEI dec number
77
+ * @property networkCongestion - A normalized number that can be used to gauge the congestion
78
+ * level of the network, with 0 meaning not congested and 1 meaning extremely congested
79
+ */
80
+ export type GasFeeEstimates = SourcedGasFeeEstimates | FallbackGasFeeEstimates;
81
+ type SourcedGasFeeEstimates = {
82
+ low: Eip1559GasFee;
83
+ medium: Eip1559GasFee;
84
+ high: Eip1559GasFee;
85
+ estimatedBaseFee: string;
86
+ historicalBaseFeeRange: [string, string];
87
+ baseFeeTrend: 'up' | 'down' | 'level';
88
+ latestPriorityFeeRange: [string, string];
89
+ historicalPriorityFeeRange: [string, string];
90
+ priorityFeeTrend: 'up' | 'down' | 'level';
91
+ networkCongestion: number;
92
+ };
93
+ type FallbackGasFeeEstimates = {
94
+ low: Eip1559GasFee;
95
+ medium: Eip1559GasFee;
96
+ high: Eip1559GasFee;
97
+ estimatedBaseFee: string;
98
+ historicalBaseFeeRange: null;
99
+ baseFeeTrend: null;
100
+ latestPriorityFeeRange: null;
101
+ historicalPriorityFeeRange: null;
102
+ priorityFeeTrend: null;
103
+ networkCongestion: null;
104
+ };
105
+ export type GasFeeStateEthGasPrice = {
106
+ gasFeeEstimates: EthGasPriceEstimate;
107
+ estimatedGasFeeTimeBounds: Record<string, never>;
108
+ gasEstimateType: EthGasPriceEstimateType;
109
+ };
110
+ export type GasFeeStateFeeMarket = {
111
+ gasFeeEstimates: GasFeeEstimates;
112
+ estimatedGasFeeTimeBounds: EstimatedGasFeeTimeBounds | Record<string, never>;
113
+ gasEstimateType: FeeMarketEstimateType;
114
+ };
115
+ export type GasFeeStateLegacy = {
116
+ gasFeeEstimates: LegacyGasPriceEstimate;
117
+ estimatedGasFeeTimeBounds: Record<string, never>;
118
+ gasEstimateType: LegacyEstimateType;
119
+ };
120
+ export type GasFeeStateNoEstimates = {
121
+ gasFeeEstimates: Record<string, never>;
122
+ estimatedGasFeeTimeBounds: Record<string, never>;
123
+ gasEstimateType: NoEstimateType;
124
+ };
125
+ export type FetchGasFeeEstimateOptions = {
126
+ shouldUpdateState?: boolean;
127
+ networkClientId?: NetworkClientId;
128
+ };
129
+ /**
130
+ * @type GasFeeState
131
+ *
132
+ * Gas Fee controller state
133
+ * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties
134
+ * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum
135
+ */
136
+ export type SingleChainGasFeeState = GasFeeStateEthGasPrice | GasFeeStateFeeMarket | GasFeeStateLegacy | GasFeeStateNoEstimates;
137
+ export type GasFeeEstimatesByChainId = {
138
+ gasFeeEstimatesByChainId?: Record<string, SingleChainGasFeeState>;
139
+ };
140
+ export type GasFeeState = GasFeeEstimatesByChainId & SingleChainGasFeeState & {
141
+ nonRPCGasFeeApisDisabled?: boolean;
142
+ };
143
+ declare const name = "GasFeeController";
144
+ export type GasFeeStateChange = ControllerStateChangeEvent<typeof name, GasFeeState>;
145
+ export type GetGasFeeState = ControllerGetStateAction<typeof name, GasFeeState>;
146
+ export type GasFeeControllerActions = GetGasFeeState;
147
+ export type GasFeeControllerEvents = GasFeeStateChange;
148
+ type AllowedActions = NetworkControllerGetStateAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetEIP1559CompatibilityAction;
149
+ type GasFeeMessenger = RestrictedControllerMessenger<typeof name, GasFeeControllerActions | AllowedActions, GasFeeControllerEvents | NetworkControllerNetworkDidChangeEvent, AllowedActions['type'], NetworkControllerNetworkDidChangeEvent['type']>;
150
+ /**
151
+ * Controller that retrieves gas fee estimate data and polls for updated data on a set interval
152
+ */
153
+ export declare class GasFeeController extends StaticIntervalPollingController<typeof name, GasFeeState, GasFeeMessenger> {
154
+ #private;
155
+ private intervalId?;
156
+ private readonly intervalDelay;
157
+ private readonly pollTokens;
158
+ private readonly legacyAPIEndpoint;
159
+ private readonly EIP1559APIEndpoint;
160
+ private readonly getCurrentNetworkEIP1559Compatibility;
161
+ private readonly getCurrentNetworkLegacyGasAPICompatibility;
162
+ private readonly getCurrentAccountEIP1559Compatibility;
163
+ private currentChainId;
164
+ private ethQuery?;
165
+ private readonly clientId?;
166
+ /**
167
+ * Creates a GasFeeController instance.
168
+ *
169
+ * @param options - The controller options.
170
+ * @param options.interval - The time in milliseconds to wait between polls.
171
+ * @param options.messenger - The controller messenger.
172
+ * @param options.state - The initial state.
173
+ * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current
174
+ * network is EIP-1559 compatible.
175
+ * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the
176
+ * current network is compatible with the legacy gas price API.
177
+ * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current
178
+ * account is EIP-1559 compatible.
179
+ * @param options.getChainId - Returns the current chain ID.
180
+ * @param options.getProvider - Returns a network provider for the current network.
181
+ * @param options.onNetworkDidChange - A function for registering an event handler for the
182
+ * network state change event.
183
+ * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for
184
+ * testing purposes.
185
+ * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.
186
+ * @param options.clientId - The client ID used to identify to the gas estimation API who is
187
+ * asking for estimates.
188
+ */
189
+ constructor({ interval, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider, onNetworkDidChange, legacyAPIEndpoint, EIP1559APIEndpoint, clientId, }: {
190
+ interval?: number;
191
+ messenger: GasFeeMessenger;
192
+ state?: GasFeeState;
193
+ getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;
194
+ getCurrentNetworkLegacyGasAPICompatibility: () => boolean;
195
+ getCurrentAccountEIP1559Compatibility?: () => boolean;
196
+ getChainId?: () => Hex;
197
+ getProvider: () => ProviderProxy;
198
+ onNetworkDidChange?: (listener: (state: NetworkState) => void) => void;
199
+ legacyAPIEndpoint?: string;
200
+ EIP1559APIEndpoint: string;
201
+ clientId?: string;
202
+ });
203
+ resetPolling(): Promise<void>;
204
+ fetchGasFeeEstimates(options?: FetchGasFeeEstimateOptions): Promise<GasFeeState>;
205
+ getGasFeeEstimatesAndStartPolling(pollToken: string | undefined): Promise<string>;
206
+ /**
207
+ * Gets and sets gasFeeEstimates in state.
208
+ *
209
+ * @param options - The gas fee estimate options.
210
+ * @param options.shouldUpdateState - Determines whether the state should be updated with the
211
+ * updated gas estimates.
212
+ * @returns The gas fee estimates.
213
+ */
214
+ _fetchGasFeeEstimateData(options?: FetchGasFeeEstimateOptions): Promise<GasFeeState>;
215
+ /**
216
+ * Remove the poll token, and stop polling if the set of poll tokens is empty.
217
+ *
218
+ * @param pollToken - The poll token to disconnect.
219
+ */
220
+ disconnectPoller(pollToken: string): void;
221
+ stopPolling(): void;
222
+ /**
223
+ * Prepare to discard this controller.
224
+ *
225
+ * This stops any active polling.
226
+ */
227
+ destroy(): void;
228
+ private _poll;
229
+ /**
230
+ * Fetching token list from the Token Service API.
231
+ *
232
+ * @private
233
+ * @param networkClientId - The ID of the network client triggering the fetch.
234
+ * @returns A promise that resolves when this operation completes.
235
+ */
236
+ _executePoll(networkClientId: string): Promise<void>;
237
+ private resetState;
238
+ private getEIP1559Compatibility;
239
+ getTimeEstimate(maxPriorityFeePerGas: string, maxFeePerGas: string): EstimatedGasFeeTimeBounds | Record<string, never>;
240
+ enableNonRPCGasFeeApis(): void;
241
+ disableNonRPCGasFeeApis(): void;
242
+ }
243
+ export default GasFeeController;
244
+ //# sourceMappingURL=GasFeeController.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GasFeeController.d.mts","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAC9B,kCAAkC;AAOnC,OAAO,KAAK,EACV,eAAe,EACf,8CAA8C,EAC9C,2CAA2C,EAC3C,+BAA+B,EAC/B,sCAAsC,EACtC,YAAY,EACZ,aAAa,EACd,qCAAqC;AACtC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAW3C,eAAO,MAAM,yBAAyB,kDAAkD,CAAC;AAIzF,MAAM,MAAM,aAAa,GAAG,SAAS,CAAC;AAItC,MAAM,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAIjD,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAK1C,MAAM,MAAM,uBAAuB,GAAG,cAAc,CAAC;AAGrD,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC;AAEpC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB;;;;;CAK9B,CAAC;AAEF,MAAM,MAAM,eAAe,GACvB,qBAAqB,GACrB,uBAAuB,GACvB,kBAAkB,GAClB,cAAc,CAAC;AAEnB,MAAM,MAAM,yBAAyB,GAAG;IACtC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,cAAc,EAAE,MAAM,GAAG,aAAa,CAAC;CACxC,CAAC;AAEF;;;;;;;GAOG;AAEH,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF;;;;;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