mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
117 lines
4.3 KiB
TypeScript
117 lines
4.3 KiB
TypeScript
import { useState, useCallback } from 'react';
|
|
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';
|
|
import type { Manager } from 'coco-cashu-core';
|
|
import { useToast } from '@/hooks/useToast';
|
|
|
|
interface UseSeedPhraseRestoreProps {
|
|
coco: Manager | null;
|
|
}
|
|
|
|
export function useSeedPhraseRestore({ coco }: UseSeedPhraseRestoreProps) {
|
|
const { toast } = useToast();
|
|
const [isRestoring, setIsRestoring] = useState(false);
|
|
|
|
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]);
|
|
|
|
return {
|
|
handleRestoreFromSeedPhrase,
|
|
isRestoring,
|
|
};
|
|
}
|