@metamask-previews/gas-fee-controller 15.0.0-preview-fb52b9eb → 15.0.0-preview-2036edd1

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 (85) hide show
  1. package/dist/GasFeeController.js +9 -3
  2. package/dist/GasFeeController.mjs +8 -2
  3. package/dist/chunk-5INBFZXY.js +127 -0
  4. package/dist/chunk-5INBFZXY.js.map +1 -0
  5. package/dist/chunk-AQN4AQEF.mjs +127 -0
  6. package/dist/chunk-AQN4AQEF.mjs.map +1 -0
  7. package/dist/chunk-C4I7KKIU.mjs +12 -0
  8. package/dist/chunk-C4I7KKIU.mjs.map +1 -0
  9. package/dist/chunk-EXCWMMNV.mjs +39 -0
  10. package/dist/chunk-EXCWMMNV.mjs.map +1 -0
  11. package/dist/chunk-EZVGDV5H.js +39 -0
  12. package/dist/chunk-EZVGDV5H.js.map +1 -0
  13. package/dist/{chunk-GJSUFSHM.mjs → chunk-G2HAZY5F.mjs} +75 -95
  14. package/dist/chunk-G2HAZY5F.mjs.map +1 -0
  15. package/dist/chunk-GE7RMDFV.js +77 -0
  16. package/dist/chunk-GE7RMDFV.js.map +1 -0
  17. package/dist/chunk-GUWY6WP6.mjs +77 -0
  18. package/dist/chunk-GUWY6WP6.mjs.map +1 -0
  19. package/dist/{chunk-2AQW4RMC.js → chunk-HCUEQ4NY.js} +83 -103
  20. package/dist/chunk-HCUEQ4NY.js.map +1 -0
  21. package/dist/chunk-LO7OP5FM.js +19 -0
  22. package/dist/chunk-LO7OP5FM.js.map +1 -0
  23. package/dist/{chunk-Q2YPK5SL.js → chunk-NARPHUTR.js} +3 -30
  24. package/dist/chunk-NARPHUTR.js.map +1 -0
  25. package/dist/{chunk-KORLXV32.mjs → chunk-QVES4OOM.mjs} +1 -28
  26. package/dist/{chunk-KORLXV32.mjs.map → chunk-QVES4OOM.mjs.map} +1 -1
  27. package/dist/chunk-S2EH2EPS.js +12 -0
  28. package/dist/chunk-S2EH2EPS.js.map +1 -0
  29. package/dist/chunk-SINQOHIN.mjs +19 -0
  30. package/dist/chunk-SINQOHIN.mjs.map +1 -0
  31. package/dist/chunk-XUI43LEZ.mjs +30 -0
  32. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  33. package/dist/chunk-Z4BLTVTB.js +30 -0
  34. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  35. package/dist/determineGasFeeCalculations.js +9 -3
  36. package/dist/determineGasFeeCalculations.mjs +8 -2
  37. package/dist/fetchBlockFeeHistory.js +8 -0
  38. package/dist/fetchBlockFeeHistory.js.map +1 -0
  39. package/dist/fetchBlockFeeHistory.mjs +8 -0
  40. package/dist/fetchBlockFeeHistory.mjs.map +1 -0
  41. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js +9 -0
  42. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map +1 -0
  43. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.mjs +9 -0
  44. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.mjs.map +1 -0
  45. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js +8 -0
  46. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js.map +1 -0
  47. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.mjs +8 -0
  48. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.mjs.map +1 -0
  49. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js +8 -0
  50. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js.map +1 -0
  51. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.mjs +8 -0
  52. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.mjs.map +1 -0
  53. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js +1 -0
  54. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js.map +1 -0
  55. package/dist/fetchGasEstimatesViaEthFeeHistory/types.mjs +1 -0
  56. package/dist/fetchGasEstimatesViaEthFeeHistory/types.mjs.map +1 -0
  57. package/dist/fetchGasEstimatesViaEthFeeHistory.js +12 -0
  58. package/dist/fetchGasEstimatesViaEthFeeHistory.js.map +1 -0
  59. package/dist/fetchGasEstimatesViaEthFeeHistory.mjs +12 -0
  60. package/dist/fetchGasEstimatesViaEthFeeHistory.mjs.map +1 -0
  61. package/dist/gas-util.js +3 -2
  62. package/dist/gas-util.mjs +2 -1
  63. package/dist/index.js +9 -3
  64. package/dist/index.mjs +8 -2
  65. package/dist/tsconfig.build.tsbuildinfo +1 -1
  66. package/dist/types/GasFeeController.d.ts +1 -5
  67. package/dist/types/GasFeeController.d.ts.map +1 -1
  68. package/dist/types/determineGasFeeCalculations.d.ts +16 -17
  69. package/dist/types/determineGasFeeCalculations.d.ts.map +1 -1
  70. package/dist/types/fetchBlockFeeHistory.d.ts +115 -0
  71. package/dist/types/fetchBlockFeeHistory.d.ts.map +1 -0
  72. package/dist/types/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts +17 -0
  73. package/dist/types/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts.map +1 -0
  74. package/dist/types/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts +12 -0
  75. package/dist/types/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts.map +1 -0
  76. package/dist/types/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts +10 -0
  77. package/dist/types/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts.map +1 -0
  78. package/dist/types/fetchGasEstimatesViaEthFeeHistory/types.d.ts +7 -0
  79. package/dist/types/fetchGasEstimatesViaEthFeeHistory/types.d.ts.map +1 -0
  80. package/dist/types/fetchGasEstimatesViaEthFeeHistory.d.ts +22 -0
  81. package/dist/types/fetchGasEstimatesViaEthFeeHistory.d.ts.map +1 -0
  82. package/package.json +1 -1
  83. package/dist/chunk-2AQW4RMC.js.map +0 -1
  84. package/dist/chunk-GJSUFSHM.mjs.map +0 -1
  85. package/dist/chunk-Q2YPK5SL.js.map +0 -1
@@ -1,13 +1,18 @@
1
1
  import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateMethod,
5
- __privateSet,
2
+ fetchGasEstimatesViaEthFeeHistory
3
+ } from "./chunk-EXCWMMNV.mjs";
4
+ import {
6
5
  calculateTimeEstimate,
7
6
  fetchEthGasPriceEstimate,
8
7
  fetchGasEstimates,
9
8
  fetchLegacyGasPriceEstimates
10
- } from "./chunk-KORLXV32.mjs";
9
+ } from "./chunk-QVES4OOM.mjs";
10
+ import {
11
+ __privateAdd,
12
+ __privateGet,
13
+ __privateMethod,
14
+ __privateSet
15
+ } from "./chunk-XUI43LEZ.mjs";
11
16
 
12
17
  // src/GasFeeController.ts
13
18
  import {
@@ -39,8 +44,7 @@ var defaultState = {
39
44
  gasFeeEstimatesByChainId: {},
40
45
  gasFeeEstimates: {},
41
46
  estimatedGasFeeTimeBounds: {},
42
- gasEstimateType: GAS_ESTIMATE_TYPES.NONE,
43
- nonRPCGasFeeApisDisabled: false
47
+ gasEstimateType: GAS_ESTIMATE_TYPES.NONE
44
48
  };
45
49
  var _getProvider, _onNetworkControllerDidChange, onNetworkControllerDidChange_fn;
46
50
  var GasFeeController = class extends StaticIntervalPollingController {
@@ -183,6 +187,7 @@ var GasFeeController = class extends StaticIntervalPollingController {
183
187
  "<chain_id>",
184
188
  `${decimalChainId}`
185
189
  ),
190
+ fetchGasEstimatesViaEthFeeHistory,
186
191
  fetchLegacyGasPriceEstimates,
187
192
  fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(
188
193
  "<chain_id>",
@@ -192,8 +197,7 @@ var GasFeeController = class extends StaticIntervalPollingController {
192
197
  calculateTimeEstimate,
193
198
  clientId: this.clientId,
194
199
  ethQuery,
195
- infuraAPIKey: this.infuraAPIKey,
196
- nonRPCGasFeeApisDisabled: this.state.nonRPCGasFeeApisDisabled
200
+ infuraAPIKey: this.infuraAPIKey
197
201
  });
198
202
  if (shouldUpdateState) {
199
203
  this.update((state) => {
@@ -275,16 +279,6 @@ var GasFeeController = class extends StaticIntervalPollingController {
275
279
  this.state.gasFeeEstimates
276
280
  );
277
281
  }
278
- enableNonRPCGasFeeApis() {
279
- this.update((state) => {
280
- state.nonRPCGasFeeApisDisabled = false;
281
- });
282
- }
283
- disableNonRPCGasFeeApis() {
284
- this.update((state) => {
285
- state.nonRPCGasFeeApisDisabled = true;
286
- });
287
- }
288
282
  };
289
283
  _getProvider = new WeakMap();
290
284
  _onNetworkControllerDidChange = new WeakSet();
@@ -299,88 +293,74 @@ onNetworkControllerDidChange_fn = async function(networkControllerState) {
299
293
  var GasFeeController_default = GasFeeController;
300
294
 
301
295
  // src/determineGasFeeCalculations.ts
302
- async function determineGasFeeCalculations(args) {
296
+ async function determineGasFeeCalculations({
297
+ isEIP1559Compatible,
298
+ isLegacyGasAPICompatible,
299
+ fetchGasEstimates: fetchGasEstimates2,
300
+ fetchGasEstimatesUrl,
301
+ fetchGasEstimatesViaEthFeeHistory: fetchGasEstimatesViaEthFeeHistory2,
302
+ fetchLegacyGasPriceEstimates: fetchLegacyGasPriceEstimates2,
303
+ fetchLegacyGasPriceEstimatesUrl,
304
+ fetchEthGasPriceEstimate: fetchEthGasPriceEstimate2,
305
+ calculateTimeEstimate: calculateTimeEstimate2,
306
+ clientId,
307
+ ethQuery,
308
+ infuraAPIKey
309
+ }) {
303
310
  try {
304
- return await getEstimatesUsingFallbacks(args);
305
- } catch (error) {
306
- if (error instanceof Error) {
307
- throw new Error(
308
- `Gas fee/price estimation failed. Message: ${error.message}`
311
+ if (isEIP1559Compatible) {
312
+ let estimates;
313
+ try {
314
+ estimates = await fetchGasEstimates2(
315
+ fetchGasEstimatesUrl,
316
+ infuraAPIKey,
317
+ clientId
318
+ );
319
+ } catch {
320
+ estimates = await fetchGasEstimatesViaEthFeeHistory2(ethQuery);
321
+ }
322
+ const { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = estimates.medium;
323
+ const estimatedGasFeeTimeBounds = calculateTimeEstimate2(
324
+ suggestedMaxPriorityFeePerGas,
325
+ suggestedMaxFeePerGas,
326
+ estimates
309
327
  );
310
- }
311
- throw error;
312
- }
313
- }
314
- async function getEstimatesUsingFallbacks(request) {
315
- const {
316
- isEIP1559Compatible,
317
- isLegacyGasAPICompatible,
318
- nonRPCGasFeeApisDisabled
319
- } = request;
320
- try {
321
- if (isEIP1559Compatible && !nonRPCGasFeeApisDisabled) {
322
- return await getEstimatesUsingFeeMarketEndpoint(request);
323
- }
324
- if (isLegacyGasAPICompatible && !nonRPCGasFeeApisDisabled) {
325
- return await getEstimatesUsingLegacyEndpoint(request);
328
+ return {
329
+ gasFeeEstimates: estimates,
330
+ estimatedGasFeeTimeBounds,
331
+ gasEstimateType: GAS_ESTIMATE_TYPES.FEE_MARKET
332
+ };
333
+ } else if (isLegacyGasAPICompatible) {
334
+ const estimates = await fetchLegacyGasPriceEstimates2(
335
+ fetchLegacyGasPriceEstimatesUrl,
336
+ infuraAPIKey,
337
+ clientId
338
+ );
339
+ return {
340
+ gasFeeEstimates: estimates,
341
+ estimatedGasFeeTimeBounds: {},
342
+ gasEstimateType: GAS_ESTIMATE_TYPES.LEGACY
343
+ };
326
344
  }
327
345
  throw new Error("Main gas fee/price estimation failed. Use fallback");
328
346
  } catch {
329
- return await getEstimatesUsingProvider(request);
347
+ try {
348
+ const estimates = await fetchEthGasPriceEstimate2(ethQuery);
349
+ return {
350
+ gasFeeEstimates: estimates,
351
+ estimatedGasFeeTimeBounds: {},
352
+ gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE
353
+ };
354
+ } catch (error) {
355
+ if (error instanceof Error) {
356
+ throw new Error(
357
+ `Gas fee/price estimation failed. Message: ${error.message}`
358
+ );
359
+ }
360
+ throw error;
361
+ }
330
362
  }
331
363
  }
332
- async function getEstimatesUsingFeeMarketEndpoint(request) {
333
- const {
334
- fetchGasEstimates: fetchGasEstimates2,
335
- fetchGasEstimatesUrl,
336
- infuraAPIKey,
337
- clientId,
338
- calculateTimeEstimate: calculateTimeEstimate2
339
- } = request;
340
- const estimates = await fetchGasEstimates2(
341
- fetchGasEstimatesUrl,
342
- infuraAPIKey,
343
- clientId
344
- );
345
- const { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = estimates.medium;
346
- const estimatedGasFeeTimeBounds = calculateTimeEstimate2(
347
- suggestedMaxPriorityFeePerGas,
348
- suggestedMaxFeePerGas,
349
- estimates
350
- );
351
- return {
352
- gasFeeEstimates: estimates,
353
- estimatedGasFeeTimeBounds,
354
- gasEstimateType: GAS_ESTIMATE_TYPES.FEE_MARKET
355
- };
356
- }
357
- async function getEstimatesUsingLegacyEndpoint(request) {
358
- const {
359
- fetchLegacyGasPriceEstimates: fetchLegacyGasPriceEstimates2,
360
- fetchLegacyGasPriceEstimatesUrl,
361
- infuraAPIKey,
362
- clientId
363
- } = request;
364
- const estimates = await fetchLegacyGasPriceEstimates2(
365
- fetchLegacyGasPriceEstimatesUrl,
366
- infuraAPIKey,
367
- clientId
368
- );
369
- return {
370
- gasFeeEstimates: estimates,
371
- estimatedGasFeeTimeBounds: {},
372
- gasEstimateType: GAS_ESTIMATE_TYPES.LEGACY
373
- };
374
- }
375
- async function getEstimatesUsingProvider(request) {
376
- const { ethQuery, fetchEthGasPriceEstimate: fetchEthGasPriceEstimate2 } = request;
377
- const estimates = await fetchEthGasPriceEstimate2(ethQuery);
378
- return {
379
- gasFeeEstimates: estimates,
380
- estimatedGasFeeTimeBounds: {},
381
- gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE
382
- };
383
- }
384
364
 
385
365
  export {
386
366
  determineGasFeeCalculations,
@@ -389,4 +369,4 @@ export {
389
369
  GasFeeController,
390
370
  GasFeeController_default
391
371
  };
392
- //# sourceMappingURL=chunk-GJSUFSHM.mjs.map
372
+ //# sourceMappingURL=chunk-G2HAZY5F.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/GasFeeController.ts","../src/determineGasFeeCalculations.ts"],"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 fetchGasEstimatesViaEthFeeHistory from './fetchGasEstimatesViaEthFeeHistory';\nimport {\n calculateTimeEstimate,\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n} from './gas-util';\n\nexport const GAS_API_BASE_URL = 'https://gas.api.infura.io';\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 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};\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 & SingleChainGasFeeState;\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};\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 private readonly EIP1559APIEndpoint: string;\n\n private readonly getCurrentNetworkEIP1559Compatibility;\n\n private readonly getCurrentNetworkLegacyGasAPICompatibility;\n\n private readonly getCurrentAccountEIP1559Compatibility;\n\n private readonly infuraAPIKey: string;\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.clientId - The client ID used to identify to the gas estimation API who is\n * asking for estimates.\n * @param options.infuraAPIKey - The Infura API key used for infura API requests.\n */\n constructor({\n interval = 15000,\n messenger,\n state,\n getCurrentNetworkEIP1559Compatibility,\n getCurrentAccountEIP1559Compatibility,\n getChainId,\n getCurrentNetworkLegacyGasAPICompatibility,\n getProvider,\n onNetworkDidChange,\n clientId,\n infuraAPIKey,\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 clientId?: string;\n infuraAPIKey: 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 = `${GAS_API_BASE_URL}/networks/<chain_id>/suggestedGasFees`;\n this.legacyAPIEndpoint = `${GAS_API_BASE_URL}/networks/<chain_id>/gasPrices`;\n this.clientId = clientId;\n this.infuraAPIKey = infuraAPIKey;\n\n this.ethQuery = new EthQuery(this.#getProvider());\n\n if (onNetworkDidChange && getChainId) {\n this.currentChainId = getChainId();\n onNetworkDidChange(async (networkControllerState) => {\n await this.#onNetworkControllerDidChange(networkControllerState);\n });\n } else {\n this.currentChainId = this.messagingSystem.call(\n 'NetworkController:getState',\n ).providerConfig.chainId;\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\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 fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery,\n infuraAPIKey: this.infuraAPIKey,\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 state.gasFeeEstimatesByChainId ??= {};\n state.gasFeeEstimatesByChainId[toHex(decimalChainId)] = {\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 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(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","import type {\n EstimatedGasFeeTimeBounds,\n EthGasPriceEstimate,\n GasFeeEstimates,\n GasFeeState as GasFeeCalculations,\n LegacyGasPriceEstimate,\n} from './GasFeeController';\nimport { GAS_ESTIMATE_TYPES } from './GasFeeController';\n\n/**\n * Obtains a set of max base and priority fee estimates along with time estimates so that we\n * can present them to users when they are sending transactions or making swaps.\n *\n * @param args - The arguments.\n * @param args.isEIP1559Compatible - Governs whether or not we can use an EIP-1559-only method to\n * produce estimates.\n * @param args.isLegacyGasAPICompatible - Governs whether or not we can use a non-EIP-1559 method to\n * produce estimates (for instance, testnets do not support estimates altogether).\n * @param args.fetchGasEstimates - A function that fetches gas estimates using an EIP-1559-specific\n * API.\n * @param args.fetchGasEstimatesUrl - The URL for the API we can use to obtain EIP-1559-specific\n * estimates.\n * @param args.fetchGasEstimatesViaEthFeeHistory - A function that fetches gas estimates using\n * `eth_feeHistory` (an EIP-1559 feature).\n * @param args.fetchLegacyGasPriceEstimates - A function that fetches gas estimates using an\n * non-EIP-1559-specific API.\n * @param args.fetchLegacyGasPriceEstimatesUrl - The URL for the API we can use to obtain\n * non-EIP-1559-specific estimates.\n * @param args.fetchEthGasPriceEstimate - A function that fetches gas estimates using\n * `eth_gasPrice`.\n * @param args.calculateTimeEstimate - A function that determine time estimate bounds.\n * @param args.clientId - An identifier that an API can use to know who is asking for estimates.\n * @param args.ethQuery - An EthQuery instance we can use to talk to Ethereum directly.\n * @param args.infuraAPIKey - Infura API key to use for requests to Infura.\n * @returns The gas fee calculations.\n */\nexport default async function determineGasFeeCalculations({\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n fetchGasEstimates,\n fetchGasEstimatesUrl,\n fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId,\n ethQuery,\n infuraAPIKey,\n}: {\n isEIP1559Compatible: boolean;\n isLegacyGasAPICompatible: boolean;\n fetchGasEstimates: (\n url: string,\n infuraAPIKey: string,\n clientId?: string,\n ) => Promise<GasFeeEstimates>;\n fetchGasEstimatesUrl: string;\n fetchGasEstimatesViaEthFeeHistory: (\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ethQuery: any,\n ) => Promise<GasFeeEstimates>;\n fetchLegacyGasPriceEstimates: (\n url: string,\n infuraAPIKey: string,\n clientId?: string,\n ) => Promise<LegacyGasPriceEstimate>;\n fetchLegacyGasPriceEstimatesUrl: string;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fetchEthGasPriceEstimate: (ethQuery: any) => Promise<EthGasPriceEstimate>;\n calculateTimeEstimate: (\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n gasFeeEstimates: GasFeeEstimates,\n ) => EstimatedGasFeeTimeBounds;\n clientId: string | undefined;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ethQuery: any;\n infuraAPIKey: string;\n}): Promise<GasFeeCalculations> {\n try {\n if (isEIP1559Compatible) {\n let estimates: GasFeeEstimates;\n try {\n estimates = await fetchGasEstimates(\n fetchGasEstimatesUrl,\n infuraAPIKey,\n clientId,\n );\n } catch {\n estimates = await fetchGasEstimatesViaEthFeeHistory(ethQuery);\n }\n const { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } =\n estimates.medium;\n const estimatedGasFeeTimeBounds = calculateTimeEstimate(\n suggestedMaxPriorityFeePerGas,\n suggestedMaxFeePerGas,\n estimates,\n );\n return {\n gasFeeEstimates: estimates,\n estimatedGasFeeTimeBounds,\n gasEstimateType: GAS_ESTIMATE_TYPES.FEE_MARKET,\n };\n } else if (isLegacyGasAPICompatible) {\n const estimates = await fetchLegacyGasPriceEstimates(\n fetchLegacyGasPriceEstimatesUrl,\n infuraAPIKey,\n clientId,\n );\n return {\n gasFeeEstimates: estimates,\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.LEGACY,\n };\n }\n throw new Error('Main gas fee/price estimation failed. Use fallback');\n } catch {\n try {\n const estimates = await fetchEthGasPriceEstimate(ethQuery);\n return {\n gasFeeEstimates: estimates,\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE,\n };\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Gas fee/price estimation failed. Message: ${error.message}`,\n );\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AAUrB,SAAS,uCAAuC;AAEhD,SAAS,MAAM,cAAc;AAWtB,IAAM,mBAAmB;AA0BzB,IAAM,qBAAqB;AAAA,EAChC,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,MAAM;AACR;AAiGA,IAAM,WAAW;AAAA,EACf,0BAA0B;AAAA,IACxB,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,iBAAiB,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EACnD,2BAA2B,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC7D,iBAAiB,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AAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAiCgC;AAC9B,MAAI;AACF,QAAI,qBAAqB;AACvB,UAAI;AACJ,UAAI;AACF,oBAAY,MAAMJ;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF,QAAQ;AACN,oBAAY,MAAMC,mCAAkC,QAAQ;AAAA,MAC9D;AACA,YAAM,EAAE,+BAA+B,sBAAsB,IAC3D,UAAU;AACZ,YAAM,4BAA4BG;AAAA,QAChC;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,QACL,iBAAiB;AAAA,QACjB;AAAA,QACA,iBAAiB,mBAAmB;AAAA,MACtC;AAAA,IACF,WAAW,0BAA0B;AACnC,YAAM,YAAY,MAAMF;AAAA,QACtB;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,QACL,iBAAiB;AAAA,QACjB,2BAA2B,CAAC;AAAA,QAC5B,iBAAiB,mBAAmB;AAAA,MACtC;AAAA,IACF;AACA,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACtE,QAAQ;AACN,QAAI;AACF,YAAM,YAAY,MAAMC,0BAAyB,QAAQ;AACzD,aAAO;AAAA,QACL,iBAAiB;AAAA,QACjB,2BAA2B,CAAC;AAAA,QAC5B,iBAAiB,mBAAmB;AAAA,MACtC;AAAA,IACF,SAAS,OAAO;AACd,UAAI,iBAAiB,OAAO;AAC1B,cAAM,IAAI;AAAA,UACR,6CAA6C,MAAM,OAAO;AAAA,QAC5D;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":["fetchGasEstimates","fetchGasEstimatesViaEthFeeHistory","fetchLegacyGasPriceEstimates","fetchEthGasPriceEstimate","calculateTimeEstimate"]}
@@ -0,0 +1,77 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
+
3
+ var _chunkS2EH2EPSjs = require('./chunk-S2EH2EPS.js');
4
+
5
+ // src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts
6
+ var _controllerutils = require('@metamask/controller-utils');
7
+ var _ethjsunit = require('@metamask/ethjs-unit');
8
+ var _bnjs = require('bn.js'); var _bnjs2 = _interopRequireDefault(_bnjs);
9
+ var PRIORITY_LEVELS = ["low", "medium", "high"];
10
+ var SETTINGS_BY_PRIORITY_LEVEL = {
11
+ low: {
12
+ percentile: 10,
13
+ baseFeePercentageMultiplier: new (0, _bnjs2.default)(110),
14
+ priorityFeePercentageMultiplier: new (0, _bnjs2.default)(94),
15
+ minSuggestedMaxPriorityFeePerGas: new (0, _bnjs2.default)(1e9),
16
+ estimatedWaitTimes: {
17
+ minWaitTimeEstimate: 15e3,
18
+ maxWaitTimeEstimate: 3e4
19
+ }
20
+ },
21
+ medium: {
22
+ percentile: 20,
23
+ baseFeePercentageMultiplier: new (0, _bnjs2.default)(120),
24
+ priorityFeePercentageMultiplier: new (0, _bnjs2.default)(97),
25
+ minSuggestedMaxPriorityFeePerGas: new (0, _bnjs2.default)(15e8),
26
+ estimatedWaitTimes: {
27
+ minWaitTimeEstimate: 15e3,
28
+ maxWaitTimeEstimate: 45e3
29
+ }
30
+ },
31
+ high: {
32
+ percentile: 30,
33
+ baseFeePercentageMultiplier: new (0, _bnjs2.default)(125),
34
+ priorityFeePercentageMultiplier: new (0, _bnjs2.default)(98),
35
+ minSuggestedMaxPriorityFeePerGas: new (0, _bnjs2.default)(2e9),
36
+ estimatedWaitTimes: {
37
+ minWaitTimeEstimate: 15e3,
38
+ maxWaitTimeEstimate: 6e4
39
+ }
40
+ }
41
+ };
42
+ function calculateEstimatesForPriorityLevel(priorityLevel, blocks) {
43
+ const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];
44
+ const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;
45
+ const adjustedBaseFee = latestBaseFeePerGas.mul(settings.baseFeePercentageMultiplier).divn(100);
46
+ const priorityFees = blocks.map((block) => {
47
+ return "priorityFeesByPercentile" in block ? block.priorityFeesByPercentile[settings.percentile] : null;
48
+ }).filter(_bnjs2.default.isBN);
49
+ const medianPriorityFee = _chunkS2EH2EPSjs.medianOf.call(void 0, priorityFees);
50
+ const adjustedPriorityFee = medianPriorityFee.mul(settings.priorityFeePercentageMultiplier).divn(100);
51
+ const suggestedMaxPriorityFeePerGas = _bnjs2.default.max(
52
+ adjustedPriorityFee,
53
+ settings.minSuggestedMaxPriorityFeePerGas
54
+ );
55
+ const suggestedMaxFeePerGas = adjustedBaseFee.add(
56
+ suggestedMaxPriorityFeePerGas
57
+ );
58
+ return {
59
+ ...settings.estimatedWaitTimes,
60
+ suggestedMaxPriorityFeePerGas: _ethjsunit.fromWei.call(void 0, suggestedMaxPriorityFeePerGas, _controllerutils.GWEI),
61
+ suggestedMaxFeePerGas: _ethjsunit.fromWei.call(void 0, suggestedMaxFeePerGas, _controllerutils.GWEI)
62
+ };
63
+ }
64
+ function calculateGasFeeEstimatesForPriorityLevels(blocks) {
65
+ return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {
66
+ const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(
67
+ priorityLevel,
68
+ blocks
69
+ );
70
+ return { ...obj, [priorityLevel]: gasEstimatesForPriorityLevel };
71
+ }, {});
72
+ }
73
+
74
+
75
+
76
+ exports.calculateGasFeeEstimatesForPriorityLevels = calculateGasFeeEstimatesForPriorityLevels;
77
+ //# sourceMappingURL=chunk-GE7RMDFV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":";;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,OAAO,QAAQ;AASf,IAAM,kBAAkB,CAAC,OAAO,UAAU,MAAM;AAEhD,IAAM,6BAA6B;AAAA,EACjC,KAAK;AAAA,IACH,YAAY;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ACL,GAAG,SAAS;AAAA,IACZ,+BAA+B,QAAQ,+BAA+B,IAAI;AAAA,IAC1E,uBAAuB,QAAQ,uBAAuB,IAAI;AAAA,EAC5D;AACF;AAUe,SAAR,0CACL,QACsC;AACtC,SAAO,gBAAgB,OAAO,CAAC,KAAK,kBAAkB;AACpD,UAAM,+BAA+B;AAAA,MACnC;AAAA,MACA;AAAA,IACF;AACA,WAAO,EAAE,GAAG,KAAK,CAAC,aAAa,GAAG,6BAA6B;AAAA,EACjE,GAAG,CAAC,CAAyC;AAC/C","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport { fromWei } from '@metamask/ethjs-unit';\nimport BN from 'bn.js';\n\nimport type { FeeHistoryBlock } from '../fetchBlockFeeHistory';\nimport type { Eip1559GasFee, GasFeeEstimates } from '../GasFeeController';\nimport medianOf from './medianOf';\n\nexport type PriorityLevel = (typeof PRIORITY_LEVELS)[number];\nexport type Percentile = (typeof PRIORITY_LEVEL_PERCENTILES)[number];\n\nconst PRIORITY_LEVELS = ['low', 'medium', 'high'] as const;\nconst PRIORITY_LEVEL_PERCENTILES = [10, 20, 30] as const;\nconst SETTINGS_BY_PRIORITY_LEVEL = {\n low: {\n percentile: 10 as Percentile,\n baseFeePercentageMultiplier: new BN(110),\n priorityFeePercentageMultiplier: new BN(94),\n minSuggestedMaxPriorityFeePerGas: new BN(1_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 30_000,\n },\n },\n medium: {\n percentile: 20 as Percentile,\n baseFeePercentageMultiplier: new BN(120),\n priorityFeePercentageMultiplier: new BN(97),\n minSuggestedMaxPriorityFeePerGas: new BN(1_500_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 45_000,\n },\n },\n high: {\n percentile: 30 as Percentile,\n baseFeePercentageMultiplier: new BN(125),\n priorityFeePercentageMultiplier: new BN(98),\n minSuggestedMaxPriorityFeePerGas: new BN(2_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 60_000,\n },\n },\n};\n\n/**\n * Calculates a set of estimates assigned to a particular priority level based on the data returned\n * by `eth_feeHistory`.\n *\n * @param priorityLevel - The level of fees that dictates how soon a transaction may go through\n * (\"low\", \"medium\", or \"high\").\n * @param blocks - A set of blocks as obtained from {@link fetchBlockFeeHistory}.\n * @returns The estimates.\n */\nfunction calculateEstimatesForPriorityLevel(\n priorityLevel: PriorityLevel,\n blocks: FeeHistoryBlock<Percentile>[],\n): Eip1559GasFee {\n const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];\n\n const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;\n\n const adjustedBaseFee = latestBaseFeePerGas\n .mul(settings.baseFeePercentageMultiplier)\n .divn(100);\n const priorityFees = blocks\n .map((block) => {\n return 'priorityFeesByPercentile' in block\n ? block.priorityFeesByPercentile[settings.percentile]\n : null;\n })\n .filter(BN.isBN);\n const medianPriorityFee = medianOf(priorityFees);\n const adjustedPriorityFee = medianPriorityFee\n .mul(settings.priorityFeePercentageMultiplier)\n .divn(100);\n\n const suggestedMaxPriorityFeePerGas = BN.max(\n adjustedPriorityFee,\n settings.minSuggestedMaxPriorityFeePerGas,\n );\n const suggestedMaxFeePerGas = adjustedBaseFee.add(\n suggestedMaxPriorityFeePerGas,\n );\n\n return {\n ...settings.estimatedWaitTimes,\n suggestedMaxPriorityFeePerGas: fromWei(suggestedMaxPriorityFeePerGas, GWEI),\n suggestedMaxFeePerGas: fromWei(suggestedMaxFeePerGas, GWEI),\n };\n}\n\n/**\n * Calculates a set of estimates suitable for different priority levels based on the data returned\n * by `eth_feeHistory`.\n *\n * @param blocks - A set of blocks populated with data for priority fee percentiles 10, 20, and 30,\n * obtained via {@link BlockFeeHistoryDatasetFetcher}.\n * @returns The estimates.\n */\nexport default function calculateGasFeeEstimatesForPriorityLevels(\n blocks: FeeHistoryBlock<Percentile>[],\n): Pick<GasFeeEstimates, PriorityLevel> {\n return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {\n const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(\n priorityLevel,\n blocks,\n );\n return { ...obj, [priorityLevel]: gasEstimatesForPriorityLevel };\n }, {} as Pick<GasFeeEstimates, PriorityLevel>);\n}\n"]}
@@ -0,0 +1,77 @@
1
+ import {
2
+ medianOf
3
+ } from "./chunk-C4I7KKIU.mjs";
4
+
5
+ // src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts
6
+ import { GWEI } from "@metamask/controller-utils";
7
+ import { fromWei } from "@metamask/ethjs-unit";
8
+ import BN from "bn.js";
9
+ var PRIORITY_LEVELS = ["low", "medium", "high"];
10
+ var SETTINGS_BY_PRIORITY_LEVEL = {
11
+ low: {
12
+ percentile: 10,
13
+ baseFeePercentageMultiplier: new BN(110),
14
+ priorityFeePercentageMultiplier: new BN(94),
15
+ minSuggestedMaxPriorityFeePerGas: new BN(1e9),
16
+ estimatedWaitTimes: {
17
+ minWaitTimeEstimate: 15e3,
18
+ maxWaitTimeEstimate: 3e4
19
+ }
20
+ },
21
+ medium: {
22
+ percentile: 20,
23
+ baseFeePercentageMultiplier: new BN(120),
24
+ priorityFeePercentageMultiplier: new BN(97),
25
+ minSuggestedMaxPriorityFeePerGas: new BN(15e8),
26
+ estimatedWaitTimes: {
27
+ minWaitTimeEstimate: 15e3,
28
+ maxWaitTimeEstimate: 45e3
29
+ }
30
+ },
31
+ high: {
32
+ percentile: 30,
33
+ baseFeePercentageMultiplier: new BN(125),
34
+ priorityFeePercentageMultiplier: new BN(98),
35
+ minSuggestedMaxPriorityFeePerGas: new BN(2e9),
36
+ estimatedWaitTimes: {
37
+ minWaitTimeEstimate: 15e3,
38
+ maxWaitTimeEstimate: 6e4
39
+ }
40
+ }
41
+ };
42
+ function calculateEstimatesForPriorityLevel(priorityLevel, blocks) {
43
+ const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];
44
+ const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;
45
+ const adjustedBaseFee = latestBaseFeePerGas.mul(settings.baseFeePercentageMultiplier).divn(100);
46
+ const priorityFees = blocks.map((block) => {
47
+ return "priorityFeesByPercentile" in block ? block.priorityFeesByPercentile[settings.percentile] : null;
48
+ }).filter(BN.isBN);
49
+ const medianPriorityFee = medianOf(priorityFees);
50
+ const adjustedPriorityFee = medianPriorityFee.mul(settings.priorityFeePercentageMultiplier).divn(100);
51
+ const suggestedMaxPriorityFeePerGas = BN.max(
52
+ adjustedPriorityFee,
53
+ settings.minSuggestedMaxPriorityFeePerGas
54
+ );
55
+ const suggestedMaxFeePerGas = adjustedBaseFee.add(
56
+ suggestedMaxPriorityFeePerGas
57
+ );
58
+ return {
59
+ ...settings.estimatedWaitTimes,
60
+ suggestedMaxPriorityFeePerGas: fromWei(suggestedMaxPriorityFeePerGas, GWEI),
61
+ suggestedMaxFeePerGas: fromWei(suggestedMaxFeePerGas, GWEI)
62
+ };
63
+ }
64
+ function calculateGasFeeEstimatesForPriorityLevels(blocks) {
65
+ return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {
66
+ const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(
67
+ priorityLevel,
68
+ blocks
69
+ );
70
+ return { ...obj, [priorityLevel]: gasEstimatesForPriorityLevel };
71
+ }, {});
72
+ }
73
+
74
+ export {
75
+ calculateGasFeeEstimatesForPriorityLevels
76
+ };
77
+ //# sourceMappingURL=chunk-GUWY6WP6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport { fromWei } from '@metamask/ethjs-unit';\nimport BN from 'bn.js';\n\nimport type { FeeHistoryBlock } from '../fetchBlockFeeHistory';\nimport type { Eip1559GasFee, GasFeeEstimates } from '../GasFeeController';\nimport medianOf from './medianOf';\n\nexport type PriorityLevel = (typeof PRIORITY_LEVELS)[number];\nexport type Percentile = (typeof PRIORITY_LEVEL_PERCENTILES)[number];\n\nconst PRIORITY_LEVELS = ['low', 'medium', 'high'] as const;\nconst PRIORITY_LEVEL_PERCENTILES = [10, 20, 30] as const;\nconst SETTINGS_BY_PRIORITY_LEVEL = {\n low: {\n percentile: 10 as Percentile,\n baseFeePercentageMultiplier: new BN(110),\n priorityFeePercentageMultiplier: new BN(94),\n minSuggestedMaxPriorityFeePerGas: new BN(1_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 30_000,\n },\n },\n medium: {\n percentile: 20 as Percentile,\n baseFeePercentageMultiplier: new BN(120),\n priorityFeePercentageMultiplier: new BN(97),\n minSuggestedMaxPriorityFeePerGas: new BN(1_500_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 45_000,\n },\n },\n high: {\n percentile: 30 as Percentile,\n baseFeePercentageMultiplier: new BN(125),\n priorityFeePercentageMultiplier: new BN(98),\n minSuggestedMaxPriorityFeePerGas: new BN(2_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 60_000,\n },\n },\n};\n\n/**\n * Calculates a set of estimates assigned to a particular priority level based on the data returned\n * by `eth_feeHistory`.\n *\n * @param priorityLevel - The level of fees that dictates how soon a transaction may go through\n * (\"low\", \"medium\", or \"high\").\n * @param blocks - A set of blocks as obtained from {@link fetchBlockFeeHistory}.\n * @returns The estimates.\n */\nfunction calculateEstimatesForPriorityLevel(\n priorityLevel: PriorityLevel,\n blocks: FeeHistoryBlock<Percentile>[],\n): Eip1559GasFee {\n const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];\n\n const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;\n\n const adjustedBaseFee = latestBaseFeePerGas\n .mul(settings.baseFeePercentageMultiplier)\n .divn(100);\n const priorityFees = blocks\n .map((block) => {\n return 'priorityFeesByPercentile' in block\n ? block.priorityFeesByPercentile[settings.percentile]\n : null;\n })\n .filter(BN.isBN);\n const medianPriorityFee = medianOf(priorityFees);\n const adjustedPriorityFee = medianPriorityFee\n .mul(settings.priorityFeePercentageMultiplier)\n .divn(100);\n\n const suggestedMaxPriorityFeePerGas = BN.max(\n adjustedPriorityFee,\n settings.minSuggestedMaxPriorityFeePerGas,\n );\n const suggestedMaxFeePerGas = adjustedBaseFee.add(\n suggestedMaxPriorityFeePerGas,\n );\n\n return {\n ...settings.estimatedWaitTimes,\n suggestedMaxPriorityFeePerGas: fromWei(suggestedMaxPriorityFeePerGas, GWEI),\n suggestedMaxFeePerGas: fromWei(suggestedMaxFeePerGas, GWEI),\n };\n}\n\n/**\n * Calculates a set of estimates suitable for different priority levels based on the data returned\n * by `eth_feeHistory`.\n *\n * @param blocks - A set of blocks populated with data for priority fee percentiles 10, 20, and 30,\n * obtained via {@link BlockFeeHistoryDatasetFetcher}.\n * @returns The estimates.\n */\nexport default function calculateGasFeeEstimatesForPriorityLevels(\n blocks: FeeHistoryBlock<Percentile>[],\n): Pick<GasFeeEstimates, PriorityLevel> {\n return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {\n const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(\n priorityLevel,\n blocks,\n );\n return { ...obj, [priorityLevel]: gasEstimatesForPriorityLevel };\n }, {} as Pick<GasFeeEstimates, PriorityLevel>);\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,OAAO,QAAQ;AASf,IAAM,kBAAkB,CAAC,OAAO,UAAU,MAAM;AAEhD,IAAM,6BAA6B;AAAA,EACjC,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,6BAA6B,IAAI,GAAG,GAAG;AAAA,IACvC,iCAAiC,IAAI,GAAG,EAAE;AAAA,IAC1C,kCAAkC,IAAI,GAAG,GAAa;AAAA,IACtD,oBAAoB;AA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