on master help sign in
bridge/src/lib/useGasPrice.js
60 lines 1.7 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, web3 } = 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(
33 networkType,
34 web3.getOrElse(null)
35 );
36 console.log(suggestedGasPrices);
38 // TODO: BN
39 setSuggestedGasPrices(suggestedGasPrices);
40 setGasPrice(suggestedGasPrices.average);
41 }, [mounted, networkType, web3]);
43 useEffect(() => {
44 setMounted(true);
45 fetchPrices();
46 return () => setMounted(false);
47 }, [mounted, networkType, web3, fetchPrices]);
49 const resetGasPrice = useCallback(
50 () => setGasPrice(suggestedGasPrices.average),
51 [suggestedGasPrices]
52 );
54 return {
55 suggestedGasPrices,
56 gasPrice,
57 setGasPrice,
58 resetGasPrice,
59 };