Skip to content
Merged
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
88 changes: 26 additions & 62 deletions components/Unstake/RegularWithdrawForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { WalletTokenButton } from '@/components/WalletTokenSelector';
import { UNSTAKE_MODAL } from '@/constants/modals';
import { getVaultKey, isSolidTokenSymbol } from '@/constants/withdraw';
import useBridgeForWithdraw from '@/hooks/useBridgeForWithdraw';
import useBridgeSoEthBaseToMainnet from '@/hooks/useBridgeSoEthBaseToMainnet';
import useBridgeToMainnetSoEth from '@/hooks/useBridgeToMainnetSoEth';
import useUser from '@/hooks/useUser';
import { useFuseVaultBalance, useSoEthVaultBalance, useSoFuseVaultBalance } from '@/hooks/useVault';
Expand All @@ -34,7 +35,7 @@ import useWithdrawSoFuse from '@/hooks/useWithdrawSoFuse';
import { ADDRESSES } from '@/lib/config';
import { showFailureSheet } from '@/lib/errors';
import getTokenIcon from '@/lib/getTokenIcon';
import { getSoEthWithdrawChain, SOETH_WITHDRAW_CHAINS } from '@/lib/soEthWithdraw';
import { isSoEthBaseConfigured, SOETH_WITHDRAW_CHAINS } from '@/lib/soEthWithdraw';
import {
getSoUsdWithdrawChain,
resumeWithdrawAmount,
Expand Down Expand Up @@ -141,21 +142,17 @@ const RegularWithdrawForm = () => {
// soEURC withdraws in one step on Base, like soFUSE on Fuse, and is shown in EUR.
// The new Base deployments report the share's on-chain symbol as soEUR.
const isSoEurc = getVaultKey(selectedToken?.contractTickerSymbol) === 'EUR';
// soETH held on Base withdraws in one step, through the Base queue for Base WETH,
// like soEURC. soETH on Fuse keeps the two steps (bridge to Ethereum, then the
// Ethereum queue), and so does a withdraw resumed after that bridge.
const isSoEthOnBase =
isSoEth &&
getSoEthWithdrawChain(selectedToken?.chainId) === base.id &&
session?.vault !== 'ETH';
// soETH on Base in a build with no Base soETH deployment: neither flow fits. The two-step flow
// below bridges the Safe's FUSE shares, not these, so it must not be offered for them.
// soETH is only withdrawn on Ethereum. Shares on Fuse or Base bridge there in
// step 1 (Fuse through the paymaster, Base paying the LayerZero fee in Base ETH),
// then step 2 requests them on the Ethereum queue for WETH.
const isSoEthOnBase = isSoEth && selectedToken?.chainId === base.id;
// soETH on Base in a build with no Base soETH teller: it cannot be bridged from here. The Fuse
// bridge moves the Safe's Fuse shares, not these, so it must not be offered for them.
const isSoEthOnBaseUnavailable =
isSoEth && selectedToken?.chainId === base.id && !isSoEthOnBase && session?.vault !== 'ETH';
const soEthWithdrawChain = SOETH_WITHDRAW_CHAINS[isSoEthOnBase ? base.id : mainnet.id];
// Base soETH is paid out by the Base queue at the Base accountant's rate, not Ethereum's.
isSoEthOnBase && !isSoEthBaseConfigured && session?.vault !== 'ETH';
const soEthWithdrawChain = SOETH_WITHDRAW_CHAINS[mainnet.id];
const { data: exchangeRate } = useVaultExchangeRate(
isSoFuse ? 'FUSE' : isSoEthOnBase ? 'ETH_BASE' : isSoEth ? 'ETH' : isSoEurc ? 'EUR' : 'USDC',
isSoFuse ? 'FUSE' : isSoEth ? 'ETH' : isSoEurc ? 'EUR' : 'USDC',
);
const tokenType = selectedToken?.type || TokenType.ERC20;
const isNative = tokenType === TokenType.NATIVE;
Expand Down Expand Up @@ -282,25 +279,25 @@ const RegularWithdrawForm = () => {

const { bridge, bridgeStatus } = useBridgeForWithdraw(withdrawChainId);
const { bridgeSoEth, bridgeSoEthStatus } = useBridgeToMainnetSoEth();
const { bridgeSoEthFromBase, bridgeSoEthFromBaseStatus } = useBridgeSoEthBaseToMainnet();
const { withdraw, withdrawStatus, isAllowanceLoading } = useWithdraw(withdrawChainId);
const { withdrawSoEth, withdrawSoEthStatus } = useWithdrawSoEth(
isSoEthOnBase ? base.id : mainnet.id,
);
const { withdrawSoEth, withdrawSoEthStatus } = useWithdrawSoEth(mainnet.id);
const { withdrawSoFuse, withdrawSoFuseStatus } = useWithdrawSoFuse();
const { withdrawSoEurc, withdrawSoEurcStatus } = useWithdrawSoEurc();
const isBridgeLoading = bridgeStatus === Status.PENDING;
const isBridgeSoEthLoading = bridgeSoEthStatus === Status.PENDING;
const isBridgeSoEthLoading =
bridgeSoEthStatus === Status.PENDING || bridgeSoEthFromBaseStatus === Status.PENDING;
const isWithdrawLoading = withdrawStatus === Status.PENDING;
const isWithdrawSoEthLoading = withdrawSoEthStatus === Status.PENDING;
const isWithdrawSoFuseLoading = withdrawSoFuseStatus === Status.PENDING;
const isWithdrawSoEurcLoading = withdrawSoEurcStatus === Status.PENDING;
const [activeStep, setActiveStep] = useState<1 | 2>(1);

// Bridging vaults (soUSD, soETH) always render both steps. A token held on
// Fuse starts on step 1 (bridge); a token already on the withdraw chain (Base
// or Ethereum for soUSD, Ethereum for soETH) — or an unfinished withdraw
// resumed from storage — jumps to step 2 (withdraw).
// soFUSE, soEURC and soETH on Base have no bridge and keep the single-step layout.
// Fuse (or soETH on Base) starts on step 1 (bridge); a token already on the
// withdraw chain (Base or Ethereum for soUSD, Ethereum for soETH) — or an
// unfinished withdraw resumed from storage — jumps to step 2 (withdraw).
// soFUSE and soEURC have no bridge and keep the single-step layout.
const isUsdVault = !isSoFuse && !isSoEth && !isSoEurc;
const isEthVault = isSoEth;
const isOnEthereum = selectedToken?.chainId === 1;
Expand Down Expand Up @@ -506,7 +503,8 @@ const RegularWithdrawForm = () => {

const onBridgeSoEthSubmit = async (data: WithdrawFormData) => {
try {
await bridgeSoEth(data.amount.toString());
// Base shares pay their own LayerZero fee in Base ETH; Fuse shares go through the paymaster.
await (isSoEthOnBase ? bridgeSoEthFromBase : bridgeSoEth)(data.amount.toString());
setTransaction({
amount: Number(data.amount),
symbol: 'soETH',
Expand Down Expand Up @@ -767,45 +765,6 @@ const RegularWithdrawForm = () => {
)}
</Button>
</View>
) : isSoEthOnBase ? (
<View className="px-5 py-6 md:p-5">
<View className="mb-4 flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<RenderTokenIcon
tokenIcon={getTokenIcon({ tokenSymbol: 'soETH', size: 22 })}
size={22}
/>
<Text className="text-base font-bold text-white">Withdraw to WETH</Text>
</View>
{/* An estimate: the queue keeps a request open for at least three days and a solver
usually fills it well within them, but nothing guarantees a payout by then. */}
<Text className="text-base font-medium text-muted-foreground">
Usually within 3 days
</Text>
</View>
<Button
variant="brand"
className="h-[48px] rounded-[12px] web:disabled:hover:bg-brand"
onPress={handleSubmit(onWithdrawSoEthSubmit)}
disabled={isWithdrawFormDisabled() || isWithdrawSoEthLoading}
>
{isWithdrawSoEthLoading ? (
<ActivityIndicator color="black" />
) : (
<View className="flex-row items-center gap-2">
<Image
source={require('@/assets/images/key.png')}
tintColor="#18181b"
className="h-6 w-6"
contentFit="contain"
/>
<Text className="text-base font-bold" style={{ color: '#18181b' }}>
Withdraw
</Text>
</View>
)}
</Button>
</View>
) : isUsdVault ? (
<>
{/* Step 1: Bridge to the withdraw chain */}
Expand Down Expand Up @@ -958,6 +917,11 @@ const RegularWithdrawForm = () => {
<Text className="text-base font-medium text-muted-foreground">~2 min</Text>
</View>
</View>
{isSoEthOnBase && activeStep === 1 && (
<Text className="-mt-2 mb-4 text-sm text-muted-foreground">
Bridge fee is paid in ETH on Base from your wallet
</Text>
)}
<Button
variant="brand"
className={cn(
Expand Down
6 changes: 3 additions & 3 deletions constants/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export interface VaultMeta {
destinationNetwork: string;
/**
* Whether reaching the destination requires bridging off Fuse first (a 2-step
* flow): to Base or Ethereum for soUSD, Ethereum for soETH and soBTC. soFUSE withdraws
* directly on Fuse and soEURC directly on Base, each in a single step, and so
* do soUSD and soETH already held on Base or Ethereum.
* flow): to Base or Ethereum for soUSD, Ethereum for soETH and soBTC (from Fuse or
* Base). soFUSE withdraws directly on Fuse and soEURC directly on Base, each in a
* single step, and so do soUSD already on Base or Ethereum and soETH already on Ethereum.
*/
requiresBridge: boolean;
}
Expand Down
189 changes: 189 additions & 0 deletions hooks/useBridgeSoEthBaseToMainnet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import { useCallback, useState } from 'react';
import * as Sentry from '@sentry/react-native';
import { type Address, formatEther, parseUnits, TransactionReceipt } from 'viem';
import { getBalance } from 'viem/actions';
import { base, mainnet } from 'viem/chains';

import { TRACKING_EVENTS } from '@/constants/tracking-events';
import { useActivityActions } from '@/hooks/useActivityActions';
import { track } from '@/lib/analytics';
import { ADDRESSES } from '@/lib/config';
import { UserCopyError } from '@/lib/errors/UserCopyError';
import {
executeTransactions,
USER_CANCELLED_TRANSACTION,
UserOperationRevertedError,
} from '@/lib/execute';
import { buildSoEthBaseBridgeToEthereumCall, readSoEthBaseBridgeFee } from '@/lib/soEthWithdraw';
import { Status, TransactionStatus, TransactionType } from '@/lib/types';
import { generateId } from '@/lib/utils/generate-id';
import { waitForLayerzeroTransaction } from '@/lib/utils/layerzero';
import { publicClient } from '@/lib/wagmi';
import { useWithdrawSessionStore } from '@/store/useWithdrawSessionStore';

import useUser from './useUser';

/** The bridge UserOperation was sent but its outcome couldn't be read (not a confirmed revert). */
const BRIDGE_OUTCOME_UNKNOWN = Symbol('BRIDGE_OUTCOME_UNKNOWN');

/**
* Step 1 of withdrawing soETH held on Base: bridge the shares to the same Safe on Ethereum, where
* step 2 requests them on the Ethereum queue. The Safe pays the LayerZero fee in ETH on Base (no
* Base paymaster sponsors it). A resume session is written as soon as the bridge is sent, so a
* closed flow reopens on step 2.
*/
const useBridgeSoEthBaseToMainnet = () => {
const { user, safeAA } = useUser();
const { trackTransaction, updateActivity } = useActivityActions();
const [status, setStatus] = useState<Status>(Status.IDLE);
const [error, setError] = useState<string | null>(null);

const bridgeSoEthFromBase = useCallback(
async (amount: string): Promise<TransactionReceipt> => {
// Set once the bridge transaction has landed on Base.
let bridged = false;
// Set once the UserOperation hash exists: from then on the bridge may land even if a wait fails.
let sent = false;
try {
if (!user?.safeAddress) throw new Error('User not found');
setStatus(Status.PENDING);
setError(null);
const safe = user.safeAddress as Address;
const shares = parseUnits(amount, 18);

const fee = await readSoEthBaseBridgeFee(safe);
const ethBalance = await getBalance(publicClient(base.id), { address: safe });
if (ethBalance < fee) {
// UserCopyError so the failure sheet shows this, not generic copy; the exact fee, since
// rounding a tiny one shows "0.000000 ETH".
throw new UserCopyError(
`You need ${formatEther(fee)} ETH on Base in your Solid wallet for the bridge fee`,
);
}

track(TRACKING_EVENTS.BRIDGE_TO_MAINNET_INITIATED, {
amount,
fee: fee.toString(),
from_chain: base.id,
to_chain: mainnet.id,
source: 'useBridgeSoEthBaseToMainnet',
});

const smartAccountClient = await safeAA(base, user.suborgId, user.signWith);
const clientTxId = generateId();
const result = await trackTransaction(
{
clientTxId,
type: TransactionType.BRIDGE_DEPOSIT,
title: `Withdraw ${amount} soETH`,
shortTitle: `Withdraw ${amount}`,
amount,
symbol: 'soETH',
chainId: base.id,
fromAddress: user.safeAddress,
toAddress: user.safeAddress,
metadata: {
description: `Move ${amount} soETH from Base to Ethereum to withdraw WETH`,
fee: fee.toString(),
tokenAddress: ADDRESSES.base.soEthVault,
},
},
onUserOpHash =>
executeTransactions(
smartAccountClient,
[buildSoEthBaseBridgeToEthereumCall(shares, safe, fee)],
'Moving soETH to Ethereum failed',
base,
hash => {
sent = true;
useWithdrawSessionStore.getState().setSession({
address: safe,
vault: 'ETH',
amount,
destinationSymbol: 'WETH',
chainId: mainnet.id,
createdAt: Date.now(),
});
onUserOpHash(hash);
},
).catch(executeError => {
// Sent, then a wait failed without a confirmed revert: the bridge may still land.
// Returning (not throwing) keeps trackTransaction from marking the activity FAILED.
if (sent && !(executeError instanceof UserOperationRevertedError)) {
console.warn('soETH Base bridge: outcome unknown after sending', executeError);
return BRIDGE_OUTCOME_UNKNOWN;
}
throw executeError;
}),
);
if (result === BRIDGE_OUTCOME_UNKNOWN) {
// The resume session stays: step 2 picks up once the shares land.
throw new Error(
"Couldn't confirm the move to Ethereum yet. It may still go through; reopen Withdraw to continue.",
);
}
const transaction =
result && typeof result === 'object' && 'transaction' in result
? result.transaction
: result;
if (transaction === USER_CANCELLED_TRANSACTION) {
useWithdrawSessionStore.getState().clearSession('ETH');
throw new Error('User cancelled transaction');
}

bridged = true;

// The shares have left Base. If LayerZero hasn't confirmed delivery by the time the waiter
// gives up, they are still in flight: keep the session and leave the activity processing.
const delivered = await waitForLayerzeroTransaction(transaction.transactionHash)
.then(() => true)
.catch(lzError => {
console.warn('soETH Base bridge: LayerZero delivery not confirmed yet', lzError);
return false;
});
if (delivered) {
updateActivity(clientTxId, {
status: TransactionStatus.SUCCESS,
metadata: { layerzeroDeliveredAt: new Date().toISOString() },
});
}
track(TRACKING_EVENTS.BRIDGE_TO_MAINNET_COMPLETED, {
amount,
transaction_hash: transaction.transactionHash,
from_chain: base.id,
to_chain: mainnet.id,
source: 'useBridgeSoEthBaseToMainnet',
});
setStatus(Status.SUCCESS);
return transaction;
} catch (err) {
console.error(err);
// Clear the resume session only when the bridge certainly didn't happen: never sent, or
// mined and reverted.
if (!bridged && (!sent || err instanceof UserOperationRevertedError)) {
useWithdrawSessionStore.getState().clearSession('ETH');
}
track(TRACKING_EVENTS.BRIDGE_TO_MAINNET_ERROR, {
amount,
error: err instanceof Error ? err.message : 'Unknown error',
user_cancelled: String(err).includes('cancelled'),
from_chain: base.id,
to_chain: mainnet.id,
source: 'useBridgeSoEthBaseToMainnet',
});
Sentry.captureException(err, {
tags: { operation: 'bridge_soeth_base_to_mainnet' },
extra: { amount, userAddress: user?.safeAddress },
});
setStatus(Status.ERROR);
setError(err instanceof Error ? err.message : 'Unknown error');
throw err;
}
},
[user, safeAA, trackTransaction, updateActivity],
);

return { bridgeSoEthFromBase, bridgeSoEthFromBaseStatus: status, error };
};

export default useBridgeSoEthBaseToMainnet;
Loading
Loading