Skip to content

Commit

Permalink
use ks setting api (#341)
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenhoaidanh authored Oct 21, 2022
1 parent 8cef191 commit 96b3978
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 585 deletions.
1 change: 1 addition & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
REACT_APP_AGGREGATOR_STATS_API=https://aggregator-stats.kyberswap.com
REACT_APP_SUPPORT_CHAINS_ID=1,137,56,43114,250,25,42161,106,1313161554,42262,199,10
REACT_APP_KS_SETTING_API=https://ks-setting.kyberswap.com/api
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module.exports = {
'no-unused-vars': 0,
'no-extra-boolean-cast': 0,
'no-inner-declarations': 0,
'no-constant-condition': 0,
},
overrides: [
// typescript
Expand Down
4 changes: 1 addition & 3 deletions src/components/PairList/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { MAX_ALLOW_APY } from '../../constants'
import { NETWORKS_INFO } from '../../constants/networks'
import { aggregatePairs } from '../../utils/aggregateData'
import { MouseoverTooltip } from '../Tooltip'
import { NetworksInfoEnv, useNetworksInfo, useTokensList } from '../../contexts/NetworkInfo'
import { NetworksInfoEnv, useNetworksInfo } from '../../contexts/NetworkInfo'

dayjs.extend(utc)

Expand Down Expand Up @@ -151,8 +151,6 @@ function PairList({ pairs, color, disbaleLinks, maxItems = 5 }) {
const below600 = useMedia('(max-width: 600px)')
const below740 = useMedia('(max-width: 740px)')
const below1080 = useMedia('(max-width: 1080px)')
let tokensLists = useTokensList() // please do not remove this line. It helps DoubleTokenLogo reload
tokensLists = tokensLists || 2

// pagination
const [page, setPage] = useState(1)
Expand Down
130 changes: 28 additions & 102 deletions src/components/TokenLogo/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'

import { ROPSTEN_TOKEN_LOGOS_MAPPING } from '../../constants'
import { isAddress } from '../../utils/index.js'
import { HelpCircle } from 'react-feather'
import { getMaticTokenLogoURL } from '../../utils/maticTokenMapping'
import { getMumbaiTokenLogoURL } from '../../utils/mumbaiTokenMapping'
import { getBscTestnetTokenLogoURL } from '../../utils/bscTestnetTokenMapping'
import { getBscTokenLogoURL } from '../../utils/bscTokenMapping'
import { getAvaxTokenLogoURL } from '../../utils/avaxTokenMapping'
import { getFantomTokenLogoURL } from '../../utils/fantomTokenMapping'
import { getCronosTokenLogoURL } from '../../utils/cronosTokenMapping'
import { ChainId } from '../../constants/networks'
import { useTokensList } from '../../contexts/NetworkInfo'

import { useWhitelistTokensMap } from '../../contexts/GlobalData'
import { useTokensList } from '../../contexts/NetworkInfo.js'

const BAD_IMAGES = {}

Expand Down Expand Up @@ -48,28 +41,18 @@ const StyledHelpCircle = styled(HelpCircle)`
background-color: ${({ theme }) => theme.white};
`

export function getCustomLogo({ address, chainId, src, size, setError, ...rest }) {
return (
<Inline>
<Image
{...rest}
alt={''}
src={src}
size={size}
onError={event => {
BAD_IMAGES[chainId] = { ...BAD_IMAGES[chainId], [address]: true }
setError(true)
event.preventDefault()
}}
/>
</Inline>
)
}

export default function TokenLogo({ address, networkInfo, header = false, size = '24px', ...rest }) {
const [error, setError] = useState(false)
const tokensList = useTokensList()?.[networkInfo.chainId]

const { chainId } = networkInfo

const tokensList = useTokensList()?.[chainId]
const whiteListMap = useWhitelistTokensMap(chainId) || {}

const formattedAddress = isAddress(address)

const logoURI =
whiteListMap?.[address]?.logoURI || whiteListMap?.[formattedAddress]?.logoURI || tokensList?.[formattedAddress]?.logoURI
useEffect(() => {
setError(false)
BAD_IMAGES[networkInfo.chainId] && (BAD_IMAGES[networkInfo.chainId][address] = false)
Expand All @@ -78,7 +61,7 @@ export default function TokenLogo({ address, networkInfo, header = false, size =

if (!networkInfo) return null

if (error || BAD_IMAGES[networkInfo.chainId]?.[address]) {
if (error || BAD_IMAGES[networkInfo.chainId]?.[address] || !logoURI) {
return (
<Inline>
<StyledHelpCircle size={size} {...rest} />
Expand All @@ -101,76 +84,19 @@ export default function TokenLogo({ address, networkInfo, header = false, size =
)
}

const formattedAddress = isAddress(address)
let path

if (formattedAddress && tokensList?.[formattedAddress]?.logoURI) {
return getCustomLogo({
address,
chainId: networkInfo.chainId,
src: tokensList[formattedAddress].logoURI,
size,
setError,
...rest,
})
}

switch (networkInfo.chainId) {
case ChainId.ROPSTEN:
if (ROPSTEN_TOKEN_LOGOS_MAPPING[address?.toLowerCase()]) {
address = ROPSTEN_TOKEN_LOGOS_MAPPING[address?.toLowerCase()]
}
path = `https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/${formattedAddress}/logo.png`
break
case ChainId.MATIC:
path = getMaticTokenLogoURL(address)
break
case ChainId.MUMBAI:
path = getMumbaiTokenLogoURL(address)
break
case ChainId.BSCTESTNET:
path = getBscTestnetTokenLogoURL(address)
break
case ChainId.BSCMAINNET:
path = getBscTokenLogoURL(address)
break

case ChainId.AVAXMAINNET:
path = getAvaxTokenLogoURL(address)
break

case ChainId.FANTOM:
path = getFantomTokenLogoURL(address)
break

case ChainId.CRONOS:
path = getCronosTokenLogoURL(address)
break

case ChainId.ARBITRUM:
path = `https://raw.githubusercontent.com/Uniswap/assets/master/blockchains/arbitrum/assets/${isAddress(address)}/logo.png`
break

case ChainId.BTTC:
case ChainId.VELAS:
case ChainId.AURORA:
case ChainId.OASIS:
case ChainId.OPTIMISM:
path = 'error'
break

default:
// hard coded fixes for trust wallet api issues
if (address?.toLowerCase() === '0x5e74c9036fb86bd7ecdcb084a0673efc32ea31cb') {
address = '0x42456d7084eacf4083f1140d3229471bba2949a8'
}

if (address?.toLowerCase() === '0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f') {
address = '0xc011a72400e58ecd99ee497cf89e3775d4bd732f'
}

path = `https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/${formattedAddress}/logo.png`
break
}
return getCustomLogo({ address, chainId: networkInfo.chainId, src: path, size, setError, ...rest })
return (
<Inline>
<Image
{...rest}
alt={''}
src={logoURI}
size={size}
onError={event => {
BAD_IMAGES[chainId] = { ...BAD_IMAGES[chainId], [address]: true }
setError(true)
event.preventDefault()
}}
/>
</Inline>
)
}
76 changes: 71 additions & 5 deletions src/contexts/GlobalData.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import weekOfYear from 'dayjs/plugin/weekOfYear'
import { useAllPoolData } from './PoolData'
import { useNetworksInfo } from './NetworkInfo'
import { calculateValuesOnGlobalData } from '../utils/aggregateData'
import { stringify } from 'querystring'
const UPDATE = 'UPDATE'
const UPDATE_TXNS = 'UPDATE_TXNS'
const UPDATE_CHART = 'UPDATE_CHART'
Expand All @@ -24,6 +25,7 @@ const ETH_PRICE_KEY = 'ETH_PRICE_KEY'
const UPDATE_ALL_PAIRS_IN_KYBERSWAP = 'UPDATE_ALL_PAIRS_IN_KYBERSWAP'
const UPDATE_ALL_TOKENS_IN_KYBERSWAP = 'UPDATE_ALL_TOKENS_IN_KYBERSWAP'
const UPDATE_TOP_LPS = 'UPDATE_TOP_LPS'
const UPDATE_WHITELIST_TOKEN_MAP = 'UPDATE_WHITELIST_TOKEN_MAP'

// format dayjs with the libraries that we need
dayjs.extend(utc)
Expand Down Expand Up @@ -64,6 +66,11 @@ function reducer(state, { type, payload }) {
return merge(state, { [chainId]: { allTokens } }, { arrayMerge: overwriteArrayMerge })
}

case UPDATE_WHITELIST_TOKEN_MAP: {
const { whitelistTokenMap, chainId } = payload
return merge(state, { [chainId]: { whitelistTokenMap } }, { arrayMerge: overwriteArrayMerge })
}

case UPDATE_TOP_LPS: {
const { topLps, chainId } = payload
return merge(state, { [chainId]: { topLps } }, { arrayMerge: overwriteArrayMerge })
Expand Down Expand Up @@ -138,6 +145,13 @@ export default function Provider({ children }) {
})
}, [])

const updateAllWhitelistToken = useCallback((whitelistTokenMap, chainId) => {
dispatch({
type: UPDATE_WHITELIST_TOKEN_MAP,
payload: { whitelistTokenMap, chainId },
})
}, [])

const updateTopLps = useCallback((topLps, chainId) => {
dispatch({
type: UPDATE_TOP_LPS,
Expand All @@ -160,6 +174,7 @@ export default function Provider({ children }) {
updateTopLps,
updateAllPairsInKyberswap,
updateAllTokensInKyberswap,
updateAllWhitelistToken,
},
],
[
Expand All @@ -171,6 +186,7 @@ export default function Provider({ children }) {
updateEthPrice,
updateAllPairsInKyberswap,
updateAllTokensInKyberswap,
updateAllWhitelistToken,
]
)}
>
Expand Down Expand Up @@ -202,8 +218,6 @@ const mergeFactoriesData = factories => {
async function getGlobalData(client, networksInfo) {
// data for each day , historic data used for % changes
let data = {}
let oneDayData = {}
let twoDayData = {}

try {
// get timestamps for the days
Expand Down Expand Up @@ -490,7 +504,10 @@ async function getAllTokensOnKyberswap(client) {
*/
export function useGlobalData() {
const exchangeSubgraphClient = useExchangeClients()
const [state, { update, updateAllPairsInKyberswap, updateAllTokensInKyberswap }] = useGlobalDataContext()
const [
state,
{ update, updateAllPairsInKyberswap, updateAllTokensInKyberswap, updateAllWhitelistToken },
] = useGlobalDataContext()
const [ethPrice, oldEthPrice] = useEthPrice()
const [networksInfo] = useNetworksInfo()
const data = networksInfo.map(networkInfo => state?.[networkInfo.chainId]?.globalData)
Expand All @@ -500,11 +517,17 @@ export function useGlobalData() {
let globalData = await getGlobalData(exchangeSubgraphClient[index], networksInfo[index])
globalData && update(globalData, networksInfo[index].chainId)

let allPairs = await getAllPairsOnKyberswap(exchangeSubgraphClient[index])
const [allPairs, whitelistTokenMap, allTokens] = await Promise.all([
getAllPairsOnKyberswap(exchangeSubgraphClient[index]),
getWhitelistToken(networksInfo[index].chainId),
getAllTokensOnKyberswap(exchangeSubgraphClient[index]),
])

allPairs?.forEach(allPair => (allPair.chainId = networksInfo[index].chainId))
updateAllPairsInKyberswap(allPairs, networksInfo[index].chainId)

let allTokens = await getAllTokensOnKyberswap(exchangeSubgraphClient[index])
updateAllWhitelistToken(whitelistTokenMap, networksInfo[index].chainId)

allTokens?.forEach(allToken => (allToken.chainId = networksInfo[index].chainId))
updateAllTokensInKyberswap(allTokens, networksInfo[index].chainId)
}
Expand All @@ -523,6 +546,7 @@ export function useGlobalData() {
updateAllTokensInKyberswap,
exchangeSubgraphClient,
networksInfo,
updateAllWhitelistToken,
])

return data || []
Expand Down Expand Up @@ -640,6 +664,13 @@ export function useAllTokensInKyberswap() {
return allTokens || []
}

export function useWhitelistTokensMap(chainId) {
const [state] = useGlobalDataContext()
const allTokens = state?.[chainId]?.whitelistTokenMap

return allTokens || {}
}

/**
* Get the top liquidity positions based on USD size
* @TODO Not a perfect lookup needs improvement
Expand Down Expand Up @@ -710,3 +741,38 @@ export function useTopLps() {

return topLps
}

function formatWhitelistToken(tokens) {
return tokens.reduce((tokenMap, token) => {
const address = token.address || ''
if (address) tokenMap[address] = token
return tokenMap
}, {})
}

// loop to fetch all whitelist token
async function getWhitelistToken(chainId) {
let tokens = []
try {
const pageSize = 100
const maximumPage = 15
let page = 1
while (true) {
const { data } = await fetch(
`${process.env.REACT_APP_KS_SETTING_API}/v1/tokens?${stringify({
pageSize,
page,
isWhitelisted: true,
chainIds: chainId,
})}`
).then(data => data.json())
page++
const tokensResponse = data.tokens ?? []
tokens = tokens.concat(tokensResponse)
if (tokensResponse.length < pageSize || page >= maximumPage) break // out of tokens, and prevent infinity loop
}
} catch (error) {
console.log(`Failed to fetch list token of chainId ${chainId}`)
}
return formatWhitelistToken(tokens)
}
36 changes: 0 additions & 36 deletions src/utils/avaxTokenMapping.js

This file was deleted.

Loading

0 comments on commit 96b3978

Please sign in to comment.