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(snaps): AccountSelector Snap UI component #30323

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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 @@ -6,13 +6,19 @@ import {
} from '@metamask/approval-controller';
import { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
import { NotificationListUpdatedEvent } from '@metamask/notification-services-controller/notification-services';
import {
AccountsControllerGetAccountByAddressAction,
AccountsControllerGetSelectedMultichainAccountAction,
} from '@metamask/accounts-controller';

type Actions =
| MaybeUpdateState
| TestOrigin
| HasApprovalRequest
| AcceptRequest
| GetSnap;
| GetSnap
| AccountsControllerGetSelectedMultichainAccountAction
| AccountsControllerGetAccountByAddressAction;

type Events = NotificationListUpdatedEvent;

Expand All @@ -39,6 +45,8 @@ export function getSnapInterfaceControllerMessenger(
`ApprovalController:hasRequest`,
`ApprovalController:acceptRequest`,
`SnapController:get`,
`AccountsController:getSelectedMultichainAccount`,
`AccountsController:getAccountByAddress`,
],
allowedEvents: ['NotificationServicesController:notificationsListUpdated'],
});
Expand Down
2 changes: 1 addition & 1 deletion builds.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ buildTypes:
- ALLOW_LOCAL_SNAPS: true
- REQUIRE_SNAPS_ALLOWLIST: false
- REJECT_INVALID_SNAPS_PLATFORM_VERSION: false
- IFRAME_EXECUTION_ENVIRONMENT_URL: https://execution.metamask.io/iframe/6.14.0/index.html
- IFRAME_EXECUTION_ENVIRONMENT_URL: http://localhost:6363
- SUPPORT_LINK: https://support.metamask.io/
- SUPPORT_REQUEST_LINK: https://support.metamask.io/
- INFURA_ENV_KEY_REF: INFURA_FLASK_PROJECT_ID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { SnapUIMarkdown } from '../snaps/snap-ui-markdown';
import { SnapUIRadioGroup } from '../snaps/snap-ui-radio-group';
import { SnapUISelector } from '../snaps/snap-ui-selector';
import { SnapUITooltip } from '../snaps/snap-ui-tooltip';
import { SnapUIAccountSelector } from '../snaps/snap-ui-account-selector';
///: BEGIN:ONLY_INCLUDE_IF(keyring-snaps)
import { SnapAccountErrorMessage } from '../../../pages/confirmations/components/snap-account-error-message';
import { SnapAccountSuccessMessage } from '../../../pages/confirmations/components/snap-account-success-message';
Expand Down Expand Up @@ -89,6 +90,7 @@ export const safeComponentList = {
Popover,
Preloader,
SnapDelineator,
SnapUIAccountSelector,
SnapUIAddress,
SnapUIAvatar,
SnapUIBanner,
Expand Down Expand Up @@ -127,5 +129,6 @@ export const safeComponentList = {
SnapAccountRedirect,
SnapAccountSuccessMessage,
SnapAuthorshipHeader,

///: END:ONLY_INCLUDE_IF
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './snap-ui-account-selector';
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
import React, { FunctionComponent } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
CaipAccountId,
CaipChainId,
KnownCaipNamespace,
parseCaipChainId,
} from '@metamask/utils';
import { InternalAccount } from '@metamask/keyring-internal-api';

import { AccountSelectorValue, State } from '@metamask/snaps-sdk';
import { EthScope } from '@metamask/keyring-api';
import { SnapUISelector } from '../snap-ui-selector';
import {
getInternalAccounts,
getShowFiatInTestnets,
getUseBlockie,
} from '../../../../selectors';

import { TEST_NETWORK_IDS } from '../../../../../shared/constants/network';
import { MultichainNetworks } from '../../../../../shared/constants/multichain/networks';
import {
AlignItems,
BlockSize,
BorderColor,
Display,
FlexDirection,
TextAlign,
TextColor,
TextVariant,
} from '../../../../helpers/constants/design-system';
import {
AvatarAccount,
AvatarAccountSize,
AvatarAccountVariant,
AvatarToken,
AvatarTokenSize,
Box,
Text,
} from '../../../component-library';
import { shortenAddress } from '../../../../helpers/utils/util';
import { normalizeSafeAddress } from '../../../../../app/scripts/lib/multichain/address';
import UserPreferencedCurrencyDisplay from '../../user-preferenced-currency-display/user-preferenced-currency-display.component';
import { PRIMARY } from '../../../../helpers/constants/common';
import { useMultichainAccountBalances } from '../../../../hooks/snaps/useMultichainTotalCrossChainFiatBalance';
import { AvatarGroup } from '../../../multichain';
import { setSelectedInternalAccount } from '../../../../store/actions';
import { useSnapInterfaceContext } from '../../../../contexts/snaps';

export function createAddressList(
address: string,
scopes: CaipChainId[],
): CaipAccountId[] {
return scopes.map((scope) => {
return `${scope}:${address}` as CaipAccountId;
});
}

export function createChainIdList(
accountScopes: CaipChainId[],
requestedChainIds?: CaipChainId[],
) {
return accountScopes.reduce((acc, scope) => {
if (scope === EthScope.Eoa && requestedChainIds) {
const targetChainIds = requestedChainIds.filter((chainId) => {
const { namespace } = parseCaipChainId(chainId);

return namespace === KnownCaipNamespace.Eip155;
});

return [...acc, ...targetChainIds];
}

if (requestedChainIds?.includes(scope)) {
return [...acc, scope];
}

if (!requestedChainIds) {
return [...acc, scope];
}

return acc;
}, [] as CaipChainId[]);
}

export type SnapUIAccountSelectorOptionProps = {
account: InternalAccount;
chainIds?: CaipChainId[];
};

export const SnapUIAccountSelectorOption: FunctionComponent<
SnapUIAccountSelectorOptionProps
> = ({ account, chainIds }) => {
const useBlockie = useSelector(getUseBlockie);
const showFiatInTestnets = useSelector(getShowFiatInTestnets);

const { totalFiatBalance, assets } = useMultichainAccountBalances(
account,
chainIds,
);

const assetsAvatars = assets.map((asset) => ({ avatarValue: asset.iconUrl }));

const isOnlyMainnet = assets.every((asset) => {
const { chainId } = asset;
const { namespace, reference } = parseCaipChainId(chainId);
if (namespace === KnownCaipNamespace.Eip155) {
return !(TEST_NETWORK_IDS as string[]).includes(
parseInt(reference, 16).toString(),
);
}

return (
chainId !== MultichainNetworks.BITCOIN_TESTNET &&
chainId !== MultichainNetworks.SOLANA_TESTNET &&
chainId !== MultichainNetworks.SOLANA_DEVNET
);
});

const shouldShowFiat =
isOnlyMainnet || (!isOnlyMainnet && showFiatInTestnets);

const amountToDisplay = shouldShowFiat
? totalFiatBalance
: assets[0].string ?? '0';

return (
<Box
display={Display.Flex}
width={BlockSize.Full}
alignItems={AlignItems.center}
>
<AvatarAccount
borderColor={BorderColor.transparent}
size={AvatarAccountSize.Md}
address={account.address}
variant={
useBlockie
? AvatarAccountVariant.Blockies
: AvatarAccountVariant.Jazzicon
}
marginInlineEnd={2}
/>
<Box
display={Display.Flex}
flexDirection={FlexDirection.Column}
width={BlockSize.Full}
marginRight={2}
>
<Text variant={TextVariant.bodyMdMedium} ellipsis>
{account.metadata.name}
</Text>
<Text variant={TextVariant.bodySm} color={TextColor.textAlternative}>
{shortenAddress(normalizeSafeAddress(account.address))}
</Text>
</Box>
<Box
display={Display.Flex}
flexDirection={FlexDirection.Column}
height={BlockSize.Full}
>
<Box>
<Text
variant={TextVariant.bodySm}
color={TextColor.textAlternative}
textAlign={TextAlign.End}
>
<UserPreferencedCurrencyDisplay
account={account}
value={amountToDisplay}
type={PRIMARY}
showFiat={shouldShowFiat}
textProps={{ color: TextColor.textAlternative }}
ethNumberOfDecimals={3}
isAggregatedFiatOverviewBalance={true}
style={{ flexWrap: 'nowrap' }}
/>
</Text>
</Box>
<Box style={{ alignSelf: 'flex-end' }}>
{assets.length > 1 && (
<AvatarGroup members={assetsAvatars} limit={3} />
)}
{assets.length === 1 && (
<AvatarToken
src={assets[0].iconUrl}
name={assets[0].symbol}
size={AvatarTokenSize.Xs}
/>
)}
</Box>
</Box>
</Box>
);
};

export type SnapUIAccountSelectorProps = {
name: string;
label?: string;
form?: string;
hideExternalAccounts?: boolean;
chainIds?: CaipChainId[];
switchSelectedAccount?: boolean;
error?: string;
disabled?: boolean;
};

export const SnapUIAccountSelector: FunctionComponent<
SnapUIAccountSelectorProps
> = ({ chainIds, switchSelectedAccount, hideExternalAccounts, ...props }) => {
const { snapId } = useSnapInterfaceContext();
const dispatch = useDispatch();
const accounts = useSelector(getInternalAccounts);

const ownedAccounts = accounts.filter(
(account) => account.metadata.snap?.id === snapId,
);

const filteredAccounts = (
hideExternalAccounts ? ownedAccounts : accounts
).filter((account) => {
const filteredChainIds = createChainIdList(account.scopes, chainIds);

return filteredChainIds.length > 0;
});

const options = filteredAccounts.map((account) => ({
value: {
accountId: account.id,
addresses: createAddressList(
account.address,
createChainIdList(account.scopes, chainIds),
),
},
disabled: false,
}));

const optionComponents = filteredAccounts.map((account) => (
<SnapUIAccountSelectorOption account={account} chainIds={chainIds} />
));

const findSelectedOptionIndex = (selectedOptionValue: State | undefined) =>
options.findIndex(
(option) =>
option.value.accountId ===
(selectedOptionValue as AccountSelectorValue).accountId,
);

const handleSelect = (value: State) => {
if (switchSelectedAccount) {
dispatch(
setSelectedInternalAccount((value as AccountSelectorValue).accountId),
);
}
};

return (
<SnapUISelector
title={'Select account'}
options={options}
{...props}
optionComponents={optionComponents}
findSelectedOptionIndex={findSelectedOptionIndex}
onSelect={handleSelect}
/>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { AccountSelectorElement } from '@metamask/snaps-sdk/jsx';
import { UIComponentFactory } from './types';

export const accountSelector: UIComponentFactory<AccountSelectorElement> = ({
element,
form,
}) => {
return {
element: 'SnapUIAccountSelector',
props: {
id: element.props.name,
name: element.props.name,
hideExternalAccounts: element.props.hideExternalAccounts,
chainIds: element.props.chainIds,
switchSelectedAccount: element.props.switchSelectedAccount,
form,
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { section } from './section';
import { avatar } from './avatar';
import { banner } from './banner';
import { skeleton } from './skeleton';
import { accountSelector } from './accountSelector';

export const COMPONENT_MAPPING = {
Box: box,
Expand Down Expand Up @@ -62,4 +63,5 @@ export const COMPONENT_MAPPING = {
Section: section,
Banner: banner,
Skeleton: skeleton,
AccountSelector: accountSelector,
};
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const SnapUIRendererComponent = ({
// We do this to avoid useless re-renders.
(oldState, newState) => isEqual(oldState.content, newState.content),
);

const rawContent = interfaceState?.content;
const content =
rawContent?.type === 'Container' || !rawContent
Expand Down
Loading