Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: using rtk query for block service #2158

Merged
merged 1 commit into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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
26 changes: 26 additions & 0 deletions src/services/blockService.ts
Original file line number Diff line number Diff line change
@@ -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
10 changes: 4 additions & 6 deletions src/state/application/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ export const getEthPrice = async (
chainId: ChainId,
apolloClient: ApolloClient<NormalizedCacheObject>,
blockClient: ApolloClient<NormalizedCacheObject>,
signal: AbortSignal,
) => {
const utcCurrentTime = dayjs()
const utcOneDayBack = utcCurrentTime.subtract(1, 'day').startOf('minute').unix()
Expand All @@ -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(),
Expand Down Expand Up @@ -281,7 +280,6 @@ const getPrommEthPrice = async (
chainId: ChainId,
apolloClient: ApolloClient<NormalizedCacheObject>,
blockClient: ApolloClient<NormalizedCacheObject>,
signal: AbortSignal,
) => {
const utcCurrentTime = dayjs()
const utcOneDayBack = utcCurrentTime.subtract(1, 'day').startOf('minute').unix()
Expand All @@ -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(),
Expand Down Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion src/state/farms/classic/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
2 changes: 2 additions & 0 deletions src/state/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 })
Expand Down
5 changes: 1 addition & 4 deletions src/state/mint/proamm/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1414,7 +1414,6 @@ export function useHourlyRateData(
const { elasticClient, blockClient, isEnableBlockService } = useKyberSwapConfig()

useEffect(() => {
const controller = new AbortController()
const currentTime = dayjs.utc()
let startTime: number

Expand Down Expand Up @@ -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
Expand Down
18 changes: 2 additions & 16 deletions src/state/pools/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ export async function getBulkPoolDataFromPoolList(
blockClient: ApolloClient<NormalizedCacheObject>,
chainId: ChainId,
ethPrice: string | undefined,
signal: AbortSignal,
): Promise<any> {
try {
const current = await apolloClient.query({
Expand All @@ -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 {
Expand Down Expand Up @@ -206,11 +205,10 @@ export 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 @@ -324,7 +322,6 @@ export function useAllPoolsData(): {
const poolCountSubgraph = usePoolCountInSubgraph()
useEffect(() => {
if (!isEVM) return
const controller = new AbortController()

const getPoolsData = async () => {
try {
Expand All @@ -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,
Expand Down Expand Up @@ -399,7 +391,6 @@ export function useSinglePoolData(

useEffect(() => {
if (!isEVM) return
const controller = new AbortController()

async function checkForPools() {
setLoading(true)
Expand All @@ -413,24 +404,19 @@ 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)
}

setLoading(false)
}

checkForPools()

return () => controller.abort()
}, [ethPrice, error, poolAddress, chainId, isEVM, networkInfo, classicClient, blockClient, isEnableBlockService])

return { loading, error, data: poolData }
Expand Down
10 changes: 1 addition & 9 deletions src/state/prommPools/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,20 +209,12 @@ export const usePoolBlocks = () => {
const [block, setBlock] = useState<number | undefined>(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 }
Expand Down
10 changes: 1 addition & 9 deletions src/state/prommPools/useGetElasticPools/useGetElasticPoolsV1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? []
Expand Down
23 changes: 8 additions & 15 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -294,7 +295,7 @@ export async function splitQuery<ResultType, T, U>(
* @dev timestamps are returns as they were provided; not the block time.
* @param {Array} timestamps
*/
export async function getBlocksFromTimestampsSubgraph(
async function getBlocksFromTimestampsSubgraph(
blockClient: ApolloClient<NormalizedCacheObject>,
timestamps: number[],
chainId: ChainId,
Expand All @@ -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)

Expand All @@ -356,9 +350,8 @@ export async function getBlocksFromTimestamps(
blockClient: ApolloClient<NormalizedCacheObject>,
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)
}

Expand Down
Loading