@@ -13,6 +13,7 @@ import { useMultipleTokensMarketData } from 'app/utils/coin-gecko'
13
13
import { useMemo } from 'react'
14
14
import { IconError } from 'app/components/icons'
15
15
import { useCoins } from 'app/provider/coins'
16
+ import { formatUnits } from 'viem'
16
17
17
18
export const InvestmentsBalanceCard = ( ) => {
18
19
const [ queryParams , setParams ] = useRootScreenParams ( )
@@ -96,22 +97,41 @@ export const InvestmentsBalanceCard = () => {
96
97
}
97
98
98
99
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 )
102
101
102
+ const tokenIds = coins . map ( ( c ) => c . coingeckoTokenId )
103
103
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
+
104
125
const aggregatePercentage = useMemo ( ( ) => {
105
- if ( ! marketData ?. length ) return 0
126
+ if ( totalValue <= 0 ) return 0
106
127
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 )
112
132
113
- return Number ( aggregatePercentage . toFixed ( 2 ) )
114
- } , [ marketData ] )
133
+ return Math . round ( weightedPercentage * 100 ) / 100
134
+ } , [ totalValue , assetValues ] )
115
135
116
136
if ( tokenIds . length === 0 )
117
137
return (
0 commit comments