Skip to content
This repository has been archived by the owner on Mar 11, 2024. It is now read-only.

Commit

Permalink
Merge pull request #778 from alephium/fix-chart
Browse files Browse the repository at this point in the history
Use latest price as last data point in chart
  • Loading branch information
nop33 authored Aug 15, 2023
2 parents 90aeedb + 8a13445 commit 66d28c4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 15 deletions.
24 changes: 14 additions & 10 deletions src/components/HistoricWorthChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ import { useGetHistoricalPriceQuery } from '@/storage/assets/priceApiSlice'
import { AddressHash } from '@/types/addresses'
import { ChartLength, DataPoint, LatestAmountPerAddress } from '@/types/chart'
import { Currency } from '@/types/settings'
import { CHART_DATE_FORMAT } from '@/utils/constants'

interface HistoricWorthChartProps {
currency: Currency
length: ChartLength
onDataPointHover: (dataPoint?: DataPoint) => void
onWorthInBeginningOfChartChange: (worthInBeginningOfChart?: DataPoint['worth']) => void
latestWorth: number
latestWorth?: number
addressHash?: AddressHash
}

Expand Down Expand Up @@ -76,8 +77,7 @@ const HistoricWorthChart = memo(function HistoricWorthChart({

const startingDate = startingDates[length].format('YYYY-MM-DD')
const isDataAvailable = addresses.length !== 0 && haveHistoricBalancesLoaded && !!alphPriceHistory
const filteredChartData = getFilteredChartData(chartData, startingDate)
const firstItem = filteredChartData.at(0)
const firstItem = chartData.at(0)

useEffect(() => {
onWorthInBeginningOfChartChange(firstItem?.worth)
Expand All @@ -92,7 +92,7 @@ const HistoricWorthChart = memo(function HistoricWorthChart({
const computeChartDataPoints = (): DataPoint[] => {
const addressesLatestAmount: LatestAmountPerAddress = {}

return alphPriceHistory.map(({ date, price }) => {
const dataPoints = alphPriceHistory.map(({ date, price }) => {
let totalAmountPerDate = BigInt(0)

addresses.forEach(({ hash, balanceHistory }) => {
Expand All @@ -112,27 +112,31 @@ const HistoricWorthChart = memo(function HistoricWorthChart({
worth: price * parseFloat(toHumanReadableAmount(totalAmountPerDate))
}
})

if (latestWorth !== undefined) dataPoints.push({ date: dayjs().format(CHART_DATE_FORMAT), worth: latestWorth })

return dataPoints
}

const trimInitialZeroDataPoints = (data: DataPoint[]) => data.slice(data.findIndex((point) => point.worth !== 0))

let dataPoints = computeChartDataPoints()
dataPoints = trimInitialZeroDataPoints(dataPoints)

setChartData(dataPoints)
}, [addresses, alphPriceHistory, isDataAvailable])
setChartData(getFilteredChartData(dataPoints, startingDate))
}, [addresses, alphPriceHistory, isDataAvailable, latestWorth, startingDate])

if (!isDataAvailable || chartData.length <= 2 || !firstItem) return null
if (!isDataAvailable || chartData.length <= 2 || !firstItem || latestWorth === undefined) return null

const xAxisDatesData = filteredChartData.map(({ date }) => date)
const yAxisWorthData = filteredChartData.map(({ worth }) => worth)
const xAxisDatesData = chartData.map(({ date }) => date)
const yAxisWorthData = chartData.map(({ worth }) => worth)

const worthHasGoneUp = firstItem.worth < latestWorth
const chartColor = stateUninitialized ? theme.font.tertiary : worthHasGoneUp ? theme.global.valid : theme.global.alert

const chartOptions = getChartOptions(chartColor, xAxisDatesData, {
mouseMove(e, chart, options) {
onDataPointHover(options.dataPointIndex === -1 ? undefined : filteredChartData[options.dataPointIndex])
onDataPointHover(options.dataPointIndex === -1 ? undefined : chartData[options.dataPointIndex])
},
mouseLeave() {
onDataPointHover(undefined)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ const AmountsOverviewPanel: FC<AmountsOverviewPanelProps> = ({ className, addres
const totalBalance = addresses.reduce((acc, address) => acc + BigInt(address.balance), BigInt(0))
const totalAvailableBalance = addresses.reduce((acc, address) => acc + getAvailableBalance(address), BigInt(0))
const totalLockedBalance = addresses.reduce((acc, address) => acc + BigInt(address.lockedBalance), BigInt(0))
const totalAmountWorth = calculateAmountWorth(totalBalance, price ?? 0)
const totalAmountWorth =
price !== undefined && !stateUninitialized ? calculateAmountWorth(totalBalance, price) : undefined
const balanceInFiat = worth ?? totalAmountWorth

const isOnline = network.status === 'online'
Expand All @@ -108,7 +109,7 @@ const AmountsOverviewPanel: FC<AmountsOverviewPanelProps> = ({ className, addres
stateUninitialized ||
(hasHistoricBalances && worthInBeginningOfChart === undefined) ? (
<SkeletonLoader height="18px" width="70px" style={{ marginBottom: 6 }} />
) : hasHistoricBalances && worthInBeginningOfChart ? (
) : hasHistoricBalances && worthInBeginningOfChart && totalAmountWorth !== undefined ? (
<DeltaPercentage initialValue={worthInBeginningOfChart} latestValue={totalAmountWorth} />
) : null}
</FiatDeltaPercentage>
Expand Down Expand Up @@ -173,7 +174,9 @@ const AmountsOverviewPanel: FC<AmountsOverviewPanelProps> = ({ className, addres

<ChartOuterContainer
variants={chartAnimationVariants}
animate={showChart && hasHistoricBalances && !discreetMode ? 'shown' : 'hidden'}
animate={
showChart && hasHistoricBalances && !discreetMode && totalAmountWorth !== undefined ? 'shown' : 'hidden'
}
>
<ChartInnerContainer animate={{ opacity: discreetMode ? 0 : 1 }} transition={{ duration: 0.5 }}>
<HistoricWorthChart
Expand Down
19 changes: 17 additions & 2 deletions src/storage/assets/priceApiSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,23 @@ export const priceApi = createApi({
}),
getHistoricalPrice: builder.query<HistoricalPriceResult[], HistoricalPriceQueryParams>({
query: ({ currency, days }) => `/coins/alephium/market_chart?vs_currency=${currency.toLowerCase()}&days=${days}`,
transformResponse: (response: { prices: number[][] }) =>
response.prices.map((p) => ({ date: dayjs(p[0]).format(CHART_DATE_FORMAT), price: p[1] }))
transformResponse: (response: { prices: number[][] }) => {
const { prices } = response
const today = dayjs().format(CHART_DATE_FORMAT)

return prices.reduce((acc, [date, price]) => {
const itemDate = dayjs(date).format(CHART_DATE_FORMAT)
const isDuplicatedItem = !!acc.find(({ date }) => dayjs(date).format(CHART_DATE_FORMAT) === itemDate)

if (!isDuplicatedItem && itemDate !== today)
acc.push({
date: itemDate,
price
})

return acc
}, [] as HistoricalPriceResult[])
}
})
})
})
Expand Down

0 comments on commit 66d28c4

Please sign in to comment.