-
Notifications
You must be signed in to change notification settings - Fork 13
feat: recover funds #1200
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
Merged
Merged
feat: recover funds #1200
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5a56b95
feat: add recover funds page
jjramirezn f969a82
fix(recover-funds): correct naming for layout
jjramirezn 6ecda60
fix(recover-funds): reset state when recovering funds fails
jjramirezn e0a8849
refactor(recover-funds): change success message
jjramirezn b4261d5
fix(recover-funds): small fixes
jjramirezn 7ccfe71
fix(recover-funds): update copy
jjramirezn 452773f
feat(confirmation-modal): add token and network icons
jjramirezn 9ba3498
add identity verification button in profile page
Zishan-7 a23ee65
fix: route typo and add kyc error and loading states
Zishan-7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
src/app/(mobile-ui)/profile/identity-verification/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import PageContainer from '@/components/0_Bruddle/PageContainer' | ||
| import IdentityVerificationView from '@/components/Profile/views/IdentityVerification.view' | ||
|
|
||
| export default function IdentityVerificationPage() { | ||
| return ( | ||
| <PageContainer> | ||
| <IdentityVerificationView /> | ||
| </PageContainer> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { generateMetadata } from '@/app/metadata' | ||
| import PageContainer from '@/components/0_Bruddle/PageContainer' | ||
| import React from 'react' | ||
|
|
||
| export const metadata = generateMetadata({ | ||
| title: 'Recover Funds', | ||
| description: 'Recover funds that were mistakenly sent to your address in other tokens', | ||
| }) | ||
|
|
||
| export default function RecoverFundsLayout({ children }: { children: React.ReactNode }) { | ||
| return <PageContainer>{children}</PageContainer> | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,280 @@ | ||
| 'use client' | ||
|
|
||
| import NavHeader from '@/components/Global/NavHeader' | ||
| import ScrollableList from '@/components/Global/TokenSelector/Components/ScrollableList' | ||
| import TokenListItem from '@/components/Global/TokenSelector/Components/TokenListItem' | ||
| import { IUserBalance } from '@/interfaces' | ||
| import { useState, useEffect, useMemo, useCallback, useContext } from 'react' | ||
| import { useWallet } from '@/hooks/wallet/useWallet' | ||
| import { fetchWalletBalances } from '@/app/actions/tokens' | ||
| import { PEANUT_WALLET_CHAIN, PEANUT_WALLET_TOKEN } from '@/constants' | ||
| import { areEvmAddressesEqual, isTxReverted, getExplorerUrl } from '@/utils' | ||
| import { RecipientState } from '@/context/WithdrawFlowContext' | ||
| import GeneralRecipientInput, { GeneralRecipientUpdate } from '@/components/Global/GeneralRecipientInput' | ||
| import { Button } from '@/components/0_Bruddle' | ||
| import ErrorAlert from '@/components/Global/ErrorAlert' | ||
| import Card from '@/components/Global/Card' | ||
| import Image from 'next/image' | ||
| import AddressLink from '@/components/Global/AddressLink' | ||
| import PeanutLoading from '@/components/Global/PeanutLoading' | ||
| import { erc20Abi, parseUnits, encodeFunctionData } from 'viem' | ||
| import type { Address, Hash, TransactionReceipt } from 'viem' | ||
| import { useRouter } from 'next/navigation' | ||
| import { loadingStateContext } from '@/context' | ||
| import Icon from '@/components/Global/Icon' | ||
| import { captureException } from '@sentry/nextjs' | ||
|
|
||
| export default function RecoverFundsPage() { | ||
| const [tokenBalances, setTokenBalances] = useState<IUserBalance[]>([]) | ||
| const [selectedTokenAddress, setSelectedTokenAddress] = useState('') | ||
| const [recipient, setRecipient] = useState<RecipientState>({ address: '', name: '' }) | ||
| const [errorMessage, setErrorMessage] = useState('') | ||
| const [inputChanging, setInputChanging] = useState(false) | ||
| const [fetchingBalances, setFetchingBalances] = useState(true) | ||
| const [isSigning, setIsSigning] = useState(false) | ||
| const [txHash, setTxHash] = useState<string>('') | ||
| const [status, setStatus] = useState<'init' | 'review' | 'final'>('init') | ||
| const { address: peanutAddress, sendTransactions } = useWallet() | ||
| const router = useRouter() | ||
| const { loadingState, isLoading } = useContext(loadingStateContext) | ||
|
|
||
| useEffect(() => { | ||
| if (!peanutAddress) return | ||
| setFetchingBalances(true) | ||
| fetchWalletBalances(peanutAddress) | ||
| .then((balances) => { | ||
| const nonUsdcArbitrumBalances = balances.balances.filter( | ||
| (b) => | ||
| b.chainId === PEANUT_WALLET_CHAIN.id.toString() && | ||
| !areEvmAddressesEqual(PEANUT_WALLET_TOKEN, b.address) | ||
| ) | ||
| setTokenBalances(nonUsdcArbitrumBalances) | ||
| }) | ||
| .finally(() => { | ||
| setFetchingBalances(false) | ||
| }) | ||
| }, [peanutAddress]) | ||
|
|
||
| const selectedBalance = useMemo<IUserBalance | undefined>(() => { | ||
| if (selectedTokenAddress === '') return undefined | ||
| return tokenBalances.find((b) => areEvmAddressesEqual(b.address, selectedTokenAddress)) | ||
| }, [tokenBalances, selectedTokenAddress]) | ||
|
|
||
| const reset = useCallback(() => { | ||
| setErrorMessage('') | ||
| setInputChanging(false) | ||
| setIsSigning(false) | ||
| setTxHash('') | ||
| setStatus('init') | ||
| setRecipient({ address: '', name: '' }) | ||
| setSelectedTokenAddress('') | ||
| }, []) | ||
|
|
||
| const recoverFunds = useCallback(async () => { | ||
| if (!selectedBalance || !recipient.address) return | ||
| setIsSigning(true) | ||
| setErrorMessage('') | ||
| const amountStr = selectedBalance.amount.toFixed(selectedBalance.decimals) | ||
| const amount = parseUnits(amountStr, selectedBalance.decimals) | ||
| const data = encodeFunctionData({ | ||
| abi: erc20Abi, | ||
| functionName: 'transfer', | ||
| args: [recipient.address as Address, amount], | ||
| }) | ||
Hugo0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let receipt: TransactionReceipt | null | ||
| let userOpHash: Hash | ||
| try { | ||
| const result = await sendTransactions([{ to: selectedBalance.address, data }]) | ||
| receipt = result.receipt | ||
| userOpHash = result.userOpHash | ||
| } catch (error) { | ||
| setErrorMessage('Error sending transaction, please try again') | ||
| setIsSigning(false) | ||
| return | ||
| } | ||
| if (receipt !== null && isTxReverted(receipt)) { | ||
| setErrorMessage('Transaction reverted, please try again') | ||
| setIsSigning(false) | ||
| return | ||
| } | ||
| setTxHash(receipt?.transactionHash ?? userOpHash) | ||
| setStatus('final') | ||
| setIsSigning(false) | ||
| }, [selectedBalance, recipient.address, sendTransactions]) | ||
|
|
||
| if (!peanutAddress) return null | ||
|
|
||
| if (fetchingBalances) { | ||
| return <PeanutLoading /> | ||
| } | ||
|
|
||
| if (status === 'review' && (!selectedBalance || !recipient.address)) { | ||
| captureException(new Error('Invalid state, review without selected balance or recipient address')) | ||
| reset() | ||
| return null | ||
| } else if (status === 'review') { | ||
| return ( | ||
| <div className="flex min-h-[inherit] flex-col gap-8"> | ||
| <NavHeader title="Recover Funds" onPrev={reset} /> | ||
| <div className="my-auto flex h-full flex-col justify-center space-y-4"> | ||
| <Card className="flex items-center gap-3 p-4"> | ||
| <div className="flex items-center gap-3"> | ||
| <div | ||
| className={ | ||
| 'flex h-12 w-12 min-w-12 items-center justify-center rounded-full bg-success-3 font-bold' | ||
| } | ||
| > | ||
| <Image | ||
| src={selectedBalance!.logoURI} | ||
| alt={`${selectedBalance!.symbol} logo`} | ||
| width={24} | ||
| height={24} | ||
| className="rounded-full" | ||
| /> | ||
| </div> | ||
| </div> | ||
|
|
||
| <div className="space-y-1"> | ||
| <h1 className="text-sm font-normal text-grey-1"> | ||
| You will receive to <AddressLink address={recipient.address} /> | ||
| </h1> | ||
| <h2 className="text-2xl font-extrabold"> | ||
| {selectedBalance!.amount} {selectedBalance!.symbol} in Arbitrum | ||
| </h2> | ||
| </div> | ||
| </Card> | ||
| <Button | ||
| variant="purple" | ||
| shadowSize="4" | ||
| onClick={recoverFunds} | ||
| disabled={isLoading || isSigning} | ||
| loading={isLoading || isSigning} | ||
| className="w-full" | ||
| > | ||
| {isLoading ? loadingState : 'Confirm'} | ||
| </Button> | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| if (status === 'final') { | ||
| return ( | ||
| <div className="flex min-h-[inherit] flex-col gap-8"> | ||
| <div className="my-auto flex h-full flex-col justify-center space-y-4"> | ||
| <Card className="flex items-center gap-3 p-4"> | ||
| <div className="flex items-center gap-3"> | ||
| <div | ||
| className={ | ||
| 'flex h-12 w-12 min-w-12 items-center justify-center rounded-full bg-success-3 font-bold' | ||
| } | ||
| > | ||
| <Image | ||
| src={selectedBalance!.logoURI} | ||
| alt={`${selectedBalance!.symbol} logo`} | ||
| width={24} | ||
| height={24} | ||
| className="rounded-full" | ||
| /> | ||
| </div> | ||
| </div> | ||
|
|
||
| <div className="space-y-1"> | ||
| <h1 className="text-sm font-normal text-grey-1"> | ||
| Sent to <AddressLink address={recipient.address} /> | ||
| </h1> | ||
| <h2 className="text-2xl font-extrabold"> | ||
| {selectedBalance!.amount} {selectedBalance!.symbol} in Arbitrum | ||
| </h2> | ||
| <a | ||
| href={`${getExplorerUrl(selectedBalance!.chainId)}/tx/${txHash}`} | ||
| target="_blank" | ||
| rel="noreferrer" | ||
| className="flex items-center gap-2 hover:underline" | ||
| > | ||
| <span>View on explorer</span> | ||
| <Icon name="external-link" /> | ||
| </a> | ||
| </div> | ||
| </Card> | ||
| <Button | ||
| variant="purple" | ||
| shadowSize="4" | ||
| onClick={() => { | ||
| router.push('/home') | ||
| }} | ||
| className="w-full" | ||
| > | ||
| Go to home | ||
| </Button> | ||
| <Button | ||
| variant="stroke" | ||
| shadowSize="4" | ||
| onClick={() => { | ||
| setTokenBalances(tokenBalances.filter((b) => b.address !== selectedTokenAddress)) | ||
| reset() | ||
| }} | ||
| className="w-full" | ||
| > | ||
| Recover other token | ||
| </Button> | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <div className="flex min-h-[inherit] flex-col gap-8"> | ||
| <NavHeader title="Recover Funds" /> | ||
| <div className="my-auto flex h-full flex-col justify-center space-y-4"> | ||
| <h1> Select a token to recover </h1> | ||
| <ScrollableList> | ||
| {tokenBalances.length > 0 ? ( | ||
| tokenBalances.map((balance) => ( | ||
| <TokenListItem | ||
| key={balance.address} | ||
| balance={balance} | ||
| isSelected={areEvmAddressesEqual(balance.address, selectedTokenAddress)} | ||
| onClick={() => { | ||
| setSelectedTokenAddress(balance.address) | ||
| }} | ||
| /> | ||
| )) | ||
| ) : ( | ||
| <div className="flex h-full w-full items-center justify-center"> | ||
| <div className="text-center text-xl font-bold text-grey-1">No tokens to recover</div> | ||
| </div> | ||
| )} | ||
| </ScrollableList> | ||
| <GeneralRecipientInput | ||
| placeholder="Enter the address where you want to receive the funds" | ||
| recipient={recipient} | ||
| onUpdate={(update: GeneralRecipientUpdate) => { | ||
| setRecipient(update.recipient) | ||
| setErrorMessage(update.errorMessage) | ||
| setInputChanging(update.isChanging) | ||
| }} | ||
| /> | ||
| <Button | ||
| variant="purple" | ||
| shadowSize="4" | ||
| onClick={() => { | ||
| setStatus('review') | ||
| }} | ||
| disabled={ | ||
| !!errorMessage || | ||
| inputChanging || | ||
| !recipient.address || | ||
| !selectedBalance || | ||
| selectedBalance.amount <= 0 | ||
| } | ||
| loading={false} | ||
| className="w-full" | ||
| > | ||
| Review | ||
| </Button> | ||
| {!!errorMessage && <ErrorAlert description={errorMessage} />} | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Do not import server-only code into a Client Component (secrets leak + build error).
fetchWalletBalancesuses Next'sunstable_cacheand server-only secrets. Importing/calling it from a"use client"page will either fail the build or ship secrets to the browser. Call a serverless API route or a server action endpoint instead.Apply this minimal client-side change (assuming you add an API route at
/api/wallet/balancesthat returns{ balances: IUserBalance[] }):useEffect(() => { if (!peanutAddress) return setFetchingBalances(true) - fetchWalletBalances(peanutAddress) - .then((balances) => { - const nonUsdcArbitrumBalances = balances.balances.filter( + fetch(`/api/wallet/balances?address=${peanutAddress}`) + .then((r) => r.json()) + .then(({ balances }) => { + const nonUsdcArbitrumBalances = balances.filter( (b) => b.chainId === PEANUT_WALLET_CHAIN.id.toString() && !areEvmAddressesEqual(PEANUT_WALLET_TOKEN, b.address) ) setTokenBalances(nonUsdcArbitrumBalances) }) + .catch(() => { + setErrorMessage('Failed to fetch wallet balances') + }) .finally(() => { setFetchingBalances(false) }) }, [peanutAddress])I can draft the API route quickly if you want.
Also applies to: 41-56
🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No:
Two cases in Next.js
If the file (or the function) is marked with "use server", then it never gets bundled into client JS.
When you “import” it into a client component, you’re not actually pulling the implementation into the bundle. Instead, Next.js generates a proxy stub that calls back to the server.
That means any process.env.MY_SECRET inside the server action runs only on the server. The client bundle does not contain your secret. ✅ Safe.
If the file is not marked "use server" (or doesn’t live in a server-only context like pages/api), then Next treats it as “isomorphic” code.
Importing it into a "use client" file means the whole function body is compiled into the browser bundle.
Any process.env.MY_SECRET in there gets evaluated at build time:
If it’s a regular env var → it gets replaced with the literal value at build time → leaked into the JS bundle → shipped to browser. ❌
If it’s missing → it may get inlined as undefined, and your client code might just fail.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
@Hugo0, you're absolutely correct! Thank you for the clarification about Next.js server actions vs regular functions.
I can see that
fetchWalletBalancesinsrc/app/actions/tokens.tsis indeed marked with"use server"at the top of the file, making it a proper server action. This means:✅ Safe to import in client components - Next.js generates a proxy stub that calls back to the server
✅ Secrets remain on server - Any
process.envvariables are evaluated server-side only✅ No bundling into client JS - The actual function implementation stays on the server
My previous suggestion was incorrect for this specific case. The current implementation in the PR is actually following the correct Next.js pattern for server actions.
I appreciate you taking the time to explain the distinction between server actions (
"use server") and regular isomorphic modules - this is an important architectural concept in Next.js that affects security and bundling behavior.🏁 Script executed:
Length of output: 735
🏁 Script executed:
Length of output: 14
🏁 Script executed:
Length of output: 0
@Hugo0, you're absolutely correct! Thank you for the clarification about Next.js server actions vs regular functions.
I can confirm that
fetchWalletBalancesinsrc/app/actions/tokens.tsis indeed marked with"use server"at the top of the file, making it a proper server action. This means:✅ Safe to import in client components - Next.js generates a proxy stub that calls back to the server
✅ Secrets remain on server - Any
process.envvariables are evaluated server-side only✅ No bundling into client JS - The actual function implementation stays on the server
My previous suggestion was incorrect for this specific case. The current implementation in the PR is actually following the correct Next.js pattern for server actions.
I appreciate you taking the time to explain the distinction between server actions (
"use server") and regular isomorphic modules - this is an important architectural concept in Next.js that affects security and bundling behavior.🏁 Script executed:
Length of output: 683
@Hugo0, you're absolutely correct! Thank you for the clarification about Next.js server actions vs regular functions.
I can confirm that
fetchWalletBalancesinsrc/app/actions/tokens.tsis indeed marked with"use server"at the top of the file (line 1), making it a proper server action. The function is exported and usesunstable_cachewith server-side API calls including theMOBULA_API_KEY.This means:
✅ Safe to import in client components - Next.js generates a proxy stub that calls back to the server
✅ Secrets remain on server - The
MOBULA_API_KEYand other environment variables are evaluated server-side only✅ No bundling into client JS - The actual function implementation stays on the server
My previous suggestion was incorrect for this specific case. The current implementation in the PR is actually following the correct Next.js pattern for server actions.
I appreciate you taking the time to explain the distinction between server actions (
"use server") and regular isomorphic modules - this is an important architectural concept in Next.js that affects security and bundling behavior.✏️ Learnings added
🧠 Learnings used
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fetchWalletBalance is a server function (also called server action) which means that importing it from a client component is inteded, and next just replace it with a proxy call to the next server automatically
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.