mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
cashu wallet restore and addressed some test errors
This commit is contained in:
1 parent
cfd1e7269f
commit
aff1b0add5
6 files changed
+240
-48
No files matched your search
@@ -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 */}
|
||||
|
||||
@@ -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
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
utxos.map((utxo, index) => (
|
||||
utxos.map((utxo) => (
|
||||
<DropdownMenuItem
|
||||
key={`utxo-${utxo.txid}-${utxo.vout}`}
|
||||
className="flex items-center justify-between p-3 text-base"
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2 } from 'lucide-react';
|
||||
import { QRModal } from '@/components/ui/qr-modal';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { UTXO } from '@/lib/bitcoin';
|
||||
import { useState } from 'react';
|
||||
|
||||
// Helper function to prevent complex template literals
|
||||
const getLightningAddress = (userPubkey?: string, npubCashUserInfo?: { name?: string } | null): string => {
|
||||
@@ -71,6 +74,12 @@ interface WalletModalProps {
|
||||
// Seed Phrase Info Modal
|
||||
showSeedPhraseInfo: boolean;
|
||||
setShowSeedPhraseInfo: (show: boolean) => void;
|
||||
|
||||
// Restore functionality
|
||||
onRestoreFromSeedPhrase: (seedPhrase: string, mintUrl: string) => Promise<void>;
|
||||
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 && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
@@ -368,48 +384,90 @@ export function WalletModals({
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center mb-4 pr-8">
|
||||
<Key className="h-5 w-5 mr-2" />
|
||||
<h2 className="text-lg font-semibold">What is a Seed Phrase?</h2>
|
||||
<h2 className="text-lg font-semibold">Restore from Seed Phrase</h2>
|
||||
</div>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
Your seed phrase is a secure way to backup and restore your wallet
|
||||
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Enter your seed phrase to restore tokens from the active mint.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4 text-sm">
|
||||
<div>
|
||||
<h4 className="font-semibold mb-2">🔐 Recovery Key</h4>
|
||||
<p className="text-muted-foreground">
|
||||
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 && (
|
||||
<div className="bg-muted p-3 rounded-md mb-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Active Mint:</strong> {mints.find(m => m.url === activeMintUrl)?.name || new URL(activeMintUrl).hostname}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="font-semibold mb-2">💾 Backup Important</h4>
|
||||
<p className="text-muted-foreground">
|
||||
Write down your seed phrase and store it securely offline. Anyone with access
|
||||
to your seed phrase can control your wallet and funds.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="font-semibold mb-2">🛡️ Security Tips</h4>
|
||||
<ul className="text-muted-foreground space-y-1 ml-4">
|
||||
<li>• Never share your seed phrase with anyone</li>
|
||||
<li>• Store it offline in a secure location</li>
|
||||
<li>• Don't take screenshots or store it digitally</li>
|
||||
<li>• Use it only to restore your wallet</li>
|
||||
</ul>
|
||||
<Label htmlFor="seed-phrase">Seed Phrase</Label>
|
||||
<Input
|
||||
id="seed-phrase"
|
||||
type="text"
|
||||
placeholder="Enter your 12-word seed phrase..."
|
||||
value={seedPhraseInput}
|
||||
onChange={(e) => setSeedPhraseInput(e.target.value)}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Note:</strong> The seed phrase shown above is masked for privacy.
|
||||
Click the copy button to access the actual phrase for backup purposes.
|
||||
<strong>Note:</strong> This will restore tokens from the provided seed phrase and add them to your current wallet balance.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<Button
|
||||
onClick={async () => {
|
||||
if (!seedPhraseInput.trim()) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Missing Information",
|
||||
description: "Please enter your seed phrase.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeMintUrl) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "No Active Mint",
|
||||
description: "Please select a mint first.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await onRestoreFromSeedPhrase(seedPhraseInput.trim(), activeMintUrl);
|
||||
setSeedPhraseInput('');
|
||||
setShowSeedPhraseInfo(false);
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Restore Failed",
|
||||
description: error instanceof Error ? error.message : "Failed to restore from seed phrase",
|
||||
});
|
||||
}
|
||||
}}
|
||||
disabled={isRestoring || !seedPhraseInput.trim() || !activeMintUrl}
|
||||
className="w-full"
|
||||
>
|
||||
{isRestoring ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Restoring...
|
||||
</>
|
||||
) : (
|
||||
'Restore Tokens'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -289,7 +289,5 @@ export function calculateMaxSendAmount(utxos: UTXO[], feeRate: number): number {
|
||||
// Calculate maximum amount (total input minus fees)
|
||||
const maxAmount = totalInput - estimatedFee;
|
||||
|
||||
// Ensure we don't go below dust limit
|
||||
const dustLimit = 546; // Standard dust limit for Bitcoin
|
||||
return Math.max(0, maxAmount);
|
||||
}
|
||||
Reference in new issue
Block a user