Skip to content

Commit

Permalink
Merge branch 'main' of github.com:KyberNetwork/kyberswap-interface in…
Browse files Browse the repository at this point in the history
…to linea
  • Loading branch information
viet-nv committed Jul 28, 2023
2 parents 6a393bf + f2100ed commit d72a683
Show file tree
Hide file tree
Showing 12 changed files with 139 additions and 78 deletions.
7 changes: 2 additions & 5 deletions src/components/SearchModal/CurrencyList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,18 +136,15 @@ export function CurrencyRow({
return false
}

if (isTokenNative(currency, currency.chainId)) {
return !!favoriteTokens.includeNativeToken
}

if (currency.isToken) {
const addr = (currency as Token).address ?? ''
const addresses = favoriteTokens?.addresses ?? []
const addresses = favoriteTokens ?? []
return !!addresses?.includes(addr) || !!addresses?.includes(addr.toLowerCase())
}

return false
})()

const balanceComponent = hideBalance ? (
'******'
) : currencyBalance ? (
Expand Down
57 changes: 24 additions & 33 deletions src/components/SearchModal/CurrencySearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ const ButtonClear = styled.div`
gap: 5px;
cursor: pointer;
`
const MAX_FAVORITE_PAIR = 12

interface CurrencySearchProps {
isOpen: boolean
Expand Down Expand Up @@ -254,32 +253,15 @@ export function CurrencySearch({
const handleClickFavorite = useCallback(
(e: React.MouseEvent, currency: any) => {
e.stopPropagation()

const address = currency?.wrapped?.address || currency.address
if (!address) return

const currentList = favoriteTokens?.addresses || []
const isAddFavorite = isTokenNative(currency, currency.chainId)
? !favoriteTokens?.includeNativeToken
: !currentList.find(el => el === address) // else remove favorite
const curTotal =
currentList.filter(address => !!defaultTokens[address]).length + (favoriteTokens?.includeNativeToken ? 1 : 0)
if (isAddFavorite && curTotal === MAX_FAVORITE_PAIR) return

if (isTokenNative(currency, currency.chainId)) {
toggleFavoriteToken({
chainId,
isNative: true,
})
return
}

toggleFavoriteToken({
chainId,
address,
})
},
[chainId, favoriteTokens, toggleFavoriteToken, defaultTokens],
[chainId, toggleFavoriteToken],
)

// menu ui
Expand All @@ -292,20 +274,30 @@ export function CurrencySearch({
if (!Object.keys(defaultTokens).length) return
setLoadingCommon(true)
let result: (Token | Currency)[] = []
if (favoriteTokens?.includeNativeToken) {
result.push(NativeCurrencies[chainId])
}
const addressesToFetch: string[] = []
favoriteTokens?.addresses.forEach(address => {
if (defaultTokens[address]) {
result.push(defaultTokens[address])

favoriteTokens?.forEach(address => {
let token
Object.entries(defaultTokens).forEach(([add, t]) => {
if (add.toLowerCase() === address.toLowerCase()) {
token = t
}
})
if (token) {
result.push(token)
return
}
addressesToFetch.push(address)
})

if (addressesToFetch.length) {
const tokens = await fetchListTokenByAddresses(addressesToFetch, chainId)
result = result.concat(tokens)
// Sort the returned token list to match the order of the passed address list
result = result.concat(
tokens.sort((x, y) => {
return addressesToFetch.indexOf(x.wrapped.address) - addressesToFetch.indexOf(y.wrapped.address)
}),
)
}
setCommonTokens(result)
} catch (error) {
Expand Down Expand Up @@ -393,14 +385,13 @@ export function CurrencySearch({
const removeImportedToken = useCallback(
(token: Token) => {
removeToken(chainId, token.address)
if (favoriteTokens?.addresses?.includes(token.address))
// remove in favorite too
toggleFavoriteToken({
chainId,
address: token.address,
})

toggleFavoriteToken({
chainId,
address: token.address,
})
},
[chainId, toggleFavoriteToken, removeToken, favoriteTokens?.addresses],
[chainId, toggleFavoriteToken, removeToken],
)

const removeAllImportToken = () => {
Expand Down
2 changes: 2 additions & 0 deletions src/constants/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ export const STATIC_FEE_OPTIONS: { [chainId: number]: number[] | undefined } = {
[ChainId.GÖRLI]: [8, 10, 50, 300, 500, 1000],
[ChainId.ZKSYNC]: [8, 10, 50, 300, 500, 1000],
[ChainId.LINEA_TESTNET]: [8, 10, 50, 300, 500, 1000],
[ChainId.LINEA]: [8, 10, 50, 300, 500, 1000],
}

export const ONLY_STATIC_FEE_CHAINS = [
Expand All @@ -175,6 +176,7 @@ export const ONLY_STATIC_FEE_CHAINS = [
ChainId.GÖRLI,
ChainId.ZKSYNC,
ChainId.LINEA_TESTNET,
ChainId.LINEA,
]

// hardcode for unavailable subgraph
Expand Down
4 changes: 2 additions & 2 deletions src/constants/networks/linea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const EMPTY = ''
const EMPTY_ARRAY: any[] = []
const NOT_SUPPORT = null

const lineaTestnetInfo: EVMNetworkInfo = {
const lineaInfo: EVMNetworkInfo = {
chainId: ChainId.LINEA,
route: 'linea',
ksSettingRoute: 'linea',
Expand Down Expand Up @@ -70,4 +70,4 @@ const lineaTestnetInfo: EVMNetworkInfo = {
geckoTermialId: NOT_SUPPORT,
}

export default lineaTestnetInfo
export default lineaInfo
34 changes: 30 additions & 4 deletions src/pages/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as Sentry from '@sentry/react'
import { Suspense, lazy, useEffect } from 'react'
import { isMobile } from 'react-device-detect'
import { AlertTriangle } from 'react-feather'
import { Navigate, Route, Routes, useLocation, useParams } from 'react-router-dom'
import { Navigate, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom'
import { useNetwork, usePrevious } from 'react-use'
import { Flex, Text } from 'rebass'
import styled from 'styled-components'
Expand All @@ -14,6 +14,7 @@ import snow from 'assets/images/snow.png'
import Popups from 'components/Announcement/Popups'
import TopBanner from 'components/Announcement/Popups/TopBanner'
import AppHaveUpdate from 'components/AppHaveUpdate'
import { ButtonPrimary } from 'components/Button'
import ModalConfirm from 'components/ConfirmModal'
import ErrorBoundary from 'components/ErrorBoundary'
import Footer from 'components/Footer/Footer'
Expand Down Expand Up @@ -45,6 +46,22 @@ import ElasticLegacyNotice from './ElasticLegacy/ElasticLegacyNotice'
import Icons from './Icons'
import VerifyAuth from './Verify/VerifyAuth'

// THIS IS ONLY TEMPORARY, WILL REMOVE IN NEXT VERSION
const CommingSoonModal = () => {
const navigate = useNavigate()
return (
<Modal isOpen onDismiss={() => navigate('/')}>
<Flex flexDirection="column" padding="24px" sx={{ gap: '2rem' }} justifyContent="center" alignItems="center">
<Text fontSize={14}>Our pools and farms will be available soon!</Text>

<ButtonPrimary style={{ width: '160px', height: '32px' }} onClick={() => navigate('/')}>
Ok
</ButtonPrimary>
</Flex>
</Modal>
)
}

// test page for swap only through elastic
const ElasticSwap = lazy(() => import('./ElasticSwap'))
const SwapV2 = lazy(() => import('./SwapV2'))
Expand Down Expand Up @@ -331,19 +348,28 @@ export default function App() {
<>
{/* Pools Routes */}
<Route path={`${APP_PATHS.POOLS}`} element={<RedirectWithNetworkSuffix />} />
<Route path={`${APP_PATHS.POOLS}/:network/:currencyIdA?/:currencyIdB?`} element={<Pools />} />
<Route
path={`${APP_PATHS.POOLS}/:network/:currencyIdA?/:currencyIdB?`}
element={chainId === ChainId.LINEA ? <CommingSoonModal /> : <Pools />}
/>
</>

<>
{/* Farms Routes */}
<Route path={`${APP_PATHS.FARMS}`} element={<RedirectWithNetworkSuffix />} />
<Route path={`${APP_PATHS.FARMS}/:network`} element={<Farm />} />
<Route
path={`${APP_PATHS.FARMS}/:network`}
element={chainId === ChainId.LINEA ? <CommingSoonModal /> : <Farm />}
/>
</>

<>
{/* My Pools Routes */}
<Route path={`${APP_PATHS.MY_POOLS}`} element={<RedirectWithNetworkSuffix />} />
<Route path={`${APP_PATHS.MY_POOLS}/:network`} element={<MyPools />} />
<Route
path={`${APP_PATHS.MY_POOLS}/:network`}
element={chainId === ChainId.LINEA ? <CommingSoonModal /> : <MyPools />}
/>
</>

<>
Expand Down
2 changes: 2 additions & 0 deletions src/services/ksSetting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type KyberSwapConfig = {
elasticClient: ApolloClient<NormalizedCacheObject>
readProvider: AppJsonRpcProvider | undefined
connection: Connection | undefined
commonTokens?: string[]
}

export type KyberSwapConfigResponse = {
Expand All @@ -25,6 +26,7 @@ export type KyberSwapConfigResponse = {
blockSubgraph: string
classicSubgraph: string
elasticSubgraph: string
commonTokens?: string[]
}

export type KyberswapConfigurationResponse = {
Expand Down
3 changes: 3 additions & 0 deletions src/state/application/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ function getDefaultConfig(chainId: ChainId): KyberSwapConfigResponse {
blockSubgraph: (evm ? NETWORKS_INFO[chainId] : ethereumInfo).defaultBlockSubgraph,
elasticSubgraph: (evm ? NETWORKS_INFO[chainId] : ethereumInfo).elastic.defaultSubgraph,
classicSubgraph: (evm ? NETWORKS_INFO[chainId] : ethereumInfo).classic.defaultSubgraph,
commonTokens: undefined,
}
}

Expand Down Expand Up @@ -469,11 +470,13 @@ export const useKyberSwapConfig = (customChainId?: ChainId): KyberSwapConfig =>
elasticClient,
classicClient,
connection: isSolana(chainId) ? new Connection(config.rpc, { commitment: 'confirmed' }) : undefined,
commonTokens: config.commonTokens,
}
}, [
config.rpc,
config.isEnableBlockService,
config.prochart,
config.commonTokens,
readProvider,
blockClient,
elasticClient,
Expand Down
1 change: 1 addition & 0 deletions src/state/application/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export default createReducer(initialState, builder =>
blockSubgraph,
elasticSubgraph,
classicSubgraph,
commonTokens: data.commonTokens,
},
}
}),
Expand Down
23 changes: 21 additions & 2 deletions src/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,31 @@ import tokenPrices from './tokenPrices'
import topTokens from './topTokens'
import transactions from './transactions/reducer'
import tutorial from './tutorial/reducer'
import user from './user/reducer'
import user, { UserState } from './user/reducer'
import vesting from './vesting/reducer'

const PERSISTED_KEYS: string[] = ['user', 'transactions', 'profile']
ENV_LEVEL < ENV_TYPE.PROD && PERSISTED_KEYS.push('customizeDexes')

// Migrate from old version to new version, prevent lost favorite tokens of user
const preloadedState: any = load({ states: PERSISTED_KEYS })
if ('user' in preloadedState) {
const userState: UserState = preloadedState.user
if (userState.favoriteTokensByChainId) {
userState.favoriteTokensByChainIdv2 = Object.entries(userState.favoriteTokensByChainId).reduce(
(acc, [chainId, obj]) => {
acc[chainId] = {}
obj.addresses.forEach((address: string) => {
acc[chainId][address.toLowerCase()] = true
})
return acc
},
{} as any,
)
userState.favoriteTokensByChainId = undefined
}
}

const store = configureStore({
devTools: process.env.NODE_ENV !== 'production',
reducer: {
Expand Down Expand Up @@ -110,7 +129,7 @@ const store = configureStore({
.concat(earningApi.middleware)
.concat(socialApi.middleware)
.concat(tokenApi.middleware),
preloadedState: load({ states: PERSISTED_KEYS }),
preloadedState,
})

const PREFIX_REDUX_PERSIST = 'redux_localstorage_simple_'
Expand Down
4 changes: 3 additions & 1 deletion src/state/user/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ export const toggleTopTrendingTokens = createAction<void>('user/toggleTopTrendin

export type ToggleFavoriteTokenPayload = {
chainId: ChainId
} & ({ isNative?: false; address: string } | { isNative: true; address?: never })
address: string
newValue?: boolean
}
export const toggleFavoriteToken = createAction<ToggleFavoriteTokenPayload>('user/toggleFavoriteToken')
export const updateChainId = createAction<ChainId>('user/updateChainId')
export const updateTokenAnalysisSettings = createAction<string>('user/updateTokenAnalysisSettings')
Expand Down
37 changes: 29 additions & 8 deletions src/state/user/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useGetParticipantInfoQuery } from 'services/kyberAISubscription'

import { SUGGESTED_BASES } from 'constants/bases'
import { DEFAULT_SLIPPAGE_TESTNET, TERM_FILES_PATH } from 'constants/index'
import { SupportedLocale } from 'constants/locales'
import { PINNED_PAIRS } from 'constants/tokens'
Expand All @@ -16,6 +17,7 @@ import {
import useDebounce from 'hooks/useDebounce'
import { ParticipantInfo, ParticipantStatus } from 'pages/TrueSightV2/types'
import { AppDispatch, AppState } from 'state'
import { useKyberSwapConfig } from 'state/application/hooks'
import { useIsConnectingWallet, useSessionInfo } from 'state/authen/hooks'
import { useAppDispatch, useAppSelector } from 'state/hooks'
import { WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
Expand Down Expand Up @@ -49,9 +51,11 @@ import {
updateUserSlippageTolerance,
updateUserSlippageToleranceForLineaTestnet,
} from 'state/user/actions'
import { CROSS_CHAIN_SETTING_DEFAULT, CrossChainSetting, VIEW_MODE, getFavoriteTokenDefault } from 'state/user/reducer'
import { CROSS_CHAIN_SETTING_DEFAULT, CrossChainSetting, VIEW_MODE } from 'state/user/reducer'
import { isAddress, isChristmasTime } from 'utils'

const MAX_FAVORITE_LIMIT = 12

function serializeToken(token: Token | WrappedTokenInfo): SerializedToken {
return {
chainId: token.chainId,
Expand Down Expand Up @@ -395,18 +399,35 @@ export function useToggleTopTrendingTokens(): () => void {

export const useUserFavoriteTokens = (chainId: ChainId) => {
const dispatch = useDispatch<AppDispatch>()
const { favoriteTokensByChainId } = useSelector((state: AppState) => state.user)
const { favoriteTokensByChainIdv2: favoriteTokensByChainId } = useSelector((state: AppState) => state.user)
const { commonTokens } = useKyberSwapConfig(chainId)
const defaultTokens = useMemo(() => {
return commonTokens || SUGGESTED_BASES[chainId || ChainId.MAINNET].map(e => e.address)
}, [commonTokens, chainId])

const favoriteTokens = useMemo(() => {
if (!chainId) return undefined
return favoriteTokensByChainId
? favoriteTokensByChainId[chainId] || getFavoriteTokenDefault(chainId)
: getFavoriteTokenDefault(chainId)
}, [chainId, favoriteTokensByChainId])
const favoritedTokens = favoriteTokensByChainId?.[chainId] || {}
const favoritedTokenAddresses = defaultTokens
.filter(address => favoritedTokens[address.toLowerCase()] !== false)
.concat(Object.keys(favoritedTokens).filter(address => favoritedTokens[address]))

return [...new Set(favoritedTokenAddresses.map(a => a.toLowerCase()))]
}, [chainId, favoriteTokensByChainId, defaultTokens])

const toggleFavoriteToken = useCallback(
(payload: ToggleFavoriteTokenPayload) => dispatch(toggleFavoriteTokenAction(payload)),
[dispatch],
(payload: ToggleFavoriteTokenPayload) => {
if (!favoriteTokens) return
const address = payload.address.toLowerCase()
// Is adding favorite and reached max limit
if (favoriteTokens.indexOf(address) < 0 && favoriteTokens.length >= MAX_FAVORITE_LIMIT) {
return
}
const newValue = favoriteTokens.indexOf(address) < 0

dispatch(toggleFavoriteTokenAction({ ...payload, newValue }))
},
[dispatch, favoriteTokens],
)

return { favoriteTokens, toggleFavoriteToken }
Expand Down
Loading

0 comments on commit d72a683

Please sign in to comment.