Skip to content

Commit 88f3bac

Browse files
Weighted average investment percent change
1 parent 54101ea commit 88f3bac

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

packages/app/features/home/InvestmentsBalanceCard.tsx

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { useMultipleTokensMarketData } from 'app/utils/coin-gecko'
1313
import { useMemo } from 'react'
1414
import { IconError } from 'app/components/icons'
1515
import { useCoins } from 'app/provider/coins'
16+
import { formatUnits } from 'viem'
1617

1718
export const InvestmentsBalanceCard = () => {
1819
const [queryParams, setParams] = useRootScreenParams()
@@ -96,22 +97,41 @@ export const InvestmentsBalanceCard = () => {
9697
}
9798

9899
function InvestmentsAggregate() {
99-
const tokenIds = useCoins()
100-
.investmentCoins.filter((c) => c?.balance && c.balance > 0n)
101-
.map((c) => c.coingeckoTokenId)
100+
const coins = useCoins().investmentCoins.filter((c) => c?.balance && c.balance > 0n)
102101

102+
const tokenIds = coins.map((c) => c.coingeckoTokenId)
103103
const { data: marketData, isLoading, isError } = useMultipleTokensMarketData(tokenIds)
104+
105+
const { totalValue, assetValues } = useMemo(() => {
106+
if (!marketData?.length) return { totalValue: 0, assetValues: [] }
107+
108+
// Calculate values for each asset and total
109+
const assetValues = coins.map((coin) => {
110+
const marketInfo = marketData.find((m) => m.id === coin.coingeckoTokenId)
111+
if (!marketInfo || !coin.balance) return { value: 0, percentChange: 0 }
112+
113+
const parsedBalance = formatUnits(coin.balance, coin.decimals)
114+
return {
115+
value: Number(parsedBalance) * (marketInfo.current_price ?? 0),
116+
percentChange: marketInfo.price_change_percentage_24h ?? 0,
117+
}
118+
})
119+
120+
const totalValue = assetValues.reduce((sum, asset) => sum + asset.value, 0)
121+
122+
return { totalValue, assetValues }
123+
}, [marketData, coins])
124+
104125
const aggregatePercentage = useMemo(() => {
105-
if (!marketData?.length) return 0
126+
if (totalValue <= 0) return 0
106127

107-
// Simple average of percentage changes
108-
const aggregatePercentage =
109-
marketData.reduce((total, coin) => {
110-
return total + (coin?.price_change_percentage_24h ?? 0)
111-
}, 0) / marketData.length
128+
const weightedPercentage = assetValues.reduce((sum, asset) => {
129+
const weight = asset.value / totalValue
130+
return sum + asset.percentChange * weight
131+
}, 0)
112132

113-
return Number(aggregatePercentage.toFixed(2))
114-
}, [marketData])
133+
return Math.round(weightedPercentage * 100) / 100
134+
}, [totalValue, assetValues])
115135

116136
if (tokenIds.length === 0)
117137
return (

0 commit comments

Comments
 (0)