on 703ff86 help sign in
bridge/src/lib/useGasPrice.js
57 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(
24 defaultGasValues(initialGasPrice).average
25 ); // GasPriceData
27 const fetchPrices = useCallback(async () => {
28 if (!mounted) {
29 return;
30 }
32 const suggestedGasPrices = await getSuggestedGasPrices(networkType);
33 console.log(suggestedGasPrices);
35 // TODO: BN
36 setSuggestedGasPrices(suggestedGasPrices);
37 setGasPrice(suggestedGasPrices.average);
38 }, [mounted, networkType]);
40 useEffect(() => {
41 setMounted(true);
42 fetchPrices();
43 return () => setMounted(false);
44 }, [mounted, networkType, fetchPrices]);
46 const resetGasPrice = useCallback(
47 () => setGasPrice(suggestedGasPrices.average),
48 [suggestedGasPrices]
49 );
51 return {
52 suggestedGasPrices,
53 gasPrice,
54 setGasPrice,
55 resetGasPrice,
56 };