change chart api data

This commit is contained in:
saml33 2021-12-31 23:17:48 +11:00
parent 5788bc9e89
commit 6e3c852ad0
2 changed files with 261 additions and 176 deletions

View File

@ -5,8 +5,15 @@ import {
FunctionComponent,
useCallback,
} from 'react'
// import dayjs from 'dayjs'
import dayjs from 'dayjs'
import { useJupiter, RouteInfo } from '@jup-ag/react-hook'
import {
AreaChart,
Area,
XAxis,
YAxis,
Tooltip as ChartTooltip,
} from 'recharts'
import { TOKEN_LIST_URL } from '@jup-ag/core'
import { PublicKey } from '@solana/web3.js'
// import Image from 'next/image'
@ -58,11 +65,7 @@ const JupiterForm: FunctionComponent = () => {
const [showOutputTokenSelect, setShowOutputTokenSelect] = useState(false)
const [swapping, setSwapping] = useState(false)
const [tokens, setTokens] = useState<Token[]>([])
const [
,
// inputTokenStats
setInputTokenStats,
] = useState(null)
const [inputTokenStats, setInputTokenStats] = useState(null)
const [outputTokenStats, setOutputTokenStats] = useState(null)
const [coinGeckoList, setCoinGeckoList] = useState(null)
const [walletTokens, setWalletTokens] = useState([])
@ -116,32 +119,32 @@ const JupiterForm: FunctionComponent = () => {
tokens,
])
// const [inputChartPrices, outputChartPrices] = useMemo(() => {
// return [
// inputTokenStats && inputTokenStats.prices
// ? inputTokenStats.prices.reduce((a, c) => {
// const found = a.find((t) => {
// return new Date(c[0]).getHours() === new Date(t.time).getHours()
// })
// if (!found) {
// a.push({ time: c[0], price: c[1] })
// }
// return a
// }, [])
// : null,
// outputTokenStats && outputTokenStats.prices
// ? outputTokenStats.prices.reduce((a, c) => {
// const found = a.find((t) => {
// return new Date(c[0]).getHours() === new Date(t.time).getHours()
// })
// if (!found) {
// a.push({ time: c[0], price: c[1] })
// }
// return a
// }, [])
// : null,
// ]
// }, [inputTokenStats, outputTokenStats])
const [inputChartPrices, outputChartPrices] = useMemo(() => {
return [
inputTokenStats && inputTokenStats.prices
? inputTokenStats.prices.reduce((a, c) => {
const found = a.find((t) => {
return new Date(c[0]).getHours() === new Date(t.time).getHours()
})
if (!found) {
a.push({ time: c[0], price: c[1] })
}
return a
}, [])
: null,
outputTokenStats && outputTokenStats.prices
? outputTokenStats.prices.reduce((a, c) => {
const found = a.find((t) => {
return new Date(c[0]).getHours() === new Date(t.time).getHours()
})
if (!found) {
a.push({ time: c[0], price: c[1] })
}
return a
}, [])
: null,
]
}, [inputTokenStats, outputTokenStats])
useEffect(() => {
const fetchCoinGeckoList = async () => {
@ -278,24 +281,21 @@ const JupiterForm: FunctionComponent = () => {
return 0.0
}
// const [inputTokenPrice, inputTokenChange] = useMemo(() => {
// if (inputTokenStats?.prices?.length) {
// const price = inputTokenStats.prices[inputTokenStats.prices.length - 1][1]
// const change =
// ((inputTokenStats.prices[0][1] -
// inputTokenStats.prices[inputTokenStats.prices.length - 1][1]) /
// inputTokenStats.prices[0][1]) *
// 100
const [inputTokenPrice, inputTokenChange] = useMemo(() => {
if (inputTokenStats?.prices?.length) {
const price = inputTokenStats.prices[inputTokenStats.prices.length - 1][1]
const change =
((inputTokenStats.prices[0][1] -
inputTokenStats.prices[inputTokenStats.prices.length - 1][1]) /
inputTokenStats.prices[0][1]) *
100
// return [price.toFixed(price < 5 ? 6 : 4), change]
// }
// return [0, 0]
// }, [inputTokenStats])
return [price.toFixed(price < 5 ? 6 : 4), change]
}
return [0, 0]
}, [inputTokenStats])
const [
outputTokenPrice,
// outputTokenChange
] = useMemo(() => {
const [outputTokenPrice, outputTokenChange] = useMemo(() => {
if (outputTokenStats?.prices?.length) {
const price =
outputTokenStats.prices[outputTokenStats.prices.length - 1][1]
@ -386,27 +386,27 @@ const JupiterForm: FunctionComponent = () => {
const swapDisabled = loading || !selectedRoute || routes?.length === 0
// const tooltipContent = (tooltipProps) => {
// if (tooltipProps.payload.length > 0) {
// return (
// <div className="bg-th-bkg-3 flex min-w-[120px] p-2 rounded">
// <div>
// <div className="text-th-fgd-3 text-xs">Time</div>
// <div className="font-bold text-th-fgd-1 text-xs">
// {dayjs(tooltipProps.payload[0].payload.time).format('h:mma')}
// </div>
// </div>
// <div className="pl-3">
// <div className="text-th-fgd-3 text-xs">Price</div>
// <div className="font-bold text-th-fgd-1 text-xs">
// {tooltipProps.payload[0].payload.price}
// </div>
// </div>
// </div>
// )
// }
// return null
// }
const tooltipContent = (tooltipProps) => {
if (tooltipProps.payload.length > 0) {
return (
<div className="bg-th-bkg-3 flex min-w-[120px] p-2 rounded">
<div>
<div className="text-th-fgd-3 text-xs">Time</div>
<div className="font-bold text-th-fgd-1 text-xs">
{dayjs(tooltipProps.payload[0].payload.time).format('h:mma')}
</div>
</div>
<div className="pl-3">
<div className="text-th-fgd-3 text-xs">Price</div>
<div className="font-bold text-th-fgd-1 text-xs">
{tooltipProps.payload[0].payload.price}
</div>
</div>
</div>
)
}
return null
}
return (
<div className="grid grid-cols-12 lg:space-x-4 mt-8">
@ -964,7 +964,7 @@ const JupiterForm: FunctionComponent = () => {
</Button>
</div>
{/* {inputTokenStats?.prices?.length &&
{inputTokenStats?.prices?.length &&
outputTokenStats?.prices?.length ? (
<>
<div className="flex items-center justify-between mt-6">
@ -998,7 +998,7 @@ const JupiterForm: FunctionComponent = () => {
</div>
</div>
<AreaChart
width={120}
width={80}
height={40}
data={inputChartPrices || null}
>
@ -1055,7 +1055,7 @@ const JupiterForm: FunctionComponent = () => {
</div>
</div>
<AreaChart
width={120}
width={80}
height={40}
data={outputChartPrices || null}
>
@ -1082,7 +1082,7 @@ const JupiterForm: FunctionComponent = () => {
</div>
</div>
</>
) : null} */}
) : null}
{showRoutesModal ? (
<Modal

View File

@ -1,7 +1,12 @@
import { FunctionComponent, useMemo, useState } from 'react'
import { EyeOffIcon } from '@heroicons/react/outline'
import { ChevronDownIcon } from '@heroicons/react/solid'
import { Disclosure } from '@headlessui/react'
import dayjs from 'dayjs'
import { AreaChart, Area, XAxis, YAxis, Tooltip } from 'recharts'
import useDimensions from 'react-cool-dimensions'
import { IconButton } from './Button'
import { TradeIcon } from './icons'
interface SwapTokenInfoProps {
inputTokenId?: string
@ -14,10 +19,11 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
inputTokenSymbol,
outputTokenId,
}) => {
const [chartData, setChartData] = useState(null)
const [chartData, setChartData] = useState([])
const [hideChart, setHideChart] = useState(false)
const [outputTokenInfo, setOutputTokenInfo] = useState(null)
const [mouseData, setMouseData] = useState<string | null>(null)
const [daysToShow, setDaysToShow] = useState(1)
// const [daysToShow, setDaysToShow] = useState(1)
const { observe, width, height } = useDimensions()
const handleMouseMove = (coords) => {
@ -30,38 +36,58 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
setMouseData(null)
}
// Use ohlc data. Don't think it works
// const getChartData = async () => {
// const inputResponse = await fetch(
// `https://api.coingecko.com/api/v3/coins/${inputTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
// )
// const outputResponse = await fetch(
// `https://api.coingecko.com/api/v3/coins/${outputTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
// )
// const inputData = await inputResponse.json()
// const outputData = await outputResponse.json()
// const data = inputData.concat(outputData)
// const formattedData = data.reduce((a, c) => {
// const found = a.find((price) => price.time === c[0])
// if (found) {
// found.price = found.inputPrice / c[2]
// } else {
// a.push({ time: c[0], inputPrice: c[2] })
// }
// return a
// }, [])
// setChartData(formattedData.filter((d) => d.price))
// }
const getChartData = async () => {
const now = Date.now() / 1000
const inputResponse = await fetch(
`https://api.coingecko.com/api/v3/coins/${inputTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
`https://api.coingecko.com/api/v3/coins/${inputTokenId}/market_chart/range?vs_currency=usd&from=${
now - 1 * 86400
}&to=${now}`
)
const outputResponse = await fetch(
`https://api.coingecko.com/api/v3/coins/${outputTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`
`https://api.coingecko.com/api/v3/coins/${outputTokenId}/market_chart/range?vs_currency=usd&from=${
now - 1 * 86400
}&to=${now}`
)
const inputData = await inputResponse.json()
const outputData = await outputResponse.json()
// let data
// if (inputData.length === outputData.length) {
// data = inputData.concat(outputData)
// } else {
// const difference = inputData.length - outputData.length
// if (difference > 0) {
// const trimmedInputData = inputData.slice(0, difference * -1)
// data = trimmedInputData.concat(outputData)
// } else {
// const trimmedOutputData = outputData.slice(0, difference)
// data = inputData.concat(trimmedOutputData)
// }
// }
const data = inputData.concat(outputData)
const data = inputData?.prices.concat(outputData?.prices)
const formattedData = data.reduce((a, c) => {
const found = a.find((price) => price.time === c[0])
const found = a.find(
(price) => c[0] >= price.time - 120000 && c[0] <= price.time + 120000
)
if (found) {
found.price = found.inputPrice / c[4]
found.price = found.inputPrice / c[1]
} else {
a.push({ time: c[0], inputPrice: c[4] })
a.push({ time: c[0], inputPrice: c[1] })
}
return a
}, [])
@ -81,7 +107,11 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
if (inputTokenId && outputTokenId) {
getChartData()
}
}, [daysToShow, inputTokenId, outputTokenId])
}, [
// daysToShow,
inputTokenId,
outputTokenId,
])
useMemo(() => {
if (outputTokenId) {
@ -91,9 +121,15 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
console.log(outputTokenInfo)
const chartChange = chartData.length
? ((chartData[chartData.length - 1]['price'] - chartData[0]['price']) /
chartData[0]['price']) *
100
: 0
return (
<div>
{chartData ? (
{chartData.length ? (
<div className="p-4">
<div className="flex justify-between">
<div>
@ -107,6 +143,13 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
minimumFractionDigits: 0,
maximumFractionDigits: 6,
})}
<span
className={`ml-2 text-sm ${
chartChange >= 0 ? 'text-th-green' : 'text-th-red'
}`}
>
{chartChange.toFixed(2)}%
</span>
</div>
<div className="text-xs font-normal text-th-fgd-4">
{dayjs(mouseData['time']).format('DD MMM YY, h:mma')}
@ -122,6 +165,13 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
maximumFractionDigits: 6,
}
)}
<span
className={`ml-2 text-sm ${
chartChange >= 0 ? 'text-th-green' : 'text-th-red'
}`}
>
{chartChange.toFixed(2)}%
</span>
</div>
<div className="text-xs font-normal text-th-fgd-4">
{dayjs(chartData[chartData.length - 1]['time']).format(
@ -131,7 +181,14 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
</>
)}
</div>
<div className="flex h-5">
<IconButton onClick={() => setHideChart(!hideChart)}>
{hideChart ? (
<TradeIcon className="w-4 h-4" />
) : (
<EyeOffIcon className="w-4 h-4" />
)}
</IconButton>
{/* <div className="flex h-5">
<button
className={`default-transition font-bold mx-3 text-th-fgd-1 text-xs hover:text-th-primary focus:outline-none ${
daysToShow === 1 && 'text-th-primary'
@ -156,91 +213,119 @@ const SwapTokenInfo: FunctionComponent<SwapTokenInfoProps> = ({
>
30D
</button>
</div> */}
</div>
{!hideChart ? (
<div className="h-52 mt-4 w-full" ref={observe}>
<AreaChart
width={width}
height={height}
data={chartData}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<Tooltip
cursor={{
strokeOpacity: 0,
}}
content={<></>}
/>
<defs>
<linearGradient id="gradientArea" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#FF9C24" stopOpacity={0.5} />
<stop offset="100%" stopColor="#FF9C24" stopOpacity={0} />
</linearGradient>
</defs>
<Area
isAnimationActive={true}
type="monotone"
dataKey="price"
stroke="#FF9C24"
fill="url(#gradientArea)"
/>
<XAxis dataKey="time" hide />
<YAxis
dataKey="price"
type="number"
domain={['dataMin', 'dataMax']}
hide
/>
</AreaChart>
</div>
</div>
<div className="h-52 mt-4 w-full" ref={observe}>
<AreaChart
width={width}
height={height}
data={chartData}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<Tooltip
cursor={{
strokeOpacity: 0,
}}
content={<></>}
/>
<defs>
<linearGradient id="gradientArea" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#FF9C24" stopOpacity={0.5} />
<stop offset="100%" stopColor="#FF9C24" stopOpacity={0} />
</linearGradient>
</defs>
<Area
isAnimationActive={true}
type="monotone"
dataKey="price"
stroke="#FF9C24"
fill="url(#gradientArea)"
/>
<XAxis dataKey="time" hide />
<YAxis
dataKey="price"
type="number"
domain={['dataMin', 'dataMax']}
hide
/>
</AreaChart>
</div>
) : null}
</div>
) : (
<div className="bg-th-bkg-3 p-4 rounded-md text-center text-th-fgd-3">
<div className="bg-th-bkg-3 mx-4 p-4 rounded-md text-center text-th-fgd-3">
Chart not available
</div>
)}
{outputTokenInfo ? (
<div className="mt-6">
<h2 className="font-bold px-4 text-lg text-th-fgd-1">
{outputTokenInfo.name}
</h2>
<div className="grid grid-flow-col grid-rows-2 mt-2 px-3">
{outputTokenInfo.market_cap_rank ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap Rank</div>
<div className="font-bold text-th-fgd-1 text-lg">
#{outputTokenInfo.market_cap_rank}
</div>
</div>
) : null}
{outputTokenInfo.market_data?.market_cap ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap</div>
<div className="font-bold text-th-fgd-1 text-lg">
$
{outputTokenInfo.market_data?.market_cap?.usd.toLocaleString()}
</div>
</div>
) : null}
{outputTokenInfo.market_cap_rank ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap Rank</div>
<div className="font-bold text-th-fgd-1 text-lg">
#{outputTokenInfo.market_cap_rank}
</div>
</div>
) : null}
{outputTokenInfo.market_data?.market_cap ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap</div>
<div className="font-bold text-th-fgd-1 text-lg">
$
{outputTokenInfo.market_data?.market_cap?.usd.toLocaleString()}
</div>
</div>
) : null}
</div>
<div className="px-4 w-full">
<Disclosure>
{({ open }) => (
<>
<Disclosure.Button
className={`bg-th-bkg-2 border border-th-bkg-4 default-transition flex items-center justify-between mt-4 p-4 rounded-md w-full hover:bg-th-bkg-3 ${
open
? 'border-b-transparent rounded-b-none'
: 'transform rotate-360'
}`}
>
<h2 className="font-bold text-base text-th-fgd-1">
About {outputTokenInfo.name}
</h2>
<ChevronDownIcon
className={`default-transition h-6 w-6 text-th-fgd-3 ${
open ? 'transform rotate-180' : 'transform rotate-360'
}`}
/>
</Disclosure.Button>
<Disclosure.Panel>
<div className="border border-th-bkg-4 border-t-0 grid grid-flow-col grid-rows-2 px-3 py-6 rounded-b-md">
{outputTokenInfo.market_cap_rank ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">
Market Cap Rank
</div>
<div className="font-bold text-th-fgd-1 text-lg">
#{outputTokenInfo.market_cap_rank}
</div>
</div>
) : null}
{outputTokenInfo.market_data?.market_cap ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap</div>
<div className="font-bold text-th-fgd-1 text-lg">
$
{outputTokenInfo.market_data?.market_cap?.usd.toLocaleString()}
</div>
</div>
) : null}
{outputTokenInfo.market_cap_rank ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">
Market Cap Rank
</div>
<div className="font-bold text-th-fgd-1 text-lg">
#{outputTokenInfo.market_cap_rank}
</div>
</div>
) : null}
{outputTokenInfo.market_data?.market_cap ? (
<div className="border border-th-bkg-4 m-1 p-3 rounded-md">
<div className="text-th-fgd-4 text-xs">Market Cap</div>
<div className="font-bold text-th-fgd-1 text-lg">
$
{outputTokenInfo.market_data?.market_cap?.usd.toLocaleString()}
</div>
</div>
) : null}
</div>
</Disclosure.Panel>
</>
)}
</Disclosure>
</div>
) : null}
</div>