Skip to content

Commit

Permalink
fix: input output currency (#2511)
Browse files Browse the repository at this point in the history
  • Loading branch information
viet-nv authored Aug 1, 2024
1 parent 1423588 commit 5ac3ca7
Show file tree
Hide file tree
Showing 11 changed files with 258 additions and 575 deletions.
144 changes: 72 additions & 72 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,78 +52,78 @@
window.EventEmitter = EventEmitter
</script>

<script>
var cookie3Options = { siteId: 301, additionalTracking: true, cookielessEnabled: true }

window._paq = window._paq || []
;(function () {
var d = document,
g = d.createElement('script'),
s = d.getElementsByTagName('script')[0]
g.async = true
g.src = '/libs/cookie3.js'
s.parentNode.insertBefore(g, s)
})()
</script>

<script>
!(function () {
var analytics = (window.analytics = window.analytics || [])
if (!analytics.initialize)
if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.')
else {
analytics.invoked = !0
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on',
'addSourceMiddleware',
'addIntegrationMiddleware',
'setAnonymousId',
'addDestinationMiddleware',
]
analytics.factory = function (e) {
return function () {
if (window.analytics.initialized) return window.analytics[e].apply(window.analytics, arguments)
var i = Array.prototype.slice.call(arguments)
i.unshift(e)
analytics.push(i)
return analytics
}
}
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i]
analytics[key] = analytics.factory(key)
}
analytics.load = function (key, i) {
var t = document.createElement('script')
t.type = 'text/javascript'
t.async = !0
t.src = '/libs/red2.js'
var n = document.getElementsByTagName('script')[0]
n.parentNode.insertBefore(t, n)
analytics._loadOptions = i
}
analytics._writeKey = 'DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52'
analytics.SNIPPET_VERSION = '4.16.1'
analytics.load('DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52')
analytics.page()
}
})()
</script>
<!-- <script> -->
<!-- var cookie3Options = { siteId: 301, additionalTracking: true, cookielessEnabled: true } -->
<!---->
<!-- window._paq = window._paq || [] -->
<!-- ;(function () { -->
<!-- var d = document, -->
<!-- g = d.createElement('script'), -->
<!-- s = d.getElementsByTagName('script')[0] -->
<!-- g.async = true -->
<!-- g.src = '/libs/cookie3.js' -->
<!-- s.parentNode.insertBefore(g, s) -->
<!-- })() -->
<!-- </script> -->

<!-- <script> -->
<!-- !(function () { -->
<!-- var analytics = (window.analytics = window.analytics || []) -->
<!-- if (!analytics.initialize) -->
<!-- if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.') -->
<!-- else { -->
<!-- analytics.invoked = !0 -->
<!-- analytics.methods = [ -->
<!-- 'trackSubmit', -->
<!-- 'trackClick', -->
<!-- 'trackLink', -->
<!-- 'trackForm', -->
<!-- 'pageview', -->
<!-- 'identify', -->
<!-- 'reset', -->
<!-- 'group', -->
<!-- 'track', -->
<!-- 'ready', -->
<!-- 'alias', -->
<!-- 'debug', -->
<!-- 'page', -->
<!-- 'once', -->
<!-- 'off', -->
<!-- 'on', -->
<!-- 'addSourceMiddleware', -->
<!-- 'addIntegrationMiddleware', -->
<!-- 'setAnonymousId', -->
<!-- 'addDestinationMiddleware', -->
<!-- ] -->
<!-- analytics.factory = function (e) { -->
<!-- return function () { -->
<!-- if (window.analytics.initialized) return window.analytics[e].apply(window.analytics, arguments) -->
<!-- var i = Array.prototype.slice.call(arguments) -->
<!-- i.unshift(e) -->
<!-- analytics.push(i) -->
<!-- return analytics -->
<!-- } -->
<!-- } -->
<!-- for (var i = 0; i < analytics.methods.length; i++) { -->
<!-- var key = analytics.methods[i] -->
<!-- analytics[key] = analytics.factory(key) -->
<!-- } -->
<!-- analytics.load = function (key, i) { -->
<!-- var t = document.createElement('script') -->
<!-- t.type = 'text/javascript' -->
<!-- t.async = !0 -->
<!-- t.src = '/libs/red2.js' -->
<!-- var n = document.getElementsByTagName('script')[0] -->
<!-- n.parentNode.insertBefore(t, n) -->
<!-- analytics._loadOptions = i -->
<!-- } -->
<!-- analytics._writeKey = 'DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52' -->
<!-- analytics.SNIPPET_VERSION = '4.16.1' -->
<!-- analytics.load('DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52') -->
<!-- analytics.page() -->
<!-- } -->
<!-- })() -->
<!-- </script> -->
</head>

<body>
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useSyncTokenSymbolToUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export default function useSyncTokenSymbolToUrl(
!disabled
) {
// call once
setTimeout(() => findTokenPairFromUrl(chainId))
// setTimeout(() => findTokenPairFromUrl(chainId))
checkedTokenFromUrlWhenInit.current = true
}
}, [isLoadedTokenDefault, firstTokenChainId, chainId, network, disabled, findTokenPairFromUrl])
Expand Down
18 changes: 2 additions & 16 deletions src/pages/SwapV3/PopulatedSwapForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,22 @@ import { useLocation, useSearchParams } from 'react-router-dom'

import SwapForm, { SwapFormProps } from 'components/SwapForm'
import { APP_PATHS } from 'constants/index'
import useSyncTokenSymbolToUrl from 'hooks/useSyncTokenSymbolToUrl'
import { useAppSelector } from 'state/hooks'
import { Field } from 'state/swap/actions'
import { useInputCurrency, useOutputCurrency, useSwapActionHandlers } from 'state/swap/hooks'
import { useDegenModeManager, usePermitData, useUserSlippageTolerance, useUserTransactionTTL } from 'state/user/hooks'
import { useCurrencyBalances } from 'state/wallet/hooks'
import { DetailedRouteSummary } from 'types/route'

import useResetCurrenciesOnRemoveImportedTokens from './useResetCurrenciesOnRemoveImportedTokens'

type Props = {
routeSummary: DetailedRouteSummary | undefined
setRouteSummary: React.Dispatch<React.SetStateAction<DetailedRouteSummary | undefined>>
onSelectSuggestedPair: (fromToken: Currency | undefined, toToken: Currency | undefined, amount?: string) => void
hidden: boolean
onOpenGasToken: () => void
}
const PopulatedSwapForm: React.FC<Props> = ({
routeSummary,
setRouteSummary,
hidden,
onSelectSuggestedPair,
onOpenGasToken,
}) => {
const PopulatedSwapForm: React.FC<Props> = ({ routeSummary, setRouteSummary, hidden, onOpenGasToken }) => {
const currencyIn = useInputCurrency()
const currencyOut = useOutputCurrency()

const isSelectTokenManually = useAppSelector(state => state.swap.isSelectTokenManually)
const [balanceIn, balanceOut] = useCurrencyBalances(
useMemo(() => [currencyIn ?? undefined, currencyOut ?? undefined], [currencyIn, currencyOut]),
)
Expand All @@ -40,13 +28,11 @@ const PopulatedSwapForm: React.FC<Props> = ({
const [slippage] = useUserSlippageTolerance()
const permitData = usePermitData(currencyIn?.wrapped.address)

const { onCurrencySelection, onResetSelectCurrency } = useSwapActionHandlers()
const { onCurrencySelection } = useSwapActionHandlers()

const { pathname } = useLocation()
const [searchParams, setSearchParams] = useSearchParams()
const isPartnerSwap = pathname.startsWith(APP_PATHS.PARTNER_SWAP)
useSyncTokenSymbolToUrl(currencyIn, currencyOut, onSelectSuggestedPair, isSelectTokenManually, isPartnerSwap)
useResetCurrenciesOnRemoveImportedTokens(currencyIn, currencyOut, onResetSelectCurrency)

const outId =
searchParams.get('outputCurrency') || (currencyOut?.isNative ? currencyOut.symbol : currencyOut?.wrapped.address)
Expand Down
47 changes: 13 additions & 34 deletions src/pages/SwapV3/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Currency } from '@kyberswap/ks-sdk-core'
import { Trans } from '@lingui/macro'
import { ReactNode, Suspense, lazy, useCallback, useEffect, useMemo, useState } from 'react'
import Skeleton from 'react-loading-skeleton'
import { useLocation } from 'react-router-dom'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { Flex, Text } from 'rebass'
import styled from 'styled-components'

Expand All @@ -29,6 +28,7 @@ import {
import { APP_PATHS } from 'constants/index'
import { useActiveWeb3React } from 'hooks'
import { useAllTokens } from 'hooks/Tokens'
import { NETWORKS_INFO } from 'hooks/useChainsConfig'
import useParsedQueryString from 'hooks/useParsedQueryString'
import useTheme from 'hooks/useTheme'
import { BodyWrapper } from 'pages/AppBody'
Expand All @@ -37,9 +37,6 @@ import CrossChainLink from 'pages/CrossChain/CrossChainLink'
import CrossChainTransfersHistory from 'pages/CrossChain/TransfersHistory'
import Header from 'pages/SwapV3/Header'
import useCurrenciesByPage from 'pages/SwapV3/useCurrenciesByPage'
import { useLimitActionHandlers } from 'state/limit/hooks'
import { Field } from 'state/swap/actions'
import { useDefaultsFromURLSearch, useSwapActionHandlers } from 'state/swap/hooks'
import { useTutorialSwapGuide } from 'state/tutorial/hooks'
import { useShowTradeRoutes } from 'state/user/hooks'
import { DetailedRouteSummary } from 'types/route'
Expand Down Expand Up @@ -105,6 +102,17 @@ export default function Swap() {
const [isSelectCurrencyManually, setIsSelectCurrencyManually] = useState(false) // true when: select token input, output manually or click rotate token.

const { pathname } = useLocation()
const [searchParams] = useSearchParams()
const navigate = useNavigate()
useEffect(() => {
const inputCurrency = searchParams.get('inputCurrency')
const outputCurrency = searchParams.get('outputCurrency')
console.log(inputCurrency, outputCurrency)

if (inputCurrency || outputCurrency) {
navigate(`/swap/${NETWORKS_INFO[chainId].route}/${inputCurrency || ''}-to-${outputCurrency || ''}`)
}
}, [searchParams, chainId, navigate])

const shouldHighlightSwapBox = qs.highlightBox === 'true'

Expand All @@ -119,42 +127,14 @@ export default function Swap() {

const [activeTab, setActiveTab] = useState<TAB>(getDefaultTab())

const { onSelectPair: onSelectPairLimit } = useLimitActionHandlers()

useEffect(() => {
setActiveTab(getDefaultTab())
}, [getDefaultTab])

useDefaultsFromURLSearch()

const { onCurrencySelection, onUserInput } = useSwapActionHandlers()

const tradeRouteComposition = useMemo(() => {
return getTradeComposition(chainId, routeSummary?.parsedAmountIn, undefined, routeSummary?.route, defaultTokens)
}, [chainId, defaultTokens, routeSummary])

const handleTypeInput = useCallback(
(value: string) => {
onUserInput(Field.INPUT, value)
},
[onUserInput],
)

const onSelectSuggestedPair = useCallback(
(fromToken: Currency | undefined, toToken: Currency | undefined, amount?: string) => {
if (isLimitPage) {
onSelectPairLimit(fromToken, toToken, amount)
setIsSelectCurrencyManually(true)
return
}

if (fromToken) onCurrencySelection(Field.INPUT, fromToken)
if (toToken) onCurrencySelection(Field.OUTPUT, toToken)
if (amount) handleTypeInput(amount)
},
[handleTypeInput, onCurrencySelection, onSelectPairLimit, isLimitPage],
)

const onBackToSwapTab = () => setActiveTab(getDefaultTab())

return (
Expand All @@ -173,7 +153,6 @@ export default function Swap() {
>
{isSwapPage && (
<PopulatedSwapForm
onSelectSuggestedPair={onSelectSuggestedPair}
routeSummary={routeSummary}
setRouteSummary={setRouteSummary}
hidden={activeTab !== TAB.SWAP}
Expand Down
11 changes: 5 additions & 6 deletions src/pages/SwapV3/useUpdateSlippageInStableCoinSwap.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { ChainId } from '@kyberswap/ks-sdk-core'
import { useEffect, useRef } from 'react'
import { useSelector } from 'react-redux'
import { useSearchParams } from 'react-router-dom'
import { usePrevious } from 'react-use'

import { DEFAULT_SLIPPAGE, DEFAULT_SLIPPAGE_CORRELATED_PAIR, DEFAULT_SLIPPAGE_STABLE_PAIR_SWAP } from 'constants/index'
import { useStableCoins } from 'hooks/Tokens'
import { AppState } from 'state'
import { Field } from 'state/swap/actions'
import { useCheckCorrelatedPair } from 'state/swap/hooks'
import { useCheckCorrelatedPair, useCurrencyFromUrl } from 'state/swap/hooks'
import { useUserSlippageTolerance } from 'state/user/hooks'

const useUpdateSlippageInStableCoinSwap = (chainId: ChainId) => {
Expand All @@ -20,8 +17,10 @@ const useUpdateSlippageInStableCoinSwap = (chainId: ChainId) => {
const inputTokenFromParam = searchParams.get('inputCurrency') ?? ''
const outputTokenFromParam = searchParams.get('outputCurrency') ?? ''

const inputCurrencyId = useSelector((state: AppState) => state.swap[Field.INPUT].currencyId) || inputTokenFromParam
const outputCurrencyId = useSelector((state: AppState) => state.swap[Field.OUTPUT].currencyId) || outputTokenFromParam
const { fromCurrency, toCurrency } = useCurrencyFromUrl()

const inputCurrencyId = fromCurrency || inputTokenFromParam
const outputCurrencyId = toCurrency || outputTokenFromParam
const isCorrelatedPair = useCheckCorrelatedPair()

const previousInputCurrencyId = usePrevious(inputCurrencyId)
Expand Down
1 change: 1 addition & 0 deletions src/services/blackjack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const blackjackApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: `${BLACKJACK_API}/v1`,
}),
keepUnusedDataFor: 1,
endpoints: builder => ({
checkBlackjack: builder.query({
query: (address: string) => ({
Expand Down
16 changes: 1 addition & 15 deletions src/state/limit/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Currency } from '@kyberswap/ks-sdk-core'
import { useCallback, useEffect } from 'react'
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { CreateOrderParam } from 'components/swapv2/LimitOrder/type'
import { APP_PATHS } from 'constants/index'
import useDefaultsTokenFromURLSearch from 'hooks/useDefaultsTokenFromURLSearch'
import { AppDispatch, AppState } from 'state/index'
import { Field } from 'state/swap/actions'
import { useInputCurrency, useOutputCurrency, useSwapActionHandlers, useSwapState } from 'state/swap/hooks'
Expand Down Expand Up @@ -32,11 +30,8 @@ export function useLimitState(): LimitState & {

export function useLimitActionHandlers() {
const dispatch = useDispatch<AppDispatch>()
const { currencyIn, currencyOut } = useLimitState()
const { onSwitchTokensV2, onCurrencySelection, onUserInput } = useSwapActionHandlers()

const { inputCurrency, outputCurrency } = useDefaultsTokenFromURLSearch(currencyIn, currencyOut, APP_PATHS.LIMIT)

const setInputValue = useCallback(
(inputAmount: string) => {
onUserInput(Field.INPUT, inputAmount)
Expand Down Expand Up @@ -69,15 +64,6 @@ export function useLimitActionHandlers() {
[setInputValue, setCurrencyIn, setCurrencyOut],
)

useEffect(() => {
if (
(inputCurrency && !currencyIn?.equals(inputCurrency)) ||
(outputCurrency && !currencyOut?.equals(outputCurrency))
) {
onSelectPair(inputCurrency ?? undefined, outputCurrency ?? undefined)
}
}, [onSelectPair, inputCurrency, outputCurrency, currencyIn, currencyOut])

const pushOrderNeedCreated = useCallback(
(order: CreateOrderParam) => {
dispatch(pushOrderNeedCreatedAction(order))
Expand Down
1 change: 0 additions & 1 deletion src/state/swap/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export enum Field {
OUTPUT = 'OUTPUT',
}

export const selectCurrency = createAction<{ field: Field; currencyId: string }>('swap/selectCurrency')
export const resetSelectCurrency = createAction<{ field: Field }>('swap/resetSelectCurrency')

export const switchCurrencies = createAction<void>('swap/switchCurrencies')
Expand Down
Loading

0 comments on commit 5ac3ca7

Please sign in to comment.