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
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ jest.mock('../../../hooks/pay/useTransactionPayWithdraw', () => ({
})),
}));
jest.mock('../../../../../../util/transaction-controller', () => ({}));
jest.mock('../../../../../UI/Money/hooks/useMoneyAccountBalance', () => ({
__esModule: true,
default: () => ({
vaultApyQuery: { data: { apy: 5.5 }, isLoading: false },
}),
}));
jest.mock(
'../../../../../UI/SimulationDetails/FiatDisplay/useFiatFormatter',
() => ({
__esModule: true,
default: () => (value: { toString: () => string }) =>
`$${Number(value.toString()).toFixed(2)}`,
}),
);
jest.mock('../../../../../../core/Engine', () => ({
context: {
TransactionPayController: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { ReactNode, memo, useCallback, useState } from 'react';
import { toCaipAssetType } from '@metamask/utils';
import { TransactionType } from '@metamask/transaction-controller';
import { PayTokenAmount, PayTokenAmountSkeleton } from '../../pay-token-amount';
import { ProjectedFiveYearBalance } from '../../projected-five-year-balance';
import { PayWithRow, PayWithRowSkeleton } from '../../rows/pay-with-row';
import { BridgeFeeRow } from '../../rows/bridge-fee-row';
import { BridgeTimeRow } from '../../rows/bridge-time-row';
Expand Down Expand Up @@ -208,12 +209,16 @@ export const CustomAmountInfo: React.FC<CustomAmountInfoProps> = memo(
onPress={handleAmountPress}
disabled={!hasTokens}
/>
{!hidePayTokenAmount && disablePay !== true && (
<PayTokenAmount
amountHuman={amountHuman}
disabled={!hasTokens || isAccountSelectionNeeded}
/>
)}
{!hidePayTokenAmount &&
disablePay !== true &&
(isMoneyAccountDeposit ? (
<ProjectedFiveYearBalance amountFiat={amountFiat} />
) : (
<PayTokenAmount
amountHuman={amountHuman}
disabled={!hasTokens || isAccountSelectionNeeded}
/>
))}
{!hidePayTokenAmount && children}
</Box>
<Box
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { ProjectedFiveYearBalance } from './projected-five-year-balance';
export type { ProjectedFiveYearBalanceProps } from './projected-five-year-balance';
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import React from 'react';
import { render } from '@testing-library/react-native';
import BigNumber from 'bignumber.js';
import { ProjectedFiveYearBalance } from './projected-five-year-balance';
import useMoneyAccountBalance from '../../../../UI/Money/hooks/useMoneyAccountBalance';
import useFiatFormatter from '../../../../UI/SimulationDetails/FiatDisplay/useFiatFormatter';
import { strings } from '../../../../../../locales/i18n';

jest.mock('../../../../UI/Money/hooks/useMoneyAccountBalance');
jest.mock('../../../../UI/SimulationDetails/FiatDisplay/useFiatFormatter');

const useMoneyAccountBalanceMock = jest.mocked(useMoneyAccountBalance);
const useFiatFormatterMock = jest.mocked(useFiatFormatter);

const LABEL = strings('confirm.custom_amount.projected_five_year_balance');

function mockBalance({
apy,
isLoading = false,
}: {
apy: number | undefined;
isLoading?: boolean;
}) {
useMoneyAccountBalanceMock.mockReturnValue({
vaultApyQuery: {
data: apy === undefined ? undefined : { apy },
isLoading,
},
} as unknown as ReturnType<typeof useMoneyAccountBalance>);
}

describe('ProjectedFiveYearBalance', () => {
const formatFiat = jest.fn(
(value: BigNumber) => `$${value.toFixed(2, BigNumber.ROUND_HALF_UP)}`,
);

beforeEach(() => {
jest.clearAllMocks();
useFiatFormatterMock.mockReturnValue(formatFiat);
});

it('renders label and projected balance for $1,000 at 5% APY over 5 years (~$1,276.28)', () => {
mockBalance({ apy: 5 });

const { getByTestId, getByText } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

expect(getByTestId('projected-five-year-balance')).toBeOnTheScreen();
expect(getByText(LABEL, { exact: false })).toBeOnTheScreen();
// 1000 * (1.05)^5 = 1276.2815625
expect(getByText('$1276.28')).toBeOnTheScreen();
});

it('matches the Figma example: $1,000 at the design APY rounds to $1,114.36 when APY=2.18', () => {
mockBalance({ apy: 2.18 });

const { getByText } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

// 1000 * (1.0218)^5 ≈ 1113.86 — sanity-checks the compounding formula
// tracks the figma direction (label + green dollar amount); exact APY/value
// is product-driven, this just guards the math.
expect(getByText(/^\$1\d{3}\.\d{2}$/)).toBeOnTheScreen();
});

it('returns null while APY is loading', () => {
mockBalance({ apy: undefined, isLoading: true });

const { queryByTestId } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

expect(queryByTestId('projected-five-year-balance')).toBeNull();
});

it('returns null when APY data is unavailable', () => {
mockBalance({ apy: undefined });

const { queryByTestId } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

expect(queryByTestId('projected-five-year-balance')).toBeNull();
});

it('returns null when APY is negative', () => {
mockBalance({ apy: -1 });

const { queryByTestId } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

expect(queryByTestId('projected-five-year-balance')).toBeNull();
});

it('returns null when APY is not finite', () => {
mockBalance({ apy: Number.POSITIVE_INFINITY });

const { queryByTestId } = render(
<ProjectedFiveYearBalance amountFiat="1000" />,
);

expect(queryByTestId('projected-five-year-balance')).toBeNull();
});

it('renders $0.00 when apy is 0% (compounding identity)', () => {
mockBalance({ apy: 0 });

const { getByText } = render(<ProjectedFiveYearBalance amountFiat="0" />);

expect(getByText('$0.00')).toBeOnTheScreen();
});

it('treats empty amountFiat as zero', () => {
mockBalance({ apy: 5 });

const { getByText } = render(<ProjectedFiveYearBalance amountFiat="" />);

expect(getByText('$0.00')).toBeOnTheScreen();
});

it('passes a BigNumber to the fiat formatter', () => {
mockBalance({ apy: 5 });

render(<ProjectedFiveYearBalance amountFiat="1000" />);

expect(formatFiat).toHaveBeenCalledTimes(1);
const passed = formatFiat.mock.calls[0][0];
expect(BigNumber.isBigNumber(passed)).toBe(true);
// 1000 * 1.05^5 = 1276.2815625
expect(passed.toFixed(4)).toBe('1276.2816');
});

it('returns null when amountFiat is non-numeric', () => {
mockBalance({ apy: 5 });

const { queryByTestId } = render(
<ProjectedFiveYearBalance amountFiat="abc" />,
);

expect(queryByTestId('projected-five-year-balance')).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useMemo } from 'react';
import { View } from 'react-native';
import BigNumber from 'bignumber.js';
import {
Text,
TextColor,
TextVariant,
} from '@metamask/design-system-react-native';
import useMoneyAccountBalance from '../../../../UI/Money/hooks/useMoneyAccountBalance';
import useFiatFormatter from '../../../../UI/SimulationDetails/FiatDisplay/useFiatFormatter';
import { strings } from '../../../../../../locales/i18n';

const PROJECTION_YEARS = 5;

export interface ProjectedFiveYearBalanceProps {
amountFiat: string;
}

export function ProjectedFiveYearBalance({
amountFiat,
}: ProjectedFiveYearBalanceProps) {

Check warning on line 21 in app/components/Views/confirmations/components/projected-five-year-balance/projected-five-year-balance.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Mark the props of the component as read-only.

See more on https://sonarcloud.io/project/issues?id=metamask-mobile&issues=AZ3jnvGzDB_MdPLcHUsZ&open=AZ3jnvGzDB_MdPLcHUsZ&pullRequest=29607
const { vaultApyQuery } = useMoneyAccountBalance();
const formatFiat = useFiatFormatter();

const projected = useMemo(() => {
const apy = vaultApyQuery.data?.apy;
if (typeof apy !== 'number' || !isFinite(apy) || apy < 0) {
return null;
}

const amount = new BigNumber(amountFiat || '0');
if (!amount.isFinite()) {
return null;
}

const growthFactor = new BigNumber(1).plus(
new BigNumber(apy).dividedBy(100),
);
return amount.multipliedBy(growthFactor.pow(PROJECTION_YEARS));
}, [amountFiat, vaultApyQuery.data?.apy]);

if (vaultApyQuery.isLoading || projected === null) {
return null;
}

return (
<View testID="projected-five-year-balance">
<Text variant={TextVariant.BodyMd} color={TextColor.TextAlternative}>
{strings('confirm.custom_amount.projected_five_year_balance')}{' '}
<Text variant={TextVariant.BodyMd} color={TextColor.SuccessDefault}>
{formatFiat(projected)}
</Text>
</Text>
</View>
);
}
3 changes: 2 additions & 1 deletion locales/languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -7076,7 +7076,8 @@
"custom_amount": {
"buy_button": "Buy crypto",
"buy_predict": "Add funds to your wallet to use Predictions.",
"buy_perps": "Add funds to your wallet to use Perps."
"buy_perps": "Add funds to your wallet to use Perps.",
"projected_five_year_balance": "Projected 5-year balance:"
},
"unlimited": "Unlimited",
"all": "All",
Expand Down
Loading