cashu wallet restore and addressed some test errors

This commit is contained in:
lemonknowsall committed 2025-10-24 22:34:26 -07:00
1 parent cfd1e7269f
commit aff1b0add5
6 files changed
+240 -48

No files matched your search

+106
View File
@@ -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,
};
+39 -11
View File
@@ -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<BitcoinTransac
throw new Error('Failed to fetch Bitcoin transactions');
}
const txs = await response.json();
const txs: BlockstreamTransaction[] = await response.json();
// Transform Blockstream API response to our BitcoinTransaction format
return txs.map((tx: any, index: number) => {
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<BitcoinTransac
if (isReceived) {
// Sum all outputs to this address
amount = 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);
} 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<BitcoinTransac
address: address,
confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified
blockHeight: tx.status.block_height,
timestamp: tx.status.block_time * 1000, // Convert to milliseconds
timestamp: (tx.status.block_time ?? 0) * 1000, // Convert to milliseconds
status: tx.status.confirmed ? 'confirmed' : 'unconfirmed'
} as BitcoinTransaction;
});