mango-v4-ui/apis/coingecko.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-10-07 16:39:06 -07:00
export const fetchChartData = async (
2022-11-18 11:11:06 -08:00
baseTokenId: string | undefined,
quoteTokenId: string | undefined,
2022-11-29 21:30:18 -08:00
daysToShow: string
2022-10-07 16:39:06 -07:00
) => {
2022-11-18 11:11:06 -08:00
console.log('fetching chart:', baseTokenId, quoteTokenId)
if (!baseTokenId || !quoteTokenId) return
2022-11-04 05:39:10 -07:00
try {
const [inputResponse, outputResponse] = await Promise.all([
fetch(
`https://api.coingecko.com/api/v3/coins/${baseTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
),
fetch(
`https://api.coingecko.com/api/v3/coins/${quoteTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
),
])
2022-10-07 16:39:06 -07:00
2022-11-04 05:39:10 -07:00
const [inputData, outputData] = await Promise.all([
inputResponse.json(),
outputResponse.json(),
])
2022-10-07 16:39:06 -07:00
2022-11-04 05:39:10 -07:00
let data: any[] = []
if (Array.isArray(inputData)) {
data = data.concat(inputData)
}
if (Array.isArray(outputData)) {
data = data.concat(outputData)
}
2022-10-07 16:39:06 -07:00
2022-11-04 05:39:10 -07:00
const formattedData = data.reduce((a, c) => {
const found = a.find((price: any) => price.time === c[0])
if (found) {
if (['usd-coin', 'tether'].includes(quoteTokenId)) {
found.price = found.inputPrice / c[4]
} else {
found.price = c[4] / found.inputPrice
}
2022-10-07 16:39:06 -07:00
} else {
2022-11-04 05:39:10 -07:00
a.push({ time: c[0], inputPrice: c[4] })
2022-10-07 16:39:06 -07:00
}
2022-11-04 05:39:10 -07:00
return a
}, [])
formattedData[formattedData.length - 1].time = Date.now()
return formattedData.filter((d: any) => d.price)
} catch {
return []
}
2022-10-07 16:39:06 -07:00
}