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
16 changes: 13 additions & 3 deletions components/Send/SendForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Max from '@/components/Max';
import RenderTokenIcon from '@/components/RenderTokenIcon';
import { Button } from '@/components/ui/button';
import { Text } from '@/components/ui/text';
import { CHAIN_NAMES } from '@/constants/chains';
import { SEND_MODAL } from '@/constants/modals';
import { TRACKING_EVENTS } from '@/constants/tracking-events';
import { useWalletTokens } from '@/hooks/useWalletTokens';
Expand Down Expand Up @@ -233,9 +234,18 @@ const SendForm: React.FC<SendFormProps> = ({ onNext }) => {
})}
size={28}
/>
<Text className="text-lg font-semibold">
{selectedToken.contractTickerSymbol}
</Text>
<View>
<Text className="text-lg font-semibold leading-tight">
{selectedToken.contractTickerSymbol}
</Text>
{/* The send executes on this chain; USDC on Base and USDC on
Fuse otherwise look identical here. */}
{CHAIN_NAMES[selectedToken.chainId] ? (
<Text className="text-xs leading-tight opacity-50">
on {CHAIN_NAMES[selectedToken.chainId]}
</Text>
) : null}
</View>
<ChevronDown size={20} color="white" />
</>
) : (
Expand Down
150 changes: 136 additions & 14 deletions components/Send/SendReview.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import React, { useState } from 'react';
import { Control } from 'react-hook-form';
import { ActivityIndicator, View } from 'react-native';
import { ActivityIndicator, Pressable, View } from 'react-native';
import Toast from 'react-native-toast-message';
import { Image } from 'expo-image';
import { useQuery } from '@tanstack/react-query';
import { Address } from 'viem';
import { useShallow } from 'zustand/react/shallow';

Expand All @@ -11,8 +12,10 @@ import Wallet from '@/assets/images/wallet';
import NeedHelp from '@/components/NeedHelp';
import RenderTokenIcon from '@/components/RenderTokenIcon';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Text } from '@/components/ui/text';
import { getBridgeChain } from '@/constants/bridge';
import { CHAIN_NAMES } from '@/constants/chains';
import { SEND_MODAL } from '@/constants/modals';
import { TRACKING_EVENTS } from '@/constants/tracking-events';
import { useActivity } from '@/hooks/useActivity';
Expand All @@ -21,33 +24,76 @@ import { useIsContract } from '@/hooks/useIsContract';
import useSend from '@/hooks/useSend';
import { useTotp } from '@/hooks/useTotp';
import { track } from '@/lib/analytics';
import { fetchAddressBook } from '@/lib/api';
import { sanitizeTechnicalMessage, showFailureSheet } from '@/lib/errors';
import getTokenIcon from '@/lib/getTokenIcon';
import {
BRIDGE_PAYMASTER_RECIPIENT_ERROR,
isBridgePaymasterAddress,
} from '@/lib/protocolAddresses';
import { isProtocolAddress, PROTOCOL_ADDRESS_RECIPIENT_ERROR } from '@/lib/protocolAddresses';
import { getExpectedRecipientChainId } from '@/lib/sendRecipients';
import { Status, TokenType } from '@/lib/types';
import { cn, eclipseAddress, formatNumber } from '@/lib/utils';
import { cn, eclipseAddress, formatNumber, withRefreshToken } from '@/lib/utils';
import { getChain } from '@/lib/wagmi';
import { useSendStore } from '@/store/useSendStore';

import ContractAddressWarning from './ContractAddressWarning';
import SaveContact from './SaveContact';

const chainName = (chainId: number) =>
CHAIN_NAMES[chainId] ?? getChain(chainId)?.name ?? `chain ${chainId}`;

const SendReview: React.FC = () => {
const { selectedToken, amount, address, name, setTransaction, setModal, setName } = useSendStore(
const {
selectedToken,
amount,
address,
name,
recipientChainId,
setTransaction,
setModal,
setName,
} = useSendStore(
useShallow(state => ({
selectedToken: state.selectedToken,
amount: state.amount,
address: state.address,
name: state.name,
recipientChainId: state.recipientChainId,
setTransaction: state.setTransaction,
setModal: state.setModal,
setName: state.setName,
})),
);
const { refetchAll } = useActivity();
const { activities, refetchAll } = useActivity();
const {
data: addressBook,
isError: isAddressBookError,
isFetching: isAddressBookFetching,
refetch: refetchAddressBook,
} = useQuery({
queryKey: ['address-book'],
queryFn: () => withRefreshToken(() => fetchAddressBook()),
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
});
// A regular send always executes on the token's chain. When this recipient is
// known on another network (picked in the bridge flow, a saved contact's, or
// the last send's), say so and make the user confirm before sending.
const expectedChainId = getExpectedRecipientChainId(
address,
activities,
addressBook ?? [],
recipientChainId,
);
const isNetworkMismatch =
!!selectedToken && !!expectedChainId && expectedChainId !== selectedToken.chainId;
// Without the address book a saved contact's network is unknown, and an empty
// list would read as "no expected network" and skip the check. A picked
// network doesn't need it. Hold Send while it loads; if it fails, offer a
// retry and make the user confirm the network themselves.
const isAddressBookMissing = !recipientChainId && !addressBook;
const isCheckingRecipient = isAddressBookMissing && !isAddressBookError;
const isRecipientCheckFailed = isAddressBookMissing && isAddressBookError;
const needsNetworkConfirmation = isNetworkMismatch || isRecipientCheckFailed;
const [networkConfirmed, setNetworkConfirmed] = useState(false);

const { send, sendStatus, totpModal } = useSend({
tokenAddress: selectedToken?.contractAddress as any,
Expand Down Expand Up @@ -81,17 +127,20 @@ const SendReview: React.FC = () => {
const { isVerified: isTotpVerified } = useTotp();

const isSendLoading = sendStatus === Status.PENDING;
const isBridgePaymasterRecipient = isBridgePaymasterAddress(address);
const isProtocolRecipient = isProtocolAddress(address);
const showSkip2fa = isTotpVerified && !hasSkipped2fa;
const isContact = !name || showSkip2fa;

const getButtonText = () => {
if (isSendLoading) return 'Sending';
if (isCheckingRecipient) return 'Checking recipient';
return 'Send';
};

const handleSend = async () => {
if (!selectedToken || !amount || !address) return;
if (isCheckingRecipient) return;
if (needsNetworkConfirmation && !networkConfirmed) return;

const nameValue = watchName('name');
const skip2fa = watchName('skip2fa');
Expand All @@ -112,6 +161,7 @@ const SendReview: React.FC = () => {
amount: amount.toString(),
to_address: address,
source: 'send_modal',
...(isNetworkMismatch ? { expected_chain_id: expectedChainId } : {}),
});

const transaction = await send(amount.toString(), address as Address);
Expand Down Expand Up @@ -243,16 +293,83 @@ const SendReview: React.FC = () => {
</Text>
</View>

{isBridgePaymasterRecipient ? (
{isProtocolRecipient ? (
<Text className="text-center text-sm text-red-500">
{BRIDGE_PAYMASTER_RECIPIENT_ERROR}
{PROTOCOL_ADDRESS_RECIPIENT_ERROR}
</Text>
) : (
isContract && (
<ContractAddressWarning chainName={getBridgeChain(selectedToken?.chainId || 1).name} />
)
)}

{isNetworkMismatch && expectedChainId ? (
<View className="gap-3 rounded-2xl border border-red-500/30 bg-red-500/10 px-5 py-4">
<Text className="text-base font-bold text-red-400">
Check the network: this sends on {chainName(selectedToken.chainId)}
</Text>
<Text className="text-sm font-medium leading-5 text-red-300">
{recipientChainId
? `You chose ${chainName(expectedChainId)} for this recipient`
: `Your last send to this address was on ${chainName(expectedChainId)}`}
, but this sends {selectedToken.contractTickerSymbol} on{' '}
{chainName(selectedToken.chainId)}. If the recipient can&apos;t receive on{' '}
{chainName(selectedToken.chainId)} (exchange deposit addresses often can&apos;t), the
funds can be lost.
</Text>
<Pressable
accessibilityRole="checkbox"
accessibilityState={{ checked: networkConfirmed }}
onPress={() => setNetworkConfirmed(value => !value)}
className="flex-row items-center gap-3"
>
<Checkbox checked={networkConfirmed} onCheckedChange={setNetworkConfirmed} />
<Text className="flex-1 text-sm text-white">
The recipient can receive {selectedToken.contractTickerSymbol} on{' '}
{chainName(selectedToken.chainId)}
</Text>
</Pressable>
</View>
) : null}

{isRecipientCheckFailed ? (
<View className="gap-3 rounded-2xl border border-red-500/30 bg-red-500/10 px-5 py-4">
<Text className="text-base font-bold text-red-400">
Couldn&apos;t check this recipient&apos;s network
</Text>
<Text className="text-sm font-medium leading-5 text-red-300">
Your contacts didn&apos;t load, so we can&apos;t tell which network this address was
saved on. This sends {selectedToken.contractTickerSymbol} on{' '}
{chainName(selectedToken.chainId)}.
</Text>
<Pressable
accessibilityRole="button"
onPress={() => void refetchAddressBook()}
disabled={isAddressBookFetching}
className="flex-row items-center gap-2 self-start"
>
<Text className="text-sm font-semibold text-white underline">
{isAddressBookFetching ? 'Retrying' : 'Retry'}
</Text>
{isAddressBookFetching && <ActivityIndicator size="small" color="white" />}
</Pressable>
{!isNetworkMismatch && (
<Pressable
accessibilityRole="checkbox"
accessibilityState={{ checked: networkConfirmed }}
onPress={() => setNetworkConfirmed(value => !value)}
className="flex-row items-center gap-3"
>
<Checkbox checked={networkConfirmed} onCheckedChange={setNetworkConfirmed} />
<Text className="flex-1 text-sm text-white">
The recipient can receive {selectedToken.contractTickerSymbol} on{' '}
{chainName(selectedToken.chainId)}
</Text>
</Pressable>
)}
</View>
) : null}

{isContact && (
<SaveContact
control={nameControl as Control<AddressBookFormData>}
Expand Down Expand Up @@ -282,11 +399,16 @@ const SendReview: React.FC = () => {
variant="brand"
className="h-12 rounded-xl"
onPress={handleSend}
disabled={isSendLoading || isBridgePaymasterRecipient}
disabled={
isSendLoading ||
isCheckingRecipient ||
isProtocolRecipient ||
(needsNetworkConfirmation && !networkConfirmed)
}
>
<Key />
<Text className="text-base font-bold">{getButtonText()}</Text>
{isSendLoading && <ActivityIndicator color="black" />}
{(isSendLoading || isCheckingRecipient) && <ActivityIndicator color="black" />}
</Button>

<NeedHelp />
Expand Down
6 changes: 6 additions & 0 deletions components/Send/TokenSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const TokenSelector: React.FC = () => {
setDestinationChainId,
setCrossChainQuote,
setCrossChainEntry,
setRecipientChainId,
} = useSendStore(
useShallow(state => ({
selectedToken: state.selectedToken,
Expand All @@ -43,6 +44,7 @@ const TokenSelector: React.FC = () => {
setDestinationChainId: state.setDestinationChainId,
setCrossChainQuote: state.setCrossChainQuote,
setCrossChainEntry: state.setCrossChainEntry,
setRecipientChainId: state.setRecipientChainId,
})),
);
// Opened from the cross-chain amount step, only the two bridgeable Fuse
Expand Down Expand Up @@ -122,6 +124,9 @@ const TokenSelector: React.FC = () => {
if (!isCrossChainSendToken(token)) {
// Not on Fuse, so no bridge: hand over to the regular send on the
// token's own chain, keeping the recipient address already entered.
// The network picked for that recipient is kept so Review can warn
// that this send lands on the token's chain instead.
if (destinationChainId) setRecipientChainId(destinationChainId);
setIsCrossChain(false);
setDestinationChainId(null);
setCrossChainQuote(null);
Expand All @@ -143,6 +148,7 @@ const TokenSelector: React.FC = () => {
setDestinationChainId,
setCrossChainQuote,
setCrossChainEntry,
setRecipientChainId,
config?.enabled,
],
);
Expand Down
9 changes: 3 additions & 6 deletions hooks/useAddressBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import { useShallow } from 'zustand/react/shallow';

import { addToAddressBook, fetchAddressBook } from '@/lib/api';
import { showErrorToast } from '@/lib/errors';
import {
BRIDGE_PAYMASTER_RECIPIENT_ERROR,
isBridgePaymasterAddress,
} from '@/lib/protocolAddresses';
import { isProtocolAddress, PROTOCOL_ADDRESS_RECIPIENT_ERROR } from '@/lib/protocolAddresses';
import { AddressBookRequest } from '@/lib/types';
import { withRefreshToken } from '@/lib/utils';
import { recipientNextModal, useSendStore } from '@/store/useSendStore';
Expand All @@ -30,8 +27,8 @@ const walletAddressField = z
.string()
.refine(val => val.trim().length > 0, { error: 'Address is required' })
.refine(val => isAddress(val.trim()), { error: 'Please enter a valid Ethereum address' })
.refine(val => !isBridgePaymasterAddress(val.trim()), {
error: BRIDGE_PAYMASTER_RECIPIENT_ERROR,
.refine(val => !isProtocolAddress(val.trim()), {
error: PROTOCOL_ADDRESS_RECIPIENT_ERROR,
})
.transform(val => val.trim());

Expand Down
9 changes: 3 additions & 6 deletions hooks/useCrossChainSend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ import { getTotpStatus, verifyTotp } from '@/lib/api';
import { authoriseCrossChainSend } from '@/lib/api/cross-chain-send';
import { getUserErrorMessage, sanitizeTechnicalMessage, showFailureSheet } from '@/lib/errors';
import { executeTransactions, USER_CANCELLED_TRANSACTION } from '@/lib/execute';
import {
BRIDGE_PAYMASTER_RECIPIENT_ERROR,
isBridgePaymasterAddress,
} from '@/lib/protocolAddresses';
import { isProtocolAddress, PROTOCOL_ADDRESS_RECIPIENT_ERROR } from '@/lib/protocolAddresses';
import { Status, TransactionType } from '@/lib/types';
import {
CrossChainSendAuthorised,
Expand Down Expand Up @@ -115,8 +112,8 @@ const useCrossChainSend = () => {

// Nothing is deployed at our bridge contract's address on the
// destination chains: a voucher to it delivers the funds to no one.
if (isBridgePaymasterAddress(params.recipient)) {
throw new Error(BRIDGE_PAYMASTER_RECIPIENT_ERROR);
if (isProtocolAddress(params.recipient)) {
throw new Error(PROTOCOL_ADDRESS_RECIPIENT_ERROR);
}

setSendStatus(Status.PENDING);
Expand Down
9 changes: 3 additions & 6 deletions hooks/useSend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ import { useActivityActions } from '@/hooks/useActivityActions';
import { track } from '@/lib/analytics';
import { getTotpStatus, verifyTotp } from '@/lib/api';
import { executeTransactions, USER_CANCELLED_TRANSACTION } from '@/lib/execute';
import {
BRIDGE_PAYMASTER_RECIPIENT_ERROR,
isBridgePaymasterAddress,
} from '@/lib/protocolAddresses';
import { isProtocolAddress, PROTOCOL_ADDRESS_RECIPIENT_ERROR } from '@/lib/protocolAddresses';
import { Status, TokenType, TransactionType } from '@/lib/types';
import { getChain } from '@/lib/wagmi';

Expand Down Expand Up @@ -82,8 +79,8 @@ const useSend = ({

// Last line of defence: no screen may hand a transfer to our bridge
// contract's address — it credits no one, on any chain.
if (isBridgePaymasterAddress(to)) {
throw new Error(BRIDGE_PAYMASTER_RECIPIENT_ERROR);
if (isProtocolAddress(to)) {
throw new Error(PROTOCOL_ADDRESS_RECIPIENT_ERROR);
}

track(TRACKING_EVENTS.SEND_TRANSACTION_INITIATED, {
Expand Down
Loading
Loading