@metamask-previews/gas-fee-controller 13.0.0-preview.d392f46 → 13.0.1-preview.0a7589e7
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.
- package/CHANGELOG.md +9 -1
- package/dist/fetchBlockFeeHistory.d.ts +1 -2
- package/dist/fetchBlockFeeHistory.d.ts.map +1 -1
- package/dist/fetchBlockFeeHistory.js +5 -2
- package/dist/fetchBlockFeeHistory.js.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js +12 -12
- package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts +1 -2
- package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.d.ts.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/medianOf.js.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts +1 -2
- package/dist/fetchGasEstimatesViaEthFeeHistory/types.d.ts.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/types.js.map +1 -1
- package/dist/gas-util.js +5 -2
- package/dist/gas-util.js.map +1 -1
- package/package.json +5 -4
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [13.0.1]
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Bump `@metamask/ethjs-unit` to `^0.3.0` ([#3897](https://github.com/MetaMask/core/pull/3897))
|
|
15
|
+
- Bump `@metamask/controller-utils` to `^8.0.3` ([#3915](https://github.com/MetaMask/core/pull/3915))
|
|
16
|
+
|
|
10
17
|
## [13.0.0]
|
|
11
18
|
|
|
12
19
|
### Changed
|
|
@@ -201,7 +208,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
201
208
|
|
|
202
209
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
203
210
|
|
|
204
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@13.0.
|
|
211
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@13.0.1...HEAD
|
|
212
|
+
[13.0.1]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@13.0.0...@metamask/gas-fee-controller@13.0.1
|
|
205
213
|
[13.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@12.0.0...@metamask/gas-fee-controller@13.0.0
|
|
206
214
|
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@11.0.0...@metamask/gas-fee-controller@12.0.0
|
|
207
215
|
[11.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@10.0.1...@metamask/gas-fee-controller@11.0.0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchBlockFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetchBlockFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,OAAO,CAAC;AAIvB,aAAK,QAAQ,GAAG,GAAG,CAAC;AAcpB;;;;;;;;;;;;;GAaG;AAEH,oBAAY,qBAAqB,GAAG;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,aAAK,uBAAuB,CAAC,UAAU,SAAS,MAAM,IAAI;IACxD,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,wBAAwB,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;CAClD,CAAC;AAEF;;;;;;GAMG;AACH,aAAK,mBAAmB,GAAG;IACzB,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,oBAAY,eAAe,CAAC,UAAU,SAAS,MAAM,IACjD,uBAAuB,CAAC,UAAU,CAAC,GACnC,mBAAmB,CAAC;AAExB;;;;;GAKG;AACH,oBAAY,qBAAqB,CAAC,CAAC,IAAI,CAAC,SAAS,eAAe,CAAC,MAAM,CAAC,CAAC,EAAE,GACvE,CAAC,GACD,KAAK,CAAC;AAIV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAA8B,oBAAoB,CAAC,UAAU,SAAS,MAAM,EAAE,EAC5E,QAAQ,EACR,cAAc,EAAE,mBAAmB,EACnC,QAAQ,EAAE,aAAwB,EAClC,WAAW,EAAE,gBAAqB,EAClC,gBAAwB,GACzB,EAAE;IACD,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,QAAQ,GAAG,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IACpC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,GAAG,OAAO,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,CAAC,CAwCzC"}
|
|
@@ -8,9 +8,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
11
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
15
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
13
|
-
const
|
|
16
|
+
const bn_js_1 = __importDefault(require("bn.js"));
|
|
14
17
|
const MAX_NUMBER_OF_BLOCKS_PER_ETH_FEE_HISTORY_CALL = 1024;
|
|
15
18
|
/**
|
|
16
19
|
* Uses `eth_feeHistory` (an EIP-1559 feature) to obtain information about gas fees from a range of
|
|
@@ -185,7 +188,7 @@ function makeRequestForChunk({ ethQuery, numberOfBlocks, endBlockNumber, percent
|
|
|
185
188
|
* retrieve all of the requested blocks, sorted from oldest block to newest block.
|
|
186
189
|
*/
|
|
187
190
|
function determineRequestChunkSpecifiers(endBlockNumber, totalNumberOfBlocks) {
|
|
188
|
-
if (endBlockNumber.lt(new
|
|
191
|
+
if (endBlockNumber.lt(new bn_js_1.default(totalNumberOfBlocks))) {
|
|
189
192
|
totalNumberOfBlocks = endBlockNumber.toNumber();
|
|
190
193
|
}
|
|
191
194
|
const specifiers = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchBlockFeeHistory.js","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iEAAmE;AACnE,qDAAqC;AAmGrC,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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qBAAqB,CAAC,IAAI,CAChD,6CAA6C,CAC9C,EACD;QACA,MAAM,aAAa,GAAG,cAAc,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC3E,MAAM,cAAc,GAClB,aAAa,GAAG,6CAA6C;YAC3D,CAAC,CAAC,aAAa;YACf,CAAC,CAAC,6CAA6C,CAAC;QACpD,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 { query, fromHex, toHex } from '@metamask/controller-utils';\nimport { BN } from 'ethereumjs-util';\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"]}
|
|
1
|
+
{"version":3,"file":"fetchBlockFeeHistory.js","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iEAAmE;AACnE,kDAAuB;AAmGvB,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,CAAC,CAAC,aAAa,CAAC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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 { 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"]}
|
|
@@ -5,16 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
7
7
|
const ethjs_unit_1 = require("@metamask/ethjs-unit");
|
|
8
|
-
const
|
|
8
|
+
const bn_js_1 = __importDefault(require("bn.js"));
|
|
9
9
|
const medianOf_1 = __importDefault(require("./medianOf"));
|
|
10
10
|
const PRIORITY_LEVELS = ['low', 'medium', 'high'];
|
|
11
11
|
const PRIORITY_LEVEL_PERCENTILES = [10, 20, 30];
|
|
12
12
|
const SETTINGS_BY_PRIORITY_LEVEL = {
|
|
13
13
|
low: {
|
|
14
14
|
percentile: 10,
|
|
15
|
-
baseFeePercentageMultiplier: new
|
|
16
|
-
priorityFeePercentageMultiplier: new
|
|
17
|
-
minSuggestedMaxPriorityFeePerGas: new
|
|
15
|
+
baseFeePercentageMultiplier: new bn_js_1.default(110),
|
|
16
|
+
priorityFeePercentageMultiplier: new bn_js_1.default(94),
|
|
17
|
+
minSuggestedMaxPriorityFeePerGas: new bn_js_1.default(1000000000),
|
|
18
18
|
estimatedWaitTimes: {
|
|
19
19
|
minWaitTimeEstimate: 15000,
|
|
20
20
|
maxWaitTimeEstimate: 30000,
|
|
@@ -22,9 +22,9 @@ const SETTINGS_BY_PRIORITY_LEVEL = {
|
|
|
22
22
|
},
|
|
23
23
|
medium: {
|
|
24
24
|
percentile: 20,
|
|
25
|
-
baseFeePercentageMultiplier: new
|
|
26
|
-
priorityFeePercentageMultiplier: new
|
|
27
|
-
minSuggestedMaxPriorityFeePerGas: new
|
|
25
|
+
baseFeePercentageMultiplier: new bn_js_1.default(120),
|
|
26
|
+
priorityFeePercentageMultiplier: new bn_js_1.default(97),
|
|
27
|
+
minSuggestedMaxPriorityFeePerGas: new bn_js_1.default(1500000000),
|
|
28
28
|
estimatedWaitTimes: {
|
|
29
29
|
minWaitTimeEstimate: 15000,
|
|
30
30
|
maxWaitTimeEstimate: 45000,
|
|
@@ -32,9 +32,9 @@ const SETTINGS_BY_PRIORITY_LEVEL = {
|
|
|
32
32
|
},
|
|
33
33
|
high: {
|
|
34
34
|
percentile: 30,
|
|
35
|
-
baseFeePercentageMultiplier: new
|
|
36
|
-
priorityFeePercentageMultiplier: new
|
|
37
|
-
minSuggestedMaxPriorityFeePerGas: new
|
|
35
|
+
baseFeePercentageMultiplier: new bn_js_1.default(125),
|
|
36
|
+
priorityFeePercentageMultiplier: new bn_js_1.default(98),
|
|
37
|
+
minSuggestedMaxPriorityFeePerGas: new bn_js_1.default(2000000000),
|
|
38
38
|
estimatedWaitTimes: {
|
|
39
39
|
minWaitTimeEstimate: 15000,
|
|
40
40
|
maxWaitTimeEstimate: 60000,
|
|
@@ -62,12 +62,12 @@ function calculateEstimatesForPriorityLevel(priorityLevel, blocks) {
|
|
|
62
62
|
? block.priorityFeesByPercentile[settings.percentile]
|
|
63
63
|
: null;
|
|
64
64
|
})
|
|
65
|
-
.filter(
|
|
65
|
+
.filter(bn_js_1.default.isBN);
|
|
66
66
|
const medianPriorityFee = (0, medianOf_1.default)(priorityFees);
|
|
67
67
|
const adjustedPriorityFee = medianPriorityFee
|
|
68
68
|
.mul(settings.priorityFeePercentageMultiplier)
|
|
69
69
|
.divn(100);
|
|
70
|
-
const suggestedMaxPriorityFeePerGas =
|
|
70
|
+
const suggestedMaxPriorityFeePerGas = bn_js_1.default.max(adjustedPriorityFee, settings.minSuggestedMaxPriorityFeePerGas);
|
|
71
71
|
const suggestedMaxFeePerGas = adjustedBaseFee.add(suggestedMaxPriorityFeePerGas);
|
|
72
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
73
|
}
|
package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calculateGasFeeEstimatesForPriorityLevels.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":";;;;;AAAA,iEAAkD;AAClD,qDAA+C;AAC/C,
|
|
1
|
+
{"version":3,"file":"calculateGasFeeEstimatesForPriorityLevels.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":";;;;;AAAA,iEAAkD;AAClD,qDAA+C;AAC/C,kDAAuB;AAIvB,0DAAkC;AAKlC,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAC3D,MAAM,0BAA0B,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAU,CAAC;AACzD,MAAM,0BAA0B,GAAG;IACjC,GAAG,EAAE;QACH,UAAU,EAAE,EAAgB;QAC5B,2BAA2B,EAAE,IAAI,eAAE,CAAC,GAAG,CAAC;QACxC,+BAA+B,EAAE,IAAI,eAAE,CAAC,EAAE,CAAC;QAC3C,gCAAgC,EAAE,IAAI,eAAE,CAAC,UAAa,CAAC;QACvD,kBAAkB,EAAE;YAClB,mBAAmB,EAAE,KAAM;YAC3B,mBAAmB,EAAE,KAAM;SAC5B;KACF;IACD,MAAM,EAAE;QACN,UAAU,EAAE,EAAgB;QAC5B,2BAA2B,EAAE,IAAI,eAAE,CAAC,GAAG,CAAC;QACxC,+BAA+B,EAAE,IAAI,eAAE,CAAC,EAAE,CAAC;QAC3C,gCAAgC,EAAE,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,GAAG,CAC1C,mBAAmB,EACnB,QAAQ,CAAC,gCAAgC,CAC1C,CAAC;IACF,MAAM,qBAAqB,GAAG,eAAe,CAAC,GAAG,CAC/C,6BAA6B,CAC9B,CAAC;IAEF,uCACK,QAAQ,CAAC,kBAAkB,KAC9B,6BAA6B,EAAE,IAAA,oBAAO,EAAC,6BAA6B,EAAE,uBAAI,CAAC,EAC3E,qBAAqB,EAAE,IAAA,oBAAO,EAAC,qBAAqB,EAAE,uBAAI,CAAC,IAC3D;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAwB,yCAAyC,CAC/D,MAAqC;IAErC,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,aAAa,EAAE,EAAE;QACnD,MAAM,4BAA4B,GAAG,kCAAkC,CACrE,aAAa,EACb,MAAM,CACP,CAAC;QACF,uCAAY,GAAG,KAAE,CAAC,aAAa,CAAC,EAAE,4BAA4B,IAAG;IACnE,CAAC,EAAE,EAA0C,CAAC,CAAC;AACjD,CAAC;AAVD,4DAUC","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport { fromWei } from '@metamask/ethjs-unit';\nimport BN from 'bn.js';\n\nimport type { FeeHistoryBlock } from '../fetchBlockFeeHistory';\nimport type { Eip1559GasFee, GasFeeEstimates } from '../GasFeeController';\nimport medianOf from './medianOf';\n\nexport type PriorityLevel = (typeof PRIORITY_LEVELS)[number];\nexport type Percentile = (typeof PRIORITY_LEVEL_PERCENTILES)[number];\n\nconst PRIORITY_LEVELS = ['low', 'medium', 'high'] as const;\nconst PRIORITY_LEVEL_PERCENTILES = [10, 20, 30] as const;\nconst SETTINGS_BY_PRIORITY_LEVEL = {\n low: {\n percentile: 10 as Percentile,\n baseFeePercentageMultiplier: new BN(110),\n priorityFeePercentageMultiplier: new BN(94),\n minSuggestedMaxPriorityFeePerGas: new BN(1_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 30_000,\n },\n },\n medium: {\n percentile: 20 as Percentile,\n baseFeePercentageMultiplier: new BN(120),\n priorityFeePercentageMultiplier: new BN(97),\n minSuggestedMaxPriorityFeePerGas: new BN(1_500_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 45_000,\n },\n },\n high: {\n percentile: 30 as Percentile,\n baseFeePercentageMultiplier: new BN(125),\n priorityFeePercentageMultiplier: new BN(98),\n minSuggestedMaxPriorityFeePerGas: new BN(2_000_000_000),\n estimatedWaitTimes: {\n minWaitTimeEstimate: 15_000,\n maxWaitTimeEstimate: 60_000,\n },\n },\n};\n\n/**\n * Calculates a set of estimates assigned to a particular priority level based on the data returned\n * by `eth_feeHistory`.\n *\n * @param priorityLevel - The level of fees that dictates how soon a transaction may go through\n * (\"low\", \"medium\", or \"high\").\n * @param blocks - A set of blocks as obtained from {@link fetchBlockFeeHistory}.\n * @returns The estimates.\n */\nfunction calculateEstimatesForPriorityLevel(\n priorityLevel: PriorityLevel,\n blocks: FeeHistoryBlock<Percentile>[],\n): Eip1559GasFee {\n const settings = SETTINGS_BY_PRIORITY_LEVEL[priorityLevel];\n\n const latestBaseFeePerGas = blocks[blocks.length - 1].baseFeePerGas;\n\n const adjustedBaseFee = latestBaseFeePerGas\n .mul(settings.baseFeePercentageMultiplier)\n .divn(100);\n const priorityFees = blocks\n .map((block) => {\n return 'priorityFeesByPercentile' in block\n ? block.priorityFeesByPercentile[settings.percentile]\n : null;\n })\n .filter(BN.isBN);\n const medianPriorityFee = medianOf(priorityFees);\n const adjustedPriorityFee = medianPriorityFee\n .mul(settings.priorityFeePercentageMultiplier)\n .divn(100);\n\n const suggestedMaxPriorityFeePerGas = BN.max(\n adjustedPriorityFee,\n settings.minSuggestedMaxPriorityFeePerGas,\n );\n const suggestedMaxFeePerGas = adjustedBaseFee.add(\n suggestedMaxPriorityFeePerGas,\n );\n\n return {\n ...settings.estimatedWaitTimes,\n suggestedMaxPriorityFeePerGas: fromWei(suggestedMaxPriorityFeePerGas, GWEI),\n suggestedMaxFeePerGas: fromWei(suggestedMaxFeePerGas, GWEI),\n };\n}\n\n/**\n * Calculates a set of estimates suitable for different priority levels based on the data returned\n * by `eth_feeHistory`.\n *\n * @param blocks - A set of blocks populated with data for priority fee percentiles 10, 20, and 30,\n * obtained via {@link BlockFeeHistoryDatasetFetcher}.\n * @returns The estimates.\n */\nexport default function calculateGasFeeEstimatesForPriorityLevels(\n blocks: FeeHistoryBlock<Percentile>[],\n): Pick<GasFeeEstimates, PriorityLevel> {\n return PRIORITY_LEVELS.reduce((obj, priorityLevel) => {\n const gasEstimatesForPriorityLevel = calculateEstimatesForPriorityLevel(\n priorityLevel,\n blocks,\n );\n return { ...obj, [priorityLevel]: gasEstimatesForPriorityLevel };\n }, {} as Pick<GasFeeEstimates, PriorityLevel>);\n}\n"]}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import type { BN } from 'ethereumjs-util';
|
|
1
|
+
import type * as BN from 'bn.js';
|
|
3
2
|
/**
|
|
4
3
|
* Finds the median among a list of numbers. Note that this is different from the implementation
|
|
5
4
|
* in the MetaSwap API, as we want to hold to using BN as much as possible.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"medianOf.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"medianOf.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,CAKlD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"medianOf.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"names":[],"mappings":";;AAEA;;;;;;GAMG;AACH,SAAwB,QAAQ,CAAC,OAAa;IAC5C,MAAM,aAAa,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,MAAM,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC;IACjC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IACxC,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AALD,2BAKC","sourcesContent":["import type
|
|
1
|
+
{"version":3,"file":"medianOf.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/medianOf.ts"],"names":[],"mappings":";;AAEA;;;;;;GAMG;AACH,SAAwB,QAAQ,CAAC,OAAa;IAC5C,MAAM,aAAa,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,MAAM,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC;IACjC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IACxC,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AALD,2BAKC","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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,OAAO,CAAC;AAEjC,oBAAY,QAAQ,GAAG;IACrB,MAAM,EAAE,EAAE,CAAC;IACX,aAAa,EAAE,EAAE,CAAC;CACnB,CAAC;AAEF,oBAAY,QAAQ,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"","sourcesContent":["import type
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/types.ts"],"names":[],"mappings":"","sourcesContent":["import type * as BN from 'bn.js';\n\nexport type EthBlock = {\n number: BN;\n baseFeePerGas: BN;\n};\n\nexport type FeeRange = [string, string];\n"]}
|
package/dist/gas-util.js
CHANGED
|
@@ -8,10 +8,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
11
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
15
|
exports.calculateTimeEstimate = exports.fetchEthGasPriceEstimate = exports.fetchLegacyGasPriceEstimates = exports.fetchGasEstimates = exports.normalizeGWEIDecimalNumbers = void 0;
|
|
13
16
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
14
|
-
const
|
|
17
|
+
const bn_js_1 = __importDefault(require("bn.js"));
|
|
15
18
|
const makeClientIdHeader = (clientId) => ({ 'X-Client-Id': clientId });
|
|
16
19
|
/**
|
|
17
20
|
* Convert a decimal GWEI value to a decimal string rounded to the nearest WEI.
|
|
@@ -103,7 +106,7 @@ function calculateTimeEstimate(maxPriorityFeePerGas, maxFeePerGas, gasFeeEstimat
|
|
|
103
106
|
const maxPriorityFeePerGasInWEI = (0, controller_utils_1.gweiDecToWEIBN)(maxPriorityFeePerGas);
|
|
104
107
|
const maxFeePerGasInWEI = (0, controller_utils_1.gweiDecToWEIBN)(maxFeePerGas);
|
|
105
108
|
const estimatedBaseFeeInWEI = (0, controller_utils_1.gweiDecToWEIBN)(estimatedBaseFee);
|
|
106
|
-
const effectiveMaxPriorityFee =
|
|
109
|
+
const effectiveMaxPriorityFee = bn_js_1.default.min(maxPriorityFeePerGasInWEI, maxFeePerGasInWEI.sub(estimatedBaseFeeInWEI));
|
|
107
110
|
const lowMaxPriorityFeeInWEI = (0, controller_utils_1.gweiDecToWEIBN)(low.suggestedMaxPriorityFeePerGas);
|
|
108
111
|
const mediumMaxPriorityFeeInWEI = (0, controller_utils_1.gweiDecToWEIBN)(medium.suggestedMaxPriorityFeePerGas);
|
|
109
112
|
const highMaxPriorityFeeInWEI = (0, controller_utils_1.gweiDecToWEIBN)(high.suggestedMaxPriorityFeePerGas);
|
package/dist/gas-util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-util.js","sourceRoot":"","sources":["../src/gas-util.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"gas-util.js","sourceRoot":"","sources":["../src/gas-util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAKoC;AAEpC,kDAAuB;AAUvB,MAAM,kBAAkB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC,EAA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Ac,GAAG,CAAC,CAAC;QACnB,cAAc,GAAG,IAAI,CAAC,mBAAmB,CAAC;KAC3C;IAED,OAAO;QACL,cAAc;QACd,cAAc;KACf,CAAC;AACJ,CAAC;AAxDD,sDAwDC","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/gas-fee-controller",
|
|
3
|
-
"version": "13.0.
|
|
3
|
+
"version": "13.0.1-preview.0a7589e7",
|
|
4
4
|
"description": "Periodically calculates gas fee estimates based on various gas limits as well as other data displayed on transaction confirm screens",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -32,14 +32,15 @@
|
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@metamask/base-controller": "^4.1.1",
|
|
35
|
-
"@metamask/controller-utils": "^8.0.
|
|
35
|
+
"@metamask/controller-utils": "^8.0.3",
|
|
36
36
|
"@metamask/eth-query": "^4.0.0",
|
|
37
|
-
"@metamask/ethjs-unit": "^0.
|
|
37
|
+
"@metamask/ethjs-unit": "^0.3.0",
|
|
38
38
|
"@metamask/network-controller": "^17.2.0",
|
|
39
39
|
"@metamask/polling-controller": "^5.0.0",
|
|
40
40
|
"@metamask/utils": "^8.3.0",
|
|
41
|
+
"@types/bn.js": "^5.1.5",
|
|
41
42
|
"@types/uuid": "^8.3.0",
|
|
42
|
-
"
|
|
43
|
+
"bn.js": "^5.2.1",
|
|
43
44
|
"uuid": "^8.3.2"
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|