Skip to content

Commit

Permalink
feat: Connect pool API (#10773)
Browse files Browse the repository at this point in the history
<!--
Before opening a pull request, please read the [contributing
guidelines](https://github.com/pancakeswap/pancake-frontend/blob/develop/CONTRIBUTING.md)
first
-->

<!-- start pr-codex -->

---

## PR-Codex overview
This PR primarily focuses on refactoring the pool configuration
retrieval methods to utilize asynchronous fetching from a new API
endpoint, enhancing data handling for pools, and removing deprecated
pool constant files.

### Detailed summary
- Deleted multiple pool constant files.
- Introduced `POOLS_API` for fetching pool data.
- Updated `getPoolsConfig` and `getLivePoolsConfig` to be asynchronous
and fetch data from the API.
- Refactored functions to use `await` for asynchronous calls.
- Removed the `setInitialPoolConfig` action, replaced with
`fetchPoolsConfigAsync`.
- Modified tests and hooks to accommodate the new asynchronous data
fetching.

> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your
question}`

<!-- end pr-codex -->
  • Loading branch information
ChefMomota authored Oct 10, 2024
1 parent 7695a23 commit aa24b3c
Show file tree
Hide file tree
Showing 28 changed files with 104 additions and 4,111 deletions.
53 changes: 1 addition & 52 deletions apps/web/src/__tests__/state/pools/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { getPoolsConfig, isLegacyPool, SUPPORTED_CHAIN_IDS, LegacySerializedPoolConfig } from '@pancakeswap/pools'
import { SerializedWrappedToken } from '@pancakeswap/token-lists'
import { Pool } from '@pancakeswap/widgets-internal'
import BigNumber from 'bignumber.js'
import { transformPool, transformUserData } from 'state/pools/helpers'
import { SerializedPool } from 'state/types'
import { transformUserData } from 'state/pools/helpers'

describe('transformUserData', () => {
it.each([
Expand Down Expand Up @@ -48,50 +44,3 @@ describe('transformUserData', () => {
expect(userData).toHaveProperty('pendingReward')
})
})

describe('transformPool', () => {
const poolsConfigs = SUPPORTED_CHAIN_IDS.map((chainId) => getPoolsConfig(chainId))
for (const poolsConfig of poolsConfigs) {
// Transform pool object with the sous id for a label. For display purposes only.
const poolTable: [
number,
Pool.SerializedPoolConfig<SerializedWrappedToken> | LegacySerializedPoolConfig<SerializedWrappedToken>,
][] = poolsConfig?.map((poolsConfigItem) => [poolsConfigItem.sousId, poolsConfigItem]) || []
it.each(poolTable)('transforms pool %d correctly', (sousId, config) => {
const pool = {
...config,
totalStaked: '10',
stakingLimit: '10',
startTimestamp: 100,
endTimestamp: 100,
userData: {
allowance: '0',
stakingTokenBalance: '0',
stakedBalance: '0',
pendingReward: '0',
},
numberSecondsForUserLimit: 0,
} as SerializedPool
const transformedPool = transformPool(pool)

expect(transformedPool).toHaveProperty('sousId', sousId)
expect(transformedPool).toHaveProperty('contractAddress')
expect(transformedPool).toHaveProperty('stakingToken.symbol')
expect(transformedPool).toHaveProperty('stakingToken.projectLink')
expect(transformedPool).toHaveProperty('earningToken.symbol')
expect(transformedPool).toHaveProperty('earningToken.projectLink')
expect(transformedPool).toHaveProperty('poolCategory')
if (isLegacyPool(pool)) {
expect(transformedPool).toHaveProperty('tokenPerBlock')
} else {
expect(transformedPool).toHaveProperty('tokenPerSecond')
}

expect(transformedPool).toHaveProperty('totalStaked')
expect(transformedPool).toHaveProperty('stakingLimit')
expect(transformedPool).toHaveProperty('startTimestamp', 100)
expect(transformedPool).toHaveProperty('endTimestamp', 100)
expect(transformedPool).toHaveProperty('userData')
})
}
})
98 changes: 0 additions & 98 deletions apps/web/src/config/__tests__/pools.test.ts

This file was deleted.

23 changes: 16 additions & 7 deletions apps/web/src/hooks/useContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { usePublicClient, useWalletClient } from 'wagmi'
import { useActiveChainId } from 'hooks/useActiveChainId'

import addresses from 'config/constants/contracts'
import { useMemo } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { getMulticallAddress, getPredictionsV1Address, getZapAddress } from 'utils/addressHelpers'
import {
getAffiliateProgramContract,
Expand Down Expand Up @@ -144,16 +144,25 @@ export const useSousChef = (id) => {
const { data: signer } = useWalletClient()
const { chainId } = useActiveChainId()
const publicClient = usePublicClient({ chainId })
return useMemo(
() =>
getPoolContractBySousId({
const [contract, setContract] = useState(null)

useEffect(() => {
if (!signer || !chainId || !publicClient || !id) return

const fetchContract = async () => {
const poolContract = await getPoolContractBySousId({
sousId: id,
signer,
chainId,
publicClient,
}),
[id, signer, chainId, publicClient],
)
})
setContract(poolContract)
}

fetchContract()
}, [id, signer, chainId, publicClient])

return contract
}

export const usePointCenterIfoContract = () => {
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/state/pools/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ import {
fetchCakeVaultPublicData,
fetchCakeVaultUserData,
fetchIfoPublicDataAsync,
fetchPoolsConfigAsync,
fetchPoolsPublicDataAsync,
fetchPoolsStakingLimitsAsync,
fetchPoolsUserDataAsync,
fetchUserIfoCreditDataAsync,
setInitialPoolConfig,
} from '.'
import { fetchFarmsPublicDataAsync } from '../farms'
import { VaultKey } from '../types'
Expand All @@ -44,7 +44,7 @@ import {
// Only fetch farms for live pools
const getActiveFarms = async (chainId: number) => {
const farmsConfig = (await getLegacyFarmConfig(chainId)) || []
const livePools = getLivePoolsConfig(chainId) || []
const livePools = (await getLivePoolsConfig(chainId)) || []
const lPoolAddresses = livePools
.filter(({ sousId }) => sousId !== 0)
.map(({ earningToken, stakingToken }) => {
Expand Down Expand Up @@ -106,7 +106,7 @@ export const usePoolsConfigInitialize = () => {
const { chainId } = useActiveChainId()
useEffect(() => {
if (chainId) {
dispatch(setInitialPoolConfig({ chainId }))
dispatch(fetchPoolsConfigAsync({ chainId }))
}
}, [dispatch, chainId])
}
Expand Down
35 changes: 20 additions & 15 deletions apps/web/src/state/pools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import {
getPoolsConfig,
isLegacyPool,
} from '@pancakeswap/pools'
import { getCurrencyUsdPrice } from '@pancakeswap/price-api-sdk'
import { bscTokens } from '@pancakeswap/tokens'
import { BIG_ZERO } from '@pancakeswap/utils/bigNumber'
import { getBalanceNumber } from '@pancakeswap/utils/formatBalance'
import { getCurrencyUsdPrice } from '@pancakeswap/price-api-sdk'
import { PayloadAction, createAsyncThunk, createSlice, isAnyOf } from '@reduxjs/toolkit'
import BigNumber from 'bignumber.js'
import keyBy from 'lodash/keyBy'
Expand Down Expand Up @@ -154,7 +154,7 @@ export const fetchPoolsPublicDataAsync = (chainId: number) => async (dispatch, g
])
const timeLimitsSousIdMap = keyBy(timeLimits, 'sousId')
const priceHelperLpsConfig = getPoolsPriceHelperLpFiles(chainId)
const poolsConfig = getPoolsConfig(chainId) || []
const poolsConfig = (await getPoolsConfig(chainId)) || []
const activePriceHelperLpsConfig = priceHelperLpsConfig.filter((priceHelperLpConfig) => {
return (
poolsConfig
Expand Down Expand Up @@ -266,7 +266,7 @@ export const fetchPoolsStakingLimitsAsync = (chainId: ChainId) => async (dispatc
try {
const stakingLimits = await fetchPoolsStakingLimits({ poolsWithStakingLimit, chainId, provider: getViemClients })

const poolsConfig = getPoolsConfig(chainId)
const poolsConfig = await getPoolsConfig(chainId)
const stakingLimitData = poolsConfig?.map((pool) => {
if (poolsWithStakingLimit.includes(pool.sousId)) {
return { sousId: pool.sousId }
Expand Down Expand Up @@ -304,7 +304,7 @@ export const fetchPoolsUserDataAsync = createAsyncThunk<
fetchUserPendingRewards({ account, chainId, provider: getViemClients }),
])

const poolsConfig = getPoolsConfig(chainId)
const poolsConfig = await getPoolsConfig(chainId)
const userData = poolsConfig?.map((pool) => ({
sousId: pool.sousId,
allowance: allowances[pool.sousId],
Expand Down Expand Up @@ -424,19 +424,18 @@ export const fetchCakeFlexibleSideVaultUserData = createAsyncThunk<
return userData
})

export const fetchPoolsConfigAsync = createAsyncThunk(
'pool/fetchPoolsConfigAsync',
async ({ chainId }: { chainId: number }) => {
const poolsConfig = await getPoolsConfig(chainId)
return poolsConfig || []
},
)

export const PoolsSlice = createSlice({
name: 'Pools',
initialState,
reducers: {
setInitialPoolConfig: (state, action) => {
const { chainId } = action.payload
const poolsConfig = getPoolsConfig(chainId) || []
state.data = [...poolsConfig]
state.userDataLoaded = false
state.cakeVault = initialPoolVaultState as any
state.ifo = initialIfoState as any
state.cakeFlexibleSideVault = initialPoolVaultState as any
},
setPoolPublicData: (state, action) => {
const { sousId } = action.payload
const poolIndex = state.data.findIndex((pool) => pool.sousId === sousId)
Expand Down Expand Up @@ -469,6 +468,13 @@ export const PoolsSlice = createSlice({
},
},
extraReducers: (builder) => {
builder.addCase(fetchPoolsConfigAsync.fulfilled, (state, action) => {
state.data = [...action.payload]
state.userDataLoaded = false
state.cakeVault = initialPoolVaultState as any
state.ifo = initialIfoState as any
state.cakeFlexibleSideVault = initialPoolVaultState as any
})
builder.addCase(resetUserState, (state) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
state.data = state.data.map(({ userData, ...pool }) => {
Expand Down Expand Up @@ -558,7 +564,6 @@ export const PoolsSlice = createSlice({
})

// Actions
export const { setPoolsPublicData, setPoolPublicData, setPoolUserData, setIfoUserCreditData, setInitialPoolConfig } =
PoolsSlice.actions
export const { setPoolsPublicData, setPoolPublicData, setPoolUserData, setIfoUserCreditData } = PoolsSlice.actions

export default PoolsSlice.reducer
2 changes: 1 addition & 1 deletion apps/web/src/utils/calls/pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const ABI = [
* Returns the total number of pools that were active at a given block
*/
export const getActivePools = async (chainId: ChainId, block?: number): Promise<SerializedPool[]> => {
const poolsConfig = getPoolsConfig(chainId)
const poolsConfig = await getPoolsConfig(chainId)
const eligiblePools = poolsConfig
? poolsConfig
.filter((pool) => pool.sousId !== 0)
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/views/Home/hooks/useGetTopPoolsByApr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { useAppDispatch } from 'state'
import {
fetchCakeVaultFees,
fetchCakeVaultPublicData,
fetchPoolsConfigAsync,
fetchPoolsPublicDataAsync,
setInitialPoolConfig,
} from 'state/pools'
import { usePoolsWithVault } from 'state/pools/hooks'
import { VaultKey } from 'state/types'
Expand All @@ -23,7 +23,8 @@ const useGetTopPoolsByApr = (isIntersecting: boolean, chainId?: number) => {
queryKey: [chainId, 'fetchTopPoolsByApr'],

queryFn: async () => {
await dispatch(setInitialPoolConfig({ chainId }))
if (!chainId) return null
await dispatch(fetchPoolsConfigAsync({ chainId }))
return Promise.all([
dispatch(fetchCakeVaultFees(chainId!)),
dispatch(fetchCakeVaultPublicData(chainId!)),
Expand Down
Loading

0 comments on commit aa24b3c

Please sign in to comment.