@metamask-previews/gas-fee-controller 10.0.1-preview.eb58a59 → 12.0.0-preview.c9a5f6a5
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 +22 -1
- package/dist/GasFeeController.d.ts +7 -7
- package/dist/GasFeeController.d.ts.map +1 -1
- package/dist/GasFeeController.js +10 -10
- package/dist/GasFeeController.js.map +1 -1
- package/dist/determineGasFeeCalculations.d.ts.map +1 -1
- package/dist/determineGasFeeCalculations.js.map +1 -1
- package/dist/fetchBlockFeeHistory.d.ts.map +1 -1
- package/dist/fetchBlockFeeHistory.js.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.js.map +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory.js +1 -1
- package/dist/fetchGasEstimatesViaEthFeeHistory.js.map +1 -1
- package/dist/gas-util.js +1 -1
- package/dist/gas-util.js.map +1 -1
- package/package.json +9 -8
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [12.0.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING:** Bump `@metamask/network-controller` dependency and peer dependency from `^17.0.0` to `^17.1.0` ([#3695](https://github.com/MetaMask/core/pull/3695))
|
|
12
|
+
- **BREAKING:** The `GasFeeController` now detects network changes using the `NetworkController:networkDidChange` event instead of `NetworkController:stateChange` ([#3610](https://github.com/MetaMask/core/pull/3610))
|
|
13
|
+
- Additionally, the optional constructor parameter `onNetworkStateChange` has been replaced by `onNetworkDidChange`
|
|
14
|
+
- Bump `@metamask/base-controller` to `^4.0.1` ([#3695](https://github.com/MetaMask/core/pull/3695))
|
|
15
|
+
- Bump `@metamask/controller-utils` to `^8.0.1` ([#3695](https://github.com/MetaMask/core/pull/3695), [#3678](https://github.com/MetaMask/core/pull/3678), [#3667](https://github.com/MetaMask/core/pull/3667), [#3580](https://github.com/MetaMask/core/pull/3580))
|
|
16
|
+
- Bump `@metamask/polling-controller` to `^4.0.0` ([#3695](https://github.com/MetaMask/core/pull/3695), [#3667](https://github.com/MetaMask/core/pull/3667), [#3636](https://github.com/MetaMask/core/pull/3636))
|
|
17
|
+
- This update adds two new methods to each polling controller: `_startPollingByNetworkClientId` and `_stopPollingByPollingTokenSetId`. These methods are intended for internal use, and should not be called directly.
|
|
18
|
+
|
|
19
|
+
## [11.0.0]
|
|
20
|
+
### Changed
|
|
21
|
+
- **BREAKING:** Bump `@metamask/base-controller` to ^4.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
22
|
+
- This is breaking because the type of the `messenger` has backward-incompatible changes. See the changelog for this package for more.
|
|
23
|
+
- Replace `ethjs-unit` ^0.1.6 with `@metamask/ethjs-unit` ^0.2.1 ([#2064](https://github.com/MetaMask/core/pull/2064))
|
|
24
|
+
- Bump `@metamask/controller-utils` to ^6.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
25
|
+
- Bump `@metamask/network-controller` to ^17.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
26
|
+
- Bump `@metamask/polling-controller` to ^2.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
27
|
+
|
|
9
28
|
## [10.0.1]
|
|
10
29
|
### Changed
|
|
11
30
|
- **BREAKING:** Bump dependency and peer dependency on `@metamask/network-controller` to ^16.0.0
|
|
@@ -125,7 +144,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
125
144
|
|
|
126
145
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
127
146
|
|
|
128
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@
|
|
147
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@12.0.0...HEAD
|
|
148
|
+
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@11.0.0...@metamask/gas-fee-controller@12.0.0
|
|
149
|
+
[11.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@10.0.1...@metamask/gas-fee-controller@11.0.0
|
|
129
150
|
[10.0.1]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@10.0.0...@metamask/gas-fee-controller@10.0.1
|
|
130
151
|
[10.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@9.0.0...@metamask/gas-fee-controller@10.0.0
|
|
131
152
|
[9.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@8.0.0...@metamask/gas-fee-controller@9.0.0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
|
-
import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction,
|
|
3
|
-
import {
|
|
2
|
+
import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerNetworkDidChangeEvent, NetworkState, ProviderProxy } from '@metamask/network-controller';
|
|
3
|
+
import { StaticIntervalPollingController } from '@metamask/polling-controller';
|
|
4
4
|
import type { Hex } from '@metamask/utils';
|
|
5
5
|
export declare const LEGACY_GAS_PRICES_API_URL = "https://api.metaswap.codefi.network/gasPrices";
|
|
6
6
|
export declare type unknownString = 'unknown';
|
|
@@ -144,11 +144,11 @@ export declare type GetGasFeeState = ControllerGetStateAction<typeof name, GasFe
|
|
|
144
144
|
export declare type GasFeeControllerActions = GetGasFeeState;
|
|
145
145
|
export declare type GasFeeControllerEvents = GasFeeStateChange;
|
|
146
146
|
declare type AllowedActions = NetworkControllerGetStateAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetEIP1559CompatibilityAction;
|
|
147
|
-
declare type GasFeeMessenger = RestrictedControllerMessenger<typeof name, GasFeeControllerActions | AllowedActions, GasFeeControllerEvents |
|
|
147
|
+
declare type GasFeeMessenger = RestrictedControllerMessenger<typeof name, GasFeeControllerActions | AllowedActions, GasFeeControllerEvents | NetworkControllerNetworkDidChangeEvent, AllowedActions['type'], NetworkControllerNetworkDidChangeEvent['type']>;
|
|
148
148
|
/**
|
|
149
149
|
* Controller that retrieves gas fee estimate data and polls for updated data on a set interval
|
|
150
150
|
*/
|
|
151
|
-
export declare class GasFeeController extends
|
|
151
|
+
export declare class GasFeeController extends StaticIntervalPollingController<typeof name, GasFeeState, GasFeeMessenger> {
|
|
152
152
|
#private;
|
|
153
153
|
private intervalId?;
|
|
154
154
|
private readonly intervalDelay;
|
|
@@ -176,7 +176,7 @@ export declare class GasFeeController extends PollingController<typeof name, Gas
|
|
|
176
176
|
* account is EIP-1559 compatible.
|
|
177
177
|
* @param options.getChainId - Returns the current chain ID.
|
|
178
178
|
* @param options.getProvider - Returns a network provider for the current network.
|
|
179
|
-
* @param options.
|
|
179
|
+
* @param options.onNetworkDidChange - A function for registering an event handler for the
|
|
180
180
|
* network state change event.
|
|
181
181
|
* @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for
|
|
182
182
|
* testing purposes.
|
|
@@ -184,7 +184,7 @@ export declare class GasFeeController extends PollingController<typeof name, Gas
|
|
|
184
184
|
* @param options.clientId - The client ID used to identify to the gas estimation API who is
|
|
185
185
|
* asking for estimates.
|
|
186
186
|
*/
|
|
187
|
-
constructor({ interval, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider,
|
|
187
|
+
constructor({ interval, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider, onNetworkDidChange, legacyAPIEndpoint, EIP1559APIEndpoint, clientId, }: {
|
|
188
188
|
interval?: number;
|
|
189
189
|
messenger: GasFeeMessenger;
|
|
190
190
|
state?: GasFeeState;
|
|
@@ -193,7 +193,7 @@ export declare class GasFeeController extends PollingController<typeof name, Gas
|
|
|
193
193
|
getCurrentAccountEIP1559Compatibility?: () => boolean;
|
|
194
194
|
getChainId?: () => Hex;
|
|
195
195
|
getProvider: () => ProviderProxy;
|
|
196
|
-
|
|
196
|
+
onNetworkDidChange?: (listener: (state: NetworkState) => void) => void;
|
|
197
197
|
legacyAPIEndpoint?: string;
|
|
198
198
|
EIP1559APIEndpoint: string;
|
|
199
199
|
clientId?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GasFeeController.d.ts","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAC9B,MAAM,2BAA2B,CAAC;AAOnC,OAAO,KAAK,EACV,eAAe,EACf,8CAA8C,EAC9C,2CAA2C,EAC3C,+BAA+B,EAC/B,
|
|
1
|
+
{"version":3,"file":"GasFeeController.d.ts","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAC9B,MAAM,2BAA2B,CAAC;AAOnC,OAAO,KAAK,EACV,eAAe,EACf,8CAA8C,EAC9C,2CAA2C,EAC3C,+BAA+B,EAC/B,sCAAsC,EACtC,YAAY,EACZ,aAAa,EACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAY3C,eAAO,MAAM,yBAAyB,kDAAkD,CAAC;AAEzF,oBAAY,aAAa,GAAG,SAAS,CAAC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,GACvC,OAAO,CAAC,WAAW,CAAC;IAkFvB;;;;OAIG;IACH,gBAAgB,CAAC,SAAS,EAAE,MAAM;IAOlC,WAAW;IAQX;;;;OAIG;IACM,OAAO;IAKhB,OAAO,CAAC,KAAK;IAUb;;;;;;OAMG;IACG,YAAY,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI1D,OAAO,CAAC,UAAU;YAMJ,uBAAuB;IAWrC,eAAe,CACb,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,GACnB,yBAAyB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC;CAwBrD;AAED,eAAe,gBAAgB,CAAC"}
|
package/dist/GasFeeController.js
CHANGED
|
@@ -22,7 +22,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
22
22
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
23
23
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
24
24
|
};
|
|
25
|
-
var _GasFeeController_instances, _GasFeeController_getProvider,
|
|
25
|
+
var _GasFeeController_instances, _GasFeeController_getProvider, _GasFeeController_onNetworkControllerDidChange;
|
|
26
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
27
|
exports.GasFeeController = exports.GAS_ESTIMATE_TYPES = exports.LEGACY_GAS_PRICES_API_URL = void 0;
|
|
28
28
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
@@ -64,7 +64,7 @@ const defaultState = {
|
|
|
64
64
|
/**
|
|
65
65
|
* Controller that retrieves gas fee estimate data and polls for updated data on a set interval
|
|
66
66
|
*/
|
|
67
|
-
class GasFeeController extends polling_controller_1.
|
|
67
|
+
class GasFeeController extends polling_controller_1.StaticIntervalPollingController {
|
|
68
68
|
/**
|
|
69
69
|
* Creates a GasFeeController instance.
|
|
70
70
|
*
|
|
@@ -80,7 +80,7 @@ class GasFeeController extends polling_controller_1.PollingController {
|
|
|
80
80
|
* account is EIP-1559 compatible.
|
|
81
81
|
* @param options.getChainId - Returns the current chain ID.
|
|
82
82
|
* @param options.getProvider - Returns a network provider for the current network.
|
|
83
|
-
* @param options.
|
|
83
|
+
* @param options.onNetworkDidChange - A function for registering an event handler for the
|
|
84
84
|
* network state change event.
|
|
85
85
|
* @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for
|
|
86
86
|
* testing purposes.
|
|
@@ -88,7 +88,7 @@ class GasFeeController extends polling_controller_1.PollingController {
|
|
|
88
88
|
* @param options.clientId - The client ID used to identify to the gas estimation API who is
|
|
89
89
|
* asking for estimates.
|
|
90
90
|
*/
|
|
91
|
-
constructor({ interval = 15000, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider,
|
|
91
|
+
constructor({ interval = 15000, messenger, state, getCurrentNetworkEIP1559Compatibility, getCurrentAccountEIP1559Compatibility, getChainId, getCurrentNetworkLegacyGasAPICompatibility, getProvider, onNetworkDidChange, legacyAPIEndpoint = exports.LEGACY_GAS_PRICES_API_URL, EIP1559APIEndpoint, clientId, }) {
|
|
92
92
|
super({
|
|
93
93
|
name,
|
|
94
94
|
metadata,
|
|
@@ -111,16 +111,16 @@ class GasFeeController extends polling_controller_1.PollingController {
|
|
|
111
111
|
this.legacyAPIEndpoint = legacyAPIEndpoint;
|
|
112
112
|
this.clientId = clientId;
|
|
113
113
|
this.ethQuery = new eth_query_1.default(__classPrivateFieldGet(this, _GasFeeController_getProvider, "f").call(this));
|
|
114
|
-
if (
|
|
114
|
+
if (onNetworkDidChange && getChainId) {
|
|
115
115
|
this.currentChainId = getChainId();
|
|
116
|
-
|
|
117
|
-
yield __classPrivateFieldGet(this, _GasFeeController_instances, "m",
|
|
116
|
+
onNetworkDidChange((networkControllerState) => __awaiter(this, void 0, void 0, function* () {
|
|
117
|
+
yield __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerDidChange).call(this, networkControllerState);
|
|
118
118
|
}));
|
|
119
119
|
}
|
|
120
120
|
else {
|
|
121
121
|
this.currentChainId = this.messagingSystem.call('NetworkController:getState').providerConfig.chainId;
|
|
122
|
-
this.messagingSystem.subscribe('NetworkController:
|
|
123
|
-
yield __classPrivateFieldGet(this, _GasFeeController_instances, "m",
|
|
122
|
+
this.messagingSystem.subscribe('NetworkController:networkDidChange', (networkControllerState) => __awaiter(this, void 0, void 0, function* () {
|
|
123
|
+
yield __classPrivateFieldGet(this, _GasFeeController_instances, "m", _GasFeeController_onNetworkControllerDidChange).call(this, networkControllerState);
|
|
124
124
|
}));
|
|
125
125
|
}
|
|
126
126
|
}
|
|
@@ -287,7 +287,7 @@ class GasFeeController extends polling_controller_1.PollingController {
|
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
289
|
exports.GasFeeController = GasFeeController;
|
|
290
|
-
_GasFeeController_getProvider = new WeakMap(), _GasFeeController_instances = new WeakSet(),
|
|
290
|
+
_GasFeeController_getProvider = new WeakMap(), _GasFeeController_instances = new WeakSet(), _GasFeeController_onNetworkControllerDidChange = function _GasFeeController_onNetworkControllerDidChange(networkControllerState) {
|
|
291
291
|
return __awaiter(this, void 0, void 0, function* () {
|
|
292
292
|
const newChainId = networkControllerState.providerConfig.chainId;
|
|
293
293
|
if (newChainId !== this.currentChainId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GasFeeController.js","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,iEAIoC;AACpC,oEAA2C;AAU3C,qEAAiE;AAEjE,+BAAoC;AAEpC,gGAAwE;AACxE,4GAAoF;AACpF,yCAKoB;AAEP,QAAA,yBAAyB,GAAG,+CAA+C,CAAC;AAoBzF;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG;IAChC,UAAU,EAAE,YAAqC;IACjD,MAAM,EAAE,QAA8B;IACtC,YAAY,EAAE,cAAyC;IAC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CAAC,CAAC;YAClD,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAE1B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC;SAClC;IACH,CAAC;;AAGH,kBAAe,gBAAgB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n convertHexToDecimal,\n safelyExecute,\n toHex,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkControllerGetEIP1559CompatibilityAction,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n NetworkState,\n ProviderProxy,\n} from '@metamask/network-controller';\nimport { PollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { v1 as random } from 'uuid';\n\nimport determineGasFeeCalculations from './determineGasFeeCalculations';\nimport fetchGasEstimatesViaEthFeeHistory from './fetchGasEstimatesViaEthFeeHistory';\nimport {\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n} from './gas-util';\n\nexport const LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;\n\nexport type unknownString = 'unknown';\n\n// Fee Market describes the way gas is set after the london hardfork, and was\n// defined by EIP-1559.\nexport type FeeMarketEstimateType = 'fee-market';\n// Legacy describes gasPrice estimates from before london hardfork, when the\n// user is connected to mainnet and are presented with fast/average/slow\n// estimate levels to choose from.\nexport type LegacyEstimateType = 'legacy';\n// EthGasPrice describes a gasPrice estimate received from eth_gasPrice. Post\n// london this value should only be used for legacy type transactions when on\n// networks that support EIP-1559. This type of estimate is the most accurate\n// to display on custom networks that don't support EIP-1559.\nexport type EthGasPriceEstimateType = 'eth_gasPrice';\n// NoEstimate describes the state of the controller before receiving its first\n// estimate.\nexport type NoEstimateType = 'none';\n\n/**\n * Indicates which type of gasEstimate the controller is currently returning.\n * This is useful as a way of asserting that the shape of gasEstimates matches\n * expectations. NONE is a special case indicating that no previous gasEstimate\n * has been fetched.\n */\nexport const GAS_ESTIMATE_TYPES = {\n FEE_MARKET: 'fee-market' as FeeMarketEstimateType,\n LEGACY: 'legacy' as LegacyEstimateType,\n ETH_GASPRICE: 'eth_gasPrice' as EthGasPriceEstimateType,\n NONE: 'none' as NoEstimateType,\n};\n\nexport type GasEstimateType =\n | FeeMarketEstimateType\n | EthGasPriceEstimateType\n | LegacyEstimateType\n | NoEstimateType;\n\nexport type EstimatedGasFeeTimeBounds = {\n lowerTimeBound: number | null;\n upperTimeBound: number | unknownString;\n};\n\n/**\n * @type EthGasPriceEstimate\n *\n * A single gas price estimate for networks and accounts that don't support EIP-1559\n * This estimate comes from eth_gasPrice but is converted to dec gwei to match other\n * return values\n * @property gasPrice - A GWEI dec string\n */\n\nexport type EthGasPriceEstimate = {\n gasPrice: string;\n};\n\n/**\n * @type LegacyGasPriceEstimate\n *\n * A set of gas price estimates for networks and accounts that don't support EIP-1559\n * These estimates include low, medium and high all as strings representing gwei in\n * decimal format.\n * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion\n * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion\n * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion\n */\nexport type LegacyGasPriceEstimate = {\n high: string;\n medium: string;\n low: string;\n};\n\n/**\n * @type Eip1559GasFee\n *\n * Data necessary to provide an estimate of a gas fee with a specific tip\n * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds\n * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds\n * @property suggestedMaxPriorityFeePerGas - A suggested \"tip\", a GWEI hex number\n * @property suggestedMaxFeePerGas - A suggested max fee, the most a user will pay. a GWEI hex number\n */\nexport type Eip1559GasFee = {\n minWaitTimeEstimate: number; // a time duration in milliseconds\n maxWaitTimeEstimate: number; // a time duration in milliseconds\n suggestedMaxPriorityFeePerGas: string; // a GWEI decimal number\n suggestedMaxFeePerGas: string; // a GWEI decimal number\n};\n\n/**\n * @type GasFeeEstimates\n *\n * Data necessary to provide multiple GasFee estimates, and supporting information, to the user\n * @property low - A GasFee for a minimum necessary combination of tip and maxFee\n * @property medium - A GasFee for a recommended combination of tip and maxFee\n * @property high - A GasFee for a high combination of tip and maxFee\n * @property estimatedBaseFee - An estimate of what the base fee will be for the pending/next block. A GWEI dec number\n * @property networkCongestion - A normalized number that can be used to gauge the congestion\n * level of the network, with 0 meaning not congested and 1 meaning extremely congested\n */\nexport type GasFeeEstimates = SourcedGasFeeEstimates | FallbackGasFeeEstimates;\n\ntype SourcedGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: [string, string];\n baseFeeTrend: 'up' | 'down' | 'level';\n latestPriorityFeeRange: [string, string];\n historicalPriorityFeeRange: [string, string];\n priorityFeeTrend: 'up' | 'down' | 'level';\n networkCongestion: number;\n};\n\ntype FallbackGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: null;\n baseFeeTrend: null;\n latestPriorityFeeRange: null;\n historicalPriorityFeeRange: null;\n priorityFeeTrend: null;\n networkCongestion: null;\n};\n\nconst metadata = {\n gasFeeEstimatesByChainId: {\n persist: true,\n anonymous: false,\n },\n gasFeeEstimates: { persist: true, anonymous: false },\n estimatedGasFeeTimeBounds: { persist: true, anonymous: false },\n gasEstimateType: { persist: true, anonymous: false },\n};\n\nexport type GasFeeStateEthGasPrice = {\n gasFeeEstimates: EthGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: EthGasPriceEstimateType;\n};\n\nexport type GasFeeStateFeeMarket = {\n gasFeeEstimates: GasFeeEstimates;\n estimatedGasFeeTimeBounds: EstimatedGasFeeTimeBounds | Record<string, never>;\n gasEstimateType: FeeMarketEstimateType;\n};\n\nexport type GasFeeStateLegacy = {\n gasFeeEstimates: LegacyGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: LegacyEstimateType;\n};\n\nexport type GasFeeStateNoEstimates = {\n gasFeeEstimates: Record<string, never>;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: NoEstimateType;\n};\n\nexport type FetchGasFeeEstimateOptions = {\n shouldUpdateState?: boolean;\n networkClientId?: NetworkClientId;\n};\n\n/**\n * @type GasFeeState\n *\n * Gas Fee controller state\n * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties\n * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum\n */\nexport type SingleChainGasFeeState =\n | GasFeeStateEthGasPrice\n | GasFeeStateFeeMarket\n | GasFeeStateLegacy\n | GasFeeStateNoEstimates;\n\nexport type GasFeeEstimatesByChainId = {\n gasFeeEstimatesByChainId?: Record<string, SingleChainGasFeeState>;\n};\n\nexport type GasFeeState = GasFeeEstimatesByChainId & SingleChainGasFeeState;\n\nconst name = 'GasFeeController';\n\nexport type GasFeeStateChange = ControllerStateChangeEvent<\n typeof name,\n GasFeeState\n>;\n\nexport type GetGasFeeState = ControllerGetStateAction<typeof name, GasFeeState>;\n\nexport type GasFeeControllerActions = GetGasFeeState;\n\nexport type GasFeeControllerEvents = GasFeeStateChange;\n\ntype AllowedActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetEIP1559CompatibilityAction;\n\ntype GasFeeMessenger = RestrictedControllerMessenger<\n typeof name,\n GasFeeControllerActions | AllowedActions,\n GasFeeControllerEvents | NetworkControllerStateChangeEvent,\n AllowedActions['type'],\n NetworkControllerStateChangeEvent['type']\n>;\n\nconst defaultState: GasFeeState = {\n gasFeeEstimatesByChainId: {},\n gasFeeEstimates: {},\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.NONE,\n};\n\n/**\n * Controller that retrieves gas fee estimate data and polls for updated data on a set interval\n */\nexport class GasFeeController extends PollingController<\n typeof name,\n GasFeeState,\n GasFeeMessenger\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay;\n\n private readonly pollTokens: Set<string>;\n\n private readonly legacyAPIEndpoint: string;\n\n private readonly EIP1559APIEndpoint: string;\n\n private readonly getCurrentNetworkEIP1559Compatibility;\n\n private readonly getCurrentNetworkLegacyGasAPICompatibility;\n\n private readonly getCurrentAccountEIP1559Compatibility;\n\n private currentChainId;\n\n private ethQuery?: EthQuery;\n\n private readonly clientId?: string;\n\n #getProvider: () => ProviderProxy;\n\n /**\n * Creates a GasFeeController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The time in milliseconds to wait between polls.\n * @param options.messenger - The controller messenger.\n * @param options.state - The initial state.\n * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current\n * network is EIP-1559 compatible.\n * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the\n * current network is compatible with the legacy gas price API.\n * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current\n * account is EIP-1559 compatible.\n * @param options.getChainId - Returns the current chain ID.\n * @param options.getProvider - Returns a network provider for the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for the\n * network state change event.\n * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for\n * testing purposes.\n * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.\n * @param options.clientId - The client ID used to identify to the gas estimation API who is\n * asking for estimates.\n */\n constructor({\n interval = 15000,\n messenger,\n state,\n getCurrentNetworkEIP1559Compatibility,\n getCurrentAccountEIP1559Compatibility,\n getChainId,\n getCurrentNetworkLegacyGasAPICompatibility,\n getProvider,\n onNetworkStateChange,\n legacyAPIEndpoint = LEGACY_GAS_PRICES_API_URL,\n EIP1559APIEndpoint,\n clientId,\n }: {\n interval?: number;\n messenger: GasFeeMessenger;\n state?: GasFeeState;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkLegacyGasAPICompatibility: () => boolean;\n getCurrentAccountEIP1559Compatibility?: () => boolean;\n getChainId?: () => Hex;\n getProvider: () => ProviderProxy;\n onNetworkStateChange?: (listener: (state: NetworkState) => void) => void;\n legacyAPIEndpoint?: string;\n EIP1559APIEndpoint: string;\n clientId?: string;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.intervalDelay = interval;\n this.setIntervalLength(interval);\n this.pollTokens = new Set();\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n this.getCurrentNetworkLegacyGasAPICompatibility =\n getCurrentNetworkLegacyGasAPICompatibility;\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.#getProvider = getProvider;\n this.EIP1559APIEndpoint = EIP1559APIEndpoint;\n this.legacyAPIEndpoint = legacyAPIEndpoint;\n this.clientId = clientId;\n\n this.ethQuery = new EthQuery(this.#getProvider());\n\n if (onNetworkStateChange && getChainId) {\n this.currentChainId = getChainId();\n onNetworkStateChange(async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n });\n } else {\n this.currentChainId = this.messagingSystem.call(\n 'NetworkController:getState',\n ).providerConfig.chainId;\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n },\n );\n }\n }\n\n async resetPolling() {\n if (this.pollTokens.size !== 0) {\n const tokens = Array.from(this.pollTokens);\n this.stopPolling();\n await this.getGasFeeEstimatesAndStartPolling(tokens[0]);\n tokens.slice(1).forEach((token) => {\n this.pollTokens.add(token);\n });\n }\n }\n\n async fetchGasFeeEstimates(options?: FetchGasFeeEstimateOptions) {\n return await this._fetchGasFeeEstimateData(options);\n }\n\n async getGasFeeEstimatesAndStartPolling(\n pollToken: string | undefined,\n ): Promise<string> {\n const _pollToken = pollToken || random();\n\n this.pollTokens.add(_pollToken);\n\n if (this.pollTokens.size === 1) {\n await this._fetchGasFeeEstimateData();\n this._poll();\n }\n\n return _pollToken;\n }\n\n /**\n * Gets and sets gasFeeEstimates in state.\n *\n * @param options - The gas fee estimate options.\n * @param options.shouldUpdateState - Determines whether the state should be updated with the\n * updated gas estimates.\n * @returns The gas fee estimates.\n */\n async _fetchGasFeeEstimateData(\n options: FetchGasFeeEstimateOptions = {},\n ): Promise<GasFeeState> {\n const { shouldUpdateState = true, networkClientId } = options;\n\n let ethQuery,\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n decimalChainId: number;\n\n if (networkClientId !== undefined) {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n isLegacyGasAPICompatible = networkClient.configuration.chainId === '0x38';\n\n decimalChainId = convertHexToDecimal(networkClient.configuration.chainId);\n\n try {\n const result = await this.messagingSystem.call(\n 'NetworkController:getEIP1559Compatibility',\n networkClientId,\n );\n isEIP1559Compatible = result || false;\n } catch {\n isEIP1559Compatible = false;\n }\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n ethQuery ??= this.ethQuery;\n\n isLegacyGasAPICompatible ??=\n this.getCurrentNetworkLegacyGasAPICompatibility();\n\n decimalChainId ??= convertHexToDecimal(this.currentChainId);\n\n try {\n isEIP1559Compatible ??= await this.getEIP1559Compatibility();\n } catch (e) {\n console.error(e);\n isEIP1559Compatible ??= false;\n }\n\n const gasFeeCalculations = await determineGasFeeCalculations({\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n fetchGasEstimates,\n fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery,\n });\n\n if (shouldUpdateState) {\n this.update((state) => {\n state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;\n state.estimatedGasFeeTimeBounds =\n gasFeeCalculations.estimatedGasFeeTimeBounds;\n state.gasEstimateType = gasFeeCalculations.gasEstimateType;\n state.gasFeeEstimatesByChainId ??= {};\n state.gasFeeEstimatesByChainId[toHex(decimalChainId)] = {\n gasFeeEstimates: gasFeeCalculations.gasFeeEstimates,\n estimatedGasFeeTimeBounds:\n gasFeeCalculations.estimatedGasFeeTimeBounds,\n gasEstimateType: gasFeeCalculations.gasEstimateType,\n } as SingleChainGasFeeState;\n });\n }\n\n return gasFeeCalculations;\n }\n\n /**\n * Remove the poll token, and stop polling if the set of poll tokens is empty.\n *\n * @param pollToken - The poll token to disconnect.\n */\n disconnectPoller(pollToken: string) {\n this.pollTokens.delete(pollToken);\n if (this.pollTokens.size === 0) {\n this.stopPolling();\n }\n }\n\n stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n this.pollTokens.clear();\n this.resetState();\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopPolling();\n }\n\n private _poll() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this._fetchGasFeeEstimateData());\n }, this.intervalDelay);\n }\n\n /**\n * Fetching token list from the Token Service API.\n *\n * @private\n * @param networkClientId - The ID of the network client triggering the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n await this._fetchGasFeeEstimateData({ networkClientId });\n }\n\n private resetState() {\n this.update(() => {\n return defaultState;\n });\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n\n getTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n ): EstimatedGasFeeTimeBounds | Record<string, never> {\n if (\n !this.state.gasFeeEstimates ||\n this.state.gasEstimateType !== GAS_ESTIMATE_TYPES.FEE_MARKET\n ) {\n return {};\n }\n return calculateTimeEstimate(\n maxPriorityFeePerGas,\n maxFeePerGas,\n this.state.gasFeeEstimates,\n );\n }\n\n async #onNetworkControllerStateChange(networkControllerState: NetworkState) {\n const newChainId = networkControllerState.providerConfig.chainId;\n\n if (newChainId !== this.currentChainId) {\n this.ethQuery = new EthQuery(this.#getProvider());\n await this.resetPolling();\n\n this.currentChainId = newChainId;\n }\n }\n}\n\nexport default GasFeeController;\n"]}
|
|
1
|
+
{"version":3,"file":"GasFeeController.js","sourceRoot":"","sources":["../src/GasFeeController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,iEAIoC;AACpC,oEAA2C;AAU3C,qEAA+E;AAE/E,+BAAoC;AAEpC,gGAAwE;AACxE,4GAAoF;AACpF,yCAKoB;AAEP,QAAA,yBAAyB,GAAG,+CAA+C,CAAC;AAoBzF;;;;;GAKG;AACU,QAAA,kBAAkB,GAAG;IAChC,UAAU,EAAE,YAAqC;IACjD,MAAM,EAAE,QAA8B;IACtC,YAAY,EAAE,cAAyC;IACvD,IAAI,EAAE,MAAwB;CAC/B,CAAC;AAiGF,MAAM,QAAQ,GAAG;IACf,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IACpD,yBAAyB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IAC9D,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACrD,CAAC;AAkDF,MAAM,IAAI,GAAG,kBAAkB,CAAC;A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YACf,OAAO,YAAY,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC;IAEa,uBAAuB;;;YACnC,MAAM,iCAAiC,GACrC,MAAM,IAAI,CAAC,qCAAqC,EAAE,CAAC;YACrD,MAAM,iCAAiC,GACrC,MAAA,MAAA,IAAI,CAAC,qCAAqC,oDAAI,mCAAI,IAAI,CAAC;YAEzD,OAAO,CACL,iCAAiC,IAAI,iCAAiC,CACvE,CAAC;;KACH;IAED,eAAe,CACb,oBAA4B,EAC5B,YAAoB;QAEpB,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe;YAC3B,IAAI,CAAC,KAAK,CAAC,eAAe,KAAK,0BAAkB,CAAC,UAAU,EAC5D;YACA,OAAO,EAAE,CAAC;SACX;QACD,OAAO,IAAA,gCAAqB,EAC1B,oBAAoB,EACpB,YAAY,EACZ,IAAI,CAAC,KAAK,CAAC,eAAe,CAC3B,CAAC;IACJ,CAAC;CAYF;AAhVD,4CAgVC;qMAVqC,sBAAoC;;QACtE,MAAM,UAAU,GAAG,sBAAsB,CAAC,cAAc,CAAC,OAAO,CAAC;QAEjE,IAAI,UAAU,KAAK,IAAI,CAAC,cAAc,EAAE;YACtC,IAAI,CAAC,QAAQ,GAAG,IAAI,mBAAQ,CAAC,uBAAA,IAAI,qCAAa,MAAjB,IAAI,CAAe,CAAC,CAAC;YAClD,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAE1B,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC;SAClC;IACH,CAAC;;AAGH,kBAAe,gBAAgB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n convertHexToDecimal,\n safelyExecute,\n toHex,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkControllerGetEIP1559CompatibilityAction,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n NetworkState,\n ProviderProxy,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { v1 as random } from 'uuid';\n\nimport determineGasFeeCalculations from './determineGasFeeCalculations';\nimport fetchGasEstimatesViaEthFeeHistory from './fetchGasEstimatesViaEthFeeHistory';\nimport {\n fetchGasEstimates,\n fetchLegacyGasPriceEstimates,\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n} from './gas-util';\n\nexport const LEGACY_GAS_PRICES_API_URL = `https://api.metaswap.codefi.network/gasPrices`;\n\nexport type unknownString = 'unknown';\n\n// Fee Market describes the way gas is set after the london hardfork, and was\n// defined by EIP-1559.\nexport type FeeMarketEstimateType = 'fee-market';\n// Legacy describes gasPrice estimates from before london hardfork, when the\n// user is connected to mainnet and are presented with fast/average/slow\n// estimate levels to choose from.\nexport type LegacyEstimateType = 'legacy';\n// EthGasPrice describes a gasPrice estimate received from eth_gasPrice. Post\n// london this value should only be used for legacy type transactions when on\n// networks that support EIP-1559. This type of estimate is the most accurate\n// to display on custom networks that don't support EIP-1559.\nexport type EthGasPriceEstimateType = 'eth_gasPrice';\n// NoEstimate describes the state of the controller before receiving its first\n// estimate.\nexport type NoEstimateType = 'none';\n\n/**\n * Indicates which type of gasEstimate the controller is currently returning.\n * This is useful as a way of asserting that the shape of gasEstimates matches\n * expectations. NONE is a special case indicating that no previous gasEstimate\n * has been fetched.\n */\nexport const GAS_ESTIMATE_TYPES = {\n FEE_MARKET: 'fee-market' as FeeMarketEstimateType,\n LEGACY: 'legacy' as LegacyEstimateType,\n ETH_GASPRICE: 'eth_gasPrice' as EthGasPriceEstimateType,\n NONE: 'none' as NoEstimateType,\n};\n\nexport type GasEstimateType =\n | FeeMarketEstimateType\n | EthGasPriceEstimateType\n | LegacyEstimateType\n | NoEstimateType;\n\nexport type EstimatedGasFeeTimeBounds = {\n lowerTimeBound: number | null;\n upperTimeBound: number | unknownString;\n};\n\n/**\n * @type EthGasPriceEstimate\n *\n * A single gas price estimate for networks and accounts that don't support EIP-1559\n * This estimate comes from eth_gasPrice but is converted to dec gwei to match other\n * return values\n * @property gasPrice - A GWEI dec string\n */\n\nexport type EthGasPriceEstimate = {\n gasPrice: string;\n};\n\n/**\n * @type LegacyGasPriceEstimate\n *\n * A set of gas price estimates for networks and accounts that don't support EIP-1559\n * These estimates include low, medium and high all as strings representing gwei in\n * decimal format.\n * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion\n * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion\n * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion\n */\nexport type LegacyGasPriceEstimate = {\n high: string;\n medium: string;\n low: string;\n};\n\n/**\n * @type Eip1559GasFee\n *\n * Data necessary to provide an estimate of a gas fee with a specific tip\n * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds\n * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds\n * @property suggestedMaxPriorityFeePerGas - A suggested \"tip\", a GWEI hex number\n * @property suggestedMaxFeePerGas - A suggested max fee, the most a user will pay. a GWEI hex number\n */\nexport type Eip1559GasFee = {\n minWaitTimeEstimate: number; // a time duration in milliseconds\n maxWaitTimeEstimate: number; // a time duration in milliseconds\n suggestedMaxPriorityFeePerGas: string; // a GWEI decimal number\n suggestedMaxFeePerGas: string; // a GWEI decimal number\n};\n\n/**\n * @type GasFeeEstimates\n *\n * Data necessary to provide multiple GasFee estimates, and supporting information, to the user\n * @property low - A GasFee for a minimum necessary combination of tip and maxFee\n * @property medium - A GasFee for a recommended combination of tip and maxFee\n * @property high - A GasFee for a high combination of tip and maxFee\n * @property estimatedBaseFee - An estimate of what the base fee will be for the pending/next block. A GWEI dec number\n * @property networkCongestion - A normalized number that can be used to gauge the congestion\n * level of the network, with 0 meaning not congested and 1 meaning extremely congested\n */\nexport type GasFeeEstimates = SourcedGasFeeEstimates | FallbackGasFeeEstimates;\n\ntype SourcedGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: [string, string];\n baseFeeTrend: 'up' | 'down' | 'level';\n latestPriorityFeeRange: [string, string];\n historicalPriorityFeeRange: [string, string];\n priorityFeeTrend: 'up' | 'down' | 'level';\n networkCongestion: number;\n};\n\ntype FallbackGasFeeEstimates = {\n low: Eip1559GasFee;\n medium: Eip1559GasFee;\n high: Eip1559GasFee;\n estimatedBaseFee: string;\n historicalBaseFeeRange: null;\n baseFeeTrend: null;\n latestPriorityFeeRange: null;\n historicalPriorityFeeRange: null;\n priorityFeeTrend: null;\n networkCongestion: null;\n};\n\nconst metadata = {\n gasFeeEstimatesByChainId: {\n persist: true,\n anonymous: false,\n },\n gasFeeEstimates: { persist: true, anonymous: false },\n estimatedGasFeeTimeBounds: { persist: true, anonymous: false },\n gasEstimateType: { persist: true, anonymous: false },\n};\n\nexport type GasFeeStateEthGasPrice = {\n gasFeeEstimates: EthGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: EthGasPriceEstimateType;\n};\n\nexport type GasFeeStateFeeMarket = {\n gasFeeEstimates: GasFeeEstimates;\n estimatedGasFeeTimeBounds: EstimatedGasFeeTimeBounds | Record<string, never>;\n gasEstimateType: FeeMarketEstimateType;\n};\n\nexport type GasFeeStateLegacy = {\n gasFeeEstimates: LegacyGasPriceEstimate;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: LegacyEstimateType;\n};\n\nexport type GasFeeStateNoEstimates = {\n gasFeeEstimates: Record<string, never>;\n estimatedGasFeeTimeBounds: Record<string, never>;\n gasEstimateType: NoEstimateType;\n};\n\nexport type FetchGasFeeEstimateOptions = {\n shouldUpdateState?: boolean;\n networkClientId?: NetworkClientId;\n};\n\n/**\n * @type GasFeeState\n *\n * Gas Fee controller state\n * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties\n * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum\n */\nexport type SingleChainGasFeeState =\n | GasFeeStateEthGasPrice\n | GasFeeStateFeeMarket\n | GasFeeStateLegacy\n | GasFeeStateNoEstimates;\n\nexport type GasFeeEstimatesByChainId = {\n gasFeeEstimatesByChainId?: Record<string, SingleChainGasFeeState>;\n};\n\nexport type GasFeeState = GasFeeEstimatesByChainId & SingleChainGasFeeState;\n\nconst name = 'GasFeeController';\n\nexport type GasFeeStateChange = ControllerStateChangeEvent<\n typeof name,\n GasFeeState\n>;\n\nexport type GetGasFeeState = ControllerGetStateAction<typeof name, GasFeeState>;\n\nexport type GasFeeControllerActions = GetGasFeeState;\n\nexport type GasFeeControllerEvents = GasFeeStateChange;\n\ntype AllowedActions =\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetEIP1559CompatibilityAction;\n\ntype GasFeeMessenger = RestrictedControllerMessenger<\n typeof name,\n GasFeeControllerActions | AllowedActions,\n GasFeeControllerEvents | NetworkControllerNetworkDidChangeEvent,\n AllowedActions['type'],\n NetworkControllerNetworkDidChangeEvent['type']\n>;\n\nconst defaultState: GasFeeState = {\n gasFeeEstimatesByChainId: {},\n gasFeeEstimates: {},\n estimatedGasFeeTimeBounds: {},\n gasEstimateType: GAS_ESTIMATE_TYPES.NONE,\n};\n\n/**\n * Controller that retrieves gas fee estimate data and polls for updated data on a set interval\n */\nexport class GasFeeController extends StaticIntervalPollingController<\n typeof name,\n GasFeeState,\n GasFeeMessenger\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay;\n\n private readonly pollTokens: Set<string>;\n\n private readonly legacyAPIEndpoint: string;\n\n private readonly EIP1559APIEndpoint: string;\n\n private readonly getCurrentNetworkEIP1559Compatibility;\n\n private readonly getCurrentNetworkLegacyGasAPICompatibility;\n\n private readonly getCurrentAccountEIP1559Compatibility;\n\n private currentChainId;\n\n private ethQuery?: EthQuery;\n\n private readonly clientId?: string;\n\n #getProvider: () => ProviderProxy;\n\n /**\n * Creates a GasFeeController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The time in milliseconds to wait between polls.\n * @param options.messenger - The controller messenger.\n * @param options.state - The initial state.\n * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current\n * network is EIP-1559 compatible.\n * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the\n * current network is compatible with the legacy gas price API.\n * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current\n * account is EIP-1559 compatible.\n * @param options.getChainId - Returns the current chain ID.\n * @param options.getProvider - Returns a network provider for the current network.\n * @param options.onNetworkDidChange - A function for registering an event handler for the\n * network state change event.\n * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for\n * testing purposes.\n * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL.\n * @param options.clientId - The client ID used to identify to the gas estimation API who is\n * asking for estimates.\n */\n constructor({\n interval = 15000,\n messenger,\n state,\n getCurrentNetworkEIP1559Compatibility,\n getCurrentAccountEIP1559Compatibility,\n getChainId,\n getCurrentNetworkLegacyGasAPICompatibility,\n getProvider,\n onNetworkDidChange,\n legacyAPIEndpoint = LEGACY_GAS_PRICES_API_URL,\n EIP1559APIEndpoint,\n clientId,\n }: {\n interval?: number;\n messenger: GasFeeMessenger;\n state?: GasFeeState;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkLegacyGasAPICompatibility: () => boolean;\n getCurrentAccountEIP1559Compatibility?: () => boolean;\n getChainId?: () => Hex;\n getProvider: () => ProviderProxy;\n onNetworkDidChange?: (listener: (state: NetworkState) => void) => void;\n legacyAPIEndpoint?: string;\n EIP1559APIEndpoint: string;\n clientId?: string;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.intervalDelay = interval;\n this.setIntervalLength(interval);\n this.pollTokens = new Set();\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n this.getCurrentNetworkLegacyGasAPICompatibility =\n getCurrentNetworkLegacyGasAPICompatibility;\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.#getProvider = getProvider;\n this.EIP1559APIEndpoint = EIP1559APIEndpoint;\n this.legacyAPIEndpoint = legacyAPIEndpoint;\n this.clientId = clientId;\n\n this.ethQuery = new EthQuery(this.#getProvider());\n\n if (onNetworkDidChange && getChainId) {\n this.currentChainId = getChainId();\n onNetworkDidChange(async (networkControllerState) => {\n await this.#onNetworkControllerDidChange(networkControllerState);\n });\n } else {\n this.currentChainId = this.messagingSystem.call(\n 'NetworkController:getState',\n ).providerConfig.chainId;\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n async (networkControllerState) => {\n await this.#onNetworkControllerDidChange(networkControllerState);\n },\n );\n }\n }\n\n async resetPolling() {\n if (this.pollTokens.size !== 0) {\n const tokens = Array.from(this.pollTokens);\n this.stopPolling();\n await this.getGasFeeEstimatesAndStartPolling(tokens[0]);\n tokens.slice(1).forEach((token) => {\n this.pollTokens.add(token);\n });\n }\n }\n\n async fetchGasFeeEstimates(options?: FetchGasFeeEstimateOptions) {\n return await this._fetchGasFeeEstimateData(options);\n }\n\n async getGasFeeEstimatesAndStartPolling(\n pollToken: string | undefined,\n ): Promise<string> {\n const _pollToken = pollToken || random();\n\n this.pollTokens.add(_pollToken);\n\n if (this.pollTokens.size === 1) {\n await this._fetchGasFeeEstimateData();\n this._poll();\n }\n\n return _pollToken;\n }\n\n /**\n * Gets and sets gasFeeEstimates in state.\n *\n * @param options - The gas fee estimate options.\n * @param options.shouldUpdateState - Determines whether the state should be updated with the\n * updated gas estimates.\n * @returns The gas fee estimates.\n */\n async _fetchGasFeeEstimateData(\n options: FetchGasFeeEstimateOptions = {},\n ): Promise<GasFeeState> {\n const { shouldUpdateState = true, networkClientId } = options;\n\n let ethQuery,\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n decimalChainId: number;\n\n if (networkClientId !== undefined) {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n isLegacyGasAPICompatible = networkClient.configuration.chainId === '0x38';\n\n decimalChainId = convertHexToDecimal(networkClient.configuration.chainId);\n\n try {\n const result = await this.messagingSystem.call(\n 'NetworkController:getEIP1559Compatibility',\n networkClientId,\n );\n isEIP1559Compatible = result || false;\n } catch {\n isEIP1559Compatible = false;\n }\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n ethQuery ??= this.ethQuery;\n\n isLegacyGasAPICompatible ??=\n this.getCurrentNetworkLegacyGasAPICompatibility();\n\n decimalChainId ??= convertHexToDecimal(this.currentChainId);\n\n try {\n isEIP1559Compatible ??= await this.getEIP1559Compatibility();\n } catch (e) {\n console.error(e);\n isEIP1559Compatible ??= false;\n }\n\n const gasFeeCalculations = await determineGasFeeCalculations({\n isEIP1559Compatible,\n isLegacyGasAPICompatible,\n fetchGasEstimates,\n fetchGasEstimatesUrl: this.EIP1559APIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchGasEstimatesViaEthFeeHistory,\n fetchLegacyGasPriceEstimates,\n fetchLegacyGasPriceEstimatesUrl: this.legacyAPIEndpoint.replace(\n '<chain_id>',\n `${decimalChainId}`,\n ),\n fetchEthGasPriceEstimate,\n calculateTimeEstimate,\n clientId: this.clientId,\n ethQuery,\n });\n\n if (shouldUpdateState) {\n this.update((state) => {\n state.gasFeeEstimates = gasFeeCalculations.gasFeeEstimates;\n state.estimatedGasFeeTimeBounds =\n gasFeeCalculations.estimatedGasFeeTimeBounds;\n state.gasEstimateType = gasFeeCalculations.gasEstimateType;\n state.gasFeeEstimatesByChainId ??= {};\n state.gasFeeEstimatesByChainId[toHex(decimalChainId)] = {\n gasFeeEstimates: gasFeeCalculations.gasFeeEstimates,\n estimatedGasFeeTimeBounds:\n gasFeeCalculations.estimatedGasFeeTimeBounds,\n gasEstimateType: gasFeeCalculations.gasEstimateType,\n } as SingleChainGasFeeState;\n });\n }\n\n return gasFeeCalculations;\n }\n\n /**\n * Remove the poll token, and stop polling if the set of poll tokens is empty.\n *\n * @param pollToken - The poll token to disconnect.\n */\n disconnectPoller(pollToken: string) {\n this.pollTokens.delete(pollToken);\n if (this.pollTokens.size === 0) {\n this.stopPolling();\n }\n }\n\n stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n this.pollTokens.clear();\n this.resetState();\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopPolling();\n }\n\n private _poll() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this._fetchGasFeeEstimateData());\n }, this.intervalDelay);\n }\n\n /**\n * Fetching token list from the Token Service API.\n *\n * @private\n * @param networkClientId - The ID of the network client triggering the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n await this._fetchGasFeeEstimateData({ networkClientId });\n }\n\n private resetState() {\n this.update(() => {\n return defaultState;\n });\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n\n getTimeEstimate(\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n ): EstimatedGasFeeTimeBounds | Record<string, never> {\n if (\n !this.state.gasFeeEstimates ||\n this.state.gasEstimateType !== GAS_ESTIMATE_TYPES.FEE_MARKET\n ) {\n return {};\n }\n return calculateTimeEstimate(\n maxPriorityFeePerGas,\n maxFeePerGas,\n this.state.gasFeeEstimates,\n );\n }\n\n async #onNetworkControllerDidChange(networkControllerState: NetworkState) {\n const newChainId = networkControllerState.providerConfig.chainId;\n\n if (newChainId !== this.currentChainId) {\n this.ethQuery = new EthQuery(this.#getProvider());\n await this.resetPolling();\n\n this.currentChainId = newChainId;\n }\n }\n}\n\nexport default GasFeeController;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"determineGasFeeCalculations.d.ts","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,mBAAmB,EACnB,eAAe,EACf,WAAW,IAAI,kBAAkB,EACjC,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAG5B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAA8B,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,GACT,EAAE;IACD,mBAAmB,EAAE,OAAO,CAAC;IAC7B,wBAAwB,EAAE,OAAO,CAAC;IAClC,iBAAiB,EAAE,CACjB,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,KACd,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,iCAAiC,EAAE,
|
|
1
|
+
{"version":3,"file":"determineGasFeeCalculations.d.ts","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,mBAAmB,EACnB,eAAe,EACf,WAAW,IAAI,kBAAkB,EACjC,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAG5B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAA8B,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,GACT,EAAE;IACD,mBAAmB,EAAE,OAAO,CAAC;IAC7B,wBAAwB,EAAE,OAAO,CAAC;IAClC,iBAAiB,EAAE,CACjB,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,KACd,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,iCAAiC,EAAE,CAGjC,QAAQ,EAAE,GAAG,KACV,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,4BAA4B,EAAE,CAC5B,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,MAAM,KACd,OAAO,CAAC,sBAAsB,CAAC,CAAC;IACrC,+BAA+B,EAAE,MAAM,CAAC;IAGxC,wBAAwB,EAAE,CAAC,QAAQ,EAAE,GAAG,KAAK,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAC1E,qBAAqB,EAAE,CACrB,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,eAAe,KAC7B,yBAAyB,CAAC;IAC/B,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAG7B,QAAQ,EAAE,GAAG,CAAC;CACf,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAkD9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"determineGasFeeCalculations.js","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":[],"mappings":";;;;;;;;;;;AAOA,yDAAwD;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;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,
|
|
1
|
+
{"version":3,"file":"determineGasFeeCalculations.js","sourceRoot":"","sources":["../src/determineGasFeeCalculations.ts"],"names":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7B,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;AA5FD,8CA4FC","sourcesContent":["import type {\n EstimatedGasFeeTimeBounds,\n EthGasPriceEstimate,\n GasFeeEstimates,\n GasFeeState as GasFeeCalculations,\n LegacyGasPriceEstimate,\n} from './GasFeeController';\nimport { GAS_ESTIMATE_TYPES } from './GasFeeController';\n\n/**\n * Obtains a set of max base and priority fee estimates along with time estimates so that we\n * can present them to users when they are sending transactions or making swaps.\n *\n * @param args - The arguments.\n * @param args.isEIP1559Compatible - Governs whether or not we can use an EIP-1559-only method to\n * produce estimates.\n * @param args.isLegacyGasAPICompatible - Governs whether or not we can use a non-EIP-1559 method to\n * produce estimates (for instance, testnets do not support estimates altogether).\n * @param args.fetchGasEstimates - A function that fetches gas estimates using an EIP-1559-specific\n * API.\n * @param args.fetchGasEstimatesUrl - The URL for the API we can use to obtain EIP-1559-specific\n * estimates.\n * @param args.fetchGasEstimatesViaEthFeeHistory - A function that fetches gas estimates using\n * `eth_feeHistory` (an EIP-1559 feature).\n * @param args.fetchLegacyGasPriceEstimates - A function that fetches gas estimates using an\n * non-EIP-1559-specific API.\n * @param args.fetchLegacyGasPriceEstimatesUrl - The URL for the API we can use to obtain\n * non-EIP-1559-specific estimates.\n * @param args.fetchEthGasPriceEstimate - A function that fetches gas estimates using\n * `eth_gasPrice`.\n * @param args.calculateTimeEstimate - A function that determine time estimate bounds.\n * @param args.clientId - An identifier that an API can use to know who is asking for estimates.\n * @param args.ethQuery - An EthQuery instance we can use to talk to Ethereum directly.\n * @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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ethQuery: any,\n ) => Promise<GasFeeEstimates>;\n fetchLegacyGasPriceEstimates: (\n url: string,\n clientId?: string,\n ) => Promise<LegacyGasPriceEstimate>;\n fetchLegacyGasPriceEstimatesUrl: string;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fetchEthGasPriceEstimate: (ethQuery: any) => Promise<EthGasPriceEstimate>;\n calculateTimeEstimate: (\n maxPriorityFeePerGas: string,\n maxFeePerGas: string,\n gasFeeEstimates: GasFeeEstimates,\n ) => EstimatedGasFeeTimeBounds;\n clientId: string | undefined;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ethQuery: any;\n}): 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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchBlockFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"fetchBlockFeeHistory.d.ts","sourceRoot":"","sources":["../src/fetchBlockFeeHistory.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAIrC,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,EA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B,CAAC,CAAC,EAAE;QAClD,mBAAmB,GAAG,cAAc,CAAC,QAAQ,EAAE,CAAC;KACjD;IAED,MAAM,UAAU,GAAG,EAAE,CAAC;IACtB,KACE,IAAI,qBAAqB,GAAG,cAAc,CAAC,IAAI,CAAC,mBAAmB,CAAC,EACpE,qBAAqB,CAAC,EAAE,CAAC,cAAc,CAAC,EACxC,qBAAqB,GAAG,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\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,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,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;YAC7D,C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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"]}
|
|
@@ -4,8 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
7
|
+
const ethjs_unit_1 = require("@metamask/ethjs-unit");
|
|
7
8
|
const ethereumjs_util_1 = require("ethereumjs-util");
|
|
8
|
-
const ethjs_unit_1 = require("ethjs-unit");
|
|
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];
|
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,
|
|
1
|
+
{"version":3,"file":"calculateGasFeeEstimatesForPriorityLevels.js","sourceRoot":"","sources":["../../src/fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels.ts"],"names":[],"mappings":";;;;;AAAA,iEAAkD;AAClD,qDAA+C;AAC/C,qDAAqC;AAIrC,0DAAkC;AAKlC,MA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0C,CAAC,CAAC;AACjD,CAAC;AAVD,4DAUC","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport { fromWei } from '@metamask/ethjs-unit';\nimport { BN } from 'ethereumjs-util';\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"]}
|
|
@@ -13,7 +13,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
13
13
|
};
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
16
|
-
const ethjs_unit_1 = require("ethjs-unit");
|
|
16
|
+
const ethjs_unit_1 = require("@metamask/ethjs-unit");
|
|
17
17
|
const fetchBlockFeeHistory_1 = __importDefault(require("./fetchBlockFeeHistory"));
|
|
18
18
|
const calculateGasFeeEstimatesForPriorityLevels_1 = __importDefault(require("./fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels"));
|
|
19
19
|
const fetchLatestBlock_1 = __importDefault(require("./fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock"));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchGasEstimatesViaEthFeeHistory.js","sourceRoot":"","sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iEAAkD;AAElD,
|
|
1
|
+
{"version":3,"file":"fetchGasEstimatesViaEthFeeHistory.js","sourceRoot":"","sources":["../src/fetchGasEstimatesViaEthFeeHistory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iEAAkD;AAElD,qDAA+C;AAE/C,kFAA0D;AAC1D,8JAAsI;AACtI,4GAAoF;AAGpF;;;;;;;;;;;;;;;;;GAiBG;AACH,SAA8B,iCAAiC,CAC7D,QAAkB;;QAElB,MAAM,WAAW,GAAG,MAAM,IAAA,0BAAgB,EAAC,QAAQ,CAAC,CAAC;QACrD,MAAM,MAAM,GAAG,MAAM,IAAA,8BAAoB,EAAC;YACxC,QAAQ;YACR,QAAQ,EAAE,WAAW,CAAC,MAAM;YAC5B,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;SAC1B,CAAC,CAAC;QACH,MAAM,gBAAgB,GAAG,IAAA,oBAAO,EAAC,WAAW,CAAC,aAAa,EAAE,uBAAI,CAAC,CAAC;QAElE,MAAM,sBAAsB,GAC1B,IAAA,mDAAyC,EAAC,MAAM,CAAC,CAAC;QAEpD,uCACK,sBAAsB,KACzB,gBAAgB,EAChB,sBAAsB,EAAE,IAAI,EAC5B,YAAY,EAAE,IAAI,EAClB,sBAAsB,EAAE,IAAI,EAC5B,0BAA0B,EAAE,IAAI,EAChC,gBAAgB,EAAE,IAAI,EACtB,iBAAiB,EAAE,IAAI,IACvB;IACJ,CAAC;CAAA;AAzBD,oDAyBC","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { fromWei } from '@metamask/ethjs-unit';\n\nimport fetchBlockFeeHistory from './fetchBlockFeeHistory';\nimport calculateGasFeeEstimatesForPriorityLevels from './fetchGasEstimatesViaEthFeeHistory/calculateGasFeeEstimatesForPriorityLevels';\nimport fetchLatestBlock from './fetchGasEstimatesViaEthFeeHistory/fetchLatestBlock';\nimport type { GasFeeEstimates } from './GasFeeController';\n\n/**\n * Generates gas fee estimates based on gas fees that have been used in the recent past so that\n * those estimates can be displayed to users.\n *\n * To produce the estimates, the last 5 blocks are read from the network, and for each block, the\n * priority fees for transactions at the 10th, 20th, and 30th percentiles are also read (here\n * \"percentile\" signifies the level at which those transactions contribute to the overall gas used\n * for the block, where higher percentiles correspond to higher fees). This information is used to\n * calculate reasonable max priority and max fees for three different priority levels (higher\n * priority = higher fee).\n *\n * Note that properties are returned for other data that are normally obtained via the API; however,\n * to prevent extra requests to Infura, these properties are empty.\n *\n * @param ethQuery - An EthQuery instance.\n * @returns Base and priority fee estimates, categorized by priority level, as well as an estimate\n * for the next block's base fee.\n */\nexport default async function fetchGasEstimatesViaEthFeeHistory(\n ethQuery: EthQuery,\n): Promise<GasFeeEstimates> {\n const latestBlock = await fetchLatestBlock(ethQuery);\n const blocks = await fetchBlockFeeHistory({\n ethQuery,\n endBlock: latestBlock.number,\n numberOfBlocks: 5,\n percentiles: [10, 20, 30],\n });\n const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI);\n\n const levelSpecificEstimates =\n calculateGasFeeEstimatesForPriorityLevels(blocks);\n\n return {\n ...levelSpecificEstimates,\n estimatedBaseFee,\n historicalBaseFeeRange: null,\n baseFeeTrend: null,\n latestPriorityFeeRange: null,\n historicalPriorityFeeRange: null,\n priorityFeeTrend: null,\n networkCongestion: null,\n };\n}\n"]}
|
package/dist/gas-util.js
CHANGED
|
@@ -21,7 +21,7 @@ const makeClientIdHeader = (clientId) => ({ 'X-Client-Id': clientId });
|
|
|
21
21
|
*/
|
|
22
22
|
function normalizeGWEIDecimalNumbers(n) {
|
|
23
23
|
const numberAsWEIHex = (0, controller_utils_1.gweiDecToWEIBN)(n).toString(16);
|
|
24
|
-
const numberAsGWEI = (0, controller_utils_1.weiHexToGweiDec)(numberAsWEIHex)
|
|
24
|
+
const numberAsGWEI = (0, controller_utils_1.weiHexToGweiDec)(numberAsWEIHex);
|
|
25
25
|
return numberAsGWEI;
|
|
26
26
|
}
|
|
27
27
|
exports.normalizeGWEIDecimalNumbers = normalizeGWEIDecimalNumbers;
|
package/dist/gas-util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-util.js","sourceRoot":"","sources":["../src/gas-util.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAKoC;AAEpC,qDAAqC;AAUrC,MAAM,kBAAkB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,CAAC;AAE/E;;;;;GAKG;AACH,SAAgB,2BAA2B,CAAC,CAAkB;IAC5D,MAAM,cAAc,GAAG,IAAA,iCAAc,EAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACtD,MAAM,YAAY,GAAG,IAAA,kCAAe,EAAC,cAAc,CAAC,CAAC
|
|
1
|
+
{"version":3,"file":"gas-util.js","sourceRoot":"","sources":["../src/gas-util.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAK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I,CAAC,mBAAmB,CAAC;QAC1C,cAAc,GAAG,IAAI,CAAC,mBAAmB,CAAC;KAC3C;SAAM;QACL,cAAc,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 'ethereumjs-util';\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": "
|
|
3
|
+
"version": "12.0.0-preview.c9a5f6a5",
|
|
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",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"build:docs": "typedoc",
|
|
25
|
+
"changelog:update": "../../scripts/update-changelog.sh @metamask/gas-fee-controller",
|
|
25
26
|
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/gas-fee-controller",
|
|
26
27
|
"publish:preview": "yarn npm publish --tag preview",
|
|
27
28
|
"test": "jest --reporters=jest-silent-reporter",
|
|
@@ -30,19 +31,19 @@
|
|
|
30
31
|
"test:watch": "jest --watch"
|
|
31
32
|
},
|
|
32
33
|
"dependencies": {
|
|
33
|
-
"@metamask/base-controller": "^
|
|
34
|
-
"@metamask/controller-utils": "^
|
|
34
|
+
"@metamask/base-controller": "^4.0.1",
|
|
35
|
+
"@metamask/controller-utils": "^8.0.1",
|
|
35
36
|
"@metamask/eth-query": "^4.0.0",
|
|
36
|
-
"@metamask/
|
|
37
|
-
"@metamask/
|
|
37
|
+
"@metamask/ethjs-unit": "^0.2.1",
|
|
38
|
+
"@metamask/network-controller": "^17.1.0",
|
|
39
|
+
"@metamask/polling-controller": "^4.0.0",
|
|
38
40
|
"@metamask/utils": "^8.2.0",
|
|
39
41
|
"@types/uuid": "^8.3.0",
|
|
40
42
|
"ethereumjs-util": "^7.0.10",
|
|
41
|
-
"ethjs-unit": "^0.1.6",
|
|
42
43
|
"uuid": "^8.3.2"
|
|
43
44
|
},
|
|
44
45
|
"devDependencies": {
|
|
45
|
-
"@metamask/auto-changelog": "^3.4.
|
|
46
|
+
"@metamask/auto-changelog": "^3.4.4",
|
|
46
47
|
"@types/jest": "^27.4.1",
|
|
47
48
|
"@types/jest-when": "^2.7.3",
|
|
48
49
|
"deepmerge": "^4.2.2",
|
|
@@ -56,7 +57,7 @@
|
|
|
56
57
|
"typescript": "~4.8.4"
|
|
57
58
|
},
|
|
58
59
|
"peerDependencies": {
|
|
59
|
-
"@metamask/network-controller": "^
|
|
60
|
+
"@metamask/network-controller": "^17.1.0"
|
|
60
61
|
},
|
|
61
62
|
"engines": {
|
|
62
63
|
"node": ">=16.0.0"
|