Skip to content

Commit

Permalink
crosschain: update sdk v2 (#2376)
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenhoaidanh authored Dec 4, 2023
1 parent 930d495 commit 46da6d6
Show file tree
Hide file tree
Showing 20 changed files with 543 additions and 2,139 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"ChromeAndroid >= 52"
],
"dependencies": {
"@0xsquid/sdk": "^1.4.1",
"@0xsquid/sdk": "^2.8.1",
"@apollo/client": "^3.7.1",
"@blocto/web3-react-connector": "^1.0.0",
"@coinbase/wallet-sdk": "^3.0.4",
Expand Down Expand Up @@ -134,6 +134,7 @@
"workbox-routing": "^6.5.4"
},
"devDependencies": {
"@0xsquid/squid-types": "^0.1.34",
"@babel/core": "^7.21.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.21.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ interface CurrencyInputPanelBridgeProps {
currency: WrappedTokenInfo | undefined
tokens: WrappedTokenInfo[]
loadingToken: boolean
usdValue?: string
usdValue?: string | number
isCrossChain?: boolean
tooltipNotSupportChain?: string
dataTestId?: string
Expand Down
42 changes: 22 additions & 20 deletions src/components/TradeRouting/RoutingCrossChain.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Call } from '@0xsquid/sdk'
import { RouteActionResponse } from '@0xsquid/sdk/dist/types'
import { ChainId, WETH } from '@kyberswap/ks-sdk-core'
import React, { useCallback, useEffect, useRef } from 'react'
import ScrollContainer from 'react-indiana-drag-scroll'
Expand All @@ -24,15 +24,20 @@ import {
StyledWrap,
StyledWrapToken,
} from 'components/TradeRouting/styled'
import { getRouInfo } from 'pages/CrossChain/helpers'
import { useCrossChainState } from 'state/crossChain/hooks'
import { useAllDexes } from 'state/customizeDexes/hooks'
import { WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
import { getEtherscanLink } from 'utils'
import { uint256ToFraction } from 'utils/numbers'
import { isTokenNative } from 'utils/tokenInfo'

const RouteRowCrossChain = ({ routes, backgroundColor }: { routes: Call[]; backgroundColor?: string }) => {
const RouteRowCrossChain = ({
routes,
backgroundColor,
}: {
routes: RouteActionResponse[]
backgroundColor?: string
}) => {
const scrollRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const shadowRef = useRef<HTMLDivElement>(null)
Expand All @@ -54,17 +59,16 @@ const RouteRowCrossChain = ({ routes, backgroundColor }: { routes: Call[]; backg
<StyledWrap ref={shadowRef} backgroundColor={backgroundColor}>
<ScrollContainer innerRef={scrollRef} vertical={false} onScroll={handleShadow}>
<StyledHops length={routes.length} ref={contentRef}>
{routes.map((subRoute: any, index, arr) => {
if (!subRoute.fromToken || !subRoute.toToken) return null
const fromToken = new WrappedTokenInfo(subRoute.fromToken)
const toToken = new WrappedTokenInfo(subRoute.toToken)

const dex = subRoute.dex
{routes.map((subRoute, index, arr) => {
const dexName = (subRoute.data as { dex: string })?.dex?.toLowerCase?.() || ''
if (!subRoute.fromToken || !subRoute.toToken || !dexName) return null
const fromToken = new WrappedTokenInfo({
...subRoute.fromToken,
chainId: +subRoute.fromToken.chainId,
})
const toToken = new WrappedTokenInfo({ ...subRoute.toToken, chainId: +subRoute.toToken.chainId })
const dexLogo = allDexes.find(
el =>
el.id === dex.dexName.toLowerCase() ||
el.name.toLowerCase() === dex.dexName.toLowerCase() ||
dex.dexName.toLowerCase().startsWith(el.name.toLowerCase()),
el => el.id === dexName || el.name.toLowerCase() === dexName || dexName.startsWith(el.name.toLowerCase()),
)?.logoURL
return [fromToken, toToken].map((token: WrappedTokenInfo, indexLast) => {
const chainId = token.chainId as ChainId
Expand All @@ -86,7 +90,7 @@ const RouteRowCrossChain = ({ routes, backgroundColor }: { routes: Call[]; backg

<StyledExchangeStatic>
{dexLogo && <img src={dexLogo} alt="" className="img--sm" />}
{dex?.dexName}
{dexName}
</StyledExchangeStatic>
</StyledHop>
{!(index === arr.length - 1 && indexLast === 1) && (
Expand All @@ -109,7 +113,7 @@ const RoutingCrossChain = () => {
const shadowRef = useRef<HTMLDivElement>(null)
const wrapperRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const [{ route, currencyIn, currencyOut }] = useCrossChainState()
const [{ route, currencyIn, currencyOut, formatRoute }] = useCrossChainState()

const renderTokenInfo = (currency: typeof currencyIn, amount: string | undefined, reverseOrder?: boolean) => {
if (!currency) return null
Expand All @@ -123,11 +127,9 @@ const RoutingCrossChain = () => {
)
}

const { routeData, inputAmount, outputAmount } = getRouInfo(route)
const { routeData, inputAmount, outputAmount } = formatRoute

const routeSource: Call[] = routeData?.fromChain ?? []
const routeDest: Call[] = routeData?.toChain ?? []
const numRoute = routeSource.length + routeDest.length
const numRoute = routeData?.length || 0
const hasRoutes = chainIdOut && numRoute > 0

const handleScroll = useCallback(() => {
Expand Down Expand Up @@ -160,7 +162,7 @@ const RoutingCrossChain = () => {
<StyledRoute>
<StyledPercent>100%</StyledPercent>
<StyledRouteLine />
<RouteRowCrossChain routes={routeSource.concat(routeDest)} />
<RouteRowCrossChain routes={routeData} />
<StyledHopChevronWrapper style={{ marginRight: '2px' }}>
<StyledHopChevronRight />
</StyledHopChevronWrapper>
Expand Down
16 changes: 11 additions & 5 deletions src/components/swapv2/AdvancedSwapDetails.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RouteData } from '@0xsquid/sdk'
import { Currency, TradeType } from '@kyberswap/ks-sdk-core'
import { Trans, t } from '@lingui/macro'
import { useState } from 'react'
Expand All @@ -20,9 +19,9 @@ import { NativeCurrencies } from 'constants/tokens'
import { useActiveWeb3React } from 'hooks'
import useTheme from 'hooks/useTheme'
import TradePrice from 'pages/CrossChain/TradePrice'
import { getRouInfo } from 'pages/CrossChain/helpers'
import { useIsEnoughGas } from 'pages/CrossChain/useIsEnoughGas'
import { OutputBridgeInfo, useBridgeState, useCrossChainState } from 'state/crossChain/hooks'
import { RouteData } from 'state/crossChain/reducer'
import { Field } from 'state/swap/actions'
import { useUserSlippageTolerance } from 'state/user/hooks'
import { TYPE } from 'theme'
Expand Down Expand Up @@ -306,14 +305,14 @@ export function TradeSummaryCrossChain({
const { chainId } = useActiveWeb3React()

const [show, setShow] = useState(true)
const { duration, minReceive, priceImpact, totalFeeUsd, gasFeeUsd, crossChainFeeUsd } = getRouInfo(route)

const nativeToken = NativeCurrencies[chainId]
const { isEnoughEth, gasFee, crossChainFee } = useIsEnoughGas(route)
const { isEnoughEth, gasFee, crossChainFee, gasRefund } = useIsEnoughGas(route)

const colorGasFee = isEnoughEth ? theme.subText : theme.warning

const [{ currencyOut }] = useCrossChainState()
const [{ currencyOut, formatRoute }] = useCrossChainState()
const { duration, minReceive, priceImpact, totalFeeUsd, gasFeeUsd, crossChainFeeUsd, gasRefundUsd } = formatRoute

return (
<AutoColumn style={style}>
Expand Down Expand Up @@ -428,6 +427,13 @@ export function TradeSummaryCrossChain({
{formattedNum(crossChainFeeUsd + '', true)})
</Text>
</RowBetween>
<RowBetween>
<Trans>Expected gas refund: </Trans>
<Text as="span" color={colorGasFee}>
{gasRefund?.toSignificant(10)} {nativeToken?.symbol} (
{formattedNum(gasRefundUsd + '', true)})
</Text>
</RowBetween>
</Text>
</>
) : null
Expand Down
2 changes: 1 addition & 1 deletion src/components/swapv2/AdvancedSwapDetailsDropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { RouteData } from '@0xsquid/sdk'
import styled from 'styled-components'

import { useLastTruthy } from 'hooks/useLast'
import { OutputBridgeInfo } from 'state/crossChain/hooks'
import { RouteData } from 'state/crossChain/reducer'

import {
AdvancedSwapDetails,
Expand Down
3 changes: 2 additions & 1 deletion src/constants/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ export const MOCK_ACCOUNT_EVM = isAddressString(ChainId.MAINNET, mock[0]?.trim()
const isSupportTestNet = ENV_LEVEL < ENV_TYPE.PROD && new URLSearchParams(window.location.search).get('test')
export const CROSS_CHAIN_CONFIG = {
AXELAR_SCAN_URL: isSupportTestNet ? 'https://testnet.axelarscan.io/gmp/' : 'https://axelarscan.io/gmp/',
API_DOMAIN: isSupportTestNet ? 'https://testnet.api.0xsquid.com' : 'https://api.squidrouter.com',
API_DOMAIN: isSupportTestNet ? 'https://testnet.api.0xsquid.com' : 'https://v2.api.squidrouter.com',
INTEGRATOR_ID: 'kyberswap-api',
GAS_REFUND: 25, // %
}
9 changes: 4 additions & 5 deletions src/pages/Bridge/ComfirmBridgeModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RouteData } from '@0xsquid/sdk'
import { Trans, t } from '@lingui/macro'
import { rgba } from 'polished'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
Expand All @@ -20,8 +19,8 @@ import { useActiveWeb3React } from 'hooks'
import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel'
import useTheme from 'hooks/useTheme'
import SwapBrief from 'pages/CrossChain/SwapBriefCrossChain'
import { getRouInfo } from 'pages/CrossChain/helpers'
import { OutputBridgeInfo, useBridgeState, useCrossChainState } from 'state/crossChain/hooks'
import { RouteData } from 'state/crossChain/reducer'
import { useDegenModeManager } from 'state/user/hooks'
import { ExternalLink } from 'theme'
import { TransactionFlowState } from 'types/TransactionFlowState'
Expand Down Expand Up @@ -312,8 +311,8 @@ export const ConfirmCrossChainModal = memo(function ConfirmCrossChainModal({
const theme = useTheme()
const [accepted, setAccepted] = useState(false)
const { chainId } = useActiveWeb3React()
const [{ chainIdOut, currencyIn, currencyOut }] = useCrossChainState()
const { inputAmount, outputAmount, priceImpact } = getRouInfo(route)
const [{ chainIdOut, currencyIn, currencyOut, formatRoute }] = useCrossChainState()
const { inputAmount, outputAmount, priceImpact } = formatRoute
const [isDegenMode] = useDegenModeManager()
const { mixpanelHandler } = useMixpanel()

Expand Down Expand Up @@ -344,7 +343,7 @@ export const ConfirmCrossChainModal = memo(function ConfirmCrossChainModal({
<Trans>Please review the details of your swap:</Trans>
</Text>

<SwapBrief route={route} />
<SwapBrief />

<TradeSummaryCrossChain
route={route}
Expand Down
14 changes: 4 additions & 10 deletions src/pages/CrossChain/SwapBriefCrossChain.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RouteData } from '@0xsquid/sdk'
import { ChainId } from '@kyberswap/ks-sdk-core'
import { Trans } from '@lingui/macro'
import React from 'react'
Expand All @@ -14,15 +13,10 @@ import { RESERVE_USD_DECIMALS } from 'constants/index'
import { NETWORKS_INFO } from 'constants/networks'
import { useActiveWeb3React } from 'hooks'
import useTheme from 'hooks/useTheme'
import { getRouInfo } from 'pages/CrossChain/helpers'
import { useCrossChainState } from 'state/crossChain/hooks'
import { formattedNum } from 'utils'
import { uint256ToFraction } from 'utils/numbers'

type Props = {
route: RouteData | undefined
}

const TruncatedText = styled(Text)`
text-overflow: ellipsis;
overflow: hidden;
Expand Down Expand Up @@ -66,12 +60,12 @@ const Network = ({ chainId }: { chainId: ChainId | undefined }) => {
)
}

export default function SwapBrief({ route }: Props) {
export default function SwapBrief() {
const theme = useTheme()
const [{ currencyIn, currencyOut, chainIdOut }] = useCrossChainState()
const [{ currencyIn, currencyOut, chainIdOut, formatRoute }] = useCrossChainState()
const { chainId } = useActiveWeb3React()

const { amountUsdIn, amountUsdOut, outputAmount, inputAmount } = getRouInfo(route)
const { amountUsdIn, amountUsdOut, outputAmount, inputAmount } = formatRoute

const renderAmount = (amount: string | undefined, decimals: number | undefined) => {
try {
Expand All @@ -85,7 +79,7 @@ export default function SwapBrief({ route }: Props) {
}
}

const renderAmountUsd = (amountUsdOut: string | undefined) => {
const renderAmountUsd = (amountUsdOut: string | undefined | number) => {
return (
<Text fontSize={14} fontWeight={500} color={theme.subText}>
{amountUsdOut ? `~${formattedNum(amountUsdOut, true)}` : '--'}
Expand Down
25 changes: 14 additions & 11 deletions src/pages/CrossChain/SwapForm/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GetRoute } from '@0xsquid/sdk'
import { RouteRequest } from '@0xsquid/sdk/dist/types'
import { ChainId } from '@kyberswap/ks-sdk-core'
import { Trans, t } from '@lingui/macro'
import { useCallback, useMemo, useState } from 'react'
Expand All @@ -19,7 +19,7 @@ import useCheckStablePairSwap from 'components/SwapForm/hooks/useCheckStablePair
import { formatDurationCrossChain } from 'components/swapv2/AdvancedSwapDetails'
import { AdvancedSwapDetailsDropdownCrossChain } from 'components/swapv2/AdvancedSwapDetailsDropdown'
import { CROSS_CHAIN_CONFIG } from 'constants/env'
import { INPUT_DEBOUNCE_TIME, TRANSACTION_STATE_DEFAULT } from 'constants/index'
import { INPUT_DEBOUNCE_TIME, TRANSACTION_STATE_DEFAULT, ZERO_ADDRESS } from 'constants/index'
import { NETWORKS_INFO } from 'constants/networks'
import { useActiveWeb3React, useWeb3React } from 'hooks'
import { captureExceptionCrossChain } from 'hooks/bridge/useBridgeCallback'
Expand All @@ -31,7 +31,6 @@ import { ConfirmCrossChainModal } from 'pages/Bridge/ComfirmBridgeModal'
import ErrorWarningPanel from 'pages/Bridge/ErrorWarning'
import TradeTypeSelection from 'pages/CrossChain/SwapForm/TradeTypeSelection'
import TradePrice from 'pages/CrossChain/TradePrice'
import { getRouInfo } from 'pages/CrossChain/helpers'
import useGetRouteCrossChain from 'pages/CrossChain/useGetRoute'
import useValidateInput, { useIsTokensSupport } from 'pages/CrossChain/useValidateInput'
import { useWalletModalToggle } from 'state/application/hooks'
Expand Down Expand Up @@ -74,6 +73,7 @@ export default function SwapForm() {
chainIdOut,
squidInstance,
inputAmount,
formatRoute,
},
] = useCrossChainState()

Expand All @@ -82,19 +82,23 @@ export default function SwapForm() {
} = useCrossChainSetting()
const isPairSupport = useIsTokensSupport()
const debouncedInput = useDebounce(inputAmount, INPUT_DEBOUNCE_TIME)
const routeParams: GetRoute | undefined = useMemo(() => {
const routeParams: RouteRequest | undefined = useMemo(() => {
if (!currencyIn || !currencyOut || !chainIdOut || !Number(debouncedInput) || !isPairSupport) return
const parseAmount = tryParseAmount(debouncedInput, currencyIn)
if (!parseAmount) return
return {
fromChain: chainId,
toChain: chainIdOut,
fromAddress: account || ZERO_ADDRESS,
fromChain: chainId.toString(),
toChain: chainIdOut.toString(),
fromToken: getTokenAddress(currencyIn),
toToken: getTokenAddress(currencyOut),
fromAmount: parseAmount?.quotient.toString() ?? '',
toAddress: account ?? '',
slippage: slippageTolerance / 100,
enableExpress: enableExpressExecution,
slippageConfig: {
slippage: slippageTolerance / 100,
autoMode: 1,
},
enableBoost: enableExpressExecution,
quoteOnly: !account,
}
}, [
Expand All @@ -116,8 +120,7 @@ export default function SwapForm() {
loading: gettingRoute,
requestId,
} = useGetRouteCrossChain(routeParams)
const { outputAmount, amountUsdIn, amountUsdOut, exchangeRate, priceImpact, duration, totalFeeUsd } =
getRouInfo(route)
const { outputAmount, amountUsdIn, amountUsdOut, exchangeRate, priceImpact, duration, totalFeeUsd } = formatRoute
const { selectCurrencyIn, selectCurrencyOut, selectDestChain, setInputAmount } = useCrossChainHandlers()

const toggleWalletModal = useWalletModalToggle()
Expand Down Expand Up @@ -183,7 +186,7 @@ export default function SwapForm() {
if (!library || !squidInstance || !route || !inputAmount || !outputAmount || !currencyIn || !currencyOut) return
setSwapState(state => ({ ...state, attemptingTxn: true }))
onTracking(MIXPANEL_TYPE.CROSS_CHAIN_SWAP_CONFIRMED)
const tx = await squidInstance.executeRoute({
const tx: any = await squidInstance.executeRoute({
signer: library.getSigner(),
route,
})
Expand Down
7 changes: 3 additions & 4 deletions src/pages/CrossChain/TradePrice.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RouteData } from '@0xsquid/sdk'
import { NativeCurrency } from '@kyberswap/ks-sdk-core'
import { Trans } from '@lingui/macro'
import { useState } from 'react'
Expand All @@ -10,8 +9,8 @@ import Dots from 'components/Dots'
import { TokenLogoWithChain } from 'components/Logo'
import RefreshButton from 'components/SwapForm/RefreshButton'
import useTheme from 'hooks/useTheme'
import { getRouInfo } from 'pages/CrossChain/helpers'
import { useCrossChainState } from 'state/crossChain/hooks'
import { RouteData } from 'state/crossChain/reducer'
import { WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
import { MEDIA_WIDTHS } from 'theme'

Expand All @@ -34,11 +33,11 @@ export default function TradePrice({
}: TradePriceProps) {
const theme = useTheme()
const [showInverted, setShowInverted] = useState<boolean>(false)
const { exchangeRate } = getRouInfo(route)
const [{ currencyIn, currencyOut, chainIdOut, formatRoute }] = useCrossChainState()
const { exchangeRate } = formatRoute
let formattedPrice
const price = exchangeRate ? Number(exchangeRate) : undefined
if (price) formattedPrice = showInverted ? (1 / price).toPrecision(6) : price?.toPrecision(6)
const [{ currencyIn, currencyOut, chainIdOut }] = useCrossChainState()

const currencyLeft = showInverted ? currencyOut : currencyIn
const currencyRight = showInverted ? currencyIn : currencyOut
Expand Down
Loading

0 comments on commit 46da6d6

Please sign in to comment.