import { BigNumber } from '@0x/utils' ; import { ETH_GAS_STATION_API_URL } from '../config' ; import { ONE_SECOND_MS } from '../constants' ; let previousGasInfo ; let lastAccessed ; const CACHE_EXPIRY_SEC = 60 ; interface GasInfoResponse { fast : number ; fastest : number ; } const getGasInfoAsync = async ( ) => { const now = Date . now ( ) / ONE_SECOND_MS ; if ( ! previousGasInfo || now - CACHE_EXPIRY_SEC > lastAccessed ) { try { const res = await fetch ( ETH_GAS_STATION_API_URL ) ; previousGasInfo = await res . json ( ) ; lastAccessed = now ; } catch ( e ) { throw new Error ( 'Failed to fetch gas price from EthGasStation' ) ; } } return previousGasInfo ; } ; export const ethGasStationUtils = { getGasPriceOrThrowAsync : async ( txConfirmationSpeed = 'fast' ) : Promise < BigNumber > => { const gasInfo = await getGasInfoAsync ( ) ; const BASE_TEN = 10 ; const gasPriceGwei = new BigNumber ( gasInfo [ txConfirmationSpeed ] / BASE_TEN ) ; const unit = new BigNumber ( BASE_TEN ) . pow ( 9 ) ; const gasPriceWei = unit . times ( gasPriceGwei ) ; return gasPriceWei ; } , } ;