on 98d950d help sign in
bridge/src/lib/useGasPrice.js
53 lines 1.4 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 { networkType } = useNetwork();
19 const [suggestedGasPrices, setSuggestedGasPrices] = useState(
20 defaultGasValues(initialGasPrice)
21 ); // fast, average, low. In gwei
22 const [gasPrice, setGasPrice] = useState(initialGasPrice); // gwei
24 useEffect(() => {
25 let mounted = true;
27 (async () => {
28 const suggestedGasPrices = await getSuggestedGasPrices(networkType);
30 if (!mounted) {
31 return;
32 }
34 // TODO: BN
35 setSuggestedGasPrices(suggestedGasPrices);
36 setGasPrice(suggestedGasPrices.average.price);
37 })();
39 return () => (mounted = true);
40 }, [networkType]);
42 const resetGasPrice = useCallback(
43 () => setGasPrice(suggestedGasPrices.average.price),
44 [suggestedGasPrices]
45 );
47 return {
48 suggestedGasPrices,
49 gasPrice,
50 setGasPrice,
51 resetGasPrice,
52 };