Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve config loading #602

Merged
merged 4 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions components/AssetInput/AssetList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ const AssetList: FC<AssetListProps> = ({
}) => {
const [tokenList, setup] = useTokenList()
const { network, chainId } = useRecoilValue(chainState)
const config = useConfig(network, chainId)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const tokens = useMemo(() => {
if (!config) {
if (!config || isConfigLoading) {
return []
}

Expand Down
8 changes: 4 additions & 4 deletions components/Pages/Bonding/Bonding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ import { useRecoilValue } from 'recoil'
import { chainState } from 'state/chainState'

import BondingOverview, { ActionType, TokenType } from './BondingOverview'
import { Config, useConfig, useDashboardData } from './hooks/useDashboardData'
import { useConfig, useDashboardData } from './hooks/useDashboardData'
import RewardsComponent from './RewardsComponent'
import { BondingData } from './types/BondingData'

const Bonding: FC = () => {
const { chainId, chainName, network, walletChainName } = useRecoilValue(chainState)
const { isWalletConnected, address } = useChain(walletChainName)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)


const data: BondingData[] = [
{
Expand Down Expand Up @@ -128,8 +130,6 @@ const Bonding: FC = () => {

const whalePrice = useWhalePrice()

const config: Config = useConfig(network, chainId)

const symbols = useMemo(() => {
const tokenSymbols = config?.bonding_tokens?.map((token) => token.symbol) || []
return Array.from(new Set([...tokenSymbols, WHALE_TOKEN_SYMBOL]))
Expand Down Expand Up @@ -171,7 +171,7 @@ const Bonding: FC = () => {
symbols,
])
const { isOpen, onOpen, onClose } = useDisclosure()
return <>{isLoading && isWalletConnected ?
return <>{(isLoading || isConfigLoading) && isWalletConnected ?
<HStack
width="full"
alignContent="center"
Expand Down
4 changes: 2 additions & 2 deletions components/Pages/Bonding/BondingActions/Bond.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const Bond = ({ balances, tokenSymbols }) => {
useRecoilState<BondingTokenState>(bondingState)
const { network, chainId, walletChainName } = useRecoilValue(chainState)
const { isWalletConnected } = useChain(walletChainName)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)

const [tokenBalances, setTokenBalances] = useState<TokenBalance[]>(null)

Expand All @@ -49,7 +50,6 @@ export const Bond = ({ balances, tokenSymbols }) => {
amount: Number(amount) })
}
}
const config = useConfig(network, chainId)

useEffect(() => {
if (config) {
Expand All @@ -60,7 +60,7 @@ export const Bond = ({ balances, tokenSymbols }) => {
denom: config.bonding_tokens[0].denom,
})
}
}, [isWalletConnected, config])
}, [isWalletConnected, config, isConfigLoading])

const { control } = useForm({
mode: 'onChange',
Expand Down
7 changes: 3 additions & 4 deletions components/Pages/Bonding/BondingActions/BondingActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ const BondingActions = ({ globalAction }) => {

const router = useRouter()

const config: Config = useConfig(network, chainId)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)

const symbols = useMemo(() => config?.bonding_tokens.map((token) => token.symbol),
[config])
[config, isConfigLoading])

const { txStep, submit } = useTransaction()

Expand Down Expand Up @@ -152,8 +152,7 @@ const BondingActions = ({ globalAction }) => {
</Text>
</HStack>
</HStack>
(
{isLoading && isWalletConnected ? (
{(isLoading || isConfigLoading) && isWalletConnected ? (
<VStack
width="full"
background={kBg}
Expand Down
7 changes: 4 additions & 3 deletions components/Pages/Bonding/BondingActions/Unbond.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const Unbond = ({ bondedAssets }: { bondedAssets: BondedData[] }) => {
const [isMobile] = useMediaQuery('(max-width: 720px)')
const [currentBondState, setCurrentBondState] =
useRecoilState<BondingTokenState>(bondingState)
const config = useConfig(network, chainId)

const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const [bondedBalances, setBondedBalances] = useState<TokenBalance[]>(null)

useEffect(() => {
Expand All @@ -41,7 +42,7 @@ const Unbond = ({ bondedAssets }: { bondedAssets: BondedData[] }) => {
[currentBondState])

useEffect(() => {
if (config) {
if (!isConfigLoading && config) {
// eslint-disable-next-line prefer-destructuring
const firstToken = config.bonding_tokens[0]
setCurrentBondState({
Expand All @@ -51,7 +52,7 @@ const Unbond = ({ bondedAssets }: { bondedAssets: BondedData[] }) => {
denom: firstToken.denom,
})
}
}, [isWalletConnected, config])
}, [isWalletConnected, config, isConfigLoading])

const { control } = useForm({
mode: 'onChange',
Expand Down
6 changes: 3 additions & 3 deletions components/Pages/Bonding/BondingActions/Withdraw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const Withdraw = ({
}: Props) => {
const { walletChainName, network, chainId } = useRecoilValue(chainState)
const { isWalletConnected } = useChain(walletChainName)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)

const prices = usePrices()

Expand All @@ -57,10 +58,9 @@ const Withdraw = ({
const [_, setCurrentBondState] =
useRecoilState<BondingTokenState>(bondingState)

const config = useConfig(network, chainId)

useEffect(() => {
if (config) {
if (!isConfigLoading && config) {
// eslint-disable-next-line prefer-destructuring
const firstToken = config.bonding_tokens[0]
setCurrentBondState({
Expand All @@ -70,7 +70,7 @@ const Withdraw = ({
denom: firstToken.denom,
})
}
}, [isWalletConnected, config])
}, [isWalletConnected, config, isConfigLoading])

const withdrawableTokens = withdrawableInfos?.map((row) => ({
...row,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { unbondTokens } from 'components/Pages/Bonding/BondingActions/hooks/unbo
import { withdrawTokens } from 'components/Pages/Bonding/BondingActions/hooks/withdrawTokens'
import { ActionType } from 'components/Pages/Bonding/BondingOverview'
import {
Config,
useConfig,
} from 'components/Pages/Bonding/hooks/useDashboardData'
import { useClients } from 'hooks/useClients'
Expand All @@ -30,8 +29,8 @@ export const useTransaction = () => {
const [txHash, setTxHash] = useState<string>(null)
const [error, setError] = useState<unknown | null>(null)
const [buttonLabel, setButtonLabel] = useState<unknown | null>(null)
const config: Config = useConfig(network, chainId)

const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const { data: fee } = useQuery<unknown, unknown, any | null>(
['fee', error],
() => {
Expand Down Expand Up @@ -72,7 +71,7 @@ export const useTransaction = () => {
}
},
{
enabled: txStep === TxStep.Idle && !error && Boolean(signingClient),
enabled: txStep === TxStep.Idle && !error && Boolean(signingClient) && !isConfigLoading,
refetchOnWindowFocus: false,
retry: false,
staleTime: 0,
Expand Down
6 changes: 2 additions & 4 deletions components/Pages/Bonding/RewardsComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { useChain } from '@cosmos-kit/react-lite'
import { BondingActionTooltip } from 'components/Pages/Bonding/BondingActions/BondingActionTooltip'
import useTransaction from 'components/Pages/Bonding/BondingActions/hooks/useTransaction'
import {
Config,
useConfig,
} from 'components/Pages/Bonding/hooks/useDashboardData'
import { RewardsTooltip } from 'components/Pages/Bonding/RewardsTooltip'
Expand Down Expand Up @@ -140,11 +139,10 @@ const RewardsComponent = ({

const { txStep, submit } = useTransaction()

const config: Config = useConfig(network, chainId)

const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const forceEpochAndTakeSnapshots = useForceEpochAndTakingSnapshots({
noSnapshotTakenAddresses: null,
config,
configState: { config, isLoading: isConfigLoading },
})
const currentEpochStartDateTimeInMilli = new Date(nanoToMilli(Number(currentEpoch?.epoch?.start_time))).getTime()

Expand Down
58 changes: 25 additions & 33 deletions components/Pages/Bonding/hooks/useDashboardData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState, useRef } from 'react'
import { useQueries, useQueryClient } from 'react-query'
import { useMemo } from 'react'
import { useQueries, useQueryClient, useQuery } from 'react-query'

import { getBonded } from 'components/Pages/Bonding/hooks/getBonded'
import { getBondingConfig } from 'components/Pages/Bonding/hooks/getBondingConfig'
Expand Down Expand Up @@ -33,41 +33,32 @@ export interface Config {
bonding_tokens: TokenInfo[]
}

const fetchConfig = async (network: NetworkType, chainId: string): Promise<Config> => {
const response = await fetch(`/${network}/${chainId}/config.json`)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return response.json()
}

export const useConfig = (network: NetworkType, chainId: string) => {
const [config, setConfig] = useState<Config | null>(null)
const cacheRef = useRef<{ [key: string]: Config | null }>({})

useEffect(() => {
if (network && chainId) {
const cacheKey = `${network}_${chainId}`

if (cacheRef.current[cacheKey]) {
setConfig(cacheRef.current[cacheKey])
return
}

const fetchConfig = async () => {
try {
const response = await fetch(`/${network}/${chainId}/config.json`)
const json: Config = await response.json()
setConfig(json)
cacheRef.current[cacheKey] = json
} catch (error) {
console.error('Failed to load config:', error)
}
}

fetchConfig()
return useQuery<Config, Error>(
['config', network, chainId],
() => fetchConfig(network, chainId),
{
enabled: Boolean(network) && Boolean(chainId),
staleTime: Infinity,
cacheTime: Infinity,
retry: 2,
}
}, [network, chainId])
return config
)
}

export const useDashboardData = (
address: string, network: NetworkType, chainId: string, walletChainName: string,
) => {
const queryClient = useQueryClient()
const config = useConfig(network, chainId)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const { cosmWasmClient } = useClients(walletChainName)

const queries = useQueries([
Expand Down Expand Up @@ -154,10 +145,11 @@ export const useDashboardData = (
},
])

const isLoading = useMemo(() => queries.some((query) => (
query.isLoading || (!query.data && query.data !== 0)
)),
[queries])
const isLoading = useMemo(() =>
isConfigLoading || queries.some((query) => (
query.isLoading || (!query.data && query.data !== 0)
)),
[queries, isConfigLoading])

const refetchAll = () => {
queries.forEach((query) => query.refetch())
Expand Down
5 changes: 2 additions & 3 deletions components/Pages/Trade/Incentivize/hooks/useEpoch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useMemo } from 'react'
import { useQuery } from 'react-query'

import {
Config,
useConfig,
} from 'components/Pages/Bonding/hooks/useDashboardData'
import dayjs from 'dayjs'
Expand Down Expand Up @@ -81,8 +80,8 @@ interface EpochConfigData {

const useEpoch = () => {
const { network, chainId, walletChainName } = useRecoilValue(chainState)
const contracts: Config = useConfig(network, chainId)

const { data: contracts, isLoading: isConfigLoading } = useConfig(network, chainId)
const { cosmWasmClient } = useClients(walletChainName)
const { data: config } = useQuery<EpochConfigData>({
queryKey: ['incentive', 'config', contracts?.fee_distributor],
Expand All @@ -94,7 +93,7 @@ const useEpoch = () => {
config: {},
})
},
enabled: Boolean(contracts?.fee_distributor) && Boolean(cosmWasmClient),
enabled: Boolean(contracts?.fee_distributor) && Boolean(cosmWasmClient) && !isConfigLoading,
})

const { data } = useQuery<EpochData>({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useQuery } from 'react-query'

import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'
import {
Config,
useConfig,
} from 'components/Pages/Bonding/hooks/useDashboardData'
import { useCurrentEpoch } from 'components/Pages/Trade/Incentivize/hooks/useCurrentEpoch'
Expand Down Expand Up @@ -192,8 +191,8 @@ export const useIncentivePoolInfo = (
) => {
const { chainId, network, walletChainName } = useRecoilValue(chainState)
const [tokenList, loading] = useTokenList()
const config: Config = useConfig(network, chainId)
const prices = usePrices()
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const { data: currentEpochData } = useCurrentEpoch(client, config)
const [poolsWithAprAnd24HrVolume, setPoolsWithAprAnd24HrVolume] = useState<
PoolData[]
Expand Down Expand Up @@ -250,7 +249,8 @@ export const useIncentivePoolInfo = (
Boolean(currentEpochData) &&
Boolean(pools) &&
Boolean(poolAssets) &&
Boolean(prices),
Boolean(prices) &&
!isConfigLoading,
},
)
return {
Expand Down
6 changes: 3 additions & 3 deletions components/Pages/Trade/Incentivize/hooks/useOpenFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { MsgExecuteContractEncodeObject } from '@cosmjs/cosmwasm-stargate'
import { coin } from '@cosmjs/proto-signing'
import { useChain } from '@cosmos-kit/react-lite'
import {
Config,
useConfig,
} from 'components/Pages/Bonding/hooks/useDashboardData'
import useEpoch from 'components/Pages/Trade/Incentivize/hooks/useEpoch'
Expand Down Expand Up @@ -39,8 +38,8 @@ export const useOpenFlow = ({ poolId, token, startDate, endDate }: Props) => {
const { network, chainId, walletChainName } = useRecoilValue(chainState)
const { signingClient, injectiveSigningClient } = useClients(walletChainName)
const { address } = useChain(walletChainName)
const config: Config = useConfig(network, chainId)
const { data: pool } = usePoolFromListQueryById({ poolId })
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const { onError, onSuccess, onMutate } = useTxStatus({
transactionType: 'Open Flow',
signingClient,
Expand All @@ -57,7 +56,8 @@ export const useOpenFlow = ({ poolId, token, startDate, endDate }: Props) => {
!tokenInfo?.denom ||
!startDate ||
!endDate ||
Number(token?.amount || 0) <= 0
Number(token?.amount || 0) <= 0 ||
isConfigLoading
) {
return null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@ const fetchIncentiveContracts = async (client: CosmWasmClient,

export const useQueryIncentiveContracts = (cosmWasmClient: CosmWasmClient): Array<string> => {
const { chainId, network } = useRecoilValue(chainState)
const config: Config = useConfig(network, chainId)
const { data: config, isLoading: isConfigLoading } = useConfig(network, chainId)
const { data } = useQuery(
['useQueryIncentiveContracts', config],
async () => await fetchIncentiveContracts(cosmWasmClient, config),
{
enabled:
Boolean(cosmWasmClient) &&
Boolean(config) &&
Boolean(config?.incentive_factory),
Boolean(config?.incentive_factory) &&
!isConfigLoading,
},
)
return data
Expand Down
Loading
Loading