Skip to content

Commit

Permalink
feat: Gauges with API (#10730)
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 focuses on refactoring the `gauges` and `smart-router` packages,
particularly enhancing API calls to fetch gauge data and improving the
handling of asynchronous operations. It also introduces new functions
for retrieving gauges by chain.

### Detailed summary
- Deleted `prod.ts` and `index.ts` files from
`packages/gauges/src/constants/config`.
- Added `GAUGES_API` constant in `endpoint.ts` for API endpoint.
- Exported `getGaugesByChain` and `safeGetGaugesByChain` functions in
`getGaugesByChain.ts`.
- Updated `getAllGauges.ts` to use `getGauges` instead of `CONFIG_PROD`.
- Modified various functions to await asynchronous operations for
fetching data.
- Refactored `getPairCombinations` to support async behavior.
- Updated tests to reflect changes in gauge configuration fetching.

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

<!-- end pr-codex -->

---------

Co-authored-by: memoyil <[email protected]>
Co-authored-by: chefjackson <[email protected]>
  • Loading branch information
3 people authored Oct 8, 2024
1 parent 6929583 commit 3e83a9c
Show file tree
Hide file tree
Showing 22 changed files with 227 additions and 5,731 deletions.
6 changes: 6 additions & 0 deletions .changeset/shy-shrimps-know.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@pancakeswap/gauges': major
'@pancakeswap/smart-router': patch
---

Read gauge list from remote endpoint
2 changes: 1 addition & 1 deletion apis/routing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ router.get('/v0/quote', async (req, event: FetchEvent) => {
let pools = await PoolCache.get(cacheKey)

if (!pools) {
const pairs = SmartRouter.getPairCombinations(currencyA, currencyB)
const pairs = await SmartRouter.getPairCombinations(currencyA, currencyB)

const [v3Pools, v2Pools, stablePools] = await Promise.all([
SmartRouter.getV3PoolSubgraph({ provider: v3SubgraphProvider, pairs }).then((res) =>
Expand Down
14 changes: 5 additions & 9 deletions apps/web/src/hooks/usePoolsOnChain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { OnChainProvider, Pool, SmartRouter } from '@pancakeswap/smart-router'
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'

import { createViemPublicClientGetter } from 'utils/viem'
import { POOLS_FAST_REVALIDATE } from 'config/pools'
import { createViemPublicClientGetter } from 'utils/viem'

interface Options {
blockNumber?: number
Expand Down Expand Up @@ -57,22 +57,18 @@ function candidatePoolsOnChainHookFactory<TPool extends Pool>(
return [...symbols, currencyA.chainId].join('_')
}, [currencyA, currencyB])

const pairs = useMemo(() => {
return currencyA && currencyB && SmartRouter.getPairCombinations(currencyA, currencyB)
}, [currencyA, currencyB])

const queryEnabled = !!(enabled && blockNumber && key && pairs)
const poolState = useQuery({
queryKey: [poolType, 'pools', key],

queryFn: async ({ signal }) => {
if (!blockNumber || !pairs) {
if (!blockNumber) {
throw new Error('Failed to get pools on chain. Missing valid params')
}
const label = `[POOLS_ONCHAIN](${poolType}) ${key} at block ${blockNumber}`
SmartRouter.logger.metric(label)
const getViemClients = createViemPublicClientGetter({ transportSignal: signal })
const pools = await getPoolsOnChain(pairs, getViemClients, blockNumber)
const resolvedPairs = await SmartRouter.getPairCombinations(currencyA, currencyB)
const pools = await getPoolsOnChain(resolvedPairs ?? [], getViemClients, blockNumber)
SmartRouter.logger.metric(label, pools)

return {
Expand All @@ -82,7 +78,7 @@ function candidatePoolsOnChainHookFactory<TPool extends Pool>(
}
},

enabled: queryEnabled,
enabled: Boolean(enabled && blockNumber && key && currencyA && currencyB),
refetchInterval,
refetchOnWindowFocus: false,
})
Expand Down
1 change: 1 addition & 0 deletions packages/gauges/src/constants/config/endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const GAUGES_API = 'https://configs.pancakeswap.com/api/data/cached/gauges'
41 changes: 41 additions & 0 deletions packages/gauges/src/constants/config/getGauges.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { GaugeConfig } from '../../types'
import { GAUGES_API } from './endpoint'

function createGaugeConfigFetcher() {
let gauges: GaugeConfig[] | undefined
let fetchRequest: Promise<GaugeConfig[]> | undefined

return async function getGaugeConfig() {
if (fetchRequest) return fetchRequest
const fetchGaugeConfig = async () => {
if (gauges) {
return gauges
}
try {
const response = await fetch(GAUGES_API, {
signal: AbortSignal.timeout(3000),
})
if (response.ok) {
gauges = await response.json()
if (!gauges) {
throw new Error(`Unexpected empty gauges fetched from remote ${gauges}`)
}
return gauges
}
throw new Error(`Fetch failed with status: ${response.status}`)
} catch (e) {
if (e instanceof Error) {
throw new Error(`Fetch failed: ${e.message}`)
} else {
throw new Error(`Fetch failed: ${e}`)
}
} finally {
fetchRequest = undefined
}
}
fetchRequest = fetchGaugeConfig()
return fetchRequest
}
}

export const getGauges = createGaugeConfigFetcher()
8 changes: 0 additions & 8 deletions packages/gauges/src/constants/config/index.ts

This file was deleted.

Loading

0 comments on commit 3e83a9c

Please sign in to comment.