@metamask/gas-fee-controller 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/GasFeeController.d.ts +229 -0
  5. package/dist/GasFeeController.js +264 -0
  6. package/dist/GasFeeController.js.map +1 -0
  7. package/dist/determineGasFeeCalculations.d.ts +40 -0
  8. package/dist/determineGasFeeCalculations.js +87 -0
  9. package/dist/determineGasFeeCalculations.js.map +1 -0
  10. package/dist/fetchBlockFeeHistory.d.ts +115 -0
  11. package/dist/fetchBlockFeeHistory.js +202 -0
  12. package/dist/fetchBlockFeeHistory.js.map +1 -0
  13. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.d.ts +16 -0
  14. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js +89 -0
  15. package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map +1 -0
  16. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.d.ts +10 -0
  17. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js +32 -0
  18. package/dist/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.js.map +1 -0
  19. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts +10 -0
  20. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js +17 -0
  21. package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js.map +1 -0
  22. package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts +10 -0
  23. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js +3 -0
  24. package/dist/fetchGasEstimatesViaEthFeeHistory/types.js.map +1 -0
  25. package/dist/fetchGasEstimatesViaEthFeeHistory.d.ts +21 -0
  26. package/dist/fetchGasEstimatesViaEthFeeHistory.js +53 -0
  27. package/dist/fetchGasEstimatesViaEthFeeHistory.js.map +1 -0
  28. package/dist/gas-util.d.ts +41 -0
  29. package/dist/gas-util.js +140 -0
  30. package/dist/gas-util.js.map +1 -0
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +18 -0
  33. package/dist/index.js.map +1 -0
  34. package/package.json +64 -0
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const GasFeeController_1 = require("./GasFeeController");
13
+ /**
14
+ * Obtains a set of max base and priority fee estimates along with time estimates so that we
15
+ * can present them to users when they are sending transactions or making swaps.
16
+ *
17
+ * @param args - The arguments.
18
+ * @param args.isEIP1559Compatible - Governs whether or not we can use an EIP-1559-only method to
19
+ * produce estimates.
20
+ * @param args.isLegacyGasAPICompatible - Governs whether or not we can use a non-EIP-1559 method to
21
+ * produce estimates (for instance, testnets do not support estimates altogether).
22
+ * @param args.fetchGasEstimates - A function that fetches gas estimates using an EIP-1559-specific
23
+ * API.
24
+ * @param args.fetchGasEstimatesUrl - The URL for the API we can use to obtain EIP-1559-specific
25
+ * estimates.
26
+ * @param args.fetchGasEstimatesViaEthFeeHistory - A function that fetches gas estimates using
27
+ * `eth_feeHistory` (an EIP-1559 feature).
28
+ * @param args.fetchLegacyGasPriceEstimates - A function that fetches gas estimates using an
29
+ * non-EIP-1559-specific API.
30
+ * @param args.fetchLegacyGasPriceEstimatesUrl - The URL for the API we can use to obtain
31
+ * non-EIP-1559-specific estimates.
32
+ * @param args.fetchEthGasPriceEstimate - A function that fetches gas estimates using
33
+ * `eth_gasPrice`.
34
+ * @param args.calculateTimeEstimate - A function that determine time estimate bounds.
35
+ * @param args.clientId - An identifier that an API can use to know who is asking for estimates.
36
+ * @param args.ethQuery - An EthQuery instance we can use to talk to Ethereum directly.
37
+ * @returns The gas fee calculations.
38
+ */
39
+ function determineGasFeeCalculations({ isEIP1559Compatible, isLegacyGasAPICompatible, fetchGasEstimates, fetchGasEstimatesUrl, fetchGasEstimatesViaEthFeeHistory, fetchLegacyGasPriceEstimates, fetchLegacyGasPriceEstimatesUrl, fetchEthGasPriceEstimate, calculateTimeEstimate, clientId, ethQuery, }) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ try {
42
+ if (isEIP1559Compatible) {
43
+ let estimates;
44
+ try {
45
+ estimates = yield fetchGasEstimates(fetchGasEstimatesUrl, clientId);
46
+ }
47
+ catch (_a) {
48
+ estimates = yield fetchGasEstimatesViaEthFeeHistory(ethQuery);
49
+ }
50
+ const { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = estimates.medium;
51
+ const estimatedGasFeeTimeBounds = calculateTimeEstimate(suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas, estimates);
52
+ return {
53
+ gasFeeEstimates: estimates,
54
+ estimatedGasFeeTimeBounds,
55
+ gasEstimateType: GasFeeController_1.GAS_ESTIMATE_TYPES.FEE_MARKET,
56
+ };
57
+ }
58
+ else if (isLegacyGasAPICompatible) {
59
+ const estimates = yield fetchLegacyGasPriceEstimates(fetchLegacyGasPriceEstimatesUrl, clientId);
60
+ return {
61
+ gasFeeEstimates: estimates,
62
+ estimatedGasFeeTimeBounds: {},
63
+ gasEstimateType: GasFeeController_1.GAS_ESTIMATE_TYPES.LEGACY,
64
+ };
65
+ }
66
+ throw new Error('Main gas fee/price estimation failed. Use fallback');
67
+ }
68
+ catch (_b) {
69
+ try {
70
+ const estimates = yield fetchEthGasPriceEstimate(ethQuery);
71
+ return {
72
+ gasFeeEstimates: estimates,
73
+ estimatedGasFeeTimeBounds: {},
74
+ gasEstimateType: GasFeeController_1.GAS_ESTIMATE_TYPES.ETH_GASPRICE,
75
+ };
76
+ }
77
+ catch (error) {
78
+ if (error instanceof Error) {
79
+ throw new Error(`Gas fee/price estimation failed. Message: ${error.message}`);
80
+ }
81
+ throw error;
82
+ }
83
+ }
84
+ });
85
+ }
86
+ exports.default = determineGasFeeCalculations;
87
+ //# sourceMappingURL=determineGasFeeCalculations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"determineGasFeeCalculations.js","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,yDAO4B;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,SAA8B,2BAA2B,CAAC,EACxD,mBAAmB,EACnB,wBAAwB,EACxB,iBAAiB,EACjB,oBAAoB,EACpB,iCAAiC,EACjC,4BAA4B,EAC5B,+BAA+B,EAC/B,wBAAwB,EACxB,qBAAqB,EACrB,QAAQ,EACR,QAAQ,GAyBT;;QACC,IAAI;YACF,IAAI,mBAAmB,EAAE;gBACvB,IAAI,SAA0B,CAAC;gBAC/B,IAAI;oBACF,SAAS,GAAG,MAAM,iBAAiB,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAC;iBACrE;gBAAC,WAAM;oBACN,SAAS,GAAG,MAAM,iCAAiC,CAAC,QAAQ,CAAC,CAAC;iBAC/D;gBACD,MAAM,EAAE,6BAA6B,EAAE,qBAAqB,EAAE,GAC5D,SAAS,CAAC,MAAM,CAAC;gBACnB,MAAM,yBAAyB,GAAG,qBAAqB,CACrD,6BAA6B,EAC7B,qBAAqB,EACrB,SAAS,CACV,CAAC;gBACF,OAAO;oBACL,eAAe,EAAE,SAAS;oBAC1B,yBAAyB;oBACzB,eAAe,EAAE,qCAAkB,CAAC,UAAU;iBAC/C,CAAC;aACH;iBAAM,IAAI,wBAAwB,EAAE;gBACnC,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAClD,+BAA+B,EAC/B,QAAQ,CACT,CAAC;gBACF,OAAO;oBACL,eAAe,EAAE,SAAS;oBAC1B,yBAAyB,EAAE,EAAE;oBAC7B,eAAe,EAAE,qCAAkB,CAAC,MAAM;iBAC3C,CAAC;aACH;YACD,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QAAC,WAAM;YACN,IAAI;gBACF,MAAM,SAAS,GAAG,MAAM,wBAAwB,CAAC,QAAQ,CAAC,CAAC;gBAC3D,OAAO;oBACL,eAAe,EAAE,SAAS;oBAC1B,yBAAyB,EAAE,EAAE;oBAC7B,eAAe,EAAE,qCAAkB,CAAC,YAAY;iBACjD,CAAC;aACH;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,KAAK,YAAY,KAAK,EAAE;oBAC1B,MAAM,IAAI,KAAK,CACb,6CAA6C,KAAK,CAAC,OAAO,EAAE,CAC7D,CAAC;iBACH;gBACD,MAAM,KAAK,CAAC;aACb;SACF;IACH,CAAC;CAAA;AAtFD,8CAsFC","sourcesContent":["import {\n GAS_ESTIMATE_TYPES,\n EstimatedGasFeeTimeBounds,\n EthGasPriceEstimate,\n GasFeeEstimates,\n GasFeeState as GasFeeCalculations,\n LegacyGasPriceEstimate,\n} 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 * @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}: {\n isEIP1559Compatible: boolean;\n isLegacyGasAPICompatible: boolean;\n fetchGasEstimates: (\n url: string,\n clientId?: string,\n ) => Promise<GasFeeEstimates>;\n fetchGasEstimatesUrl: string;\n fetchGasEstimatesViaEthFeeHistory: (\n ethQuery: any,\n ) => Promise<GasFeeEstimates>;\n fetchLegacyGasPriceEstimates: (\n url: string,\n clientId?: string,\n ) => Promise<LegacyGasPriceEstimate>;\n fetchLegacyGasPriceEstimatesUrl: string;\n fetchEthGasPriceEstimate: (ethQuery: any) => Promise<EthGasPriceEstimate>;\n calculateTimeEstimate: (\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n gasFeeEstimates: GasFeeEstimates,\n ) => EstimatedGasFeeTimeBounds;\n clientId: string | undefined;\n ethQuery: any;\n}): Promise<GasFeeCalculations> {\n try {\n if (isEIP1559Compatible) {\n let estimates: GasFeeEstimates;\n try {\n estimates = await fetchGasEstimates(fetchGasEstimatesUrl, clientId);\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 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"]}
@@ -0,0 +1,115 @@
1
+ /// <reference types="bn.js" />
2
+ import { BN } from 'ethereumjs-util';
3
+ declare type EthQuery = any;
4
+ /**
5
+ * @type EthFeeHistoryResponse
6
+ *
7
+ * Response data for `eth_feeHistory`.
8
+ * @property oldestBlock - The id of the oldest block (in hex format) in the range of blocks
9
+ * requested.
10
+ * @property baseFeePerGas - Base fee per gas for each block in the range of blocks requested.
11
+ * For go-ethereum based chains baseFeePerGas will not returned in case of empty results
12
+ * <github.com/ethereum/go-ethereum/blob/v1.10.16/internal/ethapi/api.go#L87>
13
+ * @property gasUsedRatio - A number between 0 and 1 that represents the gas used vs. gas limit for
14
+ * each block in the range of blocks requested.
15
+ * @property reward - The priority fee at the percentiles requested for each block in the range of
16
+ * blocks requested.
17
+ */
18
+ export declare type EthFeeHistoryResponse = {
19
+ oldestBlock: string;
20
+ baseFeePerGas?: string[];
21
+ gasUsedRatio: number[];
22
+ reward?: string[][];
23
+ };
24
+ /**
25
+ * @type ExistingFeeHistoryBlock
26
+ *
27
+ * Historical data for a particular block that exists on the blockchain.
28
+ * @property number - The number of the block, as a BN.
29
+ * @property baseFeePerGas - The base fee per gas for the block in WEI, as a BN.
30
+ * @property gasUsedRatio - A number between 0 and 1 that represents the ratio between the gas paid
31
+ * for the block and its set gas limit.
32
+ * @property priorityFeesByPercentile - The priority fees paid for the transactions in the block
33
+ * that occurred at particular levels at which those transactions contributed to the overall gas
34
+ * used for the block, indexed by those percentiles. (See docs for {@link fetchBlockFeeHistory} for more
35
+ * on how this works.)
36
+ */
37
+ declare type ExistingFeeHistoryBlock<Percentile extends number> = {
38
+ number: BN;
39
+ baseFeePerGas: BN;
40
+ gasUsedRatio: number;
41
+ priorityFeesByPercentile: Record<Percentile, BN>;
42
+ };
43
+ /**
44
+ * @type NextFeeHistoryBlock
45
+ *
46
+ * Historical data for a theoretical block that could exist in the future.
47
+ * @property number - The number of the block, as a BN.
48
+ * @property baseFeePerGas - The estimated base fee per gas for the block in WEI, as a BN.
49
+ */
50
+ declare type NextFeeHistoryBlock = {
51
+ number: BN;
52
+ baseFeePerGas: BN;
53
+ };
54
+ /**
55
+ * @type FeeHistoryBlock
56
+ *
57
+ * Historical data for a particular block.
58
+ * @property number - The number of the block, as a BN.
59
+ * @property baseFeePerGas - The base fee per gas for the block in WEI, as a BN.
60
+ * @property gasUsedRatio - A number between 0 and 1 that represents the ratio between the gas paid
61
+ * for the block and its set gas limit.
62
+ * @property priorityFeesByPercentile - The priority fees paid for the transactions in the block
63
+ * that occurred at particular levels at which those transactions contributed to the overall gas
64
+ * used for the block, indexed by those percentiles. (See docs for {@link fetchBlockFeeHistory} for more
65
+ * on how this works.)
66
+ */
67
+ export declare type FeeHistoryBlock<Percentile extends number> = ExistingFeeHistoryBlock<Percentile> | NextFeeHistoryBlock;
68
+ /**
69
+ * @type ExtractPercentileFrom
70
+ *
71
+ * Extracts the percentiles that the type assigned to an array of FeeHistoryBlock has been created
72
+ * with. This makes use of the `infer` keyword to read the type argument.
73
+ */
74
+ export declare type ExtractPercentileFrom<T> = T extends FeeHistoryBlock<infer P>[] ? P : never;
75
+ /**
76
+ * Uses `eth_feeHistory` (an EIP-1559 feature) to obtain information about gas fees from a range of
77
+ * blocks that have occurred recently on a network.
78
+ *
79
+ * To learn more, see these resources:
80
+ *
81
+ * - <https://infura.io/docs/ethereum#operation/eth_feeHistory>
82
+ * - <https://github.com/zsfelfoldi/feehistory/blob/main/docs/feeHistory.md>
83
+ * - <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L180>
84
+ * - <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md>
85
+ * - <https://gas-api.metaswap.codefi.network/testFeeHistory>
86
+ *
87
+ * @param args - The arguments to this function.
88
+ * @param args.ethQuery - An EthQuery instance that wraps a provider for the network in question.
89
+ * @param args.endBlock - The desired end of the requested block range. Can be "latest" if you want
90
+ * to start from the latest successful block or the number of a known past block.
91
+ * @param args.numberOfBlocks - How many total blocks to fetch. Note that if this is more than 1024,
92
+ * multiple calls to `eth_feeHistory` will be made.
93
+ * @param args.percentiles - A set of numbers between 1 and 100 which will dictate how
94
+ * `priorityFeesByPercentile` in each returned block will be formed. When Ethereum runs the
95
+ * `eth_feeHistory` method, for each block it is considering, it will first sort all transactions by
96
+ * the priority fee. It will then go through each transaction and add the total amount of gas paid
97
+ * for that transaction to a bucket which maxes out at the total gas used for the whole block. As
98
+ * the bucket fills, it will cross percentages which correspond to the percentiles specified here,
99
+ * and the priority fees of the first transactions which cause it to reach those percentages will be
100
+ * recorded. Hence, `priorityFeesByPercentile` represents the priority fees of transactions at key
101
+ * gas used contribution levels, where earlier levels have smaller contributions and later levels
102
+ * have higher contributions.
103
+ * @param args.includeNextBlock - Whether to include an extra block that represents the next
104
+ * block after the latest one. Only the `baseFeePerGas` will be filled in for this block (which is
105
+ * estimated).
106
+ * @returns The list of blocks and their fee data, sorted from oldest to newest.
107
+ */
108
+ export default function fetchBlockFeeHistory<Percentile extends number>({ ethQuery, numberOfBlocks: totalNumberOfBlocks, endBlock: givenEndBlock, percentiles: givenPercentiles, includeNextBlock, }: {
109
+ ethQuery: EthQuery;
110
+ numberOfBlocks: number;
111
+ endBlock?: 'latest' | BN;
112
+ percentiles?: readonly Percentile[];
113
+ includeNextBlock?: boolean;
114
+ }): Promise<FeeHistoryBlock<Percentile>[]>;
115
+ export {};
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const ethereumjs_util_1 = require("ethereumjs-util");
13
+ const controller_utils_1 = require("@metamask/controller-utils");
14
+ const MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL = 1024;
15
+ /**
16
+ * Uses `eth_feeHistory` (an EIP-1559 feature) to obtain information about gas fees from a range of
17
+ * blocks that have occurred recently on a network.
18
+ *
19
+ * To learn more, see these resources:
20
+ *
21
+ * - <https://infura.io/docs/ethereum#operation/eth_feeHistory>
22
+ * - <https://github.com/zsfelfoldi/feehistory/blob/main/docs/feeHistory.md>
23
+ * - <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L180>
24
+ * - <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md>
25
+ * - <https://gas-api.metaswap.codefi.network/testFeeHistory>
26
+ *
27
+ * @param args - The arguments to this function.
28
+ * @param args.ethQuery - An EthQuery instance that wraps a provider for the network in question.
29
+ * @param args.endBlock - The desired end of the requested block range. Can be "latest" if you want
30
+ * to start from the latest successful block or the number of a known past block.
31
+ * @param args.numberOfBlocks - How many total blocks to fetch. Note that if this is more than 1024,
32
+ * multiple calls to `eth_feeHistory` will be made.
33
+ * @param args.percentiles - A set of numbers between 1 and 100 which will dictate how
34
+ * `priorityFeesByPercentile` in each returned block will be formed. When Ethereum runs the
35
+ * `eth_feeHistory` method, for each block it is considering, it will first sort all transactions by
36
+ * the priority fee. It will then go through each transaction and add the total amount of gas paid
37
+ * for that transaction to a bucket which maxes out at the total gas used for the whole block. As
38
+ * the bucket fills, it will cross percentages which correspond to the percentiles specified here,
39
+ * and the priority fees of the first transactions which cause it to reach those percentages will be
40
+ * recorded. Hence, `priorityFeesByPercentile` represents the priority fees of transactions at key
41
+ * gas used contribution levels, where earlier levels have smaller contributions and later levels
42
+ * have higher contributions.
43
+ * @param args.includeNextBlock - Whether to include an extra block that represents the next
44
+ * block after the latest one. Only the `baseFeePerGas` will be filled in for this block (which is
45
+ * estimated).
46
+ * @returns The list of blocks and their fee data, sorted from oldest to newest.
47
+ */
48
+ function fetchBlockFeeHistory({ ethQuery, numberOfBlocks: totalNumberOfBlocks, endBlock: givenEndBlock = 'latest', percentiles: givenPercentiles = [], includeNextBlock = false, }) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ const percentiles = givenPercentiles.length > 0
51
+ ? Array.from(new Set(givenPercentiles)).sort((a, b) => a - b)
52
+ : [];
53
+ const finalEndBlockNumber = givenEndBlock === 'latest'
54
+ ? (0, controller_utils_1.fromHex)(yield (0, controller_utils_1.query)(ethQuery, 'blockNumber'))
55
+ : givenEndBlock;
56
+ const requestChunkSpecifiers = determineRequestChunkSpecifiers(finalEndBlockNumber, totalNumberOfBlocks);
57
+ const blockChunks = yield Promise.all(requestChunkSpecifiers.map(({ numberOfBlocks, endBlockNumber }, i) => {
58
+ return i === requestChunkSpecifiers.length - 1
59
+ ? makeRequestForChunk({
60
+ ethQuery,
61
+ numberOfBlocks,
62
+ endBlockNumber,
63
+ percentiles,
64
+ includeNextBlock,
65
+ })
66
+ : makeRequestForChunk({
67
+ ethQuery,
68
+ numberOfBlocks,
69
+ endBlockNumber,
70
+ percentiles,
71
+ includeNextBlock: false,
72
+ });
73
+ }));
74
+ return blockChunks.reduce((array, blocks) => [...array, ...blocks], []);
75
+ });
76
+ }
77
+ exports.default = fetchBlockFeeHistory;
78
+ /**
79
+ * Builds an ExistingFeeHistoryBlock.
80
+ *
81
+ * @param args - The args to this function.
82
+ * @param args.number - The number of the block.
83
+ * @param args.baseFeePerGas - The base fee per gas of the block.
84
+ * @param args.blockIndex - The index of the block in the source chunk.
85
+ * @param args.gasUsedRatios - The gas used ratios for the block.
86
+ * @param args.priorityFeePercentileGroups - The priority fee percentile groups for the block.
87
+ * @param args.percentiles - The percentiles used to fetch the source chunk.
88
+ * @returns The ExistingFeeHistoryBlock.
89
+ */
90
+ function buildExistingFeeHistoryBlock({ baseFeePerGas, number, blockIndex, gasUsedRatios, priorityFeePercentileGroups, percentiles, }) {
91
+ const gasUsedRatio = gasUsedRatios[blockIndex];
92
+ const priorityFeesForEachPercentile = priorityFeePercentileGroups[blockIndex];
93
+ const priorityFeesByPercentile = percentiles.reduce((obj, percentile, percentileIndex) => {
94
+ const priorityFee = priorityFeesForEachPercentile[percentileIndex];
95
+ return Object.assign(Object.assign({}, obj), { [percentile]: (0, controller_utils_1.fromHex)(priorityFee) });
96
+ }, {});
97
+ return {
98
+ number,
99
+ baseFeePerGas,
100
+ gasUsedRatio,
101
+ priorityFeesByPercentile,
102
+ };
103
+ }
104
+ /**
105
+ * Builds a NextFeeHistoryBlock.
106
+ *
107
+ * @param args - The args to this function.
108
+ * @param args.baseFeePerGas - The base fee per gas of the block.
109
+ * @param args.number - The number of the block.
110
+ * @returns The NextFeeHistoryBlock.
111
+ */
112
+ function buildNextFeeHistoryBlock({ baseFeePerGas, number, }) {
113
+ return {
114
+ number,
115
+ baseFeePerGas,
116
+ gasUsedRatio: null,
117
+ priorityFeesByPercentile: null,
118
+ };
119
+ }
120
+ /**
121
+ * Uses eth_feeHistory to request historical data about a group of blocks (max size 1024).
122
+ *
123
+ * @param args - The arguments
124
+ * @param args.ethQuery - An EthQuery instance.
125
+ * @param args.numberOfBlocks - The number of blocks in the chunk. Must be at most 1024, as this is
126
+ * the maximum that `eth_feeHistory` can return in one call.
127
+ * @param args.endBlockNumber - The end of the requested block range.
128
+ * @param args.percentiles - A set of numbers between 1 and 100 that will be used to pull priority
129
+ * fees for each block.
130
+ * @param args.includeNextBlock - Whether to include an extra block that represents the next
131
+ * block after the latest one. Only the `baseFeePerGas` will be filled in for this block (which is
132
+ * estimated).
133
+ * @returns A list of block data.
134
+ */
135
+ function makeRequestForChunk({ ethQuery, numberOfBlocks, endBlockNumber, percentiles, includeNextBlock, }) {
136
+ var _a;
137
+ return __awaiter(this, void 0, void 0, function* () {
138
+ const response = yield (0, controller_utils_1.query)(ethQuery, 'eth_feeHistory', [(0, controller_utils_1.toHex)(numberOfBlocks), (0, controller_utils_1.toHex)(endBlockNumber), percentiles]);
139
+ const startBlockNumber = (0, controller_utils_1.fromHex)(response.oldestBlock);
140
+ if (response.baseFeePerGas !== undefined &&
141
+ response.baseFeePerGas.length > 0 &&
142
+ response.gasUsedRatio.length > 0 &&
143
+ (response.reward === undefined || response.reward.length > 0)) {
144
+ // Per
145
+ // <https://github.com/ethereum/go-ethereum/blob/57a3fab8a75eeb9c2f4fab770b73b51b9fe672c5/eth/gasprice/feehistory.go#L191-L192>,
146
+ // baseFeePerGas will always include an extra item which is the calculated base fee for the
147
+ // next (future) block. We may or may not care about this; if we don't, chop it off.
148
+ const baseFeesPerGasAsHex = includeNextBlock
149
+ ? response.baseFeePerGas
150
+ : response.baseFeePerGas.slice(0, numberOfBlocks);
151
+ const gasUsedRatios = response.gasUsedRatio;
152
+ const priorityFeePercentileGroups = (_a = response.reward) !== null && _a !== void 0 ? _a : [];
153
+ // Chain is allowed to return fewer number of block results
154
+ const numberOfExistingResults = gasUsedRatios.length;
155
+ return baseFeesPerGasAsHex.map((baseFeePerGasAsHex, blockIndex) => {
156
+ const baseFeePerGas = (0, controller_utils_1.fromHex)(baseFeePerGasAsHex);
157
+ const number = startBlockNumber.addn(blockIndex);
158
+ return blockIndex >= numberOfExistingResults
159
+ ? buildNextFeeHistoryBlock({ baseFeePerGas, number })
160
+ : buildExistingFeeHistoryBlock({
161
+ baseFeePerGas,
162
+ number,
163
+ blockIndex,
164
+ gasUsedRatios,
165
+ priorityFeePercentileGroups,
166
+ percentiles,
167
+ });
168
+ });
169
+ }
170
+ return [];
171
+ });
172
+ }
173
+ /**
174
+ * Divides a block range (specified by a range size and the end of the range) into chunks based on
175
+ * the maximum number of blocks that `eth_feeHistory` can return in a single call.
176
+ *
177
+ * If the requested totalNumberOfBlocks exceed endBlockNumber, totalNumberOfBlocks is
178
+ * truncated to avoid requesting chunks with negative endBlockNumber.
179
+ *
180
+ * @param endBlockNumber - The final block in the complete desired block range after all
181
+ * `eth_feeHistory` requests have been made.
182
+ * @param totalNumberOfBlocks - The total number of desired blocks after all `eth_feeHistory`
183
+ * requests have been made.
184
+ * @returns A set of arguments that can be used to make requests to `eth_feeHistory` in order to
185
+ * retrieve all of the requested blocks, sorted from oldest block to newest block.
186
+ */
187
+ function determineRequestChunkSpecifiers(endBlockNumber, totalNumberOfBlocks) {
188
+ if (endBlockNumber.lt(new ethereumjs_util_1.BN(totalNumberOfBlocks))) {
189
+ totalNumberOfBlocks = endBlockNumber.toNumber();
190
+ }
191
+ const specifiers = [];
192
+ for (let chunkStartBlockNumber = endBlockNumber.subn(totalNumberOfBlocks); chunkStartBlockNumber.lt(endBlockNumber); chunkStartBlockNumber = chunkStartBlockNumber.addn(MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL)) {
193
+ const distanceToEnd = endBlockNumber.sub(chunkStartBlockNumber).toNumber();
194
+ const numberOfBlocks = distanceToEnd < MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL
195
+ ? distanceToEnd
196
+ : MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL;
197
+ const chunkEndBlockNumber = chunkStartBlockNumber.addn(numberOfBlocks);
198
+ specifiers.push({ numberOfBlocks, endBlockNumber: chunkEndBlockNumber });
199
+ }
200
+ return specifiers;
201
+ }
202
+ //# sourceMappingURL=fetchBlockFeeHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchBlockFeeHistory.js","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,qDAAqC;AACrC,iEAAmE;AAiGnE,MAAM,6CAA6C,GAAG,IAAI,CAAC;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,SAA8B,oBAAoB,CAA4B,EAC5E,QAAQ,EACR,cAAc,EAAE,mBAAmB,EACnC,QAAQ,EAAE,aAAa,GAAG,QAAQ,EAClC,WAAW,EAAE,gBAAgB,GAAG,EAAE,EAClC,gBAAgB,GAAG,KAAK,GAOzB;;QACC,MAAM,WAAW,GACf,gBAAgB,CAAC,MAAM,GAAG,CAAC;YACzB,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;YAC7D,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,mBAAmB,GACvB,aAAa,KAAK,QAAQ;YACxB,CAAC,CAAC,IAAA,0BAAO,EAAC,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;YAC/C,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pD,MAAM,mBAAmB,GAAG,qBAAqB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACvE,UAAU,CAAC,IAAI,CAAC,EAAE,cAAc,EAAE,cAAc,EAAE,mBAAmB,EAAE,CAAC,CAAC;KAC1E;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { BN } from 'ethereumjs-util';\nimport { query, fromHex, toHex } from '@metamask/controller-utils';\n\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"]}
@@ -0,0 +1,16 @@
1
+ import { GasFeeEstimates } from '../GasFeeController';
2
+ import { FeeHistoryBlock } from '../fetchBlockFeeHistory';
3
+ export declare type PriorityLevel = typeof PRIORITY_LEVELS[number];
4
+ export declare type Percentile = typeof PRIORITY_LEVEL_PERCENTILES[number];
5
+ declare const PRIORITY_LEVELS: readonly ["low", "medium", "high"];
6
+ declare const PRIORITY_LEVEL_PERCENTILES: readonly [10, 20, 30];
7
+ /**
8
+ * Calculates a set of estimates suitable for different priority levels based on the data returned
9
+ * by `eth_feeHistory`.
10
+ *
11
+ * @param blocks - A set of blocks populated with data for priority fee percentiles 10, 20, and 30,
12
+ * obtained via {@link BlockFeeHistoryDatasetFetcher}.
13
+ * @returns The estimates.
14
+ */
15
+ export default function calculateGasFeeEstimatesForPriorityLevels(blocks: FeeHistoryBlock<Percentile>[]): Pick<GasFeeEstimates, PriorityLevel>;
16
+ export {};
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethereumjs_util_1 = require("ethereumjs-util");
7
+ const ethjs_unit_1 = require("ethjs-unit");
8
+ const controller_utils_1 = require("@metamask/controller-utils");
9
+ const medianOf_1 = __importDefault(require("./medianOf"));
10
+ const PRIORITY_LEVELS = ['low', 'medium', 'high'];
11
+ const PRIORITY_LEVEL_PERCENTILES = [10, 20, 30];
12
+ const SETTINGS_BY_PRIORITY_LEVEL = {
13
+ low: {
14
+ percentile: 10,
15
+ baseFeePercentageMultiplier: new ethereumjs_util_1.BN(110),
16
+ priorityFeePercentageMultiplier: new ethereumjs_util_1.BN(94),
17
+ minSuggestedMaxPriorityFeePerGas: new ethereumjs_util_1.BN(1000000000),
18
+ estimatedWaitTimes: {
19
+ minWaitTimeEstimate: 15000,
20
+ maxWaitTimeEstimate: 30000,
21
+ },
22
+ },
23
+ medium: {
24
+ percentile: 20,
25
+ baseFeePercentageMultiplier: new ethereumjs_util_1.BN(120),
26
+ priorityFeePercentageMultiplier: new ethereumjs_util_1.BN(97),
27
+ minSuggestedMaxPriorityFeePerGas: new ethereumjs_util_1.BN(1500000000),
28
+ estimatedWaitTimes: {
29
+ minWaitTimeEstimate: 15000,
30
+ maxWaitTimeEstimate: 45000,
31
+ },
32
+ },
33
+ high: {
34
+ percentile: 30,
35
+ baseFeePercentageMultiplier: new ethereumjs_util_1.BN(125),
36
+ priorityFeePercentageMultiplier: new ethereumjs_util_1.BN(98),
37
+ minSuggestedMaxPriorityFeePerGas: new ethereumjs_util_1.BN(2000000000),
38
+ estimatedWaitTimes: {
39
+ minWaitTimeEstimate: 15000,
40
+ maxWaitTimeEstimate: 60000,
41
+ },
42
+ },
43
+ };
44
+ /**
45
+ * Calculates a set of estimates assigned to a particular priority level based on the data returned
46
+ * by `eth_feeHistory`.
47
+ *
48
+ * @param priorityLevel - The level of fees that dictates how soon a transaction may go through
49
+ * ("low", "medium", or "high").
50
+ * @param blocks - A set of blocks as obtained from {@link fetchBlockFeeHistory}.
51
+ * @returns The estimates.
52
+ */
53
+ function calculateEstimatesForPriorityLevel(priorityLevel, blocks) {
54
+ const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];
55
+ const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;
56
+ const adjustedBaseFee = latestBaseFeePerGas
57
+ .mul(settings.baseFeePercentageMultiplier)
58
+ .divn(100);
59
+ const priorityFees = blocks
60
+ .map((block) => {
61
+ return 'priorityFeesByPercentile' in block
62
+ ? block.priorityFeesByPercentile[settings.percentile]
63
+ : null;
64
+ })
65
+ .filter(ethereumjs_util_1.BN.isBN);
66
+ const medianPriorityFee = (0, medianOf_1.default)(priorityFees);
67
+ const adjustedPriorityFee = medianPriorityFee
68
+ .mul(settings.priorityFeePercentageMultiplier)
69
+ .divn(100);
70
+ const suggestedMaxPriorityFeePerGas = ethereumjs_util_1.BN.max(adjustedPriorityFee, settings.minSuggestedMaxPriorityFeePerGas);
71
+ const suggestedMaxFeePerGas = adjustedBaseFee.add(suggestedMaxPriorityFeePerGas);
72
+ return Object.assign(Object.assign({}, settings.estimatedWaitTimes), { suggestedMaxPriorityFeePerGas: (0, ethjs_unit_1.fromWei)(suggestedMaxPriorityFeePerGas, controller_utils_1.GWEI), suggestedMaxFeePerGas: (0, ethjs_unit_1.fromWei)(suggestedMaxFeePerGas, controller_utils_1.GWEI) });
73
+ }
74
+ /**
75
+ * Calculates a set of estimates suitable for different priority levels based on the data returned
76
+ * by `eth_feeHistory`.
77
+ *
78
+ * @param blocks - A set of blocks populated with data for priority fee percentiles 10, 20, and 30,
79
+ * obtained via {@link BlockFeeHistoryDatasetFetcher}.
80
+ * @returns The estimates.
81
+ */
82
+ function calculateGasFeeEstimatesForPriorityLevels(blocks) {
83
+ return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {
84
+ const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(priorityLevel, blocks);
85
+ return Object.assign(Object.assign({}, obj), { [priorityLevel]: gasEstimatesForPriorityLevel });
86
+ }, {});
87
+ }
88
+ exports.default = calculateGasFeeEstimatesForPriorityLevels;
89
+ //# sourceMappingURL=calculateGasFeeEstimatesForPriorityLevels.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculateGasFeeEstimatesForPriorityLevels.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":";;;;;AAAA,qDAAqC;AACrC,2CAAqC;AACrC,iEAAkD;AAGlD,0DAAkC;AAKlC,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAC3D,MAAM,0BAA0B,GAAG,CAAC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nimport { GWEI } from '@metamask/controller-utils';\nimport { Eip1559GasFee, GasFeeEstimates } from '../GasFeeController';\nimport { FeeHistoryBlock } from '../fetchBlockFeeHistory';\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,10 @@
1
+ import { EthBlock, EthQuery } from './types';
2
+ /**
3
+ * Returns information about the latest completed block.
4
+ *
5
+ * @param ethQuery - An EthQuery instance
6
+ * @param includeFullTransactionData - Whether or not to include all data for transactions as
7
+ * opposed to merely hashes. False by default.
8
+ * @returns The block.
9
+ */
10
+ export default function fetchLatestBlock(ethQuery: EthQuery, includeFullTransactionData?: boolean): Promise<EthBlock>;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const controller_utils_1 = require("@metamask/controller-utils");
13
+ /**
14
+ * Returns information about the latest completed block.
15
+ *
16
+ * @param ethQuery - An EthQuery instance
17
+ * @param includeFullTransactionData - Whether or not to include all data for transactions as
18
+ * opposed to merely hashes. False by default.
19
+ * @returns The block.
20
+ */
21
+ function fetchLatestBlock(ethQuery, includeFullTransactionData = false) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const blockNumber = yield (0, controller_utils_1.query)(ethQuery, 'blockNumber');
24
+ const block = yield (0, controller_utils_1.query)(ethQuery, 'getBlockByNumber', [
25
+ blockNumber,
26
+ includeFullTransactionData,
27
+ ]);
28
+ return Object.assign(Object.assign({}, block), { number: (0, controller_utils_1.fromHex)(block.number), baseFeePerGas: (0, controller_utils_1.fromHex)(block.baseFeePerGas) });
29
+ });
30
+ }
31
+ exports.default = fetchLatestBlock;
32
+ //# sourceMappingURL=fetchLatestBlock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchLatestBlock.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iEAA4D;AAG5D;;;;;;;GAOG;AACH,SAA8B,gBAAgB,CAC5C,QAAkB,EAClB,0BAA0B,GAAG,KAAK;;QAElC,MAAM,WAAW,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;QACzD,MAAM,KAAK,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,kBAAkB,EAAE;YACtD,WAAW;YACX,0BAA0B;SAC3B,CAAC,CAAC;QACH,uCACK,KAAK,KACR,MAAM,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,MAAM,CAAC,EAC7B,aAAa,EAAE,IAAA,0BAAO,EAAC,KAAK,CAAC,aAAa,CAAC,IAC3C;IACJ,CAAC;CAAA;AAdD,mCAcC","sourcesContent":["import { query, fromHex } from '@metamask/controller-utils';\nimport { EthBlock, EthQuery } from './types';\n\n/**\n * Returns information about the latest completed block.\n *\n * @param ethQuery - An EthQuery instance\n * @param includeFullTransactionData - Whether or not to include all data for transactions as\n * opposed to merely hashes. False by default.\n * @returns The block.\n */\nexport default async function fetchLatestBlock(\n ethQuery: EthQuery,\n includeFullTransactionData = false,\n): Promise<EthBlock> {\n const blockNumber = await query(ethQuery, 'blockNumber');\n const block = await query(ethQuery, 'getBlockByNumber', [\n blockNumber,\n includeFullTransactionData,\n ]);\n return {\n ...block,\n number: fromHex(block.number),\n baseFeePerGas: fromHex(block.baseFeePerGas),\n };\n}\n"]}