aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/gas_price_estimator.ts
blob: 9eccfe5101b0e8b92738811e36be8a7af6941099 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { BigNumber } from '@0x/utils';

import { DEFAULT_GAS_PRICE } from '../constants';

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 endpointUrl = 'https://ethgasstation.info/json/ethgasAPI.json';
const fetchFastAmountInWei = async () => {
    const res = await fetch(endpointUrl);
    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;
    }
}
export const gasPriceEstimator = new GasPriceEstimator();