aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/gas_price_estimator.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/instant/src/util/gas_price_estimator.ts')
-rw-r--r--packages/instant/src/util/gas_price_estimator.ts45
1 files changed, 45 insertions, 0 deletions
diff --git a/packages/instant/src/util/gas_price_estimator.ts b/packages/instant/src/util/gas_price_estimator.ts
new file mode 100644
index 000000000..bd81ea05f
--- /dev/null
+++ b/packages/instant/src/util/gas_price_estimator.ts
@@ -0,0 +1,45 @@
+import { BigNumber } from '@0x/utils';
+
+// TODO: merge development and move to constants
+const ENDPOINT_URL = 'https://ethgasstation.info/json/ethgasAPI.json';
+const DEFAULT_GAS_PRICE_WEI = new BigNumber(20000000000);
+
+interface GasStationResult {
+ average: number;
+ fastestWait: number;
+ fastWait: number;
+ fast: number;
+ safeLowWait: number;
+ blockNum: number;
+ avgWait: number;
+ block_time: number;
+ speed: number;
+ fastest: number;
+ safeLow: number;
+}
+
+const fetchFastAmountInWei = async () => {
+ const res = await fetch(ENDPOINT_URL);
+ const gasInfo = (await res.json()) as GasStationResult;
+ const gasPriceInGwei = new BigNumber(gasInfo.fast / 10);
+ return gasPriceInGwei.mul(1000000000);
+};
+
+export class GasPriceEstimator {
+ private _lastFetched?: BigNumber;
+ public async getFastAmountInWeiAsync(): Promise<BigNumber> {
+ let fetchedAmount: BigNumber | undefined;
+ try {
+ fetchedAmount = await fetchFastAmountInWei();
+ } catch {
+ fetchedAmount = undefined;
+ }
+
+ if (fetchedAmount) {
+ this._lastFetched = fetchedAmount;
+ }
+
+ return fetchedAmount || this._lastFetched || DEFAULT_GAS_PRICE_WEI;
+ }
+}
+export const gasPriceEstimator = new GasPriceEstimator();