Skip to content

Commit a58121d

Browse files
authored
chore: use data api v2 (#1817)
* use data api v2 * lint * fix build * remove obsolete type * add api route * remove logs * remove obsolete import * lint
1 parent 290df06 commit a58121d

File tree

11 files changed

+87
-35
lines changed

11 files changed

+87
-35
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { type NextRequest, NextResponse } from 'next/server'
2+
3+
export async function GET(
4+
req: NextRequest,
5+
{ params }: { params: Promise<{ address: string }> },
6+
) {
7+
try {
8+
const { searchParams } = new URL(req.url)
9+
const { address } = await params
10+
const url = `https://api.indexcoop.com/v2/data/${address}?${searchParams.toString()}`
11+
const res = await fetch(url, {
12+
method: 'GET',
13+
headers: {
14+
'Content-Type': 'application/json',
15+
'x-api-key': process.env.INDEX_COOP_API_V2_KEY,
16+
} as HeadersInit,
17+
})
18+
const json = await res.json()
19+
return NextResponse.json(json, { status: 200 })
20+
} catch (error) {
21+
return NextResponse.json(error, { status: 500 })
22+
}
23+
}

src/app/api/stats/route.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
import { CoinGeckoService, CoingeckoProvider } from '@indexcoop/analytics-sdk'
2-
import { NextRequest, NextResponse } from 'next/server'
2+
import { type NextRequest, NextResponse } from 'next/server'
33

44
import { fetchTokenMetrics } from '@/lib/utils/api/index-data-provider'
55
import { fetchCarryCosts } from '@/lib/utils/fetch'
66

77
export async function GET(req: NextRequest) {
88
const { searchParams } = new URL(req.url)
99

10+
const chainId = Number(searchParams.get('chainId'))
1011
const tokenAddress = searchParams.get('address')
1112
const symbol = searchParams.get('symbol')
1213
const base = searchParams.get('base')
1314
const baseCurrency = searchParams.get('baseCurrency')
14-
if (!tokenAddress || !symbol || !base || !baseCurrency) {
15+
if (!chainId || !tokenAddress || !symbol || !base || !baseCurrency) {
1516
return NextResponse.json('Bad Request', { status: 400 })
1617
}
1718
try {
@@ -28,6 +29,7 @@ export async function GET(req: NextRequest) {
2829
? (carryCosts[formattedSymbol] ?? null)
2930
: null
3031
const metrics = await fetchTokenMetrics({
32+
chainId,
3133
tokenAddress: tokenAddress,
3234
metrics: ['fees', 'nav', 'navchange'],
3335
})

src/app/earn/provider.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@ import { isAddress } from 'viem'
1313
import { base } from 'viem/chains'
1414

1515
import { useQueryParams } from '@/app/earn/use-query-params'
16-
import { ETH, Token } from '@/constants/tokens'
17-
import { TokenBalance, useBalances } from '@/lib/hooks/use-balance'
18-
import { QuoteResult } from '@/lib/hooks/use-best-quote/types'
16+
import { ETH, type Token } from '@/constants/tokens'
17+
import { type TokenBalance, useBalances } from '@/lib/hooks/use-balance'
1918
import { useNetwork } from '@/lib/hooks/use-network'
2019
import { useQuoteResult } from '@/lib/hooks/use-quote-result'
2120
import { useWallet } from '@/lib/hooks/use-wallet'
@@ -29,6 +28,8 @@ import { calculateApy } from '@/lib/utils/apy'
2928

3029
import { getCurrencyTokens, getYieldTokens } from './constants'
3130

31+
import type { QuoteResult } from '@/lib/hooks/use-best-quote/types'
32+
3233
const hyEthTokenlist = getTokenByChainAndSymbol(1, 'hyETH')
3334
const hyETH = { ...hyEthTokenlist, image: hyEthTokenlist.logoURI }
3435
const icETH = getTokenByChainAndSymbol(1, 'icETH')
@@ -176,6 +177,7 @@ export function EarnProvider(props: { children: any }) {
176177
queryKey: ['token-latest-stats', indexTokenAddress],
177178
queryFn: async () => {
178179
const data = await fetchTokenMetrics({
180+
chainId: indexToken.chainId!,
179181
tokenAddress: indexTokenAddress!,
180182
metrics: ['nav', 'apy', 'pav'],
181183
})
@@ -199,6 +201,7 @@ export function EarnProvider(props: { children: any }) {
199201
queryKey: ['token-apy-stats', indexTokenAddress],
200202
queryFn: async () => {
201203
const data = await fetchTokenHistoricalData({
204+
chainId,
202205
tokenAddress: indexTokenAddress!,
203206
metrics: ['apy'],
204207
interval: 'daily',

src/app/leverage/components/portfolio-widget/columns.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@ import * as chains from 'viem/chains'
1313
import { formatAmount } from '@/app/leverage/utils/currency'
1414
import { leverageShortTypeMap } from '@/app/leverage/utils/get-leverage-type'
1515
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/tooltip'
16-
import { GetApiV2UserAddressPositionsQueryResponse } from '@/gen'
1716
import { useNetwork } from '@/lib/hooks/use-network'
1817
import { cn } from '@/lib/utils/tailwind'
1918

19+
import type { GetApiV2UserAddressPositionsQueryResponse } from '@/gen'
20+
2021
const columnsHelper =
2122
createColumnHelper<GetApiV2UserAddressPositionsQueryResponse[number]>()
2223

src/app/leverage/components/stats/leverage-selector-container.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { LeverageSelector } from '@/app/leverage/components/stats/leverage-selec
1111
import { useQuickStats } from '@/app/leverage/components/stats/use-quick-stats'
1212
import { getPathForRatio, ratios } from '@/app/leverage/constants'
1313
import { useLeverageToken } from '@/app/leverage/provider'
14-
import { LeverageRatio, LeverageType } from '@/app/leverage/types'
14+
import { type LeverageRatio, LeverageType } from '@/app/leverage/types'
1515
import { formatPercentage } from '@/app/products/utils/formatters'
1616
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/tooltip'
1717
import { useNetwork } from '@/lib/hooks/use-network'
@@ -31,7 +31,7 @@ export function LeverageSelectorContainer() {
3131
const {
3232
data: { token },
3333
isFetchingQuickStats,
34-
} = useQuickStats(market, indexToken)
34+
} = useQuickStats(market, { ...indexToken, chainId: chainId ?? 1 })
3535

3636
const { data } = useQuery({
3737
gcTime: 5 * 60 * 1000,

src/app/leverage/components/stats/use-quick-stats.tsx

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { QueryFunctionContext, useQuery } from '@tanstack/react-query'
1+
import { type QueryFunctionContext, useQuery } from '@tanstack/react-query'
22

33
import { formatAmount, formatDollarAmount } from '@/lib/utils'
44

@@ -38,7 +38,12 @@ interface QuickStatsApiResponse {
3838

3939
type QuickStatsQueryKey = [
4040
string,
41-
{ address: string | undefined; symbol: string; market: string },
41+
{
42+
chainId: number
43+
address: string | undefined
44+
symbol: string
45+
market: string
46+
},
4247
]
4348

4449
export function formatStatsAmount(
@@ -54,18 +59,18 @@ export function formatStatsAmount(
5459

5560
export function useQuickStats(
5661
market: string,
57-
indexToken: { address: string | undefined; symbol: string },
62+
indexToken: { address: string | undefined; chainId: number; symbol: string },
5863
) {
5964
async function fetchStats(
6065
context: QueryFunctionContext<QuickStatsQueryKey>,
6166
): Promise<QuickStats> {
62-
const [, { address, symbol, market }] = context.queryKey
67+
const [, { address, chainId, symbol, market }] = context.queryKey
6368
const m = market.split(' / ')
6469
const baseToken = m[0]
6570
const baseCurrency = m[1].toLowerCase()
6671
try {
6772
const response = await fetch(
68-
`/api/stats?address=${address}&symbol=${symbol}&base=${baseToken}&baseCurrency=${baseCurrency}`,
73+
`/api/stats?address=${address}&chainId=${chainId}&symbol=${symbol}&base=${baseToken}&baseCurrency=${baseCurrency}`,
6974
{
7075
method: 'GET',
7176
},
@@ -106,6 +111,7 @@ export function useQuickStats(
106111
queryKey: [
107112
'fetch-quick-stats',
108113
{
114+
chainId: indexToken.chainId,
109115
symbol: indexToken.symbol,
110116
address: indexToken.address,
111117
market,

src/app/leverage/utils/fetch-leverage-token-prices.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1-
import { getTokenByChainAndAddress, LeverageToken } from '@indexcoop/tokenlists'
1+
import { getTokenByChainAndAddress } from '@indexcoop/tokenlists'
22

33
import { getLeverageType } from '@/app/leverage/utils/get-leverage-type'
44
import { formatPrice } from '@/app/products/utils/formatters'
5-
import { GetApiV2UserAddressPositions200 } from '@/gen'
6-
import { TokenBalance } from '@/lib/hooks/use-balance'
75
import { formatWei } from '@/lib/utils'
86
import { fetchTokenMetrics } from '@/lib/utils/api/index-data-provider'
97

108
import { leverageTokens } from '../constants'
11-
import { EnrichedToken } from '../types'
9+
10+
import type { EnrichedToken } from '@/app/leverage/types'
11+
import type { GetApiV2UserAddressPositions200 } from '@/gen'
12+
import type { TokenBalance } from '@/lib/hooks/use-balance'
13+
import type { LeverageToken } from '@indexcoop/tokenlists'
1214

1315
export const calculateAverageEntryPrice = (
1416
positions: GetApiV2UserAddressPositions200 = [],
@@ -89,6 +91,7 @@ export async function fetchLeverageTokenPrices(
8991
const navResponses = await Promise.all(
9092
tokenBalances.map((token) =>
9193
fetchTokenMetrics({
94+
chainId,
9295
tokenAddress: token.address ?? '',
9396
metrics: ['nav'],
9497
}),
@@ -103,7 +106,8 @@ export async function fetchLeverageTokenPrices(
103106

104107
const enrichedTokens = tokenBalances.map((token, idx) => {
105108
const usd =
106-
parseFloat(formatWei(token.balance, token.decimals)) * tokenPrices[idx]
109+
Number.parseFloat(formatWei(token.balance, token.decimals)) *
110+
tokenPrices[idx]
107111
return {
108112
...token,
109113
size: formatPrice(usd),

src/app/products/components/product-panel.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ import { Suspense } from 'react'
66

77
import { ProductList } from '@/app/products/components/product-list'
88
import { productTokens } from '@/app/products/constants/tokens'
9-
import { ProductRow } from '@/app/products/types/product'
10-
import { SortBy, SortDirection } from '@/app/products/types/sort'
9+
import { type SortBy, SortDirection } from '@/app/products/types/sort'
1110
import { sortProducts } from '@/app/products/utils/sort'
11+
import { useNetwork } from '@/lib/hooks/use-network'
1212
import { fetchTokenMetrics } from '@/lib/utils/api/index-data-provider'
1313
import { calculateApy } from '@/lib/utils/apy'
1414

15+
import type { ProductRow } from '@/app/products/types/product'
16+
1517
export function ProductPanel() {
18+
const { chainId } = useNetwork()
1619
const router = useRouter()
1720
const pathname = usePathname()
1821
const searchParams = useSearchParams()
@@ -30,6 +33,7 @@ export function ProductPanel() {
3033
productTokens.map((token) =>
3134
token.address
3235
? fetchTokenMetrics({
36+
chainId: chainId ?? 1,
3337
tokenAddress: token.address,
3438
metrics: [
3539
'nav',

src/components/charts/use-chart-data.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ import { useState } from 'react'
44
import { isAddress } from 'viem'
55

66
import { ChartPeriod } from '@/components/charts/types'
7+
import { useNetwork } from '@/lib/hooks/use-network'
78
import {
9+
type IndexData,
10+
type IndexDataInterval,
11+
type IndexDataMetric,
12+
type IndexDataPeriod,
813
fetchTokenHistoricalData,
9-
IndexData,
10-
IndexDataInterval,
11-
IndexDataMetric,
12-
IndexDataPeriod,
1314
} from '@/lib/utils/api/index-data-provider'
1415
import { calculateApy } from '@/lib/utils/apy'
1516
import { digitsByAddress } from '@/lib/utils/tokens'
@@ -61,7 +62,7 @@ type PartialIndexData = Partial<IndexData> & {
6162
function formatData(
6263
data: PartialIndexData[],
6364
metric: IndexDataMetric,
64-
digits: number = 2,
65+
digits = 2,
6566
) {
6667
if (metric === 'nav') {
6768
return data.map((datum) => ({
@@ -91,6 +92,7 @@ export function useChartData(
9192
indexTokenAddress?: string,
9293
metric: IndexDataMetric = 'nav',
9394
) {
95+
const { chainId } = useNetwork()
9496
const [selectedPeriod, setSelectedPeriod] = useState(
9597
metric === 'apy' ? ChartPeriod.Week : ChartPeriod.Day,
9698
)
@@ -106,6 +108,7 @@ export function useChartData(
106108
queryFn: async () => {
107109
const { sample, ...fetchSettings } = fetchSettingsByPeriod[selectedPeriod]
108110
const data = await fetchTokenHistoricalData({
111+
chainId: chainId ?? 1,
109112
metrics: [metric],
110113
tokenAddress: indexTokenAddress!,
111114
...fetchSettings,

src/lib/hooks/use-token-price.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { useEffect, useState } from 'react'
33
import { base } from 'viem/chains'
44

55
import { PolygonLegacyTokenList } from '@/app/legacy/config'
6-
import { ETH, Token } from '@/constants/tokens'
6+
import { ETH, type Token } from '@/constants/tokens'
77
import { useNetwork } from '@/lib/hooks/use-network'
88
import { fetchCoingeckoTokenPrice } from '@/lib/utils/api/coingecko'
99
import { fetchTokenMetrics } from '@/lib/utils/api/index-data-provider'
@@ -67,6 +67,7 @@ export const getTokenPrice = async (
6767
}
6868
if (shouldOverrideNav(token.symbol, chainId)) {
6969
const dataResponse = await fetchTokenMetrics({
70+
chainId,
7071
tokenAddress,
7172
metrics: ['nav'],
7273
})

0 commit comments

Comments
 (0)