Skip to content

Commit

Permalink
refactor: use query factory
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielSchiavini committed Oct 23, 2024
1 parent 9520b93 commit c7e3d84
Show file tree
Hide file tree
Showing 24 changed files with 68 additions and 146 deletions.
14 changes: 2 additions & 12 deletions apps/lend/src/entities/chain/api/markets-api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import { QueryFunction } from '@tanstack/react-query'
import { logQuery } from '@/shared/lib/logging'
import { assertChainValidity } from '../lib/validation'
import { ChainQuery } from '@/shared/model/query'
import useStore from '@/store/useStore'
import { ChainQueryKeyType } from '../model'

export const queryOneWayMarketNames: QueryFunction<
string[],
ChainQueryKeyType<'markets'>
> = async ({ queryKey }) => {
logQuery(queryKey)
const [, chainId, , ] = queryKey
assertChainValidity({ chainId })

export const queryOneWayMarketNames = async ({}: ChainQuery): Promise<string[]> => {
const {api} = useStore.getState()
return api!.oneWayfactory.getMarketList()
}
1 change: 0 additions & 1 deletion apps/lend/src/entities/chain/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export * from './lib'
export * from './types'
9 changes: 5 additions & 4 deletions apps/lend/src/entities/chain/lib/data-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { useOneWayMarketNames } from './query-hooks'
import networks from '@/networks'
import { OneWayMarketTemplate } from '@curvefi/lending-api/lib/markets'
import { useMemo } from 'react'
import { chainValidationSuite } from '@/entities/chain/model'
import { checkValidity } from '@/shared/lib/validation'
import { useApi } from './chain-info'
import { checkChainValidity } from '@/entities/chain'
import { useOneWayMarketNames } from './query-hooks'
import networks from '@/networks'

export const useOneWayMarketMapping = (chainId: ChainId) => {
const chainValid = checkChainValidity({ chainId }) // extra check to make sure the API is loaded before we use stale market names
const chainValid = checkValidity(chainValidationSuite, { chainId }); // extra check to make sure the API is loaded before we use stale market names

const { data: marketNames, ...rest } = useOneWayMarketNames({ chainId })
const { data: api } = useApi();
Expand Down
1 change: 0 additions & 1 deletion apps/lend/src/entities/chain/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './validation'
export * from './data-hooks'
export * from './query-hooks'
export * from './chain-info'
Expand Down
5 changes: 2 additions & 3 deletions apps/lend/src/entities/chain/lib/query-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { createQueryHook } from '@/shared/lib/queries'
import { getOneWayMarketNames } from '../model/query-options'
import { oneWayMarketNames } from '../model'

export const useOneWayMarketNames = createQueryHook(getOneWayMarketNames);
export const { useQuery: useOneWayMarketNames } = oneWayMarketNames;
9 changes: 0 additions & 9 deletions apps/lend/src/entities/chain/lib/validation.ts

This file was deleted.

6 changes: 3 additions & 3 deletions apps/lend/src/entities/chain/model/query-keys.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { ChainQueryParams } from '../types'
import type { ExtractQueryKeyType } from '@/shared/types/api'
import { ChainParams } from '@/shared/model/query'

export const chainKeys = {
root: ({ chainId }: ChainQueryParams) => ['chain', chainId] as const,
markets: ({ chainId }: ChainQueryParams) => ['chain', chainId, 'markets'] as const,
root: ({ chainId }: ChainParams) => ['chain', chainId] as const,

} as const

export type ChainQueryKeyType<K extends keyof typeof chainKeys> = ExtractQueryKeyType<typeof chainKeys, K>
Expand Down
22 changes: 9 additions & 13 deletions apps/lend/src/entities/chain/model/query-options.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { queryOptions } from '@tanstack/react-query'
import { REFRESH_INTERVAL } from '@/constants'
import { checkChainValidity } from '../lib/validation'
import { queryOneWayMarketNames } from '../api/markets-api'
import { chainKeys } from './query-keys'
import { ChainQueryParams } from '../types'
import { queryOneWayMarketNames } from '@/entities/chain/api/markets-api'
import { chainValidationSuite } from '@/entities/chain/model/validation'
import { ChainParams, queryFactory } from '@/shared/model/query'

export const getOneWayMarketNames = (params: ChainQueryParams, condition = true) =>
queryOptions({
queryKey: chainKeys.markets(params),
queryFn: queryOneWayMarketNames,
staleTime: REFRESH_INTERVAL['5m'],
enabled: condition && checkChainValidity(params),
})
export const oneWayMarketNames = queryFactory({
queryKey: ({ chainId }: ChainParams) => ['chain', { chainId }, 'markets'] as const,
queryFn: queryOneWayMarketNames,
staleTime: '5m',
validationSuite: chainValidationSuite
})
4 changes: 2 additions & 2 deletions apps/lend/src/entities/chain/model/validation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { ChainQueryParams } from '../types'
import { createValidationSuite } from '@/shared/lib/validation'
import { enforce, group, test } from 'vest'
import useStore from '@/store/useStore'
import { ChainParams } from '@/shared/model/query'

export const chainValidationGroup = ({ chainId }: ChainQueryParams) =>
export const chainValidationGroup = ({ chainId }: ChainParams) =>
group('chainValidation', () => {
test('chainId', () => {
enforce(chainId).message('Chain ID is required').isNotEmpty().message('Invalid chain ID').isValidChainId()
Expand Down
5 changes: 0 additions & 5 deletions apps/lend/src/entities/chain/types.ts

This file was deleted.

7 changes: 7 additions & 0 deletions apps/lend/src/entities/token/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { TokenQuery } from '@/entities/token/index'
import useStore from '@/store/useStore'

export const queryTokenUsdRate = async ({ tokenAddress}: TokenQuery): Promise<number> => {
const { api } = useStore.getState()
return await api!.getUsdRate(tokenAddress)
}
13 changes: 0 additions & 13 deletions apps/lend/src/entities/token/api/token-rates.ts

This file was deleted.

15 changes: 15 additions & 0 deletions apps/lend/src/entities/token/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { tokenUsdRate } from '@/entities/token/model'
import { useQueryMapping } from '@/shared/lib/queries'
import { ChainParams } from '@/shared/model/query'

export const {
getQueryData: getTokenUsdRateQueryData,
useQuery: useTokenUsdRate,
getQueryOptions: getTokenUsdRateQueryOptions
} = tokenUsdRate

export const useTokenUsdRates = ({ chainId, tokenAddresses = [] }: ChainParams & { tokenAddresses?: string[] }) =>
useQueryMapping(
tokenAddresses.map((tokenAddress) => getTokenUsdRateQueryOptions({ chainId, tokenAddress })),
tokenAddresses
)
3 changes: 0 additions & 3 deletions apps/lend/src/entities/token/lib/index.ts

This file was deleted.

5 changes: 0 additions & 5 deletions apps/lend/src/entities/token/lib/query-data.ts

This file was deleted.

10 changes: 0 additions & 10 deletions apps/lend/src/entities/token/lib/query-hooks.ts

This file was deleted.

9 changes: 0 additions & 9 deletions apps/lend/src/entities/token/lib/validation.ts

This file was deleted.

4 changes: 1 addition & 3 deletions apps/lend/src/entities/token/model/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
export * from './query-keys'
export * from './query-options'
export * from './validation'
export { tokenUsdRate } from './token-query'
6 changes: 0 additions & 6 deletions apps/lend/src/entities/token/model/query-keys.ts

This file was deleted.

14 changes: 0 additions & 14 deletions apps/lend/src/entities/token/model/query-options.ts

This file was deleted.

13 changes: 13 additions & 0 deletions apps/lend/src/entities/token/model/token-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { TokenParams } from '@/entities/token'
import { queryTokenUsdRate } from '@/entities/token/api'
import { tokenValidationSuite } from '@/entities/token/model'
import { queryFactory, rootKeys } from '@/shared/model/query'

const root = ({ chainId, tokenAddress }: TokenParams) => [...rootKeys.chain({chainId}), 'token', { tokenAddress }] as const

export const tokenUsdRate = queryFactory({
queryKey: (params: TokenParams) => [...root(params), 'usdRate'] as const,
queryFn: queryTokenUsdRate,
staleTime: '5m',
validationSuite: tokenValidationSuite,
})
6 changes: 3 additions & 3 deletions apps/lend/src/entities/token/model/validation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { TokenQueryParams } from '@/entities/token/types'
import { createValidationSuite } from '@/shared/lib/validation'
import { enforce, group, test } from 'vest'
import { chainValidationGroup } from '@/entities/chain/model'
import type { TokenParams } from '@/entities/token/types'
import { createValidationSuite } from '@/shared/lib/validation'

export const tokenValidationGroup = ({ chainId, tokenAddress }: TokenQueryParams) =>
export const tokenValidationGroup = ({ chainId, tokenAddress }: TokenParams) =>
group('tokenValidation', () => {
chainValidationGroup({ chainId })
test('tokenAddress', () => {
Expand Down
15 changes: 4 additions & 11 deletions apps/lend/src/entities/token/types.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { ChainQueryParams } from '@/entities/chain/types'
import type { ExtractQueryKeyType } from '@/shared/types/api'
import { tokenKeys } from '@/entities/token/model'
import { FieldsOf } from '@/shared/lib/validation'
import { ChainQuery } from '@/shared/model/query'

export type TokenQueryParams = ChainQueryParams & {
tokenAddress?: string
}

export type CombinedTokenParams = TokenQueryParams

export type TokenKey = keyof typeof tokenKeys
export type TokenQueryKeyType<K extends TokenKey = TokenKey> = ExtractQueryKeyType<typeof tokenKeys, K>
export type TokenQuery = ChainQuery & { tokenAddress: string };
export type TokenParams = FieldsOf<TokenQuery>;
18 changes: 2 additions & 16 deletions apps/lend/src/store/createMarketListSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type {
FilterTypeKey,
FormStatus,
MarketListItemResult,
MarketListMapper,
SearchParams,
TableSettings
} from '@/components/PageMarketList/types'
Expand All @@ -19,7 +18,7 @@ import { getTotalApr } from '@/utils/utilsRewards'
import { helpers } from '@/lib/apiLending'
import { sleep } from '@/utils/helpers'
import networks from '@/networks'
import { getTokenQueryData } from '@/entities/token'
import { getTokenUsdRateQueryData } from '@/entities/token'
import { IDict } from '@curvefi/lending-api/lib/interfaces'
import { OneWayMarketTemplate } from '@curvefi/lending-api/lib/markets'

Expand Down Expand Up @@ -90,7 +89,7 @@ const createMarketListSlice = (set: SetState<State>, get: GetState<State>): Mark
const { smallMarketAmount, marketListShowOnlyInSmallMarkets } = networks[chainId]
return markets.filter((market) => {
const { cap } = capAndAvailableMapper[market.id] ?? {}
const usdRate = getTokenQueryData<number>('usdRate', { chainId, tokenAddress: market.borrowed_token.address })
const usdRate = getTokenUsdRateQueryData({ chainId, tokenAddress: market.borrowed_token.address })
if (typeof usdRate === 'undefined') return true
if (marketListShowOnlyInSmallMarkets[market.id]) return false
return +cap * usdRate > smallMarketAmount
Expand Down Expand Up @@ -420,19 +419,6 @@ export function _getActiveKey(chainId: ChainId, searchParams: SearchParams) {
return `${chainId}-${filterTypeKey}-${filterKey}-${parsedSearchText}${sortByStr}`
}

function _getOwmDatasFromMarketList(marketListMapper: MarketListMapper, marketMapping: IDict<OneWayMarketTemplate>) {
let result: { [owmId: string]: OneWayMarketTemplate } = {}

// get all owmIds
Object.keys(marketListMapper).forEach((tokenAddress) => {
const { markets } = marketListMapper[tokenAddress]
Object.keys(markets).forEach((owmId) => {
result[owmId] = marketMapping[owmId]
})
})
return Object.values(result) ?? []
}

function sortByRewards(market: OneWayMarketTemplate, rewardsMapper: MarketsRewardsMapper, ratesMapper: MarketsRatesMapper) {
const rewards = rewardsMapper[market.id]?.rewards
const rates = ratesMapper[market.id]?.rates
Expand Down

0 comments on commit c7e3d84

Please sign in to comment.