improve use query config options

This commit is contained in:
tjs 2023-01-20 11:13:03 -05:00
parent 9c8ef98cfd
commit 63909e2bb7
10 changed files with 81 additions and 63 deletions

View File

@ -54,7 +54,7 @@ const PerpMarketsTable = ({
const coingeckoData = coingeckoPrices.find((asset) => const coingeckoData = coingeckoPrices.find((asset) =>
symbol === 'soETH' symbol === 'soETH'
? asset.symbol === 'ETH' ? asset.symbol === 'ETH'
: asset.symbol === symbol : asset.symbol.toUpperCase() === symbol.toUpperCase()
) )
const change = coingeckoData const change = coingeckoData

View File

@ -107,6 +107,7 @@ const SwapTokenChart = () => {
cacheTime: 1000 * 60 * 15, cacheTime: 1000 * 60 * 15,
staleTime: 1000 * 60 * 1, staleTime: 1000 * 60 * 1,
enabled: !!baseTokenId && !!quoteTokenId, enabled: !!baseTokenId && !!quoteTokenId,
refetchOnWindowFocus: false,
} }
) )

View File

@ -185,7 +185,10 @@ const useQuoteRoutes = ({
wallet wallet
), ),
{ {
cacheTime: 1000 * 60,
staleTime: 1000 * 30,
enabled: amount ? true : false, enabled: amount ? true : false,
retry: 3,
} }
) )

View File

@ -94,8 +94,10 @@ const CoingeckoStats = ({
const coingeckoTokenPrices = useMemo(() => { const coingeckoTokenPrices = useMemo(() => {
if (daysToShow === '1' && coingeckoPrices.length && bank) { if (daysToShow === '1' && coingeckoPrices.length && bank) {
const tokenPriceData = coingeckoPrices.find( const tokenPriceData = coingeckoPrices.find((asset) =>
(asset) => asset.symbol === bank.name bank.name === 'soETH'
? asset.symbol === 'ETH'
: asset.symbol.toUpperCase() === bank.name.toUpperCase()
) )
if (tokenPriceData) { if (tokenPriceData) {

View File

@ -3,7 +3,7 @@ import DailyRange from '@components/shared/DailyRange'
import { useTranslation } from 'next-i18next' import { useTranslation } from 'next-i18next'
import Image from 'next/legacy/image' import Image from 'next/legacy/image'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import FlipNumbers from 'react-flip-numbers' import FlipNumbers from 'react-flip-numbers'
import { formatDecimal, formatFixedDecimals } from 'utils/numbers' import { formatDecimal, formatFixedDecimals } from 'utils/numbers'
import Link from 'next/link' import Link from 'next/link'
@ -17,6 +17,7 @@ import { INITIAL_ANIMATION_SETTINGS } from '@components/settings/AnimationSettin
import ActionPanel from './ActionPanel' import ActionPanel from './ActionPanel'
import ChartTabs from './ChartTabs' import ChartTabs from './ChartTabs'
import CoingeckoStats from './CoingeckoStats' import CoingeckoStats from './CoingeckoStats'
import { useQuery } from '@tanstack/react-query'
const DEFAULT_COINGECKO_VALUES = { const DEFAULT_COINGECKO_VALUES = {
ath: 0, ath: 0,
@ -36,9 +37,18 @@ const DEFAULT_COINGECKO_VALUES = {
total_volume: 0, total_volume: 0,
} }
const fetchTokenInfo = async (tokenId: string | undefined) => {
if (!tokenId) return
const response = await fetch(
`https://api.coingecko.com/api/v3/coins/${tokenId}?localization=false&tickers=false&developer_data=false&sparkline=false
`
)
const data = await response.json()
return data
}
const TokenPage = () => { const TokenPage = () => {
const { t } = useTranslation(['common', 'token']) const { t } = useTranslation(['common', 'token'])
const [coingeckoData, setCoingeckoData] = useState<any>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const router = useRouter() const router = useRouter()
const { token } = router.query const { token } = router.query
@ -74,30 +84,21 @@ const TokenPage = () => {
} }
}, [bank, mangoTokens]) }, [bank, mangoTokens])
const fetchTokenInfo = async (tokenId: string) => { const coingeckoTokenInfo = useQuery<
const response = await fetch( { market_data: any; name: string },
`https://api.coingecko.com/api/v3/coins/${tokenId}?localization=false&tickers=false&developer_data=false&sparkline=false Error
` >(['ip-address', coingeckoId], () => fetchTokenInfo(coingeckoId), {
) cacheTime: 1000 * 60 * 15,
const data = await response.json() staleTime: 1000 * 60 * 5,
return data retry: 3,
} refetchOnWindowFocus: false,
enabled: !!coingeckoId,
})
useEffect(() => { const { high_24h, low_24h, price_change_percentage_24h } =
const getCoingeckoData = async (id: string) => { coingeckoTokenInfo.data
const response = await fetchTokenInfo(id) ? coingeckoTokenInfo.data.market_data
setCoingeckoData(response) : DEFAULT_COINGECKO_VALUES
setLoading(false)
}
if (coingeckoId) {
getCoingeckoData(coingeckoId)
}
}, [coingeckoId])
const { high_24h, low_24h, price_change_percentage_24h } = coingeckoData
? coingeckoData.market_data
: DEFAULT_COINGECKO_VALUES
return ( return (
<> <>
@ -107,9 +108,9 @@ const TokenPage = () => {
<div className="mb-4 md:mb-1"> <div className="mb-4 md:mb-1">
<div className="mb-1.5 flex items-center space-x-2"> <div className="mb-1.5 flex items-center space-x-2">
<Image src={logoURI!} height="20" width="20" /> <Image src={logoURI!} height="20" width="20" />
{coingeckoData ? ( {coingeckoTokenInfo.data ? (
<h1 className="text-base font-normal"> <h1 className="text-base font-normal">
{coingeckoData.name}{' '} {coingeckoTokenInfo.data.name}{' '}
<span className="text-th-fgd-4">({bank.name})</span> <span className="text-th-fgd-4">({bank.name})</span>
</h1> </h1>
) : ( ) : (
@ -131,13 +132,13 @@ const TokenPage = () => {
<span>{formatFixedDecimals(bank.uiPrice, true)}</span> <span>{formatFixedDecimals(bank.uiPrice, true)}</span>
)} )}
</div> </div>
{coingeckoData ? ( {coingeckoTokenInfo.data ? (
<div className="mb-2"> <div className="mb-2">
<Change change={price_change_percentage_24h} suffix="%" /> <Change change={price_change_percentage_24h} suffix="%" />
</div> </div>
) : null} ) : null}
</div> </div>
{coingeckoData ? ( {coingeckoTokenInfo.data ? (
<DailyRange <DailyRange
high={high_24h.usd} high={high_24h.usd}
low={low_24h.usd} low={low_24h.usd}
@ -165,10 +166,10 @@ const TokenPage = () => {
% %
</span> </span>
</div> </div>
{coingeckoData && coingeckoId ? ( {coingeckoTokenInfo.data && coingeckoId ? (
<CoingeckoStats <CoingeckoStats
bank={bank} bank={bank}
coingeckoData={coingeckoData} coingeckoData={coingeckoTokenInfo.data}
coingeckoId={coingeckoId} coingeckoId={coingeckoId}
/> />
) : ( ) : (

View File

@ -25,7 +25,7 @@ const AdvancedMarketHeader = ({
return tokenPrices.find((asset) => return tokenPrices.find((asset) =>
baseSymbol === 'soETH' baseSymbol === 'soETH'
? asset.symbol === 'ETH' ? asset.symbol === 'ETH'
: asset.symbol === baseSymbol : asset.symbol.toUpperCase() === baseSymbol?.toUpperCase()
) )
}, [baseSymbol, tokenPrices]) }, [baseSymbol, tokenPrices])

View File

@ -21,9 +21,9 @@ export const usePerpFundingRate = () => {
['funding-rate'], ['funding-rate'],
() => fetchFundingRate(group?.publicKey?.toString()), () => fetchFundingRate(group?.publicKey?.toString()),
{ {
cacheTime: 1000 * 60, cacheTime: 1000 * 60 * 10,
staleTime: 1000 * 60, staleTime: 1000 * 60,
retry: true, retry: 3,
enabled: !!group, enabled: !!group,
} }
) )

View File

@ -9,21 +9,21 @@ const fetchCoingecko = async (
id: token.extensions?.coingeckoId, id: token.extensions?.coingeckoId,
symbol: token.symbol, symbol: token.symbol,
})) }))
const promises: any = [] const promises: any = []
for (const token of coingeckoIds) { for (const token of coingeckoIds) {
if (token.id) { if (token.id) {
promises.push( promises.push(
fetch( fetch(
`https://api.coingecko.com/api/v3/coins/${token.id}/market_chart?vs_currency=usd&days=1` `https://api.coingecko.com/api/v3/coins/${token.id}/market_chart?vs_currency=usd&days=1`
).then((res) => res.json()) ).then((res) =>
res.json().then((r) => ({ ...r, symbol: token.symbol }))
)
) )
} }
} }
const data = await Promise.all(promises) const data = await Promise.all(promises)
for (let i = 0; i < data.length; i++) {
data[i].symbol = coingeckoIds[i].symbol
}
return data || [] return data || []
} }
@ -33,12 +33,13 @@ export const useCoingecko = () => {
const res = useQuery<any[], Error>( const res = useQuery<any[], Error>(
['coingecko-tokens'], ['coingecko-tokens'],
() => fetchCoingecko(mangoTokens!), () => fetchCoingecko(mangoTokens),
{ {
cacheTime: 1000 * 60 * 2, cacheTime: 1000 * 60 * 15,
staleTime: 1000 * 60 * 2, staleTime: 1000 * 60 * 10,
retry: true, retry: 3,
enabled: !!mangoTokens, enabled: !!mangoTokens?.length,
refetchOnWindowFocus: false,
} }
) )

View File

@ -1,5 +1,6 @@
import { CLUSTER } from '@store/mangoStore' import { CLUSTER } from '@store/mangoStore'
import { useCallback, useEffect, useState } from 'react' import { useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
const SANCTIONED_COUNTRIES = [ const SANCTIONED_COUNTRIES = [
['AG', 'Antigua and Barbuda'], ['AG', 'Antigua and Barbuda'],
@ -36,29 +37,37 @@ const SANCTIONED_COUNTRY_CODES = SANCTIONED_COUNTRIES.map(
const SPOT_ALLOWED = ['GB'] const SPOT_ALLOWED = ['GB']
const fetchIpGeolocation = async () => {
const response = await fetch(`https://country-code.mangomarkets.workers.dev`)
const parsedResponse = await response.json()
const ipCountryCode = parsedResponse ? parsedResponse?.country : ''
return ipCountryCode
}
export default function useIpAddress() { export default function useIpAddress() {
const [ipAllowed, setIpAllowed] = useState(false) const [ipAllowed, setIpAllowed] = useState(false)
const [spotAllowed, setSpotAllowed] = useState(false) const [spotAllowed, setSpotAllowed] = useState(false)
const [ipCountry, setIpCountry] = useState('') const [ipCountry, setIpCountry] = useState('')
const checkIpLocation = useCallback(async () => { const ipCountryCode = useQuery<string, Error>(
const response = await fetch( ['ip-address'],
`https://country-code.mangomarkets.workers.dev` () => fetchIpGeolocation(),
) {
const parsedResponse = await response.json() cacheTime: 1000 * 60 * 2,
const ipCountryCode = parsedResponse ? parsedResponse?.country : '' staleTime: 1000 * 60 * 2,
retry: 3,
setIpCountry(ipCountryCode) refetchOnWindowFocus: true,
if (ipCountryCode) {
setIpAllowed(!SANCTIONED_COUNTRY_CODES.includes(ipCountryCode))
setSpotAllowed(SPOT_ALLOWED.includes(ipCountryCode))
} }
}, []) )
useEffect(() => { useEffect(() => {
checkIpLocation() if (ipCountryCode.data) {
}, [checkIpLocation]) setIpCountry(ipCountryCode.data)
setIpAllowed(!SANCTIONED_COUNTRY_CODES.includes(ipCountryCode.data))
setSpotAllowed(SPOT_ALLOWED.includes(ipCountryCode.data))
}
}, [ipCountryCode])
if (CLUSTER === 'mainnet-beta') { if (CLUSTER === 'mainnet-beta') {
return { ipAllowed, spotAllowed, ipCountry } return { ipAllowed, spotAllowed, ipCountry }

View File

@ -37,8 +37,9 @@ const useJupiterMints = (): {
{ {
cacheTime: 1000 * 60 * 10, cacheTime: 1000 * 60 * 10,
staleTime: 1000 * 60 * 10, staleTime: 1000 * 60 * 10,
retry: true, retry: 3,
enabled: !!group, enabled: !!group,
refetchOnWindowFocus: false,
} }
) )