Skip to content

Commit

Permalink
Fix issues for iframe partner-swap (#2390)
Browse files Browse the repository at this point in the history
* Remove history tab in "qs" for CrossChain tab

* Check customChainId for Edit/CancelOrderModal

* Update useTokensBalanceOfAnotherChain by rtkQuery

Update

* Fix rawToken not by customChainId

* Revert using new variable array

* Get dex by chainId
  • Loading branch information
neikop authored Nov 27, 2023
1 parent be3b1d8 commit 9323de7
Show file tree
Hide file tree
Showing 12 changed files with 107 additions and 59 deletions.
2 changes: 1 addition & 1 deletion src/components/SearchModal/CurrencyList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ function CurrencyList({
const canShowBalance = customChainId && customChainId !== chainId ? isEVM(customChainId) === isEVM(chainId) : true
const { favoriteTokens } = useUserFavoriteTokens(customChainId)

const Row: any = useCallback(
const Row = useCallback(
function TokenRow({ style, currency, currencyBalance }: TokenRowProps) {
const isSelected = Boolean(currency && selectedCurrency?.equals(currency))
const otherSelected = Boolean(currency && otherCurrency?.equals(currency))
Expand Down
2 changes: 1 addition & 1 deletion src/components/SearchModal/CurrencySearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export function CurrencySearch({
return (debouncedQuery ? filterTokens(chainId, tokenImports, debouncedQuery) : tokenImports).sort(tokenComparator)
}, [debouncedQuery, chainId, tokenImports, tokenComparator])

const fetchERC20TokenFromRPC = useFetchERC20TokenFromRPC()
const fetchERC20TokenFromRPC = useFetchERC20TokenFromRPC(chainId)

// input eth => output filter weth, input weth => output filter eth
const filterWrapFunc = useCallback(
Expand Down
2 changes: 1 addition & 1 deletion src/components/TradeRouting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const RouteRow = ({ route, chainId, backgroundColor }: RouteRowProps) => {
const contentRef = useRef<HTMLDivElement>(null)
const shadowRef = useRef<HTMLDivElement>(null)

const allDexes = useAllDexes()
const allDexes = useAllDexes(chainId)
const handleShadow = useShadow(scrollRef, shadowRef, contentRef)

useEffect(() => {
Expand Down
8 changes: 6 additions & 2 deletions src/components/swapv2/LimitOrder/EditOrderModal.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ChainId } from '@kyberswap/ks-sdk-core'
import { Trans } from '@lingui/macro'
import { ethers } from 'ethers'
import { useEffect, useMemo, useRef, useState } from 'react'
Expand Down Expand Up @@ -42,6 +43,7 @@ enum Steps {
export default function EditOrderModal({
onSubmit,
onDismiss,
customChainId,
order,
note,
isOpen,
Expand All @@ -50,6 +52,7 @@ export default function EditOrderModal({
}: {
onSubmit: CancelOrderFunction
onDismiss: () => void
customChainId?: ChainId
order: LimitOrder
note: string
isOpen: boolean
Expand All @@ -60,8 +63,8 @@ export default function EditOrderModal({
const [step, setStep] = useState(Steps.EDIT_ORDER)

const { status, makingAmount, takingAmount, makerAsset, takerAsset, filledTakingAmount, expiredAt } = order
const currencyIn = useCurrencyV2(makerAsset) ?? undefined
const currencyOut = useCurrencyV2(takerAsset) ?? undefined
const currencyIn = useCurrencyV2(makerAsset, customChainId) ?? undefined
const currencyOut = useCurrencyV2(takerAsset, customChainId) ?? undefined
const inputAmount = currencyIn ? ethers.utils.formatUnits(makingAmount, currencyIn.decimals) : ''
const outputAmount = currencyOut ? ethers.utils.formatUnits(takingAmount, currencyOut.decimals) : ''

Expand Down Expand Up @@ -193,6 +196,7 @@ export default function EditOrderModal({
note={note}
orderInfo={order}
defaultExpire={defaultExpire}
useUrlParams
/>
)}
</Wrapper>
Expand Down
8 changes: 6 additions & 2 deletions src/components/swapv2/LimitOrder/ListOrder/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,14 @@ export default function ListLimitOrder({ customChainId }: { customChainId?: Chai
setCurPage(1)
}

const isPartnerSwap = window.location.pathname.includes(APP_PATHS.PARTNER_SWAP)
const navigate = useNavigate()
const onSelectTab = (type: LimitOrderStatus) => {
setOrderType(type)
onReset()
if (!window.location.pathname.includes(APP_PATHS.PARTNER_SWAP))
if (!isPartnerSwap) {
navigate({ search: stringify(qs) }, { replace: true })
}
}

const onChangeKeyword = (val: string) => {
Expand Down Expand Up @@ -296,7 +298,7 @@ export default function ListLimitOrder({ customChainId }: { customChainId?: Chai
}, [totalOrderNotCancelling, orders, ordersUpdating])

const upToSmall = useMedia(`(max-width: ${MEDIA_WIDTHS.upToSmall}px)`)
const subscribeBtn = !window.location.pathname.includes(APP_PATHS.PARTNER_SWAP) && (
const subscribeBtn = !isPartnerSwap && (
<SubscribeNotificationButton
iconOnly={false}
style={{ margin: upToSmall ? 0 : '12px 12px 0px 12px' }}
Expand Down Expand Up @@ -397,6 +399,7 @@ export default function ListLimitOrder({ customChainId }: { customChainId?: Chai
flowState={flowState}
onDismiss={hideConfirmCancel}
onSubmit={onCancelOrder}
customChainId={customChainId}
order={currentOrder}
isCancelAll={isCancelAll}
/>
Expand All @@ -405,6 +408,7 @@ export default function ListLimitOrder({ customChainId }: { customChainId?: Chai
<EditOrderModal
flowState={flowState}
setFlowState={setFlowState}
customChainId={customChainId}
isOpen={isOpenEdit}
onDismiss={hideEditModal}
onSubmit={onCancelOrder}
Expand Down
13 changes: 10 additions & 3 deletions src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ChainId } from '@kyberswap/ks-sdk-core'
import { Trans, t } from '@lingui/macro'
import { useEffect, useMemo, useState } from 'react'
import { Text } from 'rebass'
Expand Down Expand Up @@ -26,21 +27,23 @@ export enum CancelStatus {
const styleLogo = { width: 20, height: 20 }
function CancelOrderModal({
isCancelAll,
customChainId,
order,
onSubmit,
onDismiss,
flowState,
isOpen,
}: {
isCancelAll: boolean
customChainId?: ChainId
order: LimitOrder | undefined
onSubmit: CancelOrderFunction
onDismiss: () => void
flowState: TransactionFlowState
isOpen: boolean
}) {
const currencyIn = useCurrencyV2(order?.makerAsset) || undefined
const currencyOut = useCurrencyV2(order?.takerAsset) || undefined
const currencyIn = useCurrencyV2(order?.makerAsset, customChainId) || undefined
const currencyOut = useCurrencyV2(order?.takerAsset, customChainId) || undefined
const { tradeInfo: marketPrice } = useBaseTradeInfoLimitOrder(currencyIn, currencyOut)

const {
Expand All @@ -56,7 +59,11 @@ function CancelOrderModal({
takerAssetDecimals,
} = order ?? ({} as LimitOrder)

const { orders = [], ordersSoftCancel = [], supportCancelGaslessAllOrders } = useAllActiveOrders(!isCancelAll)
const {
orders = [],
ordersSoftCancel = [],
supportCancelGaslessAllOrders,
} = useAllActiveOrders(!isCancelAll, customChainId)

const isOrderSupportGaslessCancel = useIsSupportSoftCancelOrder()
const { orderSupportGasless, chainSupportGasless } = isOrderSupportGaslessCancel(order)
Expand Down
5 changes: 3 additions & 2 deletions src/components/swapv2/LimitOrder/useFetchActiveAllOrders.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ChainId } from '@kyberswap/ks-sdk-core'
import { useCallback, useMemo } from 'react'
import { useGetLOConfigQuery, useGetListOrdersQuery } from 'services/limitOrder'

Expand All @@ -18,10 +19,10 @@ export const useIsSupportSoftCancelOrder = () => {
)
}

export default function useAllActiveOrders(disabled = false) {
export default function useAllActiveOrders(disabled = false, customChainId?: ChainId) {
const { account, chainId } = useActiveWeb3React()
const { data } = useGetListOrdersQuery(
{ chainId, maker: account, status: LimitOrderStatus.ACTIVE, pageSize: 100 },
{ chainId: customChainId ?? chainId, maker: account, status: LimitOrderStatus.ACTIVE, pageSize: 100 },
{ skip: !account || disabled },
)

Expand Down
79 changes: 37 additions & 42 deletions src/hooks/bridge/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Contract } from '@ethersproject/contracts'
import { ChainId, Currency, CurrencyAmount } from '@kyberswap/ks-sdk-core'
import JSBI from 'jsbi'
import { useCallback, useEffect, useMemo, useState } from 'react'
import contractQuery from 'services/contractQuery'

import ERC20_INTERFACE from 'constants/abis/erc20'
import { NativeCurrencies } from 'constants/tokens'
Expand Down Expand Up @@ -45,7 +47,7 @@ export const useEthBalanceOfAnotherChain = (chainId: ChainId | undefined) => {
return balance
}

export const useTokenBalanceOfAnotherChain = (chainId: ChainId | undefined, token: WrappedTokenInfo | undefined) => {
export const useTokenBalanceOfAnotherChain = (chainId?: ChainId, token?: WrappedTokenInfo) => {
const isNative = isTokenNative(token, chainId)
const param = useMemo(() => (token && !isNative ? [token] : []), [token, isNative])

Expand All @@ -57,56 +59,49 @@ export const useTokenBalanceOfAnotherChain = (chainId: ChainId | undefined, toke
}, [balances, ethBalance, isNative])
}

const EMPTY_ARRAY: TokenAmountLoading[] = []
export type FetchBalancesArg = {
account?: string
tokens: Currency[]
multicallContract: Contract | null
chainId?: ChainId
}

export const fetchBalancesQuery = async ({ account, tokens, multicallContract }: FetchBalancesArg) => {
if (!account || !tokens.length || !multicallContract) return []
const calls: CallParam[] = tokens.map(token => ({
callData: ERC20_INTERFACE.encodeFunctionData('balanceOf', [account]),
target: token.wrapped.address,
fragment: 'balanceOf',
key: token.wrapped.address,
}))
const { results } = await fetchChunk(
multicallContract,
calls.map(call => ({ address: call.target, callData: call.callData })),
undefined as any,
)
const result = formatResult(results, calls)
const balances = tokens.map(token => {
const balance = result[token.wrapped.address]
return [balance ? CurrencyAmount.fromRawAmount(token, JSBI.BigInt(balance)) : undefined, false]
})
return balances as TokenAmountLoading[]
}

export const useTokensBalanceOfAnotherChain = (
chainId: ChainId | undefined,
tokens: Currency[],
): [TokenAmountLoading[], boolean] => {
const [balances, setBalances] = useState<TokenAmountLoading[]>([])
const { account } = useActiveWeb3React()
const multicallContract = useMulticallContract(chainId)
const [loading, setLoading] = useState(false)

const getBalance = useCallback(async () => {
try {
setBalances(EMPTY_ARRAY)
if (!chainId || !account || !tokens.length || !multicallContract) {
return
}
setLoading(true)
const calls: CallParam[] = tokens.map(token => ({
callData: ERC20_INTERFACE.encodeFunctionData('balanceOf', [account]),
target: token.wrapped.address,
fragment: 'balanceOf',
key: token.wrapped.address,
}))

const { results } = await fetchChunk(
multicallContract,
calls.map(e => ({ address: e.target, callData: e.callData })),
undefined as any,
)

const result = formatResult(results, calls)
const balances = tokens.map(token => {
const balance = result[token.wrapped.address]
return [balance ? CurrencyAmount.fromRawAmount(token, JSBI.BigInt(balance)) : undefined, false]
})
setBalances(balances as TokenAmountLoading[])
return
} catch (error) {
console.error('get balance chain err', { chainId, error })
} finally {
setLoading(false)
}
}, [chainId, tokens, account, multicallContract])

useEffect(() => {
getBalance()
}, [getBalance])
const { data: balances = [], isLoading } = contractQuery.useFetchBalancesQuery({
account,
tokens,
multicallContract,
chainId,
})

return [balances, loading]
return [balances, isLoading]
}

type TokenList = { anytoken: string; underlying: string }[]
Expand Down
17 changes: 12 additions & 5 deletions src/pages/CrossChain/TransfersHistory/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,28 @@ type Props = {
}

const BridgeHistory: React.FC<Props> = ({ className }) => {
const navigate = useNavigate()
const theme = useTheme()
const qs = useParsedQueryString<{ tab: CrossChainTab }>()
const [activeTab, setTab] = useState<CrossChainTab>(qs.tab || CrossChainTab.ROUTE)
const isShowTradeRoutes = useShowTradeRoutes()
const navigate = useNavigate()
const isPartnerSwap = window.location.pathname.includes(APP_PATHS.PARTNER_SWAP)

const [activeTab, setTab] = useState<CrossChainTab>(
isPartnerSwap ? CrossChainTab.ROUTE : qs.tab || CrossChainTab.ROUTE,
)

const onClickTab = (tab: CrossChainTab) => {
navigate({ search: `tab=${tab}` }, { replace: true })
if (!isPartnerSwap) {
navigate({ search: `tab=${tab}` }, { replace: true })
}
setTab(tab)
}

const theme = useTheme()
return (
<div className={className}>
<RowBetween>
<TabSelector activeTab={activeTab} setTab={onClickTab} isShowTradeRoutes={isShowTradeRoutes} />
{!window.location.pathname.includes(APP_PATHS.PARTNER_SWAP) && (
{!isPartnerSwap && (
<SubscribeNotificationButton
subscribeTooltip={t`Subscribe to receive notifications on your cross-chain transaction.`}
trackingEvent={MIXPANEL_TYPE.CROSS_CHAIN_CLICK_SUBSCRIBE}
Expand Down
26 changes: 26 additions & 0 deletions src/services/contractQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

import { FetchBalancesArg, fetchBalancesQuery } from 'hooks/bridge'
import { TokenAmountLoading } from 'state/wallet/hooks'

const contractQuery = createApi({
reducerPath: 'contractQuery',
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: builder => ({
fetchBalances: builder.query<TokenAmountLoading[], FetchBalancesArg>({
queryFn: async (arg: FetchBalancesArg) => {
const data = await fetchBalancesQuery(arg)
return { data }
},
serializeQueryArgs: ({ queryArgs }) => {
const { account, tokens, chainId } = queryArgs
return { account, tokens, chainId }
},
keepUnusedDataFor: 10,
}),
}),
})

export const { useFetchBalancesQuery } = contractQuery

export default contractQuery
3 changes: 3 additions & 0 deletions src/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import blackjackApi from 'services/blackjack'
import blockServiceApi from 'services/blockService'
import campaignApi from 'services/campaign'
import coingeckoApi from 'services/coingecko'
import contractQuery from 'services/contractQuery'
import crosschainApi from 'services/crossChain'
import earningApi from 'services/earning'
import geckoTerminalApi from 'services/geckoTermial'
Expand Down Expand Up @@ -98,6 +99,7 @@ const store = configureStore({
[publicAnnouncementApi.reducerPath]: publicAnnouncementApi.reducer,
[geckoTerminalApi.reducerPath]: geckoTerminalApi.reducer,
[coingeckoApi.reducerPath]: coingeckoApi.reducer,
[contractQuery.reducerPath]: contractQuery.reducer,
[limitOrderApi.reducerPath]: limitOrderApi.reducer,

[campaignApi.reducerPath]: campaignApi.reducer,
Expand Down Expand Up @@ -132,6 +134,7 @@ const store = configureStore({
.concat(save({ states: PERSISTED_KEYS, debounce: 100 }))
.concat(geckoTerminalApi.middleware)
.concat(coingeckoApi.middleware)
.concat(contractQuery.middleware)
.concat(limitOrderApi.middleware)
.concat(kyberAIApi.middleware)
.concat(coinmarketcapApi.middleware)
Expand Down
1 change: 1 addition & 0 deletions src/state/wallet/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export function useTokenBalancesWithLoadingIndicator(
const isFetchOtherChain = chainId !== currentChain

const balancesCurrentChain = useTokensBalance(isFetchOtherChain ? EMPTY_ARRAY : tokens, chainId)

const [balancesOtherChain, isLoadingAnotherChain] = useTokensBalanceOfAnotherChain(
chainId,
isFetchOtherChain ? tokens : EMPTY_ARRAY,
Expand Down

0 comments on commit 9323de7

Please sign in to comment.