This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
useDexEthPrice.ts
60 lines (53 loc) 路 2.15 KB
/
useDexEthPrice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Token, WETH, Fetcher, Route } from '@uniswap/sdk';
import { useQuery } from 'react-query';
import { useBlockNumberContext } from '~~/context';
import { mergeDefaultUpdateOptions, processQueryOptions, providerKey, TRequiredKeys } from '~~/functions';
import { useEthersUpdater } from '~~/hooks/useEthersUpdater';
import { THookResult, TNetworkInfo, TUpdateOptions } from '~~/models';
import { keyNamespace } from '~~/models/constants';
import { TEthersProvider } from '~~/models/providerTypes';
const queryKey: TRequiredKeys = { namespace: keyNamespace.signer, key: 'useDexEthPrice' } as const;
/**
* #### Summary
* Get the Exchange price of ETH/USD (extrapolated from WETH/DAI) from uniswap
*
* ##### 鉁忥笍 Notes
* - uses useOnRepetition, does not use context
*
* @category Hooks
*
* @param mainnetProvider
* @param targetNetworkInfo
* @param pollTime if >0 use polling, else use instead of onBlock event
* @returns price in USD
*/
export const useDexEthPrice = (
mainnetProvider: TEthersProvider | undefined,
targetNetworkInfo?: TNetworkInfo,
options: TUpdateOptions = mergeDefaultUpdateOptions()
): THookResult<number> => {
const keys = [{ ...queryKey, ...providerKey(mainnetProvider) }, { networkPrice: targetNetworkInfo?.price }] as const;
type TAsyncResult = number | undefined;
const { data, refetch, status } = useQuery(
keys,
async (keys): Promise<TAsyncResult> => {
const { networkPrice } = keys.queryKey[1];
if (networkPrice) {
return networkPrice;
} else if (mainnetProvider) {
const network = await mainnetProvider.getNetwork();
const DAI = new Token(network ? network.chainId : 1, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18);
const pair = await Fetcher.fetchPairData(DAI, WETH[DAI.chainId], mainnetProvider);
const route = new Route([pair], WETH[DAI.chainId]);
const price = parseFloat(route.midPrice.toSignificant(6));
return price;
}
},
{
...processQueryOptions<TAsyncResult>(options),
}
);
const blockNumber = useBlockNumberContext();
useEthersUpdater(refetch, blockNumber, options);
return [data ?? 0, refetch, status];
};