Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 106 additions & 19 deletions src/components/charts/useLegacyLastDayChangeRowData.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import type {Wallet} from '../../store/wallet/wallet.models';
import {calculatePercentageDifference} from '../../utils/helper-methods';
import {HISTORIC_RATES_CACHE_DURATION} from '../../constants/wallet';
import {useAppSelector} from '../../utils/hooks';
import {
buildLegacyLastDayRateRequestsForWallets,
getLegacyLastDayPnlForRepresentativeAsset,
getLegacyLastDayPnlForWallets,
getLegacyLastDayPnlFromTotals,
getLegacyLastDayRateRequestForAsset,
type LegacyLastDayAssetIdentity,
type LegacyLastDayPnl,
type LegacyLastDayPnlMode,
} from '../../utils/portfolio/assets';
import {
buildBalanceHistoryChartChangeRowData,
type ChangeRowData,
} from './balanceHistoryChartSelection';
import {getRangeLabelForFiatTimeframe} from './fiatTimeframes';
import useRuntimeFiatRateSeriesCache from '../../portfolio/ui/hooks/useRuntimeFiatRateSeriesCache';
import {getLastDayTimestampStartOfHourMs} from '../../utils/helper-methods';

const toFiniteNumber = (value: unknown): number => {
const n = typeof value === 'number' ? value : Number(value);
Expand All @@ -24,6 +37,20 @@ export const getLegacyLastDayFiatBalance = (
0,
);

const buildLegacyLastDayChangeRowDataFromPnl = (args: {
legacyPnl: LegacyLastDayPnl;
quoteCurrency: string;
label: string;
}): ChangeRowData =>
buildBalanceHistoryChartChangeRowData({
displayedAnalysisPoint: {
totalPnlChange: args.legacyPnl.deltaFiat,
totalPnlPercent: args.legacyPnl.percent,
},
quoteCurrency: args.quoteCurrency,
label: args.label,
});

export const buildLegacyLastDayChangeRowData = (args: {
wallets: Wallet[] | undefined;
currentFiatBalance: number | undefined;
Expand All @@ -32,19 +59,17 @@ export const buildLegacyLastDayChangeRowData = (args: {
}): ChangeRowData | undefined => {
const currentFiatBalance = toFiniteNumber(args.currentFiatBalance);
const lastDayFiatBalance = getLegacyLastDayFiatBalance(args.wallets);
const legacyPnl = getLegacyLastDayPnlFromTotals({
currentFiatBalance,
lastDayFiatBalance,
});

if (!(currentFiatBalance > 0) || !(lastDayFiatBalance > 0)) {
if (!legacyPnl) {
return undefined;
}

return buildBalanceHistoryChartChangeRowData({
displayedAnalysisPoint: {
totalPnlChange: currentFiatBalance - lastDayFiatBalance,
totalPnlPercent: calculatePercentageDifference(
currentFiatBalance,
lastDayFiatBalance,
),
},
return buildLegacyLastDayChangeRowDataFromPnl({
legacyPnl,
quoteCurrency: args.quoteCurrency,
label: args.label,
});
Expand All @@ -55,29 +80,91 @@ const useLegacyLastDayChangeRowData = (args: {
currentFiatBalance: number | undefined;
quoteCurrency: string;
enabled?: boolean;
mode?: LegacyLastDayPnlMode;
representativeAsset?: LegacyLastDayAssetIdentity;
}): ChangeRowData | undefined => {
const {t} = useTranslation();
const rates = useAppSelector(({RATE}) => RATE.rates);
const {
currentFiatBalance,
enabled: enabledArg,
mode = 'walletLevel',
quoteCurrency,
representativeAsset,
wallets,
} = args;
const enabled = enabledArg !== false;
const lastDayLabel = getRangeLabelForFiatTimeframe(t, '1D');
const baselineTimestampMs = useMemo(
() => getLastDayTimestampStartOfHourMs(),
[quoteCurrency],
);
const rateRequests = useMemo(() => {
if (!enabled) {
return [];
}

return useMemo(
() =>
enabled
? buildLegacyLastDayChangeRowData({
wallets,
if (mode === 'representativeAsset') {
const request = getLegacyLastDayRateRequestForAsset(representativeAsset);
return request ? [request] : [];
}

return buildLegacyLastDayRateRequestsForWallets({wallets});
}, [enabled, mode, representativeAsset, wallets]);
const {cache: fiatRateSeriesCache} = useRuntimeFiatRateSeriesCache({
quoteCurrency,
requests: rateRequests,
maxAgeMs: HISTORIC_RATES_CACHE_DURATION * 1000,
enabled: enabled && rateRequests.length > 0,
clearOnRequestChange: true,
});

return useMemo(() => {
if (!enabled) {
return undefined;
}

const legacyPnl =
mode === 'representativeAsset'
? getLegacyLastDayPnlForRepresentativeAsset({
currentFiatBalance,
fallbackLastDayFiatBalance: getLegacyLastDayFiatBalance(wallets),
rates,
fiatRateSeriesCache,
quoteCurrency,
label: lastDayLabel,
baselineTimestampMs,
identity: representativeAsset || {},
})
: undefined,
[currentFiatBalance, enabled, lastDayLabel, quoteCurrency, wallets],
);
: getLegacyLastDayPnlForWallets({
wallets,
currentFiatBalance,
rates,
fiatRateSeriesCache,
quoteCurrency,
baselineTimestampMs,
});

if (!legacyPnl) {
return undefined;
}

return buildLegacyLastDayChangeRowDataFromPnl({
legacyPnl,
quoteCurrency,
label: lastDayLabel,
});
}, [
baselineTimestampMs,
currentFiatBalance,
enabled,
fiatRateSeriesCache,
lastDayLabel,
mode,
quoteCurrency,
rates,
representativeAsset,
wallets,
]);
};

export default useLegacyLastDayChangeRowData;
20 changes: 12 additions & 8 deletions src/navigation/tabs/home/HomeRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ const HomeRoot: React.FC<HomeScreenProps> = ({route, navigation}) => {
({APP}) => APP.keyMigrationFailureModalHasBeenShown,
);
const showPortfolioValue = useAppSelector(selectShowPortfolioValue);
const portfolioChartsRequested = showPortfolioValue === true;
const hasKeys = Object.values(keys).length;

const portfolioAllocationTotalFiat = useMemo(() => {
Expand Down Expand Up @@ -402,14 +403,12 @@ const HomeRoot: React.FC<HomeScreenProps> = ({route, navigation}) => {
/>
}>
{/* ////////////////////////////// PORTFOLIO BALANCE */}
{showPortfolioValue ? (
<HomeSection style={{marginTop: 20, marginBottom: 20}}>
<PortfolioBalance />
</HomeSection>
) : null}
<HomeSection style={{marginTop: 20, marginBottom: 20}}>
<PortfolioBalance />
</HomeSection>

{/* ////////////////////////////// CTA BUY SWAP RECEIVE SEND BUTTONS */}
{hasKeys && showPortfolioValue ? (
{hasKeys ? (
<HomeSection style={{marginBottom: 25}}>
<LinkingButtons
receive={{
Expand Down Expand Up @@ -451,12 +450,17 @@ const HomeRoot: React.FC<HomeScreenProps> = ({route, navigation}) => {
{/* ////////////////////////////// SECURE WITH PASSKEY */}
<SecurePasskeyBannerGate />

{showPortfolioValue ? (
{hasKeys ? (
<HomeSection>
<View
ref={homeAssetsSectionRef}
onLayout={onHomeAssetsSectionLayout}>
<AssetsSection enabled={shouldActivateHomeAssetsSection} />
<AssetsSection
enabled={
portfolioChartsRequested &&
shouldActivateHomeAssetsSection
}
/>
</View>
</HomeSection>
) : null}
Expand Down
89 changes: 75 additions & 14 deletions src/navigation/tabs/home/components/AssetsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ import AssetsList from './AssetsList';
import {
AssetRowItem,
GainLossMode,
buildLegacyLastDayRateRequestsForAssetRows,
buildAssetPreviewRowItemsFromWallets,
getVisibleWalletsFromKeys,
walletsHaveNonZeroLiveBalance,
} from '../../../../utils/portfolio/assets';
import AssetsGainLossDropdown from './AssetsGainLossDropdown';
import {useAppSelector} from '../../../../utils/hooks';
import {selectShowPortfolioValue} from '../../../../store/app/app.selectors';
import {
CharcoalBlack,
GhostWhite,
Expand All @@ -30,6 +32,9 @@ import {
toAllocationWallet,
} from '../../../../utils/portfolio/allocation';
import type {Key} from '../../../../store/wallet/wallet.models';
import useRuntimeFiatRateSeriesCache from '../../../../portfolio/ui/hooks/useRuntimeFiatRateSeriesCache';
import {HISTORIC_RATES_CACHE_DURATION} from '../../../../constants/wallet';
import {getLastDayTimestampStartOfHourMs} from '../../../../utils/helper-methods';

const Container = styled.View`
margin-top: 5px;
Expand Down Expand Up @@ -83,10 +88,13 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
const navigation = useNavigation<NavigationProp<RootStackParamList>>();
const [gainLossMode, setGainLossMode] = useState<GainLossMode>('1D');
const portfolio = useAppSelector(({PORTFOLIO}) => PORTFOLIO);
const rates = useAppSelector(({RATE}) => RATE.rates);
const defaultAltCurrency = useAppSelector(({APP}) => APP.defaultAltCurrency);
const showPortfolioValue = useAppSelector(selectShowPortfolioValue);
const homeCarouselConfig = useAppSelector(({APP}) => APP.homeCarouselConfig);
const keys = useAppSelector(({WALLET}) => WALLET.keys) as Record<string, Key>;
const focusRefreshToken = useScreenFocusRefreshToken();
const portfolioChartsEnabled = showPortfolioValue === true;
const visibleWallets = useMemo(() => {
return getVisibleWalletsFromKeys(keys, homeCarouselConfig);
}, [homeCarouselConfig, keys]);
Expand All @@ -101,14 +109,50 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {

return allocationData.rows.slice(0, 4).map(row => row.key);
}, [defaultAltCurrency.isoCode, visibleWallets]);
const legacyAssetRowsEnabled = !portfolioChartsEnabled;
const legacyAssetRateRequests = useMemo(() => {
if (!legacyAssetRowsEnabled) {
return [];
}

return buildLegacyLastDayRateRequestsForAssetRows({
wallets: visibleWallets,
orderedAssetKeys: topAssetKeys,
});
}, [legacyAssetRowsEnabled, topAssetKeys, visibleWallets]);
const legacyAssetBaselineTimestampMs = useMemo(
() => getLastDayTimestampStartOfHourMs(),
[defaultAltCurrency.isoCode, focusRefreshToken],
);
const {cache: legacyAssetFiatRateSeriesCache} = useRuntimeFiatRateSeriesCache(
{
quoteCurrency: defaultAltCurrency.isoCode,
requests: legacyAssetRateRequests,
maxAgeMs: HISTORIC_RATES_CACHE_DURATION * 1000,
enabled: legacyAssetRowsEnabled && legacyAssetRateRequests.length > 0,
clearOnRequestChange: true,
},
);
const previewItems = useMemo(() => {
return buildAssetPreviewRowItemsFromWallets({
wallets: visibleWallets,
quoteCurrency: defaultAltCurrency.isoCode,
orderedAssetKeys: topAssetKeys,
showScopedPnlLoading: topAssetKeys.length > 0,
showScopedPnlLoading: portfolioChartsEnabled && topAssetKeys.length > 0,
includeLegacyLastDayPnl: !portfolioChartsEnabled,
rates,
fiatRateSeriesCache: legacyAssetFiatRateSeriesCache,
baselineTimestampMs: legacyAssetBaselineTimestampMs,
});
}, [defaultAltCurrency.isoCode, topAssetKeys, visibleWallets]);
}, [
defaultAltCurrency.isoCode,
legacyAssetBaselineTimestampMs,
legacyAssetFiatRateSeriesCache,
portfolioChartsEnabled,
rates,
topAssetKeys,
visibleWallets,
]);
const {
visibleItems,
isFiatLoading: isPnlLoading,
Expand All @@ -117,7 +161,7 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
presentationResetToken,
} = usePortfolioAssetRows({
gainLossMode,
enabled,
enabled: enabled && portfolioChartsEnabled,
assetKeys: topAssetKeys,
externalRefreshToken: focusRefreshToken,
});
Expand All @@ -136,7 +180,10 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
const nextItems: AssetRowItem[] = [];
const seenKeys = new Set<string>();
const shouldUsePreviewFallback =
!enabled || !!isPnlLoading || !visibleItems.length;
!portfolioChartsEnabled ||
!enabled ||
!!isPnlLoading ||
!visibleItems.length;
const resolveDisplayItem = (key: string): AssetRowItem | undefined => {
const previewItem = previewItemsByKey.get(key);
const visibleItem = visibleItemsByKey.get(key);
Expand Down Expand Up @@ -180,8 +227,16 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
}

return nextItems.slice(0, 4);
}, [enabled, isPnlLoading, previewItems, topAssetKeys, visibleItems]);
}, [
enabled,
isPnlLoading,
portfolioChartsEnabled,
previewItems,
topAssetKeys,
visibleItems,
]);
const shouldShowActivationPlaceholder =
portfolioChartsEnabled &&
hasAnyVisibleWalletBalance &&
!items.length &&
(!!visibleWallets.length || !!portfolio.populateStatus?.inProgress);
Expand All @@ -191,10 +246,12 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
<Container>
<Header>
<HomeSectionTitle>{t('Assets')}</HomeSectionTitle>
<AssetsGainLossDropdown
value={gainLossMode}
onChange={setGainLossMode}
/>
{portfolioChartsEnabled ? (
<AssetsGainLossDropdown
value={gainLossMode}
onChange={setGainLossMode}
/>
) : null}
</Header>

<AssetsList items={SKELETON_ASSET_ITEMS} forceSkeleton />
Expand Down Expand Up @@ -226,16 +283,20 @@ const AssetsSection: React.FC<AssetsSectionProps> = ({enabled = true}) => {
<Container>
<Header>
<HomeSectionTitle>{t('Assets')}</HomeSectionTitle>
<AssetsGainLossDropdown
value={gainLossMode}
onChange={setGainLossMode}
/>
{portfolioChartsEnabled ? (
<AssetsGainLossDropdown
value={gainLossMode}
onChange={setGainLossMode}
/>
) : null}
</Header>

<AssetsList
items={items}
isPnlLoading={isPnlLoading}
populateInProgress={!!portfolio.populateStatus?.inProgress}
populateInProgress={
portfolioChartsEnabled && !!portfolio.populateStatus?.inProgress
}
isPopulateLoadingByKey={isPopulateLoadingByKey}
presentationResetToken={presentationResetToken}
/>
Expand Down
Loading
Loading