@metamask-previews/gas-fee-controller 13.0.2-preview.e5c396b → 13.0.2-preview.eb2135e

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 (103) hide show
  1. package/dist/GasFeeController.js +19 -300
  2. package/dist/GasFeeController.js.map +1 -1
  3. package/dist/GasFeeController.mjs +20 -0
  4. package/dist/GasFeeController.mjs.map +1 -0
  5. package/dist/chunk-4T54ULFA.mjs +367 -0
  6. package/dist/chunk-4T54ULFA.mjs.map +1 -0
  7. package/dist/chunk-5INBFZXY.js +127 -0
  8. package/dist/chunk-5INBFZXY.js.map +1 -0
  9. package/dist/chunk-AQN4AQEF.mjs +127 -0
  10. package/dist/chunk-AQN4AQEF.mjs.map +1 -0
  11. package/dist/chunk-C4I7KKIU.mjs +12 -0
  12. package/dist/chunk-C4I7KKIU.mjs.map +1 -0
  13. package/dist/chunk-CCRUODGE.mjs +129 -0
  14. package/dist/chunk-CCRUODGE.mjs.map +1 -0
  15. package/dist/chunk-EXCWMMNV.mjs +39 -0
  16. package/dist/chunk-EXCWMMNV.mjs.map +1 -0
  17. package/dist/chunk-EZVGDV5H.js +39 -0
  18. package/dist/chunk-EZVGDV5H.js.map +1 -0
  19. package/dist/chunk-F46NZXRQ.js +129 -0
  20. package/dist/chunk-F46NZXRQ.js.map +1 -0
  21. package/dist/chunk-GE7RMDFV.js +77 -0
  22. package/dist/chunk-GE7RMDFV.js.map +1 -0
  23. package/dist/chunk-GUWY6WP6.mjs +77 -0
  24. package/dist/chunk-GUWY6WP6.mjs.map +1 -0
  25. package/dist/chunk-LO7OP5FM.js +19 -0
  26. package/dist/chunk-LO7OP5FM.js.map +1 -0
  27. package/dist/chunk-N5BANBTW.js +367 -0
  28. package/dist/chunk-N5BANBTW.js.map +1 -0
  29. package/dist/chunk-S2EH2EPS.js +12 -0
  30. package/dist/chunk-S2EH2EPS.js.map +1 -0
  31. package/dist/chunk-SINQOHIN.mjs +19 -0
  32. package/dist/chunk-SINQOHIN.mjs.map +1 -0
  33. package/dist/chunk-XUI43LEZ.mjs +30 -0
  34. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  35. package/dist/chunk-Z4BLTVTB.js +30 -0
  36. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  37. package/dist/determineGasFeeCalculations.js +13 -86
  38. package/dist/determineGasFeeCalculations.js.map +1 -1
  39. package/dist/determineGasFeeCalculations.mjs +14 -0
  40. package/dist/determineGasFeeCalculations.mjs.map +1 -0
  41. package/dist/fetchBlockFeeHistory.js +7 -204
  42. package/dist/fetchBlockFeeHistory.js.map +1 -1
  43. package/dist/fetchBlockFeeHistory.mjs +8 -0
  44. package/dist/fetchBlockFeeHistory.mjs.map +1 -0
  45. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js +8 -88
  46. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map +1 -1
  47. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.mjs +9 -0
  48. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.mjs.map +1 -0
  49. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js +7 -31
  50. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js.map +1 -1
  51. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.mjs +8 -0
  52. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.mjs.map +1 -0
  53. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js +7 -16
  54. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js.map +1 -1
  55. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.mjs +8 -0
  56. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.mjs.map +1 -0
  57. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js +1 -3
  58. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js.map +1 -1
  59. package/dist/fetchGasEstimatesViaEthFeeHistory/types.mjs +1 -0
  60. package/dist/fetchGasEstimatesViaEthFeeHistory/types.mjs.map +1 -0
  61. package/dist/fetchGasEstimatesViaEthFeeHistory.js +11 -52
  62. package/dist/fetchGasEstimatesViaEthFeeHistory.js.map +1 -1
  63. package/dist/fetchGasEstimatesViaEthFeeHistory.mjs +12 -0
  64. package/dist/fetchGasEstimatesViaEthFeeHistory.mjs.map +1 -0
  65. package/dist/gas-util.js +15 -142
  66. package/dist/gas-util.js.map +1 -1
  67. package/dist/gas-util.mjs +16 -0
  68. package/dist/gas-util.mjs.map +1 -0
  69. package/dist/index.js +17 -17
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +18 -0
  72. package/dist/index.mjs.map +1 -0
  73. package/dist/tsconfig.build.tsbuildinfo +1 -0
  74. package/dist/types/GasFeeController.d.ts.map +1 -0
  75. package/dist/types/determineGasFeeCalculations.d.ts.map +1 -0
  76. package/dist/types/fetchBlockFeeHistory.d.ts.map +1 -0
  77. package/dist/types/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts.map +1 -0
  78. package/dist/types/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts.map +1 -0
  79. package/dist/types/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts.map +1 -0
  80. package/dist/types/fetchGasEstimatesViaEthFeeHistory/types.d.ts.map +1 -0
  81. package/dist/types/fetchGasEstimatesViaEthFeeHistory.d.ts.map +1 -0
  82. package/dist/types/gas-util.d.ts.map +1 -0
  83. package/dist/{index.d.ts.map → types/index.d.ts.map} +1 -1
  84. package/package.json +11 -1
  85. package/dist/GasFeeController.d.ts.map +0 -1
  86. package/dist/determineGasFeeCalculations.d.ts.map +0 -1
  87. package/dist/fetchBlockFeeHistory.d.ts.map +0 -1
  88. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts.map +0 -1
  89. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts.map +0 -1
  90. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts.map +0 -1
  91. package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts.map +0 -1
  92. package/dist/fetchGasEstimatesViaEthFeeHistory.d.ts.map +0 -1
  93. package/dist/gas-util.d.ts.map +0 -1
  94. /package/dist/{GasFeeController.d.ts → types/GasFeeController.d.ts} +0 -0
  95. /package/dist/{determineGasFeeCalculations.d.ts → types/determineGasFeeCalculations.d.ts} +0 -0
  96. /package/dist/{fetchBlockFeeHistory.d.ts → types/fetchBlockFeeHistory.d.ts} +0 -0
  97. /package/dist/{fetchGasEstimatesViaEthFeeHistory → types/fetchGasEstimatesViaEthFeeHistory}/calculateGasFeeEstimatesForPriorityLevels.d.ts +0 -0
  98. /package/dist/{fetchGasEstimatesViaEthFeeHistory → types/fetchGasEstimatesViaEthFeeHistory}/fetchLatestBlock.d.ts +0 -0
  99. /package/dist/{fetchGasEstimatesViaEthFeeHistory → types/fetchGasEstimatesViaEthFeeHistory}/medianOf.d.ts +0 -0
  100. /package/dist/{fetchGasEstimatesViaEthFeeHistory → types/fetchGasEstimatesViaEthFeeHistory}/types.d.ts +0 -0
  101. /package/dist/{fetchGasEstimatesViaEthFeeHistory.d.ts → types/fetchGasEstimatesViaEthFeeHistory.d.ts} +0 -0
  102. /package/dist/{gas-util.d.ts → types/gas-util.d.ts} +0 -0
  103. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
@@ -0,0 +1,127 @@
1
+ // src/fetchBlockFeeHistory.ts
2
+ import { query, fromHex, toHex } from "@metamask/controller-utils";
3
+ import BN from "bn.js";
4
+ var MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL = 1024;
5
+ async function fetchBlockFeeHistory({
6
+ ethQuery,
7
+ numberOfBlocks: totalNumberOfBlocks,
8
+ endBlock: givenEndBlock = "latest",
9
+ percentiles: givenPercentiles = [],
10
+ includeNextBlock = false
11
+ }) {
12
+ const percentiles = givenPercentiles.length > 0 ? Array.from(new Set(givenPercentiles)).sort((a, b) => a - b) : [];
13
+ const finalEndBlockNumber = givenEndBlock === "latest" ? fromHex(await query(ethQuery, "blockNumber")) : givenEndBlock;
14
+ const requestChunkSpecifiers = determineRequestChunkSpecifiers(
15
+ finalEndBlockNumber,
16
+ totalNumberOfBlocks
17
+ );
18
+ const blockChunks = await Promise.all(
19
+ requestChunkSpecifiers.map(({ numberOfBlocks, endBlockNumber }, i) => {
20
+ return i === requestChunkSpecifiers.length - 1 ? makeRequestForChunk({
21
+ ethQuery,
22
+ numberOfBlocks,
23
+ endBlockNumber,
24
+ percentiles,
25
+ includeNextBlock
26
+ }) : makeRequestForChunk({
27
+ ethQuery,
28
+ numberOfBlocks,
29
+ endBlockNumber,
30
+ percentiles,
31
+ includeNextBlock: false
32
+ });
33
+ })
34
+ );
35
+ return blockChunks.reduce(
36
+ (array, blocks) => [...array, ...blocks],
37
+ []
38
+ );
39
+ }
40
+ function buildExistingFeeHistoryBlock({
41
+ baseFeePerGas,
42
+ number,
43
+ blockIndex,
44
+ gasUsedRatios,
45
+ priorityFeePercentileGroups,
46
+ percentiles
47
+ }) {
48
+ const gasUsedRatio = gasUsedRatios[blockIndex];
49
+ const priorityFeesForEachPercentile = priorityFeePercentileGroups[blockIndex];
50
+ const priorityFeesByPercentile = percentiles.reduce(
51
+ (obj, percentile, percentileIndex) => {
52
+ const priorityFee = priorityFeesForEachPercentile[percentileIndex];
53
+ return { ...obj, [percentile]: fromHex(priorityFee) };
54
+ },
55
+ {}
56
+ );
57
+ return {
58
+ number,
59
+ baseFeePerGas,
60
+ gasUsedRatio,
61
+ priorityFeesByPercentile
62
+ };
63
+ }
64
+ function buildNextFeeHistoryBlock({
65
+ baseFeePerGas,
66
+ number
67
+ }) {
68
+ return {
69
+ number,
70
+ baseFeePerGas,
71
+ gasUsedRatio: null,
72
+ priorityFeesByPercentile: null
73
+ };
74
+ }
75
+ async function makeRequestForChunk({
76
+ ethQuery,
77
+ numberOfBlocks,
78
+ endBlockNumber,
79
+ percentiles,
80
+ includeNextBlock
81
+ }) {
82
+ const response = await query(
83
+ ethQuery,
84
+ "eth_feeHistory",
85
+ [toHex(numberOfBlocks), toHex(endBlockNumber), percentiles]
86
+ );
87
+ const startBlockNumber = fromHex(response.oldestBlock);
88
+ if (response.baseFeePerGas !== void 0 && response.baseFeePerGas.length > 0 && response.gasUsedRatio.length > 0 && (response.reward === void 0 || response.reward.length > 0)) {
89
+ const baseFeesPerGasAsHex = includeNextBlock ? response.baseFeePerGas : response.baseFeePerGas.slice(0, numberOfBlocks);
90
+ const gasUsedRatios = response.gasUsedRatio;
91
+ const priorityFeePercentileGroups = response.reward ?? [];
92
+ const numberOfExistingResults = gasUsedRatios.length;
93
+ return baseFeesPerGasAsHex.map((baseFeePerGasAsHex, blockIndex) => {
94
+ const baseFeePerGas = fromHex(baseFeePerGasAsHex);
95
+ const number = startBlockNumber.addn(blockIndex);
96
+ return blockIndex >= numberOfExistingResults ? buildNextFeeHistoryBlock({ baseFeePerGas, number }) : buildExistingFeeHistoryBlock({
97
+ baseFeePerGas,
98
+ number,
99
+ blockIndex,
100
+ gasUsedRatios,
101
+ priorityFeePercentileGroups,
102
+ percentiles
103
+ });
104
+ });
105
+ }
106
+ return [];
107
+ }
108
+ function determineRequestChunkSpecifiers(endBlockNumber, totalNumberOfBlocks) {
109
+ if (endBlockNumber.lt(new BN(totalNumberOfBlocks))) {
110
+ totalNumberOfBlocks = endBlockNumber.toNumber();
111
+ }
112
+ const specifiers = [];
113
+ for (let chunkStartBlockNumber = endBlockNumber.subn(totalNumberOfBlocks); chunkStartBlockNumber.lt(endBlockNumber); chunkStartBlockNumber = chunkStartBlockNumber.addn(
114
+ MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL
115
+ )) {
116
+ const distanceToEnd = endBlockNumber.sub(chunkStartBlockNumber).toNumber();
117
+ const numberOfBlocks = distanceToEnd < MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL ? distanceToEnd : MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL;
118
+ const chunkEndBlockNumber = chunkStartBlockNumber.addn(numberOfBlocks);
119
+ specifiers.push({ numberOfBlocks, endBlockNumber: chunkEndBlockNumber });
120
+ }
121
+ return specifiers;
122
+ }
123
+
124
+ export {
125
+ fetchBlockFeeHistory
126
+ };
127
+ //# sourceMappingURL=chunk-AQN4AQEF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchBlockFeeHistory.ts"],"sourcesContent":["import { query, fromHex, toHex } from '@metamask/controller-utils';\nimport BN from 'bn.js';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype EthQuery = any;\n\n/**\n * @type RequestChunkSpecifier\n *\n * Arguments to `eth_feeHistory` that can be used to fetch a set of historical data.\n * @property blockCount - The number of blocks requested.\n * @property endBlockNumber - The number of the block at the end of the requested range.\n */\ntype RequestChunkSpecifier = {\n numberOfBlocks: number;\n endBlockNumber: BN;\n};\n\n/**\n * @type EthFeeHistoryResponse\n *\n * Response data for `eth_feeHistory`.\n * @property oldestBlock - The id of the oldest block (in hex format) in the range of blocks\n * requested.\n * @property baseFeePerGas - Base fee per gas for each block in the range of blocks requested.\n * For go-ethereum based chains baseFeePerGas will not returned in case of empty results\n * <github.com/ethereum/go-ethereum/blob/v1.10.16/internal/ethapi/api.go#L87>\n * @property gasUsedRatio - A number between 0 and 1 that represents the gas used vs. gas limit for\n * each block in the range of blocks requested.\n * @property reward - The priority fee at the percentiles requested for each block in the range of\n * blocks requested.\n */\n\nexport type EthFeeHistoryResponse = {\n oldestBlock: string;\n baseFeePerGas?: string[];\n gasUsedRatio: number[];\n reward?: string[][];\n};\n\n/**\n * @type ExistingFeeHistoryBlock\n *\n * Historical data for a particular block that exists on the blockchain.\n * @property number - The number of the block, as a BN.\n * @property baseFeePerGas - The base fee per gas for the block in WEI, as a BN.\n * @property gasUsedRatio - A number between 0 and 1 that represents the ratio between the gas paid\n * for the block and its set gas limit.\n * @property priorityFeesByPercentile - The priority fees paid for the transactions in the block\n * that occurred at particular levels at which those transactions contributed to the overall gas\n * used for the block, indexed by those percentiles. (See docs for {@link fetchBlockFeeHistory} for more\n * on how this works.)\n */\ntype ExistingFeeHistoryBlock<Percentile extends number> = {\n number: BN;\n baseFeePerGas: BN;\n gasUsedRatio: number;\n priorityFeesByPercentile: Record<Percentile, BN>;\n};\n\n/**\n * @type NextFeeHistoryBlock\n *\n * Historical data for a theoretical block that could exist in the future.\n * @property number - The number of the block, as a BN.\n * @property baseFeePerGas - The estimated base fee per gas for the block in WEI, as a BN.\n */\ntype NextFeeHistoryBlock = {\n number: BN;\n baseFeePerGas: BN;\n};\n\n/**\n * @type FeeHistoryBlock\n *\n * Historical data for a particular block.\n * @property number - The number of the block, as a BN.\n * @property baseFeePerGas - The base fee per gas for the block in WEI, as a BN.\n * @property gasUsedRatio - A number between 0 and 1 that represents the ratio between the gas paid\n * for the block and its set gas limit.\n * @property priorityFeesByPercentile - The priority fees paid for the transactions in the block\n * that occurred at particular levels at which those transactions contributed to the overall gas\n * used for the block, indexed by those percentiles. (See docs for {@link fetchBlockFeeHistory} for more\n * on how this works.)\n */\nexport type FeeHistoryBlock<Percentile extends number> =\n | ExistingFeeHistoryBlock<Percentile>\n | NextFeeHistoryBlock;\n\n/**\n * @type ExtractPercentileFrom\n *\n * Extracts the percentiles that the type assigned to an array of FeeHistoryBlock has been created\n * with. This makes use of the `infer` keyword to read the type argument.\n */\nexport type ExtractPercentileFrom<T> = T extends FeeHistoryBlock<infer P>[]\n ? P\n : never;\n\nconst MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL = 1024;\n\n/**\n * Uses `eth_feeHistory` (an EIP-1559 feature) to obtain information about gas fees from a range of\n * blocks that have occurred recently on a network.\n *\n * To learn more, see these resources:\n *\n * - <https://infura.io/docs/ethereum#operation/eth_feeHistory>\n * - <https://github.com/zsfelfoldi/feehistory/blob/main/docs/feeHistory.md>\n * - <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L180>\n * - <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md>\n * - <https://gas-api.metaswap.codefi.network/testFeeHistory>\n *\n * @param args - The arguments to this function.\n * @param args.ethQuery - An EthQuery instance that wraps a provider for the network in question.\n * @param args.endBlock - The desired end of the requested block range. Can be \"latest\" if you want\n * to start from the latest successful block or the number of a known past block.\n * @param args.numberOfBlocks - How many total blocks to fetch. Note that if this is more than 1024,\n * multiple calls to `eth_feeHistory` will be made.\n * @param args.percentiles - A set of numbers between 1 and 100 which will dictate how\n * `priorityFeesByPercentile` in each returned block will be formed. When Ethereum runs the\n * `eth_feeHistory` method, for each block it is considering, it will first sort all transactions by\n * the priority fee. It will then go through each transaction and add the total amount of gas paid\n * for that transaction to a bucket which maxes out at the total gas used for the whole block. As\n * the bucket fills, it will cross percentages which correspond to the percentiles specified here,\n * and the priority fees of the first transactions which cause it to reach those percentages will be\n * recorded. Hence, `priorityFeesByPercentile` represents the priority fees of transactions at key\n * gas used contribution levels, where earlier levels have smaller contributions and later levels\n * have higher contributions.\n * @param args.includeNextBlock - Whether to include an extra block that represents the next\n * block after the latest one. Only the `baseFeePerGas` will be filled in for this block (which is\n * estimated).\n * @returns The list of blocks and their fee data, sorted from oldest to newest.\n */\nexport default async function fetchBlockFeeHistory<Percentile extends number>({\n ethQuery,\n numberOfBlocks: totalNumberOfBlocks,\n endBlock: givenEndBlock = 'latest',\n percentiles: givenPercentiles = [],\n includeNextBlock = false,\n}: {\n ethQuery: EthQuery;\n numberOfBlocks: number;\n endBlock?: 'latest' | BN;\n percentiles?: readonly Percentile[];\n includeNextBlock?: boolean;\n}): Promise<FeeHistoryBlock<Percentile>[]> {\n const percentiles =\n givenPercentiles.length > 0\n ? Array.from(new Set(givenPercentiles)).sort((a, b) => a - b)\n : [];\n\n const finalEndBlockNumber =\n givenEndBlock === 'latest'\n ? fromHex(await query(ethQuery, 'blockNumber'))\n : givenEndBlock;\n\n const requestChunkSpecifiers = determineRequestChunkSpecifiers(\n finalEndBlockNumber,\n totalNumberOfBlocks,\n );\n\n const blockChunks = await Promise.all(\n requestChunkSpecifiers.map(({ numberOfBlocks, endBlockNumber }, i) => {\n return i === requestChunkSpecifiers.length - 1\n ? makeRequestForChunk({\n ethQuery,\n numberOfBlocks,\n endBlockNumber,\n percentiles,\n includeNextBlock,\n })\n : makeRequestForChunk({\n ethQuery,\n numberOfBlocks,\n endBlockNumber,\n percentiles,\n includeNextBlock: false,\n });\n }),\n );\n\n return blockChunks.reduce(\n (array, blocks) => [...array, ...blocks],\n [] as FeeHistoryBlock<Percentile>[],\n );\n}\n\n/**\n * Builds an ExistingFeeHistoryBlock.\n *\n * @param args - The args to this function.\n * @param args.number - The number of the block.\n * @param args.baseFeePerGas - The base fee per gas of the block.\n * @param args.blockIndex - The index of the block in the source chunk.\n * @param args.gasUsedRatios - The gas used ratios for the block.\n * @param args.priorityFeePercentileGroups - The priority fee percentile groups for the block.\n * @param args.percentiles - The percentiles used to fetch the source chunk.\n * @returns The ExistingFeeHistoryBlock.\n */\nfunction buildExistingFeeHistoryBlock<Percentile extends number>({\n baseFeePerGas,\n number,\n blockIndex,\n gasUsedRatios,\n priorityFeePercentileGroups,\n percentiles,\n}: {\n baseFeePerGas: BN;\n number: BN;\n blockIndex: number;\n gasUsedRatios: number[];\n priorityFeePercentileGroups: string[][];\n percentiles: readonly Percentile[];\n}): ExistingFeeHistoryBlock<Percentile> {\n const gasUsedRatio = gasUsedRatios[blockIndex];\n const priorityFeesForEachPercentile = priorityFeePercentileGroups[blockIndex];\n const priorityFeesByPercentile = percentiles.reduce(\n (obj, percentile, percentileIndex) => {\n const priorityFee = priorityFeesForEachPercentile[percentileIndex];\n return { ...obj, [percentile]: fromHex(priorityFee) };\n },\n {} as Record<Percentile, BN>,\n );\n\n return {\n number,\n baseFeePerGas,\n gasUsedRatio,\n priorityFeesByPercentile,\n };\n}\n\n/**\n * Builds a NextFeeHistoryBlock.\n *\n * @param args - The args to this function.\n * @param args.baseFeePerGas - The base fee per gas of the block.\n * @param args.number - The number of the block.\n * @returns The NextFeeHistoryBlock.\n */\nfunction buildNextFeeHistoryBlock({\n baseFeePerGas,\n number,\n}: {\n baseFeePerGas: BN;\n number: BN;\n}) {\n return {\n number,\n baseFeePerGas,\n gasUsedRatio: null,\n priorityFeesByPercentile: null,\n };\n}\n\n/**\n * Uses eth_feeHistory to request historical data about a group of blocks (max size 1024).\n *\n * @param args - The arguments\n * @param args.ethQuery - An EthQuery instance.\n * @param args.numberOfBlocks - The number of blocks in the chunk. Must be at most 1024, as this is\n * the maximum that `eth_feeHistory` can return in one call.\n * @param args.endBlockNumber - The end of the requested block range.\n * @param args.percentiles - A set of numbers between 1 and 100 that will be used to pull priority\n * fees for each block.\n * @param args.includeNextBlock - Whether to include an extra block that represents the next\n * block after the latest one. Only the `baseFeePerGas` will be filled in for this block (which is\n * estimated).\n * @returns A list of block data.\n */\nasync function makeRequestForChunk<Percentile extends number>({\n ethQuery,\n numberOfBlocks,\n endBlockNumber,\n percentiles,\n includeNextBlock,\n}: {\n ethQuery: EthQuery;\n numberOfBlocks: number;\n endBlockNumber: BN;\n percentiles: readonly Percentile[];\n includeNextBlock: boolean;\n}): Promise<FeeHistoryBlock<Percentile>[]> {\n const response: EthFeeHistoryResponse = await query(\n ethQuery,\n 'eth_feeHistory',\n [toHex(numberOfBlocks), toHex(endBlockNumber), percentiles],\n );\n\n const startBlockNumber = fromHex(response.oldestBlock);\n\n if (\n response.baseFeePerGas !== undefined &&\n response.baseFeePerGas.length > 0 &&\n response.gasUsedRatio.length > 0 &&\n (response.reward === undefined || response.reward.length > 0)\n ) {\n // Per\n // <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L191-L192>,\n // baseFeePerGas will always include an extra item which is the calculated base fee for the\n // next (future) block. We may or may not care about this; if we don't, chop it off.\n const baseFeesPerGasAsHex = includeNextBlock\n ? response.baseFeePerGas\n : response.baseFeePerGas.slice(0, numberOfBlocks);\n const gasUsedRatios = response.gasUsedRatio;\n const priorityFeePercentileGroups = response.reward ?? [];\n // Chain is allowed to return fewer number of block results\n const numberOfExistingResults = gasUsedRatios.length;\n\n return baseFeesPerGasAsHex.map((baseFeePerGasAsHex, blockIndex) => {\n const baseFeePerGas = fromHex(baseFeePerGasAsHex);\n const number = startBlockNumber.addn(blockIndex);\n\n return blockIndex >= numberOfExistingResults\n ? buildNextFeeHistoryBlock({ baseFeePerGas, number })\n : buildExistingFeeHistoryBlock({\n baseFeePerGas,\n number,\n blockIndex,\n gasUsedRatios,\n priorityFeePercentileGroups,\n percentiles,\n });\n });\n }\n\n return [];\n}\n\n/**\n * Divides a block range (specified by a range size and the end of the range) into chunks based on\n * the maximum number of blocks that `eth_feeHistory` can return in a single call.\n *\n * If the requested totalNumberOfBlocks exceed endBlockNumber, totalNumberOfBlocks is\n * truncated to avoid requesting chunks with negative endBlockNumber.\n *\n * @param endBlockNumber - The final block in the complete desired block range after all\n * `eth_feeHistory` requests have been made.\n * @param totalNumberOfBlocks - The total number of desired blocks after all `eth_feeHistory`\n * requests have been made.\n * @returns A set of arguments that can be used to make requests to `eth_feeHistory` in order to\n * retrieve all of the requested blocks, sorted from oldest block to newest block.\n */\nfunction determineRequestChunkSpecifiers(\n endBlockNumber: BN,\n totalNumberOfBlocks: number,\n): RequestChunkSpecifier[] {\n if (endBlockNumber.lt(new BN(totalNumberOfBlocks))) {\n totalNumberOfBlocks = endBlockNumber.toNumber();\n }\n\n const specifiers = [];\n for (\n let chunkStartBlockNumber = endBlockNumber.subn(totalNumberOfBlocks);\n chunkStartBlockNumber.lt(endBlockNumber);\n chunkStartBlockNumber = chunkStartBlockNumber.addn(\n MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL,\n )\n ) {\n const distanceToEnd = endBlockNumber.sub(chunkStartBlockNumber).toNumber();\n const numberOfBlocks =\n distanceToEnd < MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL\n ? distanceToEnd\n : MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL;\n const chunkEndBlockNumber = chunkStartBlockNumber.addn(numberOfBlocks);\n specifiers.push({ numberOfBlocks, endBlockNumber: chunkEndBlockNumber });\n }\n return specifiers;\n}\n"],"mappings":";AAAA,SAAS,OAAO,SAAS,aAAa;AACtC,OAAO,QAAQ;AAmGf,IAAM,gDAAgD;AAmCtD,eAAO,qBAAuE;AAAA,EAC5E;AAAA,EACA,gBAAgB;AAAA,EAChB,UAAU,gBAAgB;AAAA,EAC1B,aAAa,mBAAmB,CAAC;AAAA,EACjC,mBAAmB;AACrB,GAM2C;AACzC,QAAM,cACJ,iBAAiB,SAAS,IACtB,MAAM,KAAK,IAAI,IAAI,gBAAgB,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,IAC1D,CAAC;AAEP,QAAM,sBACJ,kBAAkB,WACd,QAAQ,MAAM,MAAM,UAAU,aAAa,CAAC,IAC5C;AAEN,QAAM,yBAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,EACF;AAEA,QAAM,cAAc,MAAM,QAAQ;AAAA,IAChC,uBAAuB,IAAI,CAAC,EAAE,gBAAgB,eAAe,GAAG,MAAM;AACpE,aAAO,MAAM,uBAAuB,SAAS,IACzC,oBAAoB;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC,IACD,oBAAoB;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AAEA,SAAO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WAAO,oBAAoB,IAAI,CAAC,oBAAoB,eAAe;AACjE,YAAM,gBAAgB,QAAQ,kBAAkB;AAChD,YAAM,SAAS,iBAAiB,KAAK,UAAU;AAE/C,aAAO,cAAc,0BACjB,yBAAyB,EAAE,eAAe,OAAO,CAAC,IAClD,6BAA6B;AAAA,QAC3B;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AAEA,SAAO,CAAC;AACV;AAgBA,SAAS,gCACP,gBACA,qBACyB;AACzB,MAAI,eAAe,GAAG,IAAI,GAAG,mBAAmB,CAAC,GAAG;AAClD,0BAAsB,eAAe,SAAS;AAAA,EAChD;AAEA,QAAM,aAAa,CAAC;AACpB,WACM,wBAAwB,eAAe,KAAK,mBAAmB,GACnE,sBAAsB,GAAG,cAAc,GACvC,wBAAwB,sBAAsB;AAAA,IAC5C;AAAA,EACF,GACA;AACA,UAAM,gBAAgB,eAAe,IAAI,qBAAqB,EAAE,SAAS;AACzE,UAAM,iBACJ,gBAAgB,gDACZ,gBACA;AACN,UAAM,sBAAsB,sBAAsB,KAAK,cAAc;AACrE,eAAW,KAAK,EAAE,gBAAgB,gBAAgB,oBAAoB,CAAC;AAAA,EACzE;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,12 @@
1
+ // src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts
2
+ function medianOf(numbers) {
3
+ const sortedNumbers = numbers.slice().sort((a, b) => a.cmp(b));
4
+ const len = sortedNumbers.length;
5
+ const index = Math.floor((len - 1) / 2);
6
+ return sortedNumbers[index];
7
+ }
8
+
9
+ export {
10
+ medianOf
11
+ };
12
+ //# sourceMappingURL=chunk-C4I7KKIU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"sourcesContent":["import type * as BN from 'bn.js';\n\n/**\n * Finds the median among a list of numbers. Note that this is different from the implementation\n * in the MetaSwap API, as we want to hold to using BN as much as possible.\n *\n * @param numbers - A list of numbers, as BNs. Will be sorted automatically if unsorted.\n * @returns The median number.\n */\nexport default function medianOf(numbers: BN[]): BN {\n const sortedNumbers = numbers.slice().sort((a, b) => a.cmp(b));\n const len = sortedNumbers.length;\n const index = Math.floor((len - 1) / 2);\n return sortedNumbers[index];\n}\n"],"mappings":";AASe,SAAR,SAA0B,SAAmB;AAClD,QAAM,gBAAgB,QAAQ,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,CAAC;AAC7D,QAAM,MAAM,cAAc;AAC1B,QAAM,QAAQ,KAAK,OAAO,MAAM,KAAK,CAAC;AACtC,SAAO,cAAc,KAAK;AAC5B;","names":[]}
@@ -0,0 +1,129 @@
1
+ // src/gas-util.ts
2
+ import {
3
+ query,
4
+ handleFetch,
5
+ gweiDecToWEIBN,
6
+ weiHexToGweiDec
7
+ } from "@metamask/controller-utils";
8
+ import BN from "bn.js";
9
+ var makeClientIdHeader = (clientId) => ({ "X-Client-Id": clientId });
10
+ function normalizeGWEIDecimalNumbers(n) {
11
+ const numberAsWEIHex = gweiDecToWEIBN(n).toString(16);
12
+ const numberAsGWEI = weiHexToGweiDec(numberAsWEIHex);
13
+ return numberAsGWEI;
14
+ }
15
+ async function fetchGasEstimates(url, clientId) {
16
+ const estimates = await handleFetch(
17
+ url,
18
+ clientId ? { headers: makeClientIdHeader(clientId) } : void 0
19
+ );
20
+ return {
21
+ low: {
22
+ ...estimates.low,
23
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
24
+ estimates.low.suggestedMaxPriorityFeePerGas
25
+ ),
26
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
27
+ estimates.low.suggestedMaxFeePerGas
28
+ )
29
+ },
30
+ medium: {
31
+ ...estimates.medium,
32
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
33
+ estimates.medium.suggestedMaxPriorityFeePerGas
34
+ ),
35
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
36
+ estimates.medium.suggestedMaxFeePerGas
37
+ )
38
+ },
39
+ high: {
40
+ ...estimates.high,
41
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
42
+ estimates.high.suggestedMaxPriorityFeePerGas
43
+ ),
44
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
45
+ estimates.high.suggestedMaxFeePerGas
46
+ )
47
+ },
48
+ estimatedBaseFee: normalizeGWEIDecimalNumbers(estimates.estimatedBaseFee),
49
+ historicalBaseFeeRange: estimates.historicalBaseFeeRange,
50
+ baseFeeTrend: estimates.baseFeeTrend,
51
+ latestPriorityFeeRange: estimates.latestPriorityFeeRange,
52
+ historicalPriorityFeeRange: estimates.historicalPriorityFeeRange,
53
+ priorityFeeTrend: estimates.priorityFeeTrend,
54
+ networkCongestion: estimates.networkCongestion
55
+ };
56
+ }
57
+ async function fetchLegacyGasPriceEstimates(url, clientId) {
58
+ const result = await handleFetch(url, {
59
+ referrer: url,
60
+ referrerPolicy: "no-referrer-when-downgrade",
61
+ method: "GET",
62
+ mode: "cors",
63
+ headers: {
64
+ "Content-Type": "application/json",
65
+ ...clientId && makeClientIdHeader(clientId)
66
+ }
67
+ });
68
+ return {
69
+ low: result.SafeGasPrice,
70
+ medium: result.ProposeGasPrice,
71
+ high: result.FastGasPrice
72
+ };
73
+ }
74
+ async function fetchEthGasPriceEstimate(ethQuery) {
75
+ const gasPrice = await query(ethQuery, "gasPrice");
76
+ return {
77
+ gasPrice: weiHexToGweiDec(gasPrice).toString()
78
+ };
79
+ }
80
+ function calculateTimeEstimate(maxPriorityFeePerGas, maxFeePerGas, gasFeeEstimates) {
81
+ const { low, medium, high, estimatedBaseFee } = gasFeeEstimates;
82
+ const maxPriorityFeePerGasInWEI = gweiDecToWEIBN(maxPriorityFeePerGas);
83
+ const maxFeePerGasInWEI = gweiDecToWEIBN(maxFeePerGas);
84
+ const estimatedBaseFeeInWEI = gweiDecToWEIBN(estimatedBaseFee);
85
+ const effectiveMaxPriorityFee = BN.min(
86
+ maxPriorityFeePerGasInWEI,
87
+ maxFeePerGasInWEI.sub(estimatedBaseFeeInWEI)
88
+ );
89
+ const lowMaxPriorityFeeInWEI = gweiDecToWEIBN(
90
+ low.suggestedMaxPriorityFeePerGas
91
+ );
92
+ const mediumMaxPriorityFeeInWEI = gweiDecToWEIBN(
93
+ medium.suggestedMaxPriorityFeePerGas
94
+ );
95
+ const highMaxPriorityFeeInWEI = gweiDecToWEIBN(
96
+ high.suggestedMaxPriorityFeePerGas
97
+ );
98
+ let lowerTimeBound;
99
+ let upperTimeBound;
100
+ if (effectiveMaxPriorityFee.lt(lowMaxPriorityFeeInWEI)) {
101
+ lowerTimeBound = null;
102
+ upperTimeBound = "unknown";
103
+ } else if (effectiveMaxPriorityFee.gte(lowMaxPriorityFeeInWEI) && effectiveMaxPriorityFee.lt(mediumMaxPriorityFeeInWEI)) {
104
+ lowerTimeBound = low.minWaitTimeEstimate;
105
+ upperTimeBound = low.maxWaitTimeEstimate;
106
+ } else if (effectiveMaxPriorityFee.gte(mediumMaxPriorityFeeInWEI) && effectiveMaxPriorityFee.lt(highMaxPriorityFeeInWEI)) {
107
+ lowerTimeBound = medium.minWaitTimeEstimate;
108
+ upperTimeBound = medium.maxWaitTimeEstimate;
109
+ } else if (effectiveMaxPriorityFee.eq(highMaxPriorityFeeInWEI)) {
110
+ lowerTimeBound = high.minWaitTimeEstimate;
111
+ upperTimeBound = high.maxWaitTimeEstimate;
112
+ } else {
113
+ lowerTimeBound = 0;
114
+ upperTimeBound = high.maxWaitTimeEstimate;
115
+ }
116
+ return {
117
+ lowerTimeBound,
118
+ upperTimeBound
119
+ };
120
+ }
121
+
122
+ export {
123
+ normalizeGWEIDecimalNumbers,
124
+ fetchGasEstimates,
125
+ fetchLegacyGasPriceEstimates,
126
+ fetchEthGasPriceEstimate,
127
+ calculateTimeEstimate
128
+ };
129
+ //# sourceMappingURL=chunk-CCRUODGE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gas-util.ts"],"sourcesContent":["import {\n query,\n handleFetch,\n gweiDecToWEIBN,\n weiHexToGweiDec,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport BN from 'bn.js';\n\nimport type {\n GasFeeEstimates,\n EthGasPriceEstimate,\n EstimatedGasFeeTimeBounds,\n unknownString,\n LegacyGasPriceEstimate,\n} from './GasFeeController';\n\nconst makeClientIdHeader = (clientId: string) => ({ 'X-Client-Id': clientId });\n\n/**\n * Convert a decimal GWEI value to a decimal string rounded to the nearest WEI.\n *\n * @param n - The input GWEI amount, as a decimal string or a number.\n * @returns The decimal string GWEI amount.\n */\nexport function normalizeGWEIDecimalNumbers(n: string | number) {\n const numberAsWEIHex = gweiDecToWEIBN(n).toString(16);\n const numberAsGWEI = weiHexToGweiDec(numberAsWEIHex);\n return numberAsGWEI;\n}\n\n/**\n * Fetch gas estimates from the given URL.\n *\n * @param url - The gas estimate URL.\n * @param clientId - The client ID used to identify to the API who is asking for estimates.\n * @returns The gas estimates.\n */\nexport async function fetchGasEstimates(\n url: string,\n clientId?: string,\n): Promise<GasFeeEstimates> {\n const estimates = await handleFetch(\n url,\n clientId ? { headers: makeClientIdHeader(clientId) } : undefined,\n );\n return {\n low: {\n ...estimates.low,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.low.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.low.suggestedMaxFeePerGas,\n ),\n },\n medium: {\n ...estimates.medium,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.medium.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.medium.suggestedMaxFeePerGas,\n ),\n },\n high: {\n ...estimates.high,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.high.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.high.suggestedMaxFeePerGas,\n ),\n },\n estimatedBaseFee: normalizeGWEIDecimalNumbers(estimates.estimatedBaseFee),\n historicalBaseFeeRange: estimates.historicalBaseFeeRange,\n baseFeeTrend: estimates.baseFeeTrend,\n latestPriorityFeeRange: estimates.latestPriorityFeeRange,\n historicalPriorityFeeRange: estimates.historicalPriorityFeeRange,\n priorityFeeTrend: estimates.priorityFeeTrend,\n networkCongestion: estimates.networkCongestion,\n };\n}\n\n/**\n * Hit the legacy MetaSwaps gasPrices estimate api and return the low, medium\n * high values from that API.\n *\n * @param url - The URL to fetch gas price estimates from.\n * @param clientId - The client ID used to identify to the API who is asking for estimates.\n * @returns The gas price estimates.\n */\nexport async function fetchLegacyGasPriceEstimates(\n url: string,\n clientId?: string,\n): Promise<LegacyGasPriceEstimate> {\n const result = await handleFetch(url, {\n referrer: url,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && makeClientIdHeader(clientId)),\n },\n });\n return {\n low: result.SafeGasPrice,\n medium: result.ProposeGasPrice,\n high: result.FastGasPrice,\n };\n}\n\n/**\n * Get a gas price estimate from the network using the `eth_gasPrice` method.\n *\n * @param ethQuery - The EthQuery instance to call the network with.\n * @returns A gas price estimate.\n */\nexport async function fetchEthGasPriceEstimate(\n ethQuery: EthQuery,\n): Promise<EthGasPriceEstimate> {\n const gasPrice = await query(ethQuery, 'gasPrice');\n return {\n gasPrice: weiHexToGweiDec(gasPrice).toString(),\n };\n}\n\n/**\n * Estimate the time it will take for a transaction to be confirmed.\n *\n * @param maxPriorityFeePerGas - The max priority fee per gas.\n * @param maxFeePerGas - The max fee per gas.\n * @param gasFeeEstimates - The gas fee estimates.\n * @returns The estimated lower and upper bounds for when this transaction will be confirmed.\n */\nexport function calculateTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n gasFeeEstimates: GasFeeEstimates,\n): EstimatedGasFeeTimeBounds {\n const { low, medium, high, estimatedBaseFee } = gasFeeEstimates;\n\n const maxPriorityFeePerGasInWEI = gweiDecToWEIBN(maxPriorityFeePerGas);\n const maxFeePerGasInWEI = gweiDecToWEIBN(maxFeePerGas);\n const estimatedBaseFeeInWEI = gweiDecToWEIBN(estimatedBaseFee);\n\n const effectiveMaxPriorityFee = BN.min(\n maxPriorityFeePerGasInWEI,\n maxFeePerGasInWEI.sub(estimatedBaseFeeInWEI),\n );\n\n const lowMaxPriorityFeeInWEI = gweiDecToWEIBN(\n low.suggestedMaxPriorityFeePerGas,\n );\n const mediumMaxPriorityFeeInWEI = gweiDecToWEIBN(\n medium.suggestedMaxPriorityFeePerGas,\n );\n const highMaxPriorityFeeInWEI = gweiDecToWEIBN(\n high.suggestedMaxPriorityFeePerGas,\n );\n\n let lowerTimeBound;\n let upperTimeBound;\n\n if (effectiveMaxPriorityFee.lt(lowMaxPriorityFeeInWEI)) {\n lowerTimeBound = null;\n upperTimeBound = 'unknown' as unknownString;\n } else if (\n effectiveMaxPriorityFee.gte(lowMaxPriorityFeeInWEI) &&\n effectiveMaxPriorityFee.lt(mediumMaxPriorityFeeInWEI)\n ) {\n lowerTimeBound = low.minWaitTimeEstimate;\n upperTimeBound = low.maxWaitTimeEstimate;\n } else if (\n effectiveMaxPriorityFee.gte(mediumMaxPriorityFeeInWEI) &&\n effectiveMaxPriorityFee.lt(highMaxPriorityFeeInWEI)\n ) {\n lowerTimeBound = medium.minWaitTimeEstimate;\n upperTimeBound = medium.maxWaitTimeEstimate;\n } else if (effectiveMaxPriorityFee.eq(highMaxPriorityFeeInWEI)) {\n lowerTimeBound = high.minWaitTimeEstimate;\n upperTimeBound = high.maxWaitTimeEstimate;\n } else {\n lowerTimeBound = 0;\n upperTimeBound = high.maxWaitTimeEstimate;\n }\n\n return {\n lowerTimeBound,\n upperTimeBound,\n };\n}\n"],"m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,OAAO;AACL,qBAAiB;AACjB,qBAAiB,KAAK;AAAA,EACxB;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,39 @@
1
+ import {
2
+ fetchBlockFeeHistory
3
+ } from "./chunk-AQN4AQEF.mjs";
4
+ import {
5
+ calculateGasFeeEstimatesForPriorityLevels
6
+ } from "./chunk-GUWY6WP6.mjs";
7
+ import {
8
+ fetchLatestBlock
9
+ } from "./chunk-SINQOHIN.mjs";
10
+
11
+ // src/fetchGasEstimatesViaEthFeeHistory.ts
12
+ import { GWEI } from "@metamask/controller-utils";
13
+ import { fromWei } from "@metamask/ethjs-unit";
14
+ async function fetchGasEstimatesViaEthFeeHistory(ethQuery) {
15
+ const latestBlock = await fetchLatestBlock(ethQuery);
16
+ const blocks = await fetchBlockFeeHistory({
17
+ ethQuery,
18
+ endBlock: latestBlock.number,
19
+ numberOfBlocks: 5,
20
+ percentiles: [10, 20, 30]
21
+ });
22
+ const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);
23
+ const levelSpecificEstimates = calculateGasFeeEstimatesForPriorityLevels(blocks);
24
+ return {
25
+ ...levelSpecificEstimates,
26
+ estimatedBaseFee,
27
+ historicalBaseFeeRange: null,
28
+ baseFeeTrend: null,
29
+ latestPriorityFeeRange: null,
30
+ historicalPriorityFeeRange: null,
31
+ priorityFeeTrend: null,
32
+ networkCongestion: null
33
+ };
34
+ }
35
+
36
+ export {
37
+ fetchGasEstimatesViaEthFeeHistory
38
+ };
39
+ //# sourceMappingURL=chunk-EXCWMMNV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { fromWei } from '@metamask/ethjs-unit';\n\nimport fetchBlockFeeHistory from './fetchBlockFeeHistory';\nimport calculateGasFeeEstimatesForPriorityLevels from './fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels';\nimport fetchLatestBlock from './fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock';\nimport type { GasFeeEstimates } from './GasFeeController';\n\n/**\n * Generates gas fee estimates based on gas fees that have been used in the recent past so that\n * those estimates can be displayed to users.\n *\n * To produce the estimates, the last 5 blocks are read from the network, and for each block, the\n * priority fees for transactions at the 10th, 20th, and 30th percentiles are also read (here\n * \"percentile\" signifies the level at which those transactions contribute to the overall gas used\n * for the block, where higher percentiles correspond to higher fees). This information is used to\n * calculate reasonable max priority and max fees for three different priority levels (higher\n * priority = higher fee).\n *\n * Note that properties are returned for other data that are normally obtained via the API; however,\n * to prevent extra requests to Infura, these properties are empty.\n *\n * @param ethQuery - An EthQuery instance.\n * @returns Base and priority fee estimates, categorized by priority level, as well as an estimate\n * for the next block's base fee.\n */\nexport default async function fetchGasEstimatesViaEthFeeHistory(\n ethQuery: EthQuery,\n): Promise<GasFeeEstimates> {\n const latestBlock = await fetchLatestBlock(ethQuery);\n const blocks = await fetchBlockFeeHistory({\n ethQuery,\n endBlock: latestBlock.number,\n numberOfBlocks: 5,\n percentiles: [10, 20, 30],\n });\n const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);\n\n const levelSpecificEstimates =\n calculateGasFeeEstimatesForPriorityLevels(blocks);\n\n return {\n ...levelSpecificEstimates,\n estimatedBaseFee,\n historicalBaseFeeRange: null,\n baseFeeTrend: null,\n latestPriorityFeeRange: null,\n historicalPriorityFeeRange: null,\n priorityFeeTrend: null,\n networkCongestion: null,\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY;AAErB,SAAS,eAAe;AAyBxB,eAAO,kCACL,UAC0B;AAC1B,QAAM,cAAc,MAAM,iBAAiB,QAAQ;AACnD,QAAM,SAAS,MAAM,qBAAqB;AAAA,IACxC;AAAA,IACA,UAAU,YAAY;AAAA,IACtB,gBAAgB;AAAA,IAChB,aAAa,CAAC,IAAI,IAAI,EAAE;AAAA,EAC1B,CAAC;AACD,QAAM,mBAAmB,QAAQ,YAAY,eAAe,IAAI;AAEhE,QAAM,yBACJ,0CAA0C,MAAM;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,wBAAwB;AAAA,IACxB,cAAc;AAAA,IACd,wBAAwB;AAAA,IACxB,4BAA4B;AAAA,IAC5B,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EACrB;AACF;","names":[]}
@@ -0,0 +1,39 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunk5INBFZXYjs = require('./chunk-5INBFZXY.js');
4
+
5
+
6
+ var _chunkGE7RMDFVjs = require('./chunk-GE7RMDFV.js');
7
+
8
+
9
+ var _chunkLO7OP5FMjs = require('./chunk-LO7OP5FM.js');
10
+
11
+ // src/fetchGasEstimatesViaEthFeeHistory.ts
12
+ var _controllerutils = require('@metamask/controller-utils');
13
+ var _ethjsunit = require('@metamask/ethjs-unit');
14
+ async function fetchGasEstimatesViaEthFeeHistory(ethQuery) {
15
+ const latestBlock = await _chunkLO7OP5FMjs.fetchLatestBlock.call(void 0, ethQuery);
16
+ const blocks = await _chunk5INBFZXYjs.fetchBlockFeeHistory.call(void 0, {
17
+ ethQuery,
18
+ endBlock: latestBlock.number,
19
+ numberOfBlocks: 5,
20
+ percentiles: [10, 20, 30]
21
+ });
22
+ const estimatedBaseFee = _ethjsunit.fromWei.call(void 0, latestBlock.baseFeePerGas, _controllerutils.GWEI);
23
+ const levelSpecificEstimates = _chunkGE7RMDFVjs.calculateGasFeeEstimatesForPriorityLevels.call(void 0, blocks);
24
+ return {
25
+ ...levelSpecificEstimates,
26
+ estimatedBaseFee,
27
+ historicalBaseFeeRange: null,
28
+ baseFeeTrend: null,
29
+ latestPriorityFeeRange: null,
30
+ historicalPriorityFeeRange: null,
31
+ priorityFeeTrend: null,
32
+ networkCongestion: null
33
+ };
34
+ }
35
+
36
+
37
+
38
+ exports.fetchGasEstimatesViaEthFeeHistory = fetchGasEstimatesViaEthFeeHistory;
39
+ //# sourceMappingURL=chunk-EZVGDV5H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,SAAS,YAAY;AAErB,SAAS,eAAe;AAyBxB,eAAO,kCACL,UAC0B;AAC1B,QAAM,cAAc,MAAM,iBAAiB,QAAQ;AACnD,QAAM,SAAS,MAAM,qBAAqB;AAAA,IACxC;AAAA,IACA,UAAU,YAAY;AAAA,IACtB,gBAAgB;AAAA,IAChB,aAAa,CAAC,IAAI,IAAI,EAAE;AAAA,EAC1B,CAAC;AACD,QAAM,mBAAmB,QAAQ,YAAY,eAAe,IAAI;AAEhE,QAAM,yBACJ,0CAA0C,MAAM;AAElD,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,wBAAwB;AAAA,IACxB,cAAc;AAAA,IACd,wBAAwB;AAAA,IACxB,4BAA4B;AAAA,IAC5B,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EACrB;AACF","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { fromWei } from '@metamask/ethjs-unit';\n\nimport fetchBlockFeeHistory from './fetchBlockFeeHistory';\nimport calculateGasFeeEstimatesForPriorityLevels from './fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels';\nimport fetchLatestBlock from './fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock';\nimport type { GasFeeEstimates } from './GasFeeController';\n\n/**\n * Generates gas fee estimates based on gas fees that have been used in the recent past so that\n * those estimates can be displayed to users.\n *\n * To produce the estimates, the last 5 blocks are read from the network, and for each block, the\n * priority fees for transactions at the 10th, 20th, and 30th percentiles are also read (here\n * \"percentile\" signifies the level at which those transactions contribute to the overall gas used\n * for the block, where higher percentiles correspond to higher fees). This information is used to\n * calculate reasonable max priority and max fees for three different priority levels (higher\n * priority = higher fee).\n *\n * Note that properties are returned for other data that are normally obtained via the API; however,\n * to prevent extra requests to Infura, these properties are empty.\n *\n * @param ethQuery - An EthQuery instance.\n * @returns Base and priority fee estimates, categorized by priority level, as well as an estimate\n * for the next block's base fee.\n */\nexport default async function fetchGasEstimatesViaEthFeeHistory(\n ethQuery: EthQuery,\n): Promise<GasFeeEstimates> {\n const latestBlock = await fetchLatestBlock(ethQuery);\n const blocks = await fetchBlockFeeHistory({\n ethQuery,\n endBlock: latestBlock.number,\n numberOfBlocks: 5,\n percentiles: [10, 20, 30],\n });\n const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);\n\n const levelSpecificEstimates =\n calculateGasFeeEstimatesForPriorityLevels(blocks);\n\n return {\n ...levelSpecificEstimates,\n estimatedBaseFee,\n historicalBaseFeeRange: null,\n baseFeeTrend: null,\n latestPriorityFeeRange: null,\n historicalPriorityFeeRange: null,\n priorityFeeTrend: null,\n networkCongestion: null,\n };\n}\n"]}
@@ -0,0 +1,129 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/gas-util.ts
2
+
3
+
4
+
5
+
6
+
7
+ var _controllerutils = require('@metamask/controller-utils');
8
+ var _bnjs = require('bn.js'); var _bnjs2 = _interopRequireDefault(_bnjs);
9
+ var makeClientIdHeader = (clientId) => ({ "X-Client-Id": clientId });
10
+ function normalizeGWEIDecimalNumbers(n) {
11
+ const numberAsWEIHex = _controllerutils.gweiDecToWEIBN.call(void 0, n).toString(16);
12
+ const numberAsGWEI = _controllerutils.weiHexToGweiDec.call(void 0, numberAsWEIHex);
13
+ return numberAsGWEI;
14
+ }
15
+ async function fetchGasEstimates(url, clientId) {
16
+ const estimates = await _controllerutils.handleFetch.call(void 0,
17
+ url,
18
+ clientId ? { headers: makeClientIdHeader(clientId) } : void 0
19
+ );
20
+ return {
21
+ low: {
22
+ ...estimates.low,
23
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
24
+ estimates.low.suggestedMaxPriorityFeePerGas
25
+ ),
26
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
27
+ estimates.low.suggestedMaxFeePerGas
28
+ )
29
+ },
30
+ medium: {
31
+ ...estimates.medium,
32
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
33
+ estimates.medium.suggestedMaxPriorityFeePerGas
34
+ ),
35
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
36
+ estimates.medium.suggestedMaxFeePerGas
37
+ )
38
+ },
39
+ high: {
40
+ ...estimates.high,
41
+ suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(
42
+ estimates.high.suggestedMaxPriorityFeePerGas
43
+ ),
44
+ suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(
45
+ estimates.high.suggestedMaxFeePerGas
46
+ )
47
+ },
48
+ estimatedBaseFee: normalizeGWEIDecimalNumbers(estimates.estimatedBaseFee),
49
+ historicalBaseFeeRange: estimates.historicalBaseFeeRange,
50
+ baseFeeTrend: estimates.baseFeeTrend,
51
+ latestPriorityFeeRange: estimates.latestPriorityFeeRange,
52
+ historicalPriorityFeeRange: estimates.historicalPriorityFeeRange,
53
+ priorityFeeTrend: estimates.priorityFeeTrend,
54
+ networkCongestion: estimates.networkCongestion
55
+ };
56
+ }
57
+ async function fetchLegacyGasPriceEstimates(url, clientId) {
58
+ const result = await _controllerutils.handleFetch.call(void 0, url, {
59
+ referrer: url,
60
+ referrerPolicy: "no-referrer-when-downgrade",
61
+ method: "GET",
62
+ mode: "cors",
63
+ headers: {
64
+ "Content-Type": "application/json",
65
+ ...clientId && makeClientIdHeader(clientId)
66
+ }
67
+ });
68
+ return {
69
+ low: result.SafeGasPrice,
70
+ medium: result.ProposeGasPrice,
71
+ high: result.FastGasPrice
72
+ };
73
+ }
74
+ async function fetchEthGasPriceEstimate(ethQuery) {
75
+ const gasPrice = await _controllerutils.query.call(void 0, ethQuery, "gasPrice");
76
+ return {
77
+ gasPrice: _controllerutils.weiHexToGweiDec.call(void 0, gasPrice).toString()
78
+ };
79
+ }
80
+ function calculateTimeEstimate(maxPriorityFeePerGas, maxFeePerGas, gasFeeEstimates) {
81
+ const { low, medium, high, estimatedBaseFee } = gasFeeEstimates;
82
+ const maxPriorityFeePerGasInWEI = _controllerutils.gweiDecToWEIBN.call(void 0, maxPriorityFeePerGas);
83
+ const maxFeePerGasInWEI = _controllerutils.gweiDecToWEIBN.call(void 0, maxFeePerGas);
84
+ const estimatedBaseFeeInWEI = _controllerutils.gweiDecToWEIBN.call(void 0, estimatedBaseFee);
85
+ const effectiveMaxPriorityFee = _bnjs2.default.min(
86
+ maxPriorityFeePerGasInWEI,
87
+ maxFeePerGasInWEI.sub(estimatedBaseFeeInWEI)
88
+ );
89
+ const lowMaxPriorityFeeInWEI = _controllerutils.gweiDecToWEIBN.call(void 0,
90
+ low.suggestedMaxPriorityFeePerGas
91
+ );
92
+ const mediumMaxPriorityFeeInWEI = _controllerutils.gweiDecToWEIBN.call(void 0,
93
+ medium.suggestedMaxPriorityFeePerGas
94
+ );
95
+ const highMaxPriorityFeeInWEI = _controllerutils.gweiDecToWEIBN.call(void 0,
96
+ high.suggestedMaxPriorityFeePerGas
97
+ );
98
+ let lowerTimeBound;
99
+ let upperTimeBound;
100
+ if (effectiveMaxPriorityFee.lt(lowMaxPriorityFeeInWEI)) {
101
+ lowerTimeBound = null;
102
+ upperTimeBound = "unknown";
103
+ } else if (effectiveMaxPriorityFee.gte(lowMaxPriorityFeeInWEI) && effectiveMaxPriorityFee.lt(mediumMaxPriorityFeeInWEI)) {
104
+ lowerTimeBound = low.minWaitTimeEstimate;
105
+ upperTimeBound = low.maxWaitTimeEstimate;
106
+ } else if (effectiveMaxPriorityFee.gte(mediumMaxPriorityFeeInWEI) && effectiveMaxPriorityFee.lt(highMaxPriorityFeeInWEI)) {
107
+ lowerTimeBound = medium.minWaitTimeEstimate;
108
+ upperTimeBound = medium.maxWaitTimeEstimate;
109
+ } else if (effectiveMaxPriorityFee.eq(highMaxPriorityFeeInWEI)) {
110
+ lowerTimeBound = high.minWaitTimeEstimate;
111
+ upperTimeBound = high.maxWaitTimeEstimate;
112
+ } else {
113
+ lowerTimeBound = 0;
114
+ upperTimeBound = high.maxWaitTimeEstimate;
115
+ }
116
+ return {
117
+ lowerTimeBound,
118
+ upperTimeBound
119
+ };
120
+ }
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+ exports.normalizeGWEIDecimalNumbers = normalizeGWEIDecimalNumbers; exports.fetchGasEstimates = fetchGasEstimates; exports.fetchLegacyGasPriceEstimates = fetchLegacyGasPriceEstimates; exports.fetchEthGasPriceEstimate = fetchEthGasPriceEstimate; exports.calculateTimeEstimate = calculateTimeEstimate;
129
+ //# sourceMappingURL=chunk-F46NZXRQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gas-util.ts"],"names":[],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,OAAO,QAAQ;AAUf,IAAM,qBAAqB,CAAC,cAAsB,EAAE,eAAe,SAAS;AAQrE,SAAS,4BAA4B,GAAoB;AAC9D,QAAM,iBAAiB,eAAe,CAAC,EAAE,SAAS,EAAE;AACpD,QAAM,eAAe,gBAAgB,cAAc;AACnD,SAAO;AACT;AASA,eAAsB,kBACpB,KACA,UAC0B;AAC1B,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA,WAAW,EAAE,SAAS,mBAAmB,QAAQ,EAAE,IAAI;AAAA,EACzD;AACA,SAAO;AAAA,IACL,KAAK;AAAA,MACH,GAAG,UAAU;AAAA,MACb,+BAA+B;AAAA,QAC7B,UAAU,IAAI;AAAA,MAChB;AAAA,MACA,uBAAuB;AAAA,QACrB,UAAU,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,GAAG,UAAU;AAAA,MACb,+BAA+B;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,qBAAqB;AAAA,EAC7C;AAEA,QAAM,yBAAyB;AAAA,IAC7B,IAAI;AAAA,EACN;AACA,QAAM,4BAA4B;AAAA,IAChC,OAAO;AAAA,EACT;AACA,QAAM,0BAA0B;AAAA,IAC9B,KAAK;AAAA,EACP;AAEA,MAAI;AACJ,MAAI;AAEJ,MAAI,wBAAwB,GAAG,sBAAsB,GAAG;AACtD,qBAAiB;AACjB,qBAAiB;AAAA,EACnB,WACE,wBAAwB,IAAI,sBAAsB,KAClD,wBAAwB,GAAG,yBAAyB,GACpD;AACA,qBAAiB,IAAI;AACrB,qBAAiB,IAAI;AAAA,EACvB,WACE,wBAAwB,IAAI,yBAAyB,KACrD,wBAAwB,GAAG,uBAAuB,GAClD;AACA,qBAAiB,OAAO;AACxB,qBAAiB,OAAO;AAAA,EAC1B,WAAW,wBAAwB,GAAG,uBAAuB,GAAG;AAC9D,qBAAiB,KAAK;AACtB,qBAAiB,KAAK;AAAA,EACxB,OAAO;AACL,qBAAiB;AACjB,qBAAiB,KAAK;AAAA,EACxB;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF","sourcesContent":["import {\n query,\n handleFetch,\n gweiDecToWEIBN,\n weiHexToGweiDec,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport BN from 'bn.js';\n\nimport type {\n GasFeeEstimates,\n EthGasPriceEstimate,\n EstimatedGasFeeTimeBounds,\n unknownString,\n LegacyGasPriceEstimate,\n} from './GasFeeController';\n\nconst makeClientIdHeader = (clientId: string) => ({ 'X-Client-Id': clientId });\n\n/**\n * Convert a decimal GWEI value to a decimal string rounded to the nearest WEI.\n *\n * @param n - The input GWEI amount, as a decimal string or a number.\n * @returns The decimal string GWEI amount.\n */\nexport function normalizeGWEIDecimalNumbers(n: string | number) {\n const numberAsWEIHex = gweiDecToWEIBN(n).toString(16);\n const numberAsGWEI = weiHexToGweiDec(numberAsWEIHex);\n return numberAsGWEI;\n}\n\n/**\n * Fetch gas estimates from the given URL.\n *\n * @param url - The gas estimate URL.\n * @param clientId - The client ID used to identify to the API who is asking for estimates.\n * @returns The gas estimates.\n */\nexport async function fetchGasEstimates(\n url: string,\n clientId?: string,\n): Promise<GasFeeEstimates> {\n const estimates = await handleFetch(\n url,\n clientId ? { headers: makeClientIdHeader(clientId) } : undefined,\n );\n return {\n low: {\n ...estimates.low,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.low.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.low.suggestedMaxFeePerGas,\n ),\n },\n medium: {\n ...estimates.medium,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.medium.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.medium.suggestedMaxFeePerGas,\n ),\n },\n high: {\n ...estimates.high,\n suggestedMaxPriorityFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.high.suggestedMaxPriorityFeePerGas,\n ),\n suggestedMaxFeePerGas: normalizeGWEIDecimalNumbers(\n estimates.high.suggestedMaxFeePerGas,\n ),\n },\n estimatedBaseFee: normalizeGWEIDecimalNumbers(estimates.estimatedBaseFee),\n historicalBaseFeeRange: estimates.historicalBaseFeeRange,\n baseFeeTrend: estimates.baseFeeTrend,\n latestPriorityFeeRange: estimates.latestPriorityFeeRange,\n historicalPriorityFeeRange: estimates.historicalPriorityFeeRange,\n priorityFeeTrend: estimates.priorityFeeTrend,\n networkCongestion: estimates.networkCongestion,\n };\n}\n\n/**\n * Hit the legacy MetaSwaps gasPrices estimate api and return the low, medium\n * high values from that API.\n *\n * @param url - The URL to fetch gas price estimates from.\n * @param clientId - The client ID used to identify to the API who is asking for estimates.\n * @returns The gas price estimates.\n */\nexport async function fetchLegacyGasPriceEstimates(\n url: string,\n clientId?: string,\n): Promise<LegacyGasPriceEstimate> {\n const result = await handleFetch(url, {\n referrer: url,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && makeClientIdHeader(clientId)),\n },\n });\n return {\n low: result.SafeGasPrice,\n medium: result.ProposeGasPrice,\n high: result.FastGasPrice,\n };\n}\n\n/**\n * Get a gas price estimate from the network using the `eth_gasPrice` method.\n *\n * @param ethQuery - The EthQuery instance to call the network with.\n * @returns A gas price estimate.\n */\nexport async function fetchEthGasPriceEstimate(\n ethQuery: EthQuery,\n): Promise<EthGasPriceEstimate> {\n const gasPrice = await query(ethQuery, 'gasPrice');\n return {\n gasPrice: weiHexToGweiDec(gasPrice).toString(),\n };\n}\n\n/**\n * Estimate the time it will take for a transaction to be confirmed.\n *\n * @param maxPriorityFeePerGas - The max priority fee per gas.\n * @param maxFeePerGas - The max fee per gas.\n * @param gasFeeEstimates - The gas fee estimates.\n * @returns The estimated lower and upper bounds for when this transaction will be confirmed.\n */\nexport function calculateTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n gasFeeEstimates: GasFeeEstimates,\n): EstimatedGasFeeTimeBounds {\n const { low, medium, high, estimatedBaseFee } = gasFeeEstimates;\n\n const maxPriorityFeePerGasInWEI = gweiDecToWEIBN(maxPriorityFeePerGas);\n const maxFeePerGasInWEI = gweiDecToWEIBN(maxFeePerGas);\n const estimatedBaseFeeInWEI = gweiDecToWEIBN(estimatedBaseFee);\n\n const effectiveMaxPriorityFee = BN.min(\n maxPriorityFeePerGasInWEI,\n maxFeePerGasInWEI.sub(estimatedBaseFeeInWEI),\n );\n\n const lowMaxPriorityFeeInWEI = gweiDecToWEIBN(\n low.suggestedMaxPriorityFeePerGas,\n );\n const mediumMaxPriorityFeeInWEI = gweiDecToWEIBN(\n medium.suggestedMaxPriorityFeePerGas,\n );\n const highMaxPriorityFeeInWEI = gweiDecToWEIBN(\n high.suggestedMaxPriorityFeePerGas,\n );\n\n let lowerTimeBound;\n let upperTimeBound;\n\n if (effectiveMaxPriorityFee.lt(lowMaxPriorityFeeInWEI)) {\n lowerTimeBound = null;\n upperTimeBound = 'unknown' as unknownString;\n } else if (\n effectiveMaxPriorityFee.gte(lowMaxPriorityFeeInWEI) &&\n effectiveMaxPriorityFee.lt(mediumMaxPriorityFeeInWEI)\n ) {\n lowerTimeBound = low.minWaitTimeEstimate;\n upperTimeBound = low.maxWaitTimeEstimate;\n } else if (\n effectiveMaxPriorityFee.gte(mediumMaxPriorityFeeInWEI) &&\n effectiveMaxPriorityFee.lt(highMaxPriorityFeeInWEI)\n ) {\n lowerTimeBound = medium.minWaitTimeEstimate;\n upperTimeBound = medium.maxWaitTimeEstimate;\n } else if (effectiveMaxPriorityFee.eq(highMaxPriorityFeeInWEI)) {\n lowerTimeBound = high.minWaitTimeEstimate;\n upperTimeBound = high.maxWaitTimeEstimate;\n } else {\n lowerTimeBound = 0;\n upperTimeBound = high.maxWaitTimeEstimate;\n }\n\n return {\n lowerTimeBound,\n upperTimeBound,\n };\n}\n"]}
@@ -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