@metamask-previews/gas-fee-controller 10.0.1-preview.eb58a59 → 11.0.0-preview.3fbb6b41
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 +11 -1
- package/dist/GasFeeController.d.ts +5 -5
- package/dist/GasFeeController.d.ts.map +1 -1
- package/dist/GasFeeController.js +9 -9
- package/dist/GasFeeController.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 +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [11.0.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING:** Bump `@metamask/base-controller` to ^4.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
12
|
+
- This is breaking because the type of the `messenger` has backward-incompatible changes. See the changelog for this package for more.
|
|
13
|
+
- Replace `ethjs-unit` ^0.1.6 with `@metamask/ethjs-unit` ^0.2.1 ([#2064](https://github.com/MetaMask/core/pull/2064))
|
|
14
|
+
- Bump `@metamask/controller-utils` to ^6.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
15
|
+
- Bump `@metamask/network-controller` to ^17.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
16
|
+
- Bump `@metamask/polling-controller` to ^2.0.0 ([#2063](https://github.com/MetaMask/core/pull/2063))
|
|
17
|
+
|
|
9
18
|
## [10.0.1]
|
|
10
19
|
### Changed
|
|
11
20
|
- **BREAKING:** Bump dependency and peer dependency on `@metamask/network-controller` to ^16.0.0
|
|
@@ -125,7 +134,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
125
134
|
|
|
126
135
|
All changes listed after this point were applied to this package following the monorepo conversion.
|
|
127
136
|
|
|
128
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@
|
|
137
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@11.0.0...HEAD
|
|
138
|
+
[11.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@10.0.1...@metamask/gas-fee-controller@11.0.0
|
|
129
139
|
[10.0.1]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@10.0.0...@metamask/gas-fee-controller@10.0.1
|
|
130
140
|
[10.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@9.0.0...@metamask/gas-fee-controller@10.0.0
|
|
131
141
|
[9.0.0]: https://github.com/MetaMask/core/compare/@metamask/gas-fee-controller@8.0.0...@metamask/gas-fee-controller@9.0.0
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
|
-
import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction,
|
|
2
|
+
import type { NetworkClientId, NetworkControllerGetEIP1559CompatibilityAction, NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerNetworkDidChangeEvent, NetworkState, ProviderProxy } from '@metamask/network-controller';
|
|
3
3
|
import { PollingController } 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";
|
|
@@ -144,7 +144,7 @@ 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
|
*/
|
|
@@ -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,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAY3C,eAAO,MAAM,yBAAyB,kDAAkD,CAAC;AAEzF,oBAAY,aAAa,GAAG,SAAS,CAAC;AAItC,oBAAY,qBAAqB,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W,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");
|
|
@@ -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;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;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,CAAC,wBAAwB,CAAC,EAAE,eAAe,EAAE,CAAC,CAAC;QAC3D,CAAC;KAAA;IAEO,UAAU;QAChB,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;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;yMAVuC,sBAAoC;;QACxE,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 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,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;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;AA0BhC,MAAM,YAAY,GAAgB;IAChC,wBAAwB,EAAE,EAAE;IAC5B,eAAe,EAAE,EAAE;IACnB,yBAAyB,EAAE,EAAE;IAC7B,eAAe,EAAE,0BAAkB,CAAC,IAAI;CACzC,CAAC;AAEF;;GAEG;AACH,MAAa,gBAAiB,SAAQ,sCAIrC;IAyBC;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,YAAY,EACV,QAAQ,GAAG,KAAK,E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ACH;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 { 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 | 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 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.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"]}
|
|
@@ -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,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAC3D,MAAM,0BAA0B,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAU,CAAC;AACzD,MAAM,0BAA0B,GAAG;IACjC,GAAG,EAAE;QACH,UAAU,EAAE,EAAgB;QAC5B,2BAA2B,EAAE,IAAI,oBAAE,CAAC,GAAG,CAAC;QACxC,+BAA+B,EAAE,IAAI,oBAAE,CAAC,EAAE,CAAC;QAC3C,gCAAgC,EAAE,IAAI,oBAAE,CAAC,UAAa,CAAC;QACvD,kBAAkB,EAAE;YAClB,mBAAmB,EAAE,KAAM;YAC3B,mBAAmB,EAAE,KAAM;SAC5B;KACF;IACD,MAAM,EAAE;QACN,UAAU,EAAE,EAAgB;QAC5B,2BAA2B,EAAE,IAAI,oBAAE,CAAC,GAAG,CAAC;QACxC,+B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7C,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,MAAM,6BAA6B,GAAG,oBAAE,CAAC,GAAG,CAC1C,mBAAmB,EACnB,QAAQ,CAAC,gCAAgC,CAC1C,CAAC;IACF,MAAM,qBAAqB,GAAG,eAAe,CAAC,GAAG,CAC/C,6BAA6B,CAC9B,CAAC;IAEF,uCACK,QAAQ,CAAC,kBAAkB,KAC9B,6BAA6B,EAAE,IAAA,oBAAO,EAAC,6BAA6B,EAAE,uBAAI,CAAC,EAC3E,qBAAqB,EAAE,IAAA,oBAAO,EAAC,qBAAqB,EAAE,uBAAI,CAAC,IAC3D;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAwB,yCAAyC,CAC/D,MAAqC;IAErC,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,aAAa,EAAE,EAAE;QACnD,MAAM,4BAA4B,GAAG,kCAAkC,CACrE,aAAa,EACb,MAAM,CACP,CAAC;QACF,uCAAY,GAAG,KAAE,CAAC,aAAa,CAAC,EAAE,4BAA4B,IAAG;IACnE,CAAC,EAAE,EAA0C,CAAC,CAAC;AACjD,CAAC;AAVD,4DAUC","sourcesContent":["import { GWEI } from '@metamask/controller-utils';\nimport { fromWei } from '@metamask/ethjs-unit';\nimport { BN } from '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,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;IACrD,OAAO,YAAY,CAAC;AACtB,CAAC;AAJD,kEAIC;AAED;;;;;;GAMG;AACH,SAAsB,iBAAiB,CACrC,GAAW,EACX,QAAiB;;QAEjB,MAAM,SAAS,GAAG,MAAM,IAAA,8BAAW,EACjC,GAAG,EACH,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,kBAA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A6B,CACnC,CAAC;IAEF,IAAI,cAAc,CAAC;IACnB,IAAI,cAAc,CAAC;IAEnB,IAAI,uBAAuB,CAAC,EAAE,CAAC,sBAAsB,CAAC,EAAE;QACtD,cAAc,GAAG,IAAI,CAAC;QACtB,cAAc,GAAG,SAA0B,CAAC;KAC7C;SAAM,IACL,uBAAuB,CAAC,GAAG,CAAC,sBAAsB,CAAC;QACnD,uBAAuB,CAAC,EAAE,CAAC,yBAAyB,CAAC,EACrD;QACA,cAAc,GAAG,GAAG,CAAC,mBAAmB,CAAC;QACzC,cAAc,GAAG,GAAG,CAAC,mBAAmB,CAAC;KAC1C;SAAM,IACL,uBAAuB,CAAC,GAAG,CAAC,yBAAyB,CAAC;QACtD,uBAAuB,CAAC,EAAE,CAAC,uBAAuB,CAAC,EACnD;QACA,cAAc,GAAG,MAAM,CAAC,mBAAmB,CAAC;QAC5C,cAAc,GAAG,MAAM,CAAC,mBAAmB,CAAC;KAC7C;SAAM,IAAI,uBAAuB,CAAC,EAAE,CAAC,uBAAuB,CAAC,EAAE;QAC9D,cAAc,GAAG,IAAI,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": "11.0.0-preview.3fbb6b41",
|
|
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",
|
|
@@ -30,15 +30,15 @@
|
|
|
30
30
|
"test:watch": "jest --watch"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@metamask/base-controller": "^
|
|
34
|
-
"@metamask/controller-utils": "^
|
|
33
|
+
"@metamask/base-controller": "^4.0.0",
|
|
34
|
+
"@metamask/controller-utils": "^6.1.0",
|
|
35
35
|
"@metamask/eth-query": "^4.0.0",
|
|
36
|
-
"@metamask/
|
|
37
|
-
"@metamask/
|
|
36
|
+
"@metamask/ethjs-unit": "^0.2.1",
|
|
37
|
+
"@metamask/network-controller": "^17.0.0",
|
|
38
|
+
"@metamask/polling-controller": "^2.0.0",
|
|
38
39
|
"@metamask/utils": "^8.2.0",
|
|
39
40
|
"@types/uuid": "^8.3.0",
|
|
40
41
|
"ethereumjs-util": "^7.0.10",
|
|
41
|
-
"ethjs-unit": "^0.1.6",
|
|
42
42
|
"uuid": "^8.3.2"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"typescript": "~4.8.4"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
|
-
"@metamask/network-controller": "^
|
|
59
|
+
"@metamask/network-controller": "^17.0.0"
|
|
60
60
|
},
|
|
61
61
|
"engines": {
|
|
62
62
|
"node": ">=16.0.0"
|