Skip to content

Commit

Permalink
wallet connect fix (#5387)
Browse files Browse the repository at this point in the history
* dont allow connections w/o accounts

* allow connections w/o chains

* purge bad sessions

* switch migration infra

* format

* nit

* i18n + align

* rm debug

---------

Co-authored-by: skylarbarrera <skylar.barrera@gmail.com>
  • Loading branch information
benisgold and skylarbarrera committed Feb 8, 2024
1 parent 14f80d4 commit 79b7f99
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 85 deletions.
75 changes: 38 additions & 37 deletions src/components/walletconnect-list/WalletConnectV2ListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,16 @@ export function WalletConnectV2ListItem({ session, reload }: { session: SessionT
const { chains } = requiredNamespaces.eip155;
const eip155Account = namespaces.eip155?.accounts?.[0] || undefined;

if (!eip155Account || !chains || !chains.length) {
if (!eip155Account) {
const e = new RainbowError(`WalletConnectV2ListItem: unsupported namespace`);
logger.error(e);

// defensive, just for types, should never happen
throw e;
}

const [ns, rawChainId, address] = eip155Account?.split(':') as [string, string, string];
const chainIds = chains.map(chain => parseInt(chain.split(':')[1])).filter(isSupportedChain);
const address = eip155Account?.split(':')?.[2];
const chainIds = chains?.map(chain => parseInt(chain.split(':')[1]))?.filter(isSupportedChain) ?? [];

if (!address) {
const e = new RainbowError(`WalletConnectV2ListItem: could not parse address`);
Expand Down Expand Up @@ -206,41 +206,42 @@ export function WalletConnectV2ListItem({ session, reload }: { session: SessionT
</Centered>
</SessionRow>
</ColumnWithMargins>

<Box borderRadius={99} paddingVertical="8px" paddingHorizontal="12px" justifyContent="center">
<RadialGradient
{...radialGradientProps}
// @ts-expect-error overloaded props RadialGradient
borderRadius={99}
radius={600}
/>
<Inline alignVertical="center" alignHorizontal="justify">
<Inline alignVertical="center">
<Box style={{ flexDirection: 'row' }}>
{availableNetworks?.map((network, index) => {
return (
<Box
background="body (Deprecated)"
key={`availableNetwork-${network}`}
marginLeft={{ custom: index > 0 ? -4 : 0 }}
style={{
backgroundColor: colors.transparent,
zIndex: availableNetworks?.length - index,
borderRadius: 30,
}}
>
{network !== Network.mainnet ? (
<ChainBadge network={network} position="relative" size="small" />
) : (
<CoinIcon address={ETH_ADDRESS} size={20} symbol={ETH_SYMBOL} network={network} />
)}
</Box>
);
})}
</Box>
{!!availableNetworks?.length && (
<Box borderRadius={99} paddingVertical="8px" paddingHorizontal="12px" justifyContent="center">
<RadialGradient
{...radialGradientProps}
// @ts-expect-error overloaded props RadialGradient
borderRadius={99}
radius={600}
/>
<Inline alignVertical="center" alignHorizontal="justify">
<Inline alignVertical="center">
<Box style={{ flexDirection: 'row' }}>
{availableNetworks?.map((network, index) => {
return (
<Box
background="body (Deprecated)"
key={`availableNetwork-${network}`}
marginLeft={{ custom: index > 0 ? -4 : 0 }}
style={{
backgroundColor: colors.transparent,
zIndex: availableNetworks?.length - index,
borderRadius: 30,
}}
>
{network !== Network.mainnet ? (
<ChainBadge network={network} position="relative" size="small" />
) : (
<CoinIcon address={ETH_ADDRESS} size={20} symbol={ETH_SYMBOL} network={network} />
)}
</Box>
);
})}
</Box>
</Inline>
</Inline>
</Inline>
</Box>
</Box>
)}
</Row>
</Row>
</ContextMenuButton>
Expand Down
4 changes: 3 additions & 1 deletion src/languages/en_US.json
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,7 @@
"message": "Paste WalletConnect URI below",
"title": "New WalletConnect Session"
},
"none": "None",
"switch_network": "Switch Network",
"switch_wallet": "Switch Wallet",
"titles": {
Expand Down Expand Up @@ -2420,7 +2421,8 @@
"request_invalid": "The request contained invalid parameters. Please try again or contact Rainbow and/or dapp support teams.",
"eth_sign": "Rainbow does not support legacy eth_sign due to security concerns. \n Please contact Rainbow and/or dapp support teams if you have any questions.",
"request_unsupported_network": "The network specified in this request is not supported by Rainbow.",
"request_unsupported_methods": "The RPC method(s) specified in this request are not supported by Rainbow."
"request_unsupported_methods": "The RPC method(s) specified in this request are not supported by Rainbow.",
"no_accounts_found": "No accounts found in approved namespaces."
},
"dapp_warnings": {
"info_alert": {
Expand Down
2 changes: 2 additions & 0 deletions src/migrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { migrateNotificationSettingsToV2 } from '@/migrations/migrations/migrate
import { prepareDefaultNotificationGroupSettingsState } from '@/migrations/migrations/prepareDefaultNotificationGroupSettingsState';
import { changeLanguageKeys } from './migrations/changeLanguageKeys';
import { fixHiddenUSDC } from './migrations/fixHiddenUSDC';
import { purgeWcConnectionsWithoutAccounts } from './migrations/purgeWcConnectionsWithoutAccounts';

/**
* Local storage for migrations only. Should not be exported.
Expand All @@ -31,6 +32,7 @@ const migrations: Migration[] = [
migrateNotificationSettingsToV2(),
changeLanguageKeys(),
fixHiddenUSDC(),
purgeWcConnectionsWithoutAccounts(),
];

/**
Expand Down
19 changes: 19 additions & 0 deletions src/migrations/migrations/purgeWcConnectionsWithoutAccounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { disconnectSession, getAllActiveSessions } from '@/walletConnect';
import { Migration, MigrationName } from '../types';

export function purgeWcConnectionsWithoutAccounts(): Migration {
return {
name: MigrationName.purgeWcConnectionsWithoutAccounts,
async defer() {
const walletConnectV2Sessions = await getAllActiveSessions();
await Promise.all(
walletConnectV2Sessions.map(session => {
if (!session.namespaces.eip155.accounts.length) {
disconnectSession(session);
}
return Promise.resolve();
})
);
},
};
}
1 change: 1 addition & 0 deletions src/migrations/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export enum MigrationName {
prepareDefaultNotificationGroupSettingsState = 'migration_addDefaultNotificationGroupSettings',
changeLanguageKeys = 'migration_changeLanguageKeys',
fixHiddenUSDC = 'migration_fixHiddenUSDC',
purgeWcConnectionsWithoutAccounts = 'migration_purgeWcConnectionsWithoutAccounts',
}

export type Migration = {
Expand Down
114 changes: 67 additions & 47 deletions src/screens/WalletConnectApprovalSheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,8 @@ export default function WalletConnectApprovalSheet() {
const handleConnect = useCallback(() => {
handled.current = true;
goBack();
if (IS_IOS) {
navigate(Routes.WALLET_CONNECT_REDIRECT_SHEET, {
type: 'connect',
});
}
handleSuccess(true);
}, [handleSuccess, goBack, navigate]);
}, [handleSuccess, goBack]);

const handleCancel = useCallback(() => {
handled.current = true;
Expand Down Expand Up @@ -326,6 +321,71 @@ export default function WalletConnectApprovalSheet() {

const sheetHeight = type === WalletConnectApprovalSheetType.connect ? 408 : 438;

const renderNetworks = useCallback(() => {
if (isWalletConnectV2) {
if (!chainIds?.length) {
return (
<Box height={{ custom: 38 }} justifyContent="center" width="full">
<LabelText align="right">{lang.t('walletconnect.none')}</LabelText>
</Box>
);
} else {
return <NetworkPill chainIds={chainIds} />;
}
} else {
return (
<NetworkSwitcherParent
activeOpacity={0}
isMenuPrimaryAction
{...(android ? { onPress: onPressAndroid } : {})}
menuConfig={{
menuItems,
menuTitle: lang.t('walletconnect.available_networks'),
}}
onPressMenuItem={handleOnPressNetworksMenuItem}
useActionSheetFallback={false}
wrapNativeComponent={false}
>
<ButtonPressAnimation
style={{
alignItems: 'center',
flexDirection: 'row',
height: 38,
}}
>
<Centered marginRight={5}>
<ChainLogo
network={
type === WalletConnectApprovalSheetType.connect
? approvalNetworkInfo.value
: ethereumUtils.getNetworkFromChainId(Number(chainId))
}
/>
</Centered>
<LabelText align="right" numberOfLines={1}>
{`${
type === WalletConnectApprovalSheetType.connect
? approvalNetworkInfo.name
: ethereumUtils.getNetworkNameFromChainId(Number(chainId))
} ${type === WalletConnectApprovalSheetType.connect && menuItems.length > 1 ? '􀁰' : ''}`}
</LabelText>
</ButtonPressAnimation>
</NetworkSwitcherParent>
);
}
}, [
NetworkSwitcherParent,
approvalNetworkInfo.name,
approvalNetworkInfo.value,
chainId,
chainIds,
handleOnPressNetworksMenuItem,
isWalletConnectV2,
menuItems,
onPressAndroid,
type,
]);

return (
<Sheet>
{!Object.keys(meta).length ? (
Expand Down Expand Up @@ -437,47 +497,7 @@ export default function WalletConnectApprovalSheet() {
: lang.t(lang.l.walletconnect.approval_sheet_network)}
</SwitchText>
</Flex>
{isWalletConnectV2 ? (
<NetworkPill chainIds={chainIds} />
) : (
<NetworkSwitcherParent
activeOpacity={0}
isMenuPrimaryAction
{...(android ? { onPress: onPressAndroid } : {})}
menuConfig={{
menuItems,
menuTitle: lang.t('walletconnect.available_networks'),
}}
onPressMenuItem={handleOnPressNetworksMenuItem}
useActionSheetFallback={false}
wrapNativeComponent={false}
>
<ButtonPressAnimation
style={{
alignItems: 'center',
flexDirection: 'row',
height: 38,
}}
>
<Centered marginRight={5}>
<ChainLogo
network={
type === WalletConnectApprovalSheetType.connect
? approvalNetworkInfo.value
: ethereumUtils.getNetworkFromChainId(Number(chainId))
}
/>
</Centered>
<LabelText align="right" numberOfLines={1}>
{`${
type === WalletConnectApprovalSheetType.connect
? approvalNetworkInfo.name
: ethereumUtils.getNetworkNameFromChainId(Number(chainId))
} ${type === WalletConnectApprovalSheetType.connect && menuItems.length > 1 ? '􀁰' : ''}`}
</LabelText>
</ButtonPressAnimation>
</NetworkSwitcherParent>
)}
{renderNetworks()}
</RDSColumn>
</Columns>
</Box>
Expand Down
13 changes: 13 additions & 0 deletions src/walletConnect/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@ export function getApprovedNamespaces(props: Parameters<typeof buildApprovedName
try {
const namespaces = buildApprovedNamespaces(props);

if (!namespaces.eip155.accounts.length) {
return {
success: false,
result: undefined,
error: new Error(lang.t(T.errors.no_accounts_found)),
};
}

return {
success: true,
result: namespaces,
Expand Down Expand Up @@ -484,6 +492,11 @@ export async function onSessionProposal(proposal: Web3WalletTypes.SessionProposa
});

maybeGoBackAndClearHasPendingRedirect();
if (IS_IOS) {
Navigation.handleAction(Routes.WALLET_CONNECT_REDIRECT_SHEET, {
type: 'connect',
});
}
} else {
await rejectProposal({
proposal,
Expand Down

0 comments on commit 79b7f99

Please sign in to comment.