diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx index bad526a90b..6a7a81f210 100644 --- a/src/components/Header/index.tsx +++ b/src/components/Header/index.tsx @@ -141,7 +141,7 @@ const IconImage = styled.img<{ isChristmas?: boolean }>` ` const BlogWrapper = styled.span` - @media (max-width: 1440px) { + @media (max-width: 1600px) { display: none; } ` diff --git a/src/components/WalletPopup/WalletView.tsx b/src/components/WalletPopup/WalletView.tsx index 6456c9c52e..9a7b32821c 100644 --- a/src/components/WalletPopup/WalletView.tsx +++ b/src/components/WalletPopup/WalletView.tsx @@ -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' @@ -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' @@ -323,7 +324,7 @@ export default function WalletView({ ) : ( - + {walletKey && ( {shortenAddress(chainId, account, 5, false)} - - - + + + + + + + + + )} diff --git a/src/components/swapv2/LimitOrder/DeltaRate.tsx b/src/components/swapv2/LimitOrder/DeltaRate.tsx index b5e408dc9e..c5cd0479f9 100644 --- a/src/components/swapv2/LimitOrder/DeltaRate.tsx +++ b/src/components/swapv2/LimitOrder/DeltaRate.tsx @@ -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' @@ -13,7 +13,7 @@ export function useGetDeltaRateLimitOrder({ marketPrice, rateInfo, }: { - marketPrice: BaseTradeInfoLO | undefined + marketPrice: BaseTradeInfo | undefined rateInfo: RateInfo }) { const { deltaText, percent } = useMemo(() => { @@ -48,7 +48,7 @@ const DeltaRate = ({ rateInfo, symbolIn, }: { - marketPrice: BaseTradeInfoLO | undefined + marketPrice: BaseTradeInfo | undefined rateInfo: RateInfo symbolIn: string }) => { diff --git a/src/components/swapv2/LimitOrder/LimitOrderForm.tsx b/src/components/swapv2/LimitOrder/LimitOrderForm.tsx index 7e08da9da1..e8d7989645 100644 --- a/src/components/swapv2/LimitOrder/LimitOrderForm.tsx +++ b/src/components/swapv2/LimitOrder/LimitOrderForm.tsx @@ -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' @@ -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' @@ -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( - - - Your order may only be filled when market price of {currencyIn?.symbol} to {currencyOut?.symbol} is <{' '} - {formattedNum(String(tradeInfo?.marketRate), true)}, as estimated gas fee to fill - your order is ~${removeTrailingZero(tradeInfo?.gasFee?.toPrecision(6) ?? '0')}. - - , - ) - } - if (!isMainNet && showWarningThresHold) { + + if (showWarningThresHold) { messages.push( @@ -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 ( diff --git a/src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx b/src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx index af2ab83c7e..b84a5dc5cd 100644 --- a/src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx +++ b/src/components/swapv2/LimitOrder/Modals/CancelOrderModal.tsx @@ -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' @@ -24,7 +24,7 @@ function ContentCancel({ }: { isCancelAll: boolean order: LimitOrder | undefined - marketPrice: BaseTradeInfoLO | undefined + marketPrice: BaseTradeInfo | undefined onSubmit: () => void onDismiss: () => void }) { diff --git a/src/components/swapv2/LimitOrder/Modals/ConfirmOrderModal.tsx b/src/components/swapv2/LimitOrder/Modals/ConfirmOrderModal.tsx index 356bf8f694..a98104fc97 100644 --- a/src/components/swapv2/LimitOrder/Modals/ConfirmOrderModal.tsx +++ b/src/components/swapv2/LimitOrder/Modals/ConfirmOrderModal.tsx @@ -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' @@ -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[] diff --git a/src/components/swapv2/LimitOrder/Modals/styled.tsx b/src/components/swapv2/LimitOrder/Modals/styled.tsx index eb6dcb8be0..9f41f93851 100644 --- a/src/components/swapv2/LimitOrder/Modals/styled.tsx +++ b/src/components/swapv2/LimitOrder/Modals/styled.tsx @@ -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' @@ -87,7 +87,7 @@ export const MarketInfo = ({ symbolIn, symbolOut, }: { - marketPrice: BaseTradeInfoLO | undefined + marketPrice: BaseTradeInfo | undefined symbolIn: string | undefined symbolOut: string | undefined }) => { diff --git a/src/components/swapv2/LimitOrder/const.ts b/src/components/swapv2/LimitOrder/const.ts index d91e2ed33d..dc6cf69fcd 100644 --- a/src/components/swapv2/LimitOrder/const.ts +++ b/src/components/swapv2/LimitOrder/const.ts @@ -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, } diff --git a/src/components/swapv2/TokenInfo/SecurityInfo/index.tsx b/src/components/swapv2/TokenInfo/SecurityInfo/index.tsx index 67447e3e75..c0cbe01509 100644 --- a/src/components/swapv2/TokenInfo/SecurityInfo/index.tsx +++ b/src/components/swapv2/TokenInfo/SecurityInfo/index.tsx @@ -11,6 +11,7 @@ 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' @@ -18,16 +19,21 @@ 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 ( diff --git a/src/data/poolRate.ts b/src/data/poolRate.ts index 796eee0ffd..afbf65335c 100644 --- a/src/data/poolRate.ts +++ b/src/data/poolRate.ts @@ -20,7 +20,6 @@ export const getHourlyRateData = async ( networkInfo: EVMNetworkInfo, elasticClient: ApolloClient, blockClient: ApolloClient, - signal: AbortSignal, ): Promise<[PoolRatesEntry[], PoolRatesEntry[]] | undefined> => { try { const utcEndTime = dayjs.utc() @@ -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 @@ -60,7 +52,6 @@ export const getHourlyRateData = async ( [poolAddress], 100, ) - if (signal.aborted) return // format token ETH price results const values: { diff --git a/src/hooks/useBaseTradeInfo.ts b/src/hooks/useBaseTradeInfo.ts index 4a99f7d360..6ee20e3f91 100644 --- a/src/hooks/useBaseTradeInfo.ts +++ b/src/hooks/useBaseTradeInfo.ts @@ -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 = { @@ -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) => { diff --git a/src/hooks/useTokenInfo.ts b/src/hooks/useTokenInfo.ts index bbe0090ecc..2f16a46d77 100644 --- a/src/hooks/useTokenInfo.ts +++ b/src/hooks/useTokenInfo.ts @@ -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, @@ -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 } } diff --git a/src/pages/MyEarnings/hooks.ts b/src/pages/MyEarnings/hooks.ts index 88a0e8007a..33656dbbbf 100644 --- a/src/pages/MyEarnings/hooks.ts +++ b/src/pages/MyEarnings/hooks.ts @@ -108,11 +108,10 @@ async function getBulkPoolDataWithPagination( blockClient: ApolloClient, ethPrice: string, chainId: ChainId, - signal: AbortSignal, ): Promise { 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 @@ -227,7 +226,6 @@ export function useAllPoolsData(chainId: ChainId): { blockClient, String(ethPrice), chainId, - controller.signal, ), ) } diff --git a/src/services/blockService.ts b/src/services/blockService.ts new file mode 100644 index 0000000000..88fe437b0c --- /dev/null +++ b/src/services/blockService.ts @@ -0,0 +1,26 @@ +import { ChainId } from '@kyberswap/ks-sdk-core' +import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' + +import { BLOCK_SERVICE_API } from 'constants/env' +import { NETWORKS_INFO } from 'constants/networks' + +const blockServiceApi = createApi({ + reducerPath: 'blockServiceApi', + baseQuery: fetchBaseQuery({ + baseUrl: BLOCK_SERVICE_API, + }), + endpoints: builder => ({ + getBlocks: builder.query< + { data: Array<{ number: number; timestamp: number }> }, + { chainId: ChainId; timestamps: number[] } + >({ + query: ({ chainId, timestamps }) => ({ + url: `/${NETWORKS_INFO[chainId].aggregatorRoute}/api/v1/block?timestamps=${timestamps.join(',')}`, + }), + }), + }), +}) + +export const { useLazyGetBlocksQuery } = blockServiceApi + +export default blockServiceApi diff --git a/src/state/application/hooks.ts b/src/state/application/hooks.ts index ab39abe3cd..4a525bb2af 100644 --- a/src/state/application/hooks.ts +++ b/src/state/application/hooks.ts @@ -241,7 +241,6 @@ export const getEthPrice = async ( chainId: ChainId, apolloClient: ApolloClient, blockClient: ApolloClient, - signal: AbortSignal, ) => { const utcCurrentTime = dayjs() const utcOneDayBack = utcCurrentTime.subtract(1, 'day').startOf('minute').unix() @@ -252,7 +251,7 @@ export const getEthPrice = async ( try { const oneDayBlock = ( - await getBlocksFromTimestamps(isEnableBlockService, blockClient, [utcOneDayBack], chainId, signal) + await getBlocksFromTimestamps(isEnableBlockService, blockClient, [utcOneDayBack], chainId) )?.[0]?.number const result = await apolloClient.query({ query: ETH_PRICE(), @@ -281,7 +280,6 @@ const getPrommEthPrice = async ( chainId: ChainId, apolloClient: ApolloClient, blockClient: ApolloClient, - signal: AbortSignal, ) => { const utcCurrentTime = dayjs() const utcOneDayBack = utcCurrentTime.subtract(1, 'day').startOf('minute').unix() @@ -292,7 +290,7 @@ const getPrommEthPrice = async ( try { const oneDayBlock = ( - await getBlocksFromTimestamps(isEnableBlockService, blockClient, [utcOneDayBack], chainId, signal) + await getBlocksFromTimestamps(isEnableBlockService, blockClient, [utcOneDayBack], chainId) )?.[0]?.number const result = await apolloClient.query({ query: PROMM_ETH_PRICE(), @@ -332,8 +330,8 @@ export function useETHPrice(version: string = VERSION.CLASSIC): AppState['applic async function checkForEthPrice() { try { const [newPrice, oneDayBackPrice, pricePercentChange] = await (version === VERSION.ELASTIC - ? getPrommEthPrice(isEnableBlockService, chainId, elasticClient, blockClient, controller.signal) - : getEthPrice(isEnableBlockService, chainId, classicClient, blockClient, controller.signal)) + ? getPrommEthPrice(isEnableBlockService, chainId, elasticClient, blockClient) + : getEthPrice(isEnableBlockService, chainId, classicClient, blockClient)) dispatch( version === VERSION.ELASTIC diff --git a/src/state/farms/classic/updater.ts b/src/state/farms/classic/updater.ts index 6dbbab3cde..9c64385b45 100644 --- a/src/state/farms/classic/updater.ts +++ b/src/state/farms/classic/updater.ts @@ -124,7 +124,6 @@ export default function Updater({ isInterval = true }: { isInterval?: boolean }) blockClient, chainId, ethPriceRef.current, - abortController.signal, ) if (abortController.signal.aborted) throw new AbortedError() diff --git a/src/state/index.ts b/src/state/index.ts index c4ad291a28..d3aab11231 100644 --- a/src/state/index.ts +++ b/src/state/index.ts @@ -1,5 +1,6 @@ import { configureStore } from '@reduxjs/toolkit' import { load, save } from 'redux-localstorage-simple' +import blockServiceApi from 'services/blockService' import coingeckoApi from 'services/coingecko' import kyberAISubscriptionApi from 'services/kyberAISubscription' import priceAlertApi from 'services/priceAlert' @@ -114,6 +115,7 @@ const store = configureStore({ [earningApi.reducerPath]: earningApi.reducer, [tokenApi.reducerPath]: tokenApi.reducer, [socialApi.reducerPath]: socialApi.reducer, + [blockServiceApi.reducerPath]: blockServiceApi.reducer, }, middleware: getDefaultMiddleware => getDefaultMiddleware({ thunk: true, immutableCheck: false, serializableCheck: false }) diff --git a/src/state/mint/proamm/hooks.tsx b/src/state/mint/proamm/hooks.tsx index 4b2855d573..ba592f1629 100644 --- a/src/state/mint/proamm/hooks.tsx +++ b/src/state/mint/proamm/hooks.tsx @@ -1414,7 +1414,6 @@ export function useHourlyRateData( const { elasticClient, blockClient, isEnableBlockService } = useKyberSwapConfig() useEffect(() => { - const controller = new AbortController() const currentTime = dayjs.utc() let startTime: number @@ -1459,13 +1458,11 @@ export function useHourlyRateData( NETWORKS_INFO[chainId], elasticClient, blockClient, - controller.signal, ) - !controller.signal.aborted && ratesData && setRatesData(ratesData) + ratesData && setRatesData(ratesData) } } fetch() - return () => controller.abort() }, [timeWindow, poolAddress, dispatch, chainId, elasticClient, blockClient, isEnableBlockService]) return ratesData diff --git a/src/state/pools/hooks.ts b/src/state/pools/hooks.ts index d17f58657f..8f664b602b 100644 --- a/src/state/pools/hooks.ts +++ b/src/state/pools/hooks.ts @@ -138,7 +138,6 @@ export async function getBulkPoolDataFromPoolList( blockClient: ApolloClient, chainId: ChainId, ethPrice: string | undefined, - signal: AbortSignal, ): Promise { try { const current = await apolloClient.query({ @@ -147,7 +146,7 @@ export async function getBulkPoolDataFromPoolList( }) let poolData const [t1] = getTimestampsForChanges() - const blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [t1], chainId, signal) + const blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [t1], chainId) if (!blocks.length) { return current.data.pools } else { @@ -206,11 +205,10 @@ export async function getBulkPoolDataWithPagination( blockClient: ApolloClient, ethPrice: string, chainId: ChainId, - signal: AbortSignal, ): Promise { 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 @@ -324,7 +322,6 @@ export function useAllPoolsData(): { const poolCountSubgraph = usePoolCountInSubgraph() useEffect(() => { if (!isEVM) return - const controller = new AbortController() const getPoolsData = async () => { try { @@ -342,25 +339,20 @@ export function useAllPoolsData(): { blockClient, ethPrice, chainId, - controller.signal, ), ) } const pools = (await Promise.all(promises.map(callback => callback()))).flat() - if (controller.signal.aborted) return dispatch(updatePools({ pools })) dispatch(setLoading(false)) } } catch (error) { - if (controller.signal.aborted) return dispatch(setError(error as Error)) dispatch(setLoading(false)) } } getPoolsData() - - return () => controller.abort() }, [ chainId, dispatch, @@ -399,7 +391,6 @@ export function useSinglePoolData( useEffect(() => { if (!isEVM) return - const controller = new AbortController() async function checkForPools() { setLoading(true) @@ -413,15 +404,12 @@ export function useSinglePoolData( blockClient, chainId, ethPrice, - controller.signal, ) - if (controller.signal.aborted) return if (pools.length > 0) { setPoolData(pools[0]) } } } catch (error) { - if (controller.signal.aborted) return setError(error as Error) } @@ -429,8 +417,6 @@ export function useSinglePoolData( } checkForPools() - - return () => controller.abort() }, [ethPrice, error, poolAddress, chainId, isEVM, networkInfo, classicClient, blockClient, isEnableBlockService]) return { loading, error, data: poolData } diff --git a/src/state/prommPools/hooks.ts b/src/state/prommPools/hooks.ts index a2ab3a8943..6d03596b2e 100644 --- a/src/state/prommPools/hooks.ts +++ b/src/state/prommPools/hooks.ts @@ -209,20 +209,12 @@ export const usePoolBlocks = () => { const [block, setBlock] = useState(undefined) useEffect(() => { - const controller = new AbortController() const getBlocks = async () => { - const [block] = await getBlocksFromTimestamps( - isEnableBlockService, - blockClient, - [last24h], - chainId, - controller.signal, - ) + const [block] = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [last24h], chainId) setBlock(block?.number) } getBlocks() - return () => controller.abort() }, [chainId, last24h, blockClient, isEnableBlockService]) return { blockLast24h: block } diff --git a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts index a4941e9fc5..790ca9f6bc 100644 --- a/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts +++ b/src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts @@ -27,20 +27,12 @@ const usePoolBlocks = () => { const [blocks, setBlocks] = useState<{ number: number }[]>([]) useEffect(() => { - const controller = new AbortController() const getBlocks = async () => { - const blocks = await getBlocksFromTimestamps( - isEnableBlockService, - blockClient, - [last24h], - chainId, - controller.signal, - ) + const blocks = await getBlocksFromTimestamps(isEnableBlockService, blockClient, [last24h], chainId) setBlocks(blocks) } getBlocks() - return () => controller.abort() }, [chainId, last24h, blockClient, isEnableBlockService]) const [blockLast24h] = blocks ?? [] diff --git a/src/utils/index.ts b/src/utils/index.ts index c2c02c48b7..478da2b351 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -5,9 +5,10 @@ import { PublicKey } from '@solana/web3.js' import dayjs from 'dayjs' import JSBI from 'jsbi' import Numeral from 'numeral' +import blockServiceApi from 'services/blockService' import { GET_BLOCKS } from 'apollo/queries' -import { BLOCK_SERVICE_API, ENV_KEY } from 'constants/env' +import { ENV_KEY } from 'constants/env' import { DEFAULT_GAS_LIMIT_MARGIN, ZERO_ADDRESS } from 'constants/index' import { NETWORKS_INFO, SUPPORTED_NETWORKS, isEVM } from 'constants/networks' import { KNC, KNCL_ADDRESS } from 'constants/tokens' @@ -294,7 +295,7 @@ export async function splitQuery( * @dev timestamps are returns as they were provided; not the block time. * @param {Array} timestamps */ -export async function getBlocksFromTimestampsSubgraph( +async function getBlocksFromTimestampsSubgraph( blockClient: ApolloClient, timestamps: number[], chainId: ChainId, @@ -320,31 +321,24 @@ export async function getBlocksFromTimestampsSubgraph( return blocks } -export async function getBlocksFromTimestampsBlockService( +async function getBlocksFromTimestampsBlockService( timestamps: number[], chainId: ChainId, - signal: AbortSignal, ): Promise<{ timestamp: number; number: number }[]> { if (!isEVM(chainId)) return [] if (timestamps?.length === 0) { return [] } + const allChunkResult = ( await Promise.all( chunk(timestamps, 50).map( async timestampsChunk => - ( - await fetch( - `${BLOCK_SERVICE_API}/${ - NETWORKS_INFO[chainId].aggregatorRoute - }/api/v1/block?timestamps=${timestampsChunk.join(',')}`, - { signal }, - ) - ).json() as Promise<{ data: { timestamp: number; number: number }[] }>, + await store.dispatch(blockServiceApi.endpoints.getBlocks.initiate({ chainId, timestamps: timestampsChunk })), ), ) ) - .map(chunk => chunk.data) + .map(chunk => chunk.data?.data || []) .flat() .sort((a, b) => a.number - b.number) @@ -356,9 +350,8 @@ export async function getBlocksFromTimestamps( blockClient: ApolloClient, timestamps: number[], chainId: ChainId, - signal: AbortSignal, ): Promise<{ timestamp: number; number: number }[]> { - if (isEnableBlockService) return getBlocksFromTimestampsBlockService(timestamps, chainId, signal) + if (isEnableBlockService) return getBlocksFromTimestampsBlockService(timestamps, chainId) return getBlocksFromTimestampsSubgraph(blockClient, timestamps, chainId) }