Skip to content

Commit

Permalink
Merge branch 'main' into fix-kyberai-list-issues
Browse files Browse the repository at this point in the history
  • Loading branch information
XiaoYhun authored Aug 14, 2023
2 parents eb4d56b + 896c678 commit a937ef9
Show file tree
Hide file tree
Showing 22 changed files with 99 additions and 147 deletions.
2 changes: 1 addition & 1 deletion src/components/Header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const IconImage = styled.img<{ isChristmas?: boolean }>`
`

const BlogWrapper = styled.span`
@media (max-width: 1440px) {
@media (max-width: 1600px) {
display: none;
}
`
Expand Down
17 changes: 12 additions & 5 deletions src/components/WalletPopup/WalletView.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Trans } from '@lingui/macro'
import { Trans, t } from '@lingui/macro'
import { rgba } from 'polished'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { ChevronLeft, FileText, LogOut, StopCircle, X } from 'react-feather'
Expand All @@ -10,6 +10,7 @@ import { ReactComponent as DragHandleIcon } from 'assets/svg/wallet_drag_handle.
import CopyHelper from 'components/Copy'
import SendIcon from 'components/Icons/SendIcon'
import Row from 'components/Row'
import { MouseoverTooltip } from 'components/Tooltip'
import AccountInfo from 'components/WalletPopup/AccountInfo'
import MyAssets from 'components/WalletPopup/MyAssets'
import PinButton from 'components/WalletPopup/PinButton'
Expand Down Expand Up @@ -323,7 +324,7 @@ export default function WalletView({
</Flex>
</>
) : (
<Flex alignItems={'center'} style={{ gap: 5 }} color={theme.subText}>
<Flex alignItems={'center'} style={{ gap: 8 }} color={theme.subText}>
{walletKey && (
<IconWrapper>
<img
Expand All @@ -336,9 +337,15 @@ export default function WalletView({
<Text as="span" fontWeight="500">
{shortenAddress(chainId, account, 5, false)}
</Text>
<CopyHelper toCopy={account} />
<ExternalLinkIcon href={getEtherscanLink(chainId, account, 'address')} color={theme.subText} />
<LogOutIcon size={16} onClick={disconnectWallet} />
<MouseoverTooltip text={t`Copy wallet address`} width="fit-content" placement="top">
<CopyHelper toCopy={account} />
</MouseoverTooltip>
<MouseoverTooltip text={t`Open scan explorer`} width="fit-content" placement="top">
<ExternalLinkIcon href={getEtherscanLink(chainId, account, 'address')} color={theme.subText} />
</MouseoverTooltip>
<MouseoverTooltip text={t`Disconnect wallet`} width="fit-content" placement="top">
<LogOutIcon size={16} onClick={disconnectWallet} />
</MouseoverTooltip>
</Flex>
)}
<Flex style={{ gap: 20 }} alignItems="center">
Expand Down
6 changes: 3 additions & 3 deletions src/components/swapv2/LimitOrder/DeltaRate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Text } from 'rebass'

import InfoHelper from 'components/InfoHelper'
import { Label } from 'components/swapv2/LimitOrder/LimitOrderForm'
import { BaseTradeInfoLO } from 'hooks/useBaseTradeInfo'
import { BaseTradeInfo } from 'hooks/useBaseTradeInfo'
import useTheme from 'hooks/useTheme'

import { RateInfo } from './type'
Expand All @@ -13,7 +13,7 @@ export function useGetDeltaRateLimitOrder({
marketPrice,
rateInfo,
}: {
marketPrice: BaseTradeInfoLO | undefined
marketPrice: BaseTradeInfo | undefined
rateInfo: RateInfo
}) {
const { deltaText, percent } = useMemo(() => {
Expand Down Expand Up @@ -48,7 +48,7 @@ const DeltaRate = ({
rateInfo,
symbolIn,
}: {
marketPrice: BaseTradeInfoLO | undefined
marketPrice: BaseTradeInfo | undefined
rateInfo: RateInfo
symbolIn: string
}) => {
Expand Down
22 changes: 4 additions & 18 deletions src/components/swapv2/LimitOrder/LimitOrderForm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChainId, Currency, CurrencyAmount, Token, TokenAmount, WETH } from '@kyberswap/ks-sdk-core'
import { Currency, CurrencyAmount, Token, TokenAmount, WETH } from '@kyberswap/ks-sdk-core'
import { Trans, t } from '@lingui/macro'
import dayjs from 'dayjs'
import { ethers } from 'ethers'
Expand Down Expand Up @@ -40,7 +40,7 @@ import { useLimitActionHandlers, useLimitState } from 'state/limit/hooks'
import { tryParseAmount } from 'state/swap/hooks'
import { useCurrencyBalance } from 'state/wallet/hooks'
import { TransactionFlowState } from 'types/TransactionFlowState'
import { formattedNum, getLimitOrderContract } from 'utils'
import { getLimitOrderContract } from 'utils'
import { subscribeNotificationOrderCancelled, subscribeNotificationOrderExpired } from 'utils/firebase'
import { maxAmountSpend } from 'utils/maxAmountSpend'

Expand Down Expand Up @@ -646,21 +646,10 @@ const LimitOrderForm = function LimitOrderForm({
)
}

const isMainNet = chainId === ChainId.MAINNET
const threshold = USD_THRESHOLD[chainId]
const showWarningThresHold = outputAmount && estimateUSD.rawInput && estimateUSD.rawInput < threshold
if (isMainNet && showWarningThresHold && tradeInfo?.gasFee) {
messages.push(
<Text>
<Trans>
Your order may only be filled when market price of {currencyIn?.symbol} to {currencyOut?.symbol} is &lt;{' '}
<HightLight>{formattedNum(String(tradeInfo?.marketRate), true)}</HightLight>, as estimated gas fee to fill
your order is ~<HightLight>${removeTrailingZero(tradeInfo?.gasFee?.toPrecision(6) ?? '0')}</HightLight>.
</Trans>
</Text>,
)
}
if (!isMainNet && showWarningThresHold) {

if (showWarningThresHold) {
messages.push(
<Text>
<Trans>
Expand All @@ -675,15 +664,12 @@ const LimitOrderForm = function LimitOrderForm({
}, [
chainId,
currencyIn,
currencyOut?.symbol,
deltaRate.percent,
deltaRate.profit,
deltaRate.rawPercent,
displayRate,
estimateUSD.rawInput,
outputAmount,
tradeInfo?.gasFee,
tradeInfo?.marketRate,
])

return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useCurrencyV2 } from 'hooks/Tokens'
import useTheme from 'hooks/useTheme'
import { TransactionFlowState } from 'types/TransactionFlowState'

import { BaseTradeInfoLO, useBaseTradeInfoLimitOrder } from '../../../../hooks/useBaseTradeInfo'
import { BaseTradeInfo, useBaseTradeInfoLimitOrder } from '../../../../hooks/useBaseTradeInfo'
import { calcPercentFilledOrder, formatAmountOrder } from '../helpers'
import { LimitOrder, LimitOrderStatus } from '../type'
import { Container, Header, Label, ListInfo, MarketInfo, Note, Rate, Value } from './styled'
Expand All @@ -24,7 +24,7 @@ function ContentCancel({
}: {
isCancelAll: boolean
order: LimitOrder | undefined
marketPrice: BaseTradeInfoLO | undefined
marketPrice: BaseTradeInfo | undefined
onSubmit: () => void
onDismiss: () => void
}) {
Expand Down
4 changes: 2 additions & 2 deletions src/components/swapv2/LimitOrder/Modals/ConfirmOrderModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import CurrencyLogo from 'components/CurrencyLogo'
import TransactionConfirmationModal, { TransactionErrorContent } from 'components/TransactionConfirmationModal'
import { WORSE_PRICE_DIFF_THRESHOLD } from 'components/swapv2/LimitOrder/const'
import { useActiveWeb3React } from 'hooks'
import { BaseTradeInfoLO } from 'hooks/useBaseTradeInfo'
import { BaseTradeInfo } from 'hooks/useBaseTradeInfo'
import ErrorWarningPanel from 'pages/Bridge/ErrorWarning'
import { TransactionFlowState } from 'types/TransactionFlowState'

Expand Down Expand Up @@ -43,7 +43,7 @@ export default memo(function ConfirmOrderModal({
inputAmount: string
outputAmount: string
expireAt: number
marketPrice: BaseTradeInfoLO | undefined
marketPrice: BaseTradeInfo | undefined
rateInfo: RateInfo
note?: string
warningMessage: ReactNode[]
Expand Down
4 changes: 2 additions & 2 deletions src/components/swapv2/LimitOrder/Modals/styled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styled from 'styled-components'

import { Swap as SwapIcon } from 'components/Icons'
import TradePrice from 'components/swapv2/LimitOrder/TradePrice'
import { BaseTradeInfoLO } from 'hooks/useBaseTradeInfo'
import { BaseTradeInfo } from 'hooks/useBaseTradeInfo'
import useTheme from 'hooks/useTheme'

import { formatAmountOrder, formatRateLimitOrder } from '../helpers'
Expand Down Expand Up @@ -87,7 +87,7 @@ export const MarketInfo = ({
symbolIn,
symbolOut,
}: {
marketPrice: BaseTradeInfoLO | undefined
marketPrice: BaseTradeInfo | undefined
symbolIn: string | undefined
symbolOut: string | undefined
}) => {
Expand Down
2 changes: 0 additions & 2 deletions src/components/swapv2/LimitOrder/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ export const CLOSE_ORDER_OPTIONS = [
},
]

export const GAS_AMOUNT_ETHEREUM = 1_200_000

const _USD_THRESHOLD: { [chainId: number]: number } = {
[ChainId.MAINNET]: 300,
}
Expand Down
14 changes: 10 additions & 4 deletions src/components/swapv2/TokenInfo/SecurityInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,29 @@ import { ReactComponent as TreadingSecurity } from 'assets/svg/security_trading.
import { CollapseItem } from 'components/Collapse'
import { getSecurityTokenInfo } from 'components/swapv2/TokenInfo/utils'
import useTheme from 'hooks/useTheme'
import { useIsDarkMode } from 'state/user/hooks'

import { Container } from '../index'
import Content from './Content'
import Header from './Header'

export default function SecurityInfo({ token }: { token: Token | undefined }) {
const theme = useTheme()
const style: CSSProperties = { background: rgba(theme.black, 0.2), borderRadius: '16px', padding: '0' }
const headerStyle: CSSProperties = { background: rgba(theme.black, 0.48) }
const isDarkMode = useIsDarkMode()
const style: CSSProperties = {
background: isDarkMode ? rgba(theme.black, 0.2) : rgba(theme.subText, 0.04),
borderRadius: '16px',
padding: '0',
}
const headerStyle: CSSProperties = { background: isDarkMode ? rgba(theme.black, 0.48) : rgba(theme.subText, 0.08) }
const arrowStyle: CSSProperties = { marginRight: '6px', color: theme.subText }
const { data, isLoading } = useGetSecurityTokenInfoQuery(
const { data, isLoading, error } = useGetSecurityTokenInfoQuery(
{ chainId: token?.chainId as ChainId, address: token?.address ?? '' },
{ skip: !token?.address },
)

const { contractData, tradingData, totalWarningContract, totalWarningTrading, totalRiskContract, totalRiskTrading } =
useMemo(() => getSecurityTokenInfo(data), [data])
useMemo(() => getSecurityTokenInfo(error ? undefined : data), [data, error])

return (
<Container>
Expand Down
11 changes: 1 addition & 10 deletions src/data/poolRate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export const getHourlyRateData = async (
networkInfo: EVMNetworkInfo,
elasticClient: ApolloClient<NormalizedCacheObject>,
blockClient: ApolloClient<NormalizedCacheObject>,
signal: AbortSignal,
): Promise<[PoolRatesEntry[], PoolRatesEntry[]] | undefined> => {
try {
const utcEndTime = dayjs.utc()
Expand All @@ -39,14 +38,7 @@ export const getHourlyRateData = async (
}

// once you have all the timestamps, get the blocks for each timestamp in a bulk query
let blocks = await getBlocksFromTimestamps(
isEnableBlockService,
blockClient,
timestamps,
networkInfo.chainId,
signal,
)
if (signal.aborted) return
let blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, timestamps, networkInfo.chainId)
// catch failing case
if (!blocks || blocks?.length === 0) {
return
Expand All @@ -60,7 +52,6 @@ export const getHourlyRateData = async (
[poolAddress],
100,
)
if (signal.aborted) return

// format token ETH price results
const values: {
Expand Down
33 changes: 3 additions & 30 deletions src/hooks/useBaseTradeInfo.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { ChainId, Currency, WETH } from '@kyberswap/ks-sdk-core'
import { ethers } from 'ethers'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo } from 'react'
import { parseGetRouteResponse } from 'services/route/utils'

import useGetRoute, { ArgsGetRoute, useGetRouteSolana } from 'components/SwapForm/hooks/useGetRoute'
import { GAS_AMOUNT_ETHEREUM } from 'components/swapv2/LimitOrder/const'
import { useActiveWeb3React, useWeb3React } from 'hooks'
import { useActiveWeb3React } from 'hooks'
import useDebounce from 'hooks/useDebounce'
import useInterval from 'hooks/useInterval'
import { useTokenPricesWithLoading } from 'state/tokenPrices/hooks'

export type BaseTradeInfo = {
Expand Down Expand Up @@ -51,34 +48,10 @@ function useBaseTradeInfo(currencyIn: Currency | undefined, currencyOut: Currenc
return { loading, tradeInfo, refetch }
}

export type BaseTradeInfoLO = BaseTradeInfo & {
gasFee: number
}

export function useBaseTradeInfoLimitOrder(currencyIn: Currency | undefined, currencyOut: Currency | undefined) {
const { library } = useWeb3React()

const [gasFee, setGasFee] = useState(0)
const { loading, tradeInfo } = useBaseTradeInfo(currencyIn, currencyOut)
const nativePriceUsd = tradeInfo?.nativePriceUsd

const fetchGasFee = useCallback(() => {
if (!library || !nativePriceUsd) return
library
.getSigner()
.getGasPrice()
.then(data => {
const gasPrice = Number(ethers.utils.formatEther(data))
if (gasPrice) setGasFee(gasPrice * nativePriceUsd * GAS_AMOUNT_ETHEREUM)
})
.catch(e => {
console.error('fetchGasFee', e)
})
}, [library, nativePriceUsd])

useInterval(fetchGasFee, nativePriceUsd ? 15_000 : 2000)
const debouncedLoading = useDebounce(loading, 100) // prevent flip flop UI when loading from true to false
return { loading: loading || debouncedLoading, tradeInfo: { ...tradeInfo, gasFee } as BaseTradeInfoLO }
return { loading: loading || debouncedLoading, tradeInfo }
}

export const useBaseTradeInfoWithAggregator = (args: ArgsGetRoute) => {
Expand Down
18 changes: 13 additions & 5 deletions src/hooks/useTokenInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,28 @@ export interface TokenInfo {
name: string
}

export default function useTokenInfo(token: Token | undefined): { data: TokenInfo; loading: boolean; error: any } {
export default function useTokenInfo(token: Token | undefined): {
data: TokenInfo
loading: boolean
error: any
} {
const { isSolana, chainId: currentChain } = useActiveWeb3React()
const chainId = token?.chainId || currentChain
const coingeckoAPI = useCoingeckoAPI()

const tokenAddress = isSolana ? token?.address || '' : (token?.address || '').toLowerCase()
const { data, error } = useGetMarketTokenInfoQuery(
const {
data: rawData,
error,
isFetching,
} = useGetMarketTokenInfoQuery(
{ chainId, address: tokenAddress, coingeckoAPI },
{ skip: !tokenAddress, pollingInterval: 60_000 },
)

const loading = !data
const data = error ? {} : rawData

const result = {
const result: TokenInfo = {
price: data?.market_data?.current_price?.usd || 0,
marketCap: data?.market_data?.market_cap?.usd || 0,
marketCapRank: data?.market_data?.market_cap_rank || 0,
Expand All @@ -44,5 +52,5 @@ export default function useTokenInfo(token: Token | undefined): { data: TokenInf
name: data?.name || '',
}

return { data: result, loading, error }
return { data: result, loading: isFetching, error }
}
4 changes: 1 addition & 3 deletions src/pages/MyEarnings/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,10 @@ async function getBulkPoolDataWithPagination(
blockClient: ApolloClient<NormalizedCacheObject>,
ethPrice: string,
chainId: ChainId,
signal: AbortSignal,
): Promise<any> {
try {
const [t1] = getTimestampsForChanges()
const blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [t1], chainId, signal)
const blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [t1], chainId)

// In case we can't get the block one day ago then we set it to 0 which is fine
// because our subgraph never syncs from block 0 => response is empty
Expand Down Expand Up @@ -227,7 +226,6 @@ export function useAllPoolsData(chainId: ChainId): {
blockClient,
String(ethPrice),
chainId,
controller.signal,
),
)
}
Expand Down
Loading

0 comments on commit a937ef9

Please sign in to comment.