|
| 1 | +/** |
| 2 | + * Extract logic from presentation component to store |
| 3 | + * we want a structure flexible enough to observe for price change |
| 4 | + * such that value is reactive to price and amount and aggregates reactive its components |
| 5 | + */ |
| 6 | + |
| 7 | +import { groupMultichainToken, withValue } from "./multi-chain"; |
| 8 | +import type { TokenBalanceEntry } from "./token-balance-entry"; |
| 9 | + |
| 10 | +import { type Atom, atom, computed, deepMap } from "nanostores"; |
| 11 | +import type { TokenPriceEntry } from "./token-price-entry"; |
| 12 | + |
| 13 | +export const tokenBalanceStore = () => { |
| 14 | + const $tokenBalances = atom<TokenBalanceEntry[]>([]); |
| 15 | + const $priceData = atom<TokenPriceEntry[]>([]); |
| 16 | + |
| 17 | + return { |
| 18 | + $tokenBalances, |
| 19 | + $priceData, |
| 20 | + }; |
| 21 | +}; |
| 22 | + |
| 23 | +export const aggregateBySymbol = ( |
| 24 | + $tokenBalances: Atom<TokenBalanceEntry[]>, |
| 25 | + $priceData?: Atom<TokenPriceEntry[]>, |
| 26 | +) => { |
| 27 | + return computed( |
| 28 | + [$tokenBalances, $priceData || atom<TokenPriceEntry[]>([])], |
| 29 | + ( |
| 30 | + tokenBalances: TokenBalanceEntry[], |
| 31 | + $priceData: TokenPriceEntry[] = [], |
| 32 | + ) => { |
| 33 | + const bySymbol = groupMultichainToken(tokenBalances); |
| 34 | + |
| 35 | + return Object.entries(bySymbol).reduce((acc, [symbol, tokenInfo]) => { |
| 36 | + const { tokenBalances } = tokenInfo; |
| 37 | + |
| 38 | + const tokenBalancesWithValue = tokenBalances.map((tokenBalance) => |
| 39 | + withValue(tokenBalance, $priceData), |
| 40 | + ); |
| 41 | + |
| 42 | + // TODO if empty price data |
| 43 | + console.log("tokenBalancesWithValue", tokenBalancesWithValue); |
| 44 | + const agg = tokenBalancesWithValue.reduce( |
| 45 | + (acc, tokenBalanceWithValue) => { |
| 46 | + return { |
| 47 | + amount: acc.amount + tokenBalanceWithValue.amount, |
| 48 | + value: acc.value + (tokenBalanceWithValue.value || 0n), |
| 49 | + }; |
| 50 | + }, |
| 51 | + { |
| 52 | + amount: 0n, |
| 53 | + value: 0n, |
| 54 | + }, |
| 55 | + ); |
| 56 | + console.log("agg", agg); |
| 57 | + acc.setKey(symbol, { |
| 58 | + tokenBalances: tokenBalancesWithValue, |
| 59 | + agg, |
| 60 | + }); |
| 61 | + return acc; |
| 62 | + }, deepMap<Record<string, unknown>>({})); |
| 63 | + }, |
| 64 | + ); |
| 65 | +}; |
0 commit comments