Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Aggregated multichain balance (Flask) #30516

Open
wants to merge 74 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
90e39b5
feat: Integrate SPL tokens
gambinish Feb 14, 2025
c31dafc
chore: Cleanup token-list
gambinish Feb 14, 2025
fa12cf8
chore: Remove some hard coded values
gambinish Feb 14, 2025
b0e5203
chore: Cleanup
gambinish Feb 14, 2025
3fb2ff5
chore: Remove hardcoded assetId
gambinish Feb 14, 2025
bdd6eb5
chore: Handle native token
gambinish Feb 14, 2025
d2629e1
fix: Dont render network text when percent change is undefined
gambinish Feb 14, 2025
f4c0201
fix: Render token balance in primary display cell
gambinish Feb 14, 2025
f47d98c
fix: Replace fallback
gambinish Feb 14, 2025
1b28ad4
chore: Remove parsedAssetId util in favor of common metamask util
gambinish Feb 14, 2025
709f551
fix: Cleanup
gambinish Feb 14, 2025
0f93bb1
chore: Integrate token rates
gambinish Feb 14, 2025
ca0a3c8
fix: fix currentChain selector
sahar-fehri Feb 18, 2025
74545f2
fix: fix path
sahar-fehri Feb 18, 2025
ca594a4
fix: fix lint
sahar-fehri Feb 18, 2025
728780e
fix: fix
sahar-fehri Feb 18, 2025
de10f52
fix: fix snap id
sahar-fehri Feb 18, 2025
da9c3e4
fix: refactor getTokenBalancesEvm to take address as arg
sahar-fehri Feb 18, 2025
e240ae7
fix: fix mock
sahar-fehri Feb 18, 2025
fd94fc2
fix: fix mock
sahar-fehri Feb 18, 2025
89ab322
fix: Hardcode multichain cached balance when cached balance is zero
gambinish Feb 19, 2025
08d5b4b
Merge branch 'feat/spl-token-rates-v3' of github.com:MetaMask/metamas…
gambinish Feb 19, 2025
ccfb092
chore: Cleanup
gambinish Feb 19, 2025
244bec2
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 19, 2025
372d89f
refactor: Begin breaking out business logic from useMultiChainAssets …
gambinish Feb 19, 2025
4183f65
Merge branch 'feat/spl-token-rates-v3' of github.com:MetaMask/metamas…
gambinish Feb 19, 2025
dd2288e
chore: Remove useNativeTokenBalance hook
gambinish Feb 19, 2025
c308dca
fix: Lint tsc and cleanup
gambinish Feb 19, 2025
a001ab6
fix: fix reading property of undefined
sahar-fehri Feb 19, 2025
3262f5a
fix: fix
sahar-fehri Feb 19, 2025
b8f4670
fix: fix aggregated balance
salimtb Feb 19, 2025
5f95596
fix: fix lint
sahar-fehri Feb 19, 2025
d9d551c
fix: fix unit tests
salimtb Feb 19, 2025
0e92e31
fix: fix unit tests
salimtb Feb 19, 2025
c77bd14
fix: remove 0 fallback
salimtb Feb 19, 2025
b8984bd
fix: fix e2e tests
salimtb Feb 19, 2025
26240ae
fix: fix and cleanup
salimtb Feb 19, 2025
bd22ea7
fix: fix and clean up
salimtb Feb 19, 2025
99a1220
Update ui/selectors/selectors.js
gambinish Feb 19, 2025
b1da5f6
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 19, 2025
89a90bb
fix: fix lint
sahar-fehri Feb 19, 2025
0e3772f
fix: Unit test
gambinish Feb 19, 2025
cb4c834
fix: Differentiate between native and non native non-evm tokens
gambinish Feb 19, 2025
2d1f856
fix: nativeRate is keyed by assetId, not ticker
gambinish Feb 19, 2025
c8dbe2c
fix: Update isNative boolean to look for slip44, flip boolean logic
gambinish Feb 19, 2025
37ce8c6
fix: Remove local snap proxy
gambinish Feb 19, 2025
d667bcf
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 19, 2025
44c89fa
chore: Move selectors to ts file
gambinish Feb 20, 2025
6d791cc
refactor: Remove custom mappings in favor of snap API metadata
gambinish Feb 20, 2025
af25b3d
fix: Cleanup
gambinish Feb 20, 2025
adb3ecb
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 20, 2025
4e3e9e1
fix: refactor getTokenBalancesEvm selector to use accountAddress arg
sahar-fehri Feb 20, 2025
7cea61b
chore: fix native fiat balance display in asset list to match coin-ov…
sahar-fehri Feb 20, 2025
d6e1a24
fix: lint
sahar-fehri Feb 20, 2025
cd357c0
fix: return image for native evm token
sahar-fehri Feb 20, 2025
af61ab5
Merge branch 'main' into feat/spl-token-rates-v3
sahar-fehri Feb 20, 2025
4c6583f
fix: use parseCaipAssetType for parsing
sahar-fehri Feb 20, 2025
5d71931
fix: fix assetsNamespace
sahar-fehri Feb 20, 2025
e308d58
fix: replace legacy rate
salimtb Feb 21, 2025
fe24341
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 21, 2025
b274717
fix: Temporarily skip failing BTC unit test
gambinish Feb 21, 2025
3cac7ba
Merge branch 'main' into feat/spl-token-rates-v3
gambinish Feb 21, 2025
0c820cf
fix: Remove circular deps
gambinish Feb 21, 2025
6c22c96
Merge branch 'feat/spl-token-rates-v3' of github.com:MetaMask/metamas…
gambinish Feb 21, 2025
27874f7
fix: Unit test
gambinish Feb 22, 2025
016a843
feat: Add aggregated multichain balance
gambinish Feb 22, 2025
ba3df9d
fix: Lint file import order
gambinish Feb 22, 2025
4e46673
fix: Lint import order
gambinish Feb 22, 2025
7b248a6
chore: Remove unused vars
gambinish Feb 24, 2025
d419935
fix: zeroBalanceAssetFallback constant
gambinish Feb 24, 2025
97cc5f1
chore: Merge main, address conflicts
gambinish Feb 24, 2025
8ef3cff
fix: Update unit tests for non-evm aggregated balance
gambinish Feb 25, 2025
55f485e
fix: Mock in router test
gambinish Feb 25, 2025
5823363
fix: Optional chain to fail gracefully when app not yet loaded
gambinish Feb 25, 2025
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
166 changes: 100 additions & 66 deletions ui/components/app/wallet-overview/coin-overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ import { useAccountTotalCrossChainFiatBalance } from '../../../hooks/useAccountT

import { useGetFormattedTokensPerChain } from '../../../hooks/useGetFormattedTokensPerChain';
import { useMultichainSelector } from '../../../hooks/useMultichainSelector';
import { AggregatedBalance } from '../../ui/aggregated-balance/aggregated-balance';
import WalletOverview from './wallet-overview';
import CoinButtons from './coin-buttons';
import { AggregatedPercentageOverview } from './aggregated-percentage-overview';
Expand All @@ -99,6 +100,92 @@ export type CoinOverviewProps = {
isSigningEnabled: boolean;
};

export const LegacyAggregatedBalance = ({
classPrefix,
account,
balance,
balanceIsCached,
handleSensitiveToggle,
}: {
classPrefix: string;
account: InternalAccount;
balance: string;
balanceIsCached: boolean;
handleSensitiveToggle: () => void;
}) => {
const isTokenNetworkFilterEqualCurrentNetwork = useSelector(
getIsTokenNetworkFilterEqualCurrentNetwork,
);
const shouldHideZeroBalanceTokens = useSelector(
getShouldHideZeroBalanceTokens,
);
const allChainIDs = useSelector(getChainIdsToPoll) as string[];
const shouldShowFiat = useMultichainSelector(
getMultichainShouldShowFiat,
account,
);
const { privacyMode, showNativeTokenAsMainBalance } =
useSelector(getPreferences);
const isTestnet = useSelector(getIsTestnet);

const { formattedTokensWithBalancesPerChain } = useGetFormattedTokensPerChain(
account,
shouldHideZeroBalanceTokens,
isTokenNetworkFilterEqualCurrentNetwork,
allChainIDs,
);

const { totalFiatBalance } = useAccountTotalCrossChainFiatBalance(
account,
formattedTokensWithBalancesPerChain,
);

const isNotAggregatedFiatBalance =
!shouldShowFiat || showNativeTokenAsMainBalance || isTestnet;

let balanceToDisplay;
if (isNotAggregatedFiatBalance) {
balanceToDisplay = balance;
} else {
balanceToDisplay = totalFiatBalance;
}

if (!balanceToDisplay) {
return <Spinner className="loading-overlay__spinner" />;
}
return (
<>
<UserPreferencedCurrencyDisplay
style={{ display: 'contents' }}
account={account}
className={classnames(`${classPrefix}-overview__primary-balance`, {
[`${classPrefix}-overview__cached-balance`]: balanceIsCached,
})}
data-testid={`${classPrefix}-overview__primary-currency`}
value={balanceToDisplay}
type={PRIMARY}
ethNumberOfDecimals={4}
hideTitle
shouldCheckShowNativeToken
isAggregatedFiatOverviewBalance={
!showNativeTokenAsMainBalance && !isTestnet && shouldShowFiat
}
privacyMode={privacyMode}
/>
<ButtonIcon
color={IconColor.iconAlternative}
marginLeft={2}
size={ButtonIconSize.Md}
onClick={handleSensitiveToggle}
iconName={privacyMode ? IconName.EyeSlash : IconName.Eye}
justifyContent={JustifyContent.center}
ariaLabel="Sensitive toggle"
data-testid="sensitive-toggle"
/>
</>
);
};

export const CoinOverview = ({
account,
balance,
Expand Down Expand Up @@ -149,36 +236,7 @@ export const CoinOverview = ({
getIsTokenNetworkFilterEqualCurrentNetwork,
);

const shouldHideZeroBalanceTokens = useSelector(
getShouldHideZeroBalanceTokens,
);
const allChainIDs = useSelector(getChainIdsToPoll);
const { formattedTokensWithBalancesPerChain } = useGetFormattedTokensPerChain(
account,
shouldHideZeroBalanceTokens,
isTokenNetworkFilterEqualCurrentNetwork,
allChainIDs,
);
const { totalFiatBalance } = useAccountTotalCrossChainFiatBalance(
account,
formattedTokensWithBalancesPerChain,
);

const shouldShowFiat = useMultichainSelector(
getMultichainShouldShowFiat,
account,
);

const isEvm = useSelector(getMultichainIsEvm);
const isNotAggregatedFiatBalance =
!shouldShowFiat || showNativeTokenAsMainBalance || isTestnet || !isEvm;

let balanceToDisplay;
if (isNotAggregatedFiatBalance) {
balanceToDisplay = balance;
} else {
balanceToDisplay = totalFiatBalance;
}

const tokensMarketData = useSelector(getTokensMarketData);
const [isOpen, setIsOpen] = useState(true);
Expand Down Expand Up @@ -296,44 +354,20 @@ export const CoinOverview = ({
onMouseEnter={handleMouseEnter}
ref={setBoxRef}
>
{balanceToDisplay ? (
<>
<UserPreferencedCurrencyDisplay
style={{ display: 'contents' }}
account={account}
className={classnames(
`${classPrefix}-overview__primary-balance`,
{
[`${classPrefix}-overview__cached-balance`]:
balanceIsCached,
},
)}
data-testid={`${classPrefix}-overview__primary-currency`}
value={balanceToDisplay}
type={PRIMARY}
ethNumberOfDecimals={4}
hideTitle
shouldCheckShowNativeToken
isAggregatedFiatOverviewBalance={
!showNativeTokenAsMainBalance &&
!isTestnet &&
shouldShowFiat
}
privacyMode={privacyMode}
/>
<ButtonIcon
color={IconColor.iconAlternative}
marginLeft={2}
size={ButtonIconSize.Md}
onClick={handleSensitiveToggle}
iconName={privacyMode ? IconName.EyeSlash : IconName.Eye}
justifyContent={JustifyContent.center}
ariaLabel="Sensitive toggle"
data-testid="sensitive-toggle"
/>
</>
{isEvm ? (
<LegacyAggregatedBalance
classPrefix={classPrefix}
account={account}
balance={balance}
balanceIsCached={balanceIsCached}
handleSensitiveToggle={handleSensitiveToggle}
/>
) : (
<Spinner className="loading-overlay__spinner" />
<AggregatedBalance
classPrefix={classPrefix}
balanceIsCached={balanceIsCached}
handleSensitiveToggle={handleSensitiveToggle}
/>
)}
{balanceIsCached && (
<span className={`${classPrefix}-overview__cached-star`}>
Expand Down
13 changes: 12 additions & 1 deletion ui/components/app/wallet-overview/non-evm-overview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ const mockBuyableChainsWithBtc = [...mockBuyableChainsWithoutBtc, mockBtcChain];

const mockMetamaskStore = {
...mockState.metamask,
accountsAssets: {
[mockNonEvmAccount.id]: [MultichainNativeAssets.BITCOIN],
},
internalAccounts: {
accounts: {
[mockNonEvmAccount.id]: mockNonEvmAccount,
Expand All @@ -103,7 +106,7 @@ const mockMetamaskStore = {
},
// (Multichain) RatesController
fiatCurrency: 'usd',
rates: {
conversionRates: {
[Cryptocurrency.Btc]: {
conversionRate: '1.000',
conversionDate: 0,
Expand All @@ -125,6 +128,9 @@ const mockRampsStore = {
function getStore(state?: Record<string, unknown>) {
return configureMockStore([thunk])({
metamask: mockMetamaskStore,
localeMessages: {
currentLocale: 'en',
},
ramps: mockRampsStore,
...state,
});
Expand Down Expand Up @@ -178,7 +184,9 @@ describe('NonEvmOverview', () => {
preferences: {
showNativeTokenAsMainBalance: false,
tokenNetworkFilter: {},
privacyMode: false,
},
currentCurrency: 'usd',
conversionRates: {
[MultichainNativeAssets.BITCOIN]: {
rate: '1',
Expand All @@ -201,6 +209,9 @@ describe('NonEvmOverview', () => {
...mockMetamaskStore,
// The balances won't be available
balances: {},
accountsAssets: {
[mockNonEvmAccount.id]: [],
},
},
}),
);
Expand Down
124 changes: 124 additions & 0 deletions ui/components/ui/aggregated-balance/aggregated-balance.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import React from 'react';
import { useSelector } from 'react-redux';
import classnames from 'classnames';
import {
AlignItems,
Display,
FlexWrap,
IconColor,
JustifyContent,
TextVariant,
} from '../../../helpers/constants/design-system';
import {
Box,
ButtonIcon,
ButtonIconSize,
IconName,
SensitiveText,
} from '../../component-library';
import {
getCurrentCurrency,
getTokenBalances,
} from '../../../ducks/metamask/metamask';
import {
getAccountAssets,
getMultichainAggregatedBalance,
getMultichainNativeTokenBalance,
} from '../../../selectors/assets';
import { getPreferences, getSelectedInternalAccount } from '../../../selectors';
import { formatWithThreshold } from '../../app/assets/util/formatWithThreshold';
import { getIntlLocale } from '../../../ducks/locale/locale';
import Spinner from '../spinner';

export const AggregatedBalance = ({
classPrefix,
balanceIsCached,
handleSensitiveToggle,
}: {
classPrefix: string;
balanceIsCached: boolean;
handleSensitiveToggle: () => void;
}) => {
const { privacyMode, showNativeTokenAsMainBalance } =
useSelector(getPreferences);
const locale = useSelector(getIntlLocale);
const balances = useSelector(getTokenBalances);
const assets = useSelector(getAccountAssets);
const selectedAccount = useSelector(getSelectedInternalAccount);
const currentCurrency = useSelector(getCurrentCurrency);
const multichainAggregatedBalance = useSelector((state) =>
getMultichainAggregatedBalance(state, selectedAccount),
);
const multichainNativeTokenBalance = useSelector((state) =>
getMultichainNativeTokenBalance(state, selectedAccount),
);

const formattedFiatDisplay = formatWithThreshold(
multichainAggregatedBalance,
0.01,
locale,
{
style: 'currency',
currency: currentCurrency.toUpperCase(),
},
);

const formattedTokenDisplay = formatWithThreshold(
multichainNativeTokenBalance.amount,
0.00001,
locale,
{
minimumFractionDigits: 5,
maximumFractionDigits: 5,
},
).replace(/(\.0+|(?<=\.\d+)0+)$/u, ''); // strip trailing zeros

if (!balances || !assets[selectedAccount.id]?.length) {
return <Spinner className="loading-overlay__spinner" />;
}

return (
<>
<Box
className={classnames(`${classPrefix}-overview__primary-balance`, {
[`${classPrefix}-overview__cached-balance`]: balanceIsCached,
})}
data-testid={`${classPrefix}-overview__primary-currency`}
display={Display.Flex}
alignItems={AlignItems.center}
flexWrap={FlexWrap.Wrap}
>
<SensitiveText
ellipsis
variant={TextVariant.inherit}
isHidden={privacyMode}
data-testid="account-value-and-suffix"
>
{showNativeTokenAsMainBalance
? formattedTokenDisplay
: formattedFiatDisplay}
</SensitiveText>
<SensitiveText
marginInlineStart={privacyMode ? 0 : 1}
variant={TextVariant.inherit}
isHidden={privacyMode}
>
{showNativeTokenAsMainBalance
? multichainNativeTokenBalance.unit
: currentCurrency.toUpperCase()}
</SensitiveText>

<ButtonIcon
color={IconColor.iconAlternative}
marginLeft={2}
size={ButtonIconSize.Md}
onClick={handleSensitiveToggle}
iconName={privacyMode ? IconName.EyeSlash : IconName.Eye}
justifyContent={JustifyContent.center}
ariaLabel="Sensitive toggle"
data-testid="sensitive-toggle"
/>
</Box>
</>
);
};
3 changes: 3 additions & 0 deletions ui/pages/routes/routes.component.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ describe('toast display', () => {
},
selectedAccount: selectedAccountId ?? mockAccount.id,
},
accountsAssets: {
[selectedAccountId ?? mockAccount.id]: [],
},
subjects: {
[mockOrigin]: {
permissions: {
Expand Down
Loading
Loading