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/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) }