From aff1b0add5dccc95c5bacd47702fe750f8878a05 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Fri, 24 Oct 2025 22:34:26 -0700 Subject: [PATCH] cashu wallet restore and addressed some test errors --- src/components/wallet/CashuWallet.tsx | 11 ++- src/components/wallet/UTXOSelector.tsx | 3 +- src/components/wallet/WalletModals.tsx | 116 +++++++++++++++++------ src/hooks/cashu/useWalletTransactions.ts | 106 +++++++++++++++++++++ src/hooks/useBitcoinBalance.ts | 50 +++++++--- src/lib/bitcoin.ts | 2 - 6 files changed, 240 insertions(+), 48 deletions(-) diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index f007c1f..ae05063 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -10,9 +10,8 @@ import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; import { useMintManager } from '@/hooks/cashu/useMintManager'; import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions'; import { useHistoryManager } from '@/hooks/cashu/useHistoryManager'; -import { useNsecAccess } from '@/hooks/useNsecAccess'; import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance'; -import { nostrPubkeyToBitcoinAddress, UTXO } from '@/lib/bitcoin'; +import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; import { TransactionCard } from './PaymentCard'; @@ -54,8 +53,6 @@ export function CashuWallet() { // Bitcoin operations hook const { utxos, - isLoadingUtxos, - feeRate, isConsolidating, bitcoinMaxAmount, fetchBitcoinUtxos, @@ -141,6 +138,8 @@ export function CashuWallet() { handleReceive, handleSend, handleConfirmInvoicePayment, + handleRestoreFromSeedPhrase, + isRestoring, mintQuoteUnsubscribeRef, } = useWalletTransactions({ coco, @@ -461,6 +460,10 @@ export function CashuWallet() { sentTokenQRCode={sentTokenQRCode} showSeedPhraseInfo={showSeedPhraseInfo} setShowSeedPhraseInfo={setShowSeedPhraseInfo} + onRestoreFromSeedPhrase={handleRestoreFromSeedPhrase} + isRestoring={isRestoring} + mints={mints} + activeMintUrl={activeMintUrl} /> {/* Bottom Drawer Modals */} diff --git a/src/components/wallet/UTXOSelector.tsx b/src/components/wallet/UTXOSelector.tsx index 19c4050..860f6b7 100644 --- a/src/components/wallet/UTXOSelector.tsx +++ b/src/components/wallet/UTXOSelector.tsx @@ -23,7 +23,6 @@ interface UTXOSelectorProps { export function UTXOSelector({ utxos, showSats, - bitcoinAddress, dropdownOpen, setDropdownOpen, onShowConsolidationModal, @@ -89,7 +88,7 @@ export function UTXOSelector({ No UTXOs available ) : ( - utxos.map((utxo, index) => ( + utxos.map((utxo) => ( { @@ -71,6 +74,12 @@ interface WalletModalProps { // Seed Phrase Info Modal showSeedPhraseInfo: boolean; setShowSeedPhraseInfo: (show: boolean) => void; + + // Restore functionality + onRestoreFromSeedPhrase: (seedPhrase: string, mintUrl: string) => Promise; + isRestoring: boolean; + mints: Array<{ url: string; name?: string }>; + activeMintUrl: string | null; } export function WalletModals({ @@ -101,8 +110,15 @@ export function WalletModals({ sentTokenQRCode, showSeedPhraseInfo, setShowSeedPhraseInfo, + onRestoreFromSeedPhrase, + isRestoring, + mints, + activeMintUrl, }: WalletModalProps) { const { toast } = useToast(); + + // Restore state + const [seedPhraseInput, setSeedPhraseInput] = useState(''); return ( <> {/* Proof Breakdown Modal */} @@ -351,7 +367,7 @@ export function WalletModals({ /> )} - {/* Seed Phrase Info Modal */} + {/* Seed Phrase Restore Modal */} {showSeedPhraseInfo && (
+
-

What is a Seed Phrase?

+

Restore from Seed Phrase

-

- Your seed phrase is a secure way to backup and restore your wallet + +

+ Enter your seed phrase to restore tokens from the active mint.

-
-
-

🔐 Recovery Key

-

- Your seed phrase is a 12-word recovery key that allows you to restore your wallet - on any device. It's generated using industry-standard BIP39 wordlists. + {activeMintUrl && ( +

+

+ Active Mint: {mints.find(m => m.url === activeMintUrl)?.name || new URL(activeMintUrl).hostname}

- + )} + +
-

💾 Backup Important

-

- Write down your seed phrase and store it securely offline. Anyone with access - to your seed phrase can control your wallet and funds. -

-
- -
-

🛡️ Security Tips

-
    -
  • • Never share your seed phrase with anyone
  • -
  • • Store it offline in a secure location
  • -
  • • Don't take screenshots or store it digitally
  • -
  • • Use it only to restore your wallet
  • -
+ + setSeedPhraseInput(e.target.value)} + className="mt-1" + />

- Note: The seed phrase shown above is masked for privacy. - Click the copy button to access the actual phrase for backup purposes. + Note: This will restore tokens from the provided seed phrase and add them to your current wallet balance.

+ +
+ +
diff --git a/src/hooks/cashu/useWalletTransactions.ts b/src/hooks/cashu/useWalletTransactions.ts index 1f22879..577d358 100644 --- a/src/hooks/cashu/useWalletTransactions.ts +++ b/src/hooks/cashu/useWalletTransactions.ts @@ -4,6 +4,10 @@ import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder'; import type { Manager } from 'coco-cashu-core'; import type { Token } from '@cashu/cashu-ts'; import { useToast } from '@/hooks/useToast'; +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english.js'; +import { initializeCoco, ConsoleLogger } from 'coco-cashu-core'; +import { IndexedDbRepositories } from 'coco-cashu-indexeddb'; interface UseWalletTransactionsProps { coco: Manager | null; @@ -54,6 +58,9 @@ export function useWalletTransactions({ expiry: number; } | null>(null); + // Restore state + const [isRestoring, setIsRestoring] = useState(false); + // Ref to store the mint quote redeemed event unsubscribe function const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null); @@ -378,6 +385,102 @@ export function useWalletTransactions({ } }, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]); + // Handle restore from seed phrase + const handleRestoreFromSeedPhrase = useCallback(async (seedPhrase: string, mintUrl: string) => { + if (!coco) { + throw new Error('Wallet not initialized'); + } + + setIsRestoring(true); + + try { + // Clean and validate the seed phrase + const cleanedSeedPhrase = seedPhrase.trim().toLowerCase(); + + // Check if it's a valid mnemonic format + if (!bip39.validateMnemonic(cleanedSeedPhrase, wordlist)) { + // Try to provide more specific error information + const words = cleanedSeedPhrase.split(/\s+/); + if (words.length !== 12) { + throw new Error(`Seed phrase must have exactly 12 words, but found ${words.length} words`); + } + + // Check if all words are valid + const invalidWords = words.filter(word => !wordlist.includes(word)); + if (invalidWords.length > 0) { + throw new Error(`Invalid words found: ${invalidWords.join(', ')}`); + } + + throw new Error('Invalid seed phrase format. Please check that all words are spelled correctly.'); + } + + // Verify this is a different seed from the current wallet + const currentMnemonic = localStorage.getItem('cashu-mnemonic'); + if (currentMnemonic && currentMnemonic.toLowerCase() === cleanedSeedPhrase) { + throw new Error('This is the same seed phrase as your current wallet. Please enter a different seed phrase to restore from.'); + } + + // Convert seed phrase to seed + const restoredSeed = bip39.mnemonicToSeedSync(cleanedSeedPhrase); + + // Get current balance before restore + const balancesBefore = await coco.wallet.getBalances(); + const balanceBefore = balancesBefore[mintUrl] || 0; + + // Create a temporary coco instance with the restored seed to fetch proofs + const tempRepo = new IndexedDbRepositories({ name: `cashu-wallet-restore-${Date.now()}` }); + await tempRepo.init(); + + const tempCoco = await initializeCoco({ + repo: tempRepo, + seedGetter: async () => restoredSeed, + logger: new ConsoleLogger(`restore-${Date.now()}`, { level: "debug" }) + }); + + try { + // Restore the proofs in the temporary wallet + await tempCoco.wallet.restore(mintUrl); + + // Get the restored balance from the temporary wallet + const tempBalances = await tempCoco.wallet.getBalances(); + const restoredAmount = tempBalances[mintUrl] || 0; + + if (restoredAmount <= 0) { + toast({ + title: "No Tokens Found", + description: "No tokens were found for this seed phrase on the selected mint.", + }); + return; + } + + // Send the restored tokens from the temporary wallet + const token = await tempCoco.wallet.send(mintUrl, restoredAmount); + + // Receive the token in the main wallet + await coco.wallet.receive(token); + + // Verify the transfer + const balancesAfter = await coco.wallet.getBalances(); + const balanceAfter = balancesAfter[mintUrl] || 0; + const actualRestored = balanceAfter - balanceBefore; + + toast({ + title: "Restore Successful", + description: `Restored ${actualRestored} sats from the seed phrase and added to your current wallet.`, + }); + } finally { + // Clean up temporary database (optional - happens automatically on next session) + // The temporary IndexedDB will be isolated to the unique name we provided + } + + } catch (error) { + console.error('Restore failed:', error); + throw error; + } finally { + setIsRestoring(false); + } + }, [coco, toast]); + // Cleanup mint quote listener on component unmount useEffect(() => { return () => { @@ -422,6 +525,9 @@ export function useWalletTransactions({ handleReceive, handleSend, handleConfirmInvoicePayment, + // Restore functionality + handleRestoreFromSeedPhrase, + isRestoring, // Refs mintQuoteUnsubscribeRef, }; diff --git a/src/hooks/useBitcoinBalance.ts b/src/hooks/useBitcoinBalance.ts index 7c16081..38c0c13 100644 --- a/src/hooks/useBitcoinBalance.ts +++ b/src/hooks/useBitcoinBalance.ts @@ -6,6 +6,34 @@ import { useToast } from '@/hooks/useToast'; import { useQRCode } from '@/hooks/useQRCode'; import { useNsecAccess } from '@/hooks/useNsecAccess'; +// Blockstream API response types +interface BlockstreamTransactionStatus { + confirmed: boolean; + block_height?: number; + block_hash?: string; + block_time?: number; +} + +interface BlockstreamTransactionInput { + prevout?: { + scriptpubkey_address?: string; + value: number; + }; +} + +interface BlockstreamTransactionOutput { + scriptpubkey_address?: string; + value: number; +} + +interface BlockstreamTransaction { + txid: string; + fee?: number; + status: BlockstreamTransactionStatus; + vin: BlockstreamTransactionInput[]; + vout: BlockstreamTransactionOutput[]; +} + /** * Fetch Bitcoin transaction history for an address from Blockstream API */ @@ -16,17 +44,17 @@ async function fetchBitcoinTransactions(address: string): Promise { + return txs.map((tx: BlockstreamTransaction, index: number) => { // Determine if this is a sent or received transaction // For simplicity, we'll consider it received if the address appears in outputs // and sent if it appears in inputs - const isReceived = tx.vout.some((output: any) => + const isReceived = tx.vout.some((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address ); - const isSent = tx.vin.some((input: any) => + const isSent = tx.vin.some((input: BlockstreamTransactionInput) => input.prevout?.scriptpubkey_address === address ); @@ -37,17 +65,17 @@ async function fetchBitcoinTransactions(address: string): Promise output.scriptpubkey_address === address) - .reduce((sum: number, output: any) => sum + output.value, 0); + .filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address) + .reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0); } else if (isSent) { // Sum all inputs from this address minus outputs to this address const inputsFromAddress = tx.vin - .filter((input: any) => input.prevout?.scriptpubkey_address === address) - .reduce((sum: number, input: any) => sum + input.prevout.value, 0); + .filter((input: BlockstreamTransactionInput) => input.prevout?.scriptpubkey_address === address) + .reduce((sum: number, input: BlockstreamTransactionInput) => sum + (input.prevout?.value || 0), 0); const outputsToAddress = tx.vout - .filter((output: any) => output.scriptpubkey_address === address) - .reduce((sum: number, output: any) => sum + output.value, 0); + .filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address) + .reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0); amount = inputsFromAddress - outputsToAddress; fee = tx.fee || 0; @@ -62,7 +90,7 @@ async function fetchBitcoinTransactions(address: string): Promise