-
Notifications
You must be signed in to change notification settings - Fork 6
/
useStrategyData.ts
95 lines (84 loc) · 2.75 KB
/
useStrategyData.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { useQuery } from "@tanstack/react-query"
import { getStrategyData } from "data/actions/common/getStrategyData"
import { cellarDataMap } from "data/cellarDataMap"
import { GetStrategyDataQuery } from "src/data/actions/types"
import { usePublicClient } from "wagmi"
import { useAllContracts } from "./useAllContracts"
import { useCoinGeckoPrice } from "./useCoinGeckoPrice"
import { fetchIndividualCellarStrategyData } from "queries/get-individual-strategy-data"
import { useState, useEffect } from "react"
import _ from 'lodash';
import { tokenConfig } from "data/tokenConfig"
export const useStrategyData = (address: string, chain: string) => {
const publicClient = usePublicClient()
const { data: allContracts } = useAllContracts()
const sommToken = tokenConfig.find(
(token) =>
token.coinGeckoId === "sommelier" &&
token.chain === chain
)!
const { data: sommPrice } = useCoinGeckoPrice(sommToken)
const [stratData, setStratData] = useState<
GetStrategyDataQuery | undefined
>(undefined)
const [error, setError] = useState(null)
const cellarData = Object.values(cellarDataMap).find(
(item) =>
item.config.cellar.address.toLowerCase() ===
address.toLowerCase() && item.config.chain.id === chain
)!
useEffect(() => {
fetchIndividualCellarStrategyData(
address.toLowerCase(),
cellarData.config.chain.id
)
.then(({ data, error }) => {
if (error) {
setError(error)
} else {
setStratData(data)
}
})
.catch((error) => setError(error))
}, [])
const config = Object.values(cellarDataMap).find(
(item) =>
item.config.cellar.address.toLowerCase() ===
address.toLowerCase() && item.config.chain.id === chain
)!.config
const isNoDataSource = Boolean(config!.isNoDataSource)
const baseAsset = config.baseAsset
const { data: baseAssetPrice } = useCoinGeckoPrice(
baseAsset
)
// if chain is not ethereum, key format is '{address}-{chain}', otherwise it is '{address}'
const key =
address + (config.chain.id !== "ethereum" ? "-" + chain : "")
// Get cellar contracts for the chain
const query = useQuery({
queryKey: [
"USE_STRATEGY_DATA",
{ provider: publicClient?.uid, address: key },
],
queryFn: async () => {
const result = await getStrategyData({
address,
contracts: allContracts![key]!,
sommPrice: sommPrice ?? "0",
stratData: _.cloneDeep(stratData?.cellar),
baseAssetPrice: baseAssetPrice ?? "0",
})
return result
},
enabled:
!!allContracts &&
!!sommPrice &&
(isNoDataSource || !!stratData) &&
!!baseAssetPrice,
}
)
return {
...query,
isError: Boolean(error) || query.isError,
}
}