on e5e005a help sign in
bridge/src/lib/useGasPrice.js
55 lines 1.6 kB history raw
1import { useCallback, useEffect, useState } from 'react';
3import { useNetwork } from 'store/network';
5import getSuggestedGasPrices, {
6 defaultGasValues,
7} from 'lib/getSuggestedGasPrice';
8import { DEFAULT_GAS_PRICE_GWEI } from './constants';
10/**
11 * handles all of the state of components that manage gas prices
12 * + simple get/set
13 * + lazy fetching optimal gas from oracle
14 * + resetting to oracle (or sync) default
15 * @param {Number} initialGasPrice the initial gas price available instantly
16 */
17export default function useGasPrice(initialGasPrice = DEFAULT_GAS_PRICE_GWEI) {
18 const [mounted, setMounted] = useState(false);
19 const { networkType } = useNetwork();
20 const [suggestedGasPrices, setSuggestedGasPrices] = useState(
21 defaultGasValues(initialGasPrice)
22 ); // fast, average, low. In gwei
23 const [gasPrice, setGasPrice] = useState(defaultGasValues(initialGasPrice).average); // GasPriceData
25 const fetchPrices = useCallback(async () => {
26 if (!mounted) {
27 return;
28 }
30 const suggestedGasPrices = await getSuggestedGasPrices(networkType);
31 console.log(suggestedGasPrices);
33 // TODO: BN
34 setSuggestedGasPrices(suggestedGasPrices);
35 setGasPrice(suggestedGasPrices.average);
36 }, [mounted]);
38 useEffect(() => {
39 setMounted(true);
40 fetchPrices();
41 return () => (setMounted(false));
42 }, [mounted, networkType]);
44 const resetGasPrice = useCallback(
45 () => setGasPrice(suggestedGasPrices.average),
46 [suggestedGasPrices]
47 );
49 return {
50 suggestedGasPrices,
51 gasPrice,
52 setGasPrice,
53 resetGasPrice,
54 };