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

remove SWR to use rtk-query #2426

Merged
merged 14 commits into from
Dec 14, 2023
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@
"redux-localstorage-simple": "^2.5.1",
"styled-components": "^5.3.6",
"swiper": "^8.4.4",
"swr": "^2.0.0",
"ua-parser-js": "^1.0.33",
"util": "^0.12.5",
"vite-plugin-env-compatible": "^1.1.1",
Expand Down
14 changes: 6 additions & 8 deletions src/components/SearchModal/CurrencySearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ChangeEvent, KeyboardEvent, ReactNode, useCallback, useEffect, useMemo,
import { Trash } from 'react-feather'
import { usePrevious } from 'react-use'
import { Flex, Text } from 'rebass'
import ksSettingApi from 'services/ksSetting'
import styled from 'styled-components'

import Column from 'components/Column'
Expand All @@ -16,17 +17,12 @@ import { KS_SETTING_API } from 'constants/env'
import { Z_INDEXS } from 'constants/styles'
import { NativeCurrencies } from 'constants/tokens'
import { useActiveWeb3React } from 'hooks'
import {
fetchListTokenByAddresses,
fetchTokenByAddress,
formatAndCacheToken,
useAllTokens,
useFetchERC20TokenFromRPC,
} from 'hooks/Tokens'
import { fetchListTokenByAddresses, formatAndCacheToken, useAllTokens, useFetchERC20TokenFromRPC } from 'hooks/Tokens'
import useDebounce from 'hooks/useDebounce'
import { useOnClickOutside } from 'hooks/useOnClickOutside'
import useTheme from 'hooks/useTheme'
import useToggle from 'hooks/useToggle'
import store from 'state'
import { WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
import { useRemoveUserAddedToken, useUserAddedTokens, useUserFavoriteTokens } from 'state/user/hooks'
import { ButtonText, CloseIcon, TYPE } from 'theme'
Expand Down Expand Up @@ -100,7 +96,9 @@ const fetchTokens = async (
): Promise<WrappedTokenInfo[]> => {
try {
if (search && chainId && isAddress(chainId, search)) {
const token = await fetchTokenByAddress(search, chainId)
const { data: token } = await store.dispatch(
ksSettingApi.endpoints.getTokenByAddress.initiate({ address: search, chainId }),
)
return token ? [token as WrappedTokenInfo] : []
}
const params: { query: string; isWhitelisted?: boolean; pageSize: number; page: number; chainIds: string } = {
Expand Down
7 changes: 0 additions & 7 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { v4 as uuid } from 'uuid'

import { TransactionFlowState } from 'types/TransactionFlowState'

import { CAMPAIGN_BASE_URL } from './env'
import * as ENV from './env'
import { MAINNET_NETWORKS, NETWORKS_INFO, SUPPORTED_NETWORKS } from './networks'

Expand Down Expand Up @@ -124,12 +123,6 @@ export const CAMPAIGN_YOUR_TRANSACTIONS_ITEM_PER_PAGE = 10000
export const ELASTIC_BASE_FEE_UNIT = 100_000
export const KYBERSWAP_SOURCE = '{"source":"kyberswap"}'

export const SWR_KEYS = {
getGrantProgramLeaderBoard: (id: number | string) => `${CAMPAIGN_BASE_URL}/api/v1/competitions/${id}/leaderboard`,
getListGrantPrograms: `${CAMPAIGN_BASE_URL}/api/v1/competitions`,
getGrantProgram: (id: number | string) => `${CAMPAIGN_BASE_URL}/api/v1/competitions/${id}`,
}

// https://www.nasdaq.com/glossary/b/bip
export const MAX_NORMAL_SLIPPAGE_IN_BIPS = 1999
export const MAX_DEGEN_SLIPPAGE_IN_BIPS = 5000
Expand Down
60 changes: 12 additions & 48 deletions src/hooks/Tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ import axios from 'axios'
import { arrayify } from 'ethers/lib/utils'
import { useCallback, useMemo } from 'react'
import { useSelector } from 'react-redux'
import ksSettingApi, { useGetTokenListQuery } from 'services/ksSetting'
import useSWR from 'swr'
import ksSettingApi from 'services/ksSetting'

import ERC20_INTERFACE, { ERC20_BYTES32_INTERFACE } from 'constants/abis/erc20'
import { KS_SETTING_API } from 'constants/env'
import { ETHER_ADDRESS, ZERO_ADDRESS } from 'constants/index'
import { NativeCurrencies } from 'constants/tokens'
import { useActiveWeb3React } from 'hooks/index'
import { useBytes32TokenContract, useMulticallContract, useTokenReadingContract } from 'hooks/useContract'
import store, { AppState } from 'state'
import { AppState } from 'state'
import { TokenAddressMap } from 'state/lists/reducer'
import { TokenInfo, WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
import { NEVER_RELOAD, useMultipleContractSingleData, useSingleCallResult } from 'state/multicall/hooks'
import { useUserAddedTokens } from 'state/user/hooks'
import { filterTruthy, isAddress } from 'utils'
import { escapeQuoteString } from 'utils/tokenInfo'

import useDebounce from './useDebounce'

Expand Down Expand Up @@ -294,25 +294,6 @@ export const findCacheToken = (address: string) => {
return cacheTokens[address] || cacheTokens[address.toLowerCase()]
}

export const fetchTokenByAddress = async (address: string, chainId: ChainId) => {
if (address === ZERO_ADDRESS) return NativeCurrencies[chainId]
const findToken = findCacheToken(address)
if (findToken && findToken.chainId === chainId) return findToken
const tokenListRes = await store.dispatch(
ksSettingApi.endpoints.getTokenList.initiate({ chainId, addresses: address }),
)
let token = tokenListRes.data?.data.tokens[0]
if (!token) {
const importTokenRes = await store.dispatch(
ksSettingApi.endpoints.importToken.initiate([{ chainId: chainId.toString(), address }]),
)
if ('data' in importTokenRes) {
token = importTokenRes.data?.data.tokens[0]
}
}
return token ? formatAndCacheToken(token) : undefined
}

export const fetchListTokenByAddresses = async (address: string[], chainId: ChainId) => {
const cached = filterTruthy(address.map(addr => findCacheToken(addr)))
if (cached.length === address.length) return cached
Expand All @@ -322,10 +303,6 @@ export const fetchListTokenByAddresses = async (address: string[], chainId: Chai
return filterTruthy(tokens.map(formatAndCacheToken)) as WrappedTokenInfo[]
}

// ex: `"BTT_b"` => BTT_b
const escapeQuoteString = (str: string) =>
str?.startsWith('"') && str?.endsWith('"') ? str.substring(1, str.length - 1) : str

export const formatAndCacheToken = (rawTokenResponse: TokenInfo) => {
try {
const tokenResponse = { ...rawTokenResponse }
Expand All @@ -343,26 +320,6 @@ export const formatAndCacheToken = (rawTokenResponse: TokenInfo) => {
}
}

function useTokenV2(
tokenAddress?: string,
customChain?: ChainId,
): WrappedTokenInfo | Token | NativeCurrency | undefined | null {
const { chainId: currentChain } = useActiveWeb3React()
const chainId = customChain || currentChain
const address = isAddress(chainId, tokenAddress)
const { data, isValidating } = useSWR(
address.toString() + chainId?.toString(),
async () => {
try {
if (chainId && address) return await fetchTokenByAddress(address, chainId)
} catch (error) {}
return undefined
},
{ revalidateOnFocus: false, shouldRetryOnError: false, revalidateIfStale: false },
)
return isValidating ? null : data
}

export function useCurrency(currencyId: string | undefined): Currency | null | undefined {
const { chainId } = useActiveWeb3React()
const isETH = useMemo(
Expand All @@ -389,7 +346,11 @@ export function useCurrencyV2(currencyId: string | undefined, customChainId?: Ch
const tokenInWhitelist = currencyId
? whitelistTokens[currencyId] || whitelistTokens[currencyId?.toLowerCase()]
: undefined
const token = useTokenV2(isETH || tokenInWhitelist ? undefined : currencyId, chainId)

const { data: token } = ksSettingApi.useGetTokenByAddressQuery(
{ address: isAddress(chainId, currencyId) || '', chainId },
{ skip: isETH || !!tokenInWhitelist || !isAddress(chainId, currencyId) },
)

return useMemo(() => {
if (!currencyId) return
Expand All @@ -399,7 +360,10 @@ export function useCurrencyV2(currencyId: string | undefined, customChainId?: Ch
}

export const useStableCoins = (chainId: ChainId | undefined) => {
const { data } = useGetTokenListQuery({ chainId: chainId as ChainId, isStable: true }, { skip: !chainId })
const { data } = ksSettingApi.useGetTokenListQuery(
{ chainId: chainId as ChainId, isStable: true },
{ skip: !chainId },
)

const stableCoins = useMemo(() => {
return data?.data?.tokens || []
Expand Down
35 changes: 0 additions & 35 deletions src/hooks/bridge/useGetBridgeTransfers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import useSWR from 'swr'

export enum MultichainTransferStatus {
Processing = 0,
Success = 1,
Expand All @@ -21,36 +19,3 @@ export type MultichainTransfer = {
createdAt: number
isReceiveAnyToken: boolean
}

type Response = {
code: number
message: string
data: {
transfers: MultichainTransfer[]
pagination: {
totalItems: number
}
}
}

const useGetBridgeTransfers = (swrKey: string | null) => {
return useSWR<Response>(
swrKey,
async (url: string) => {
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (data) {
return data
}

throw new Error(`No transfers found with url = ${swrKey}`)
}

throw new Error(`Fetching bridge transfers failed with url = ${swrKey}`)
},
{ revalidateOnFocus: false, refreshInterval: 5_000 },
)
}

export default useGetBridgeTransfers
32 changes: 0 additions & 32 deletions src/hooks/campaigns/useGetGrantProgram.ts

This file was deleted.

38 changes: 0 additions & 38 deletions src/hooks/campaigns/useGetGrantPrograms.ts

This file was deleted.

61 changes: 0 additions & 61 deletions src/hooks/campaigns/useGetLeaderboardGrantProgram.ts

This file was deleted.

Loading
Loading