UTXO consolidator, removed UTXO selection, centralized bitcoin hooks

This commit is contained in:
lemonknowsall committed 2025-10-23 10:41:56 -07:00
1 parent fabbb0b50e
commit cfd1e7269f
5 files changed
+403 -233

No files matched your search

+36 -151
View File
@@ -11,8 +11,8 @@ 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 } from '@/hooks/useBitcoinBalance';
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, UTXO } from '@/lib/bitcoin';
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
import { nostrPubkeyToBitcoinAddress, UTXO } from '@/lib/bitcoin';
import { QRModal } from '@/components/ui/qr-modal';
import { WalletHeader } from './WalletHeader';
import { TransactionCard } from './PaymentCard';
@@ -48,9 +48,22 @@ export function CashuWallet() {
const { copy: copyToClipboard } = useCopyToClipboard();
// Bitcoin hooks - including balance and transaction history
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
// Bitcoin operations hook
const {
utxos,
isLoadingUtxos,
feeRate,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
const {
setMint: setNpubCashMint,
@@ -177,23 +190,11 @@ export function CashuWallet() {
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
// UTXO state
const [utxos, setUtxos] = useState<UTXO[]>([]);
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
const [selectedUtxo, setSelectedUtxo] = useState<UTXO | null>(null);
const [isLoadingUtxos, setIsLoadingUtxos] = useState(false);
const [feeRate, setFeeRate] = useState<number>(1);
// Calculate max send amount
const bitcoinMaxAmount = utxos.length > 0 ? calculateMaxSendAmount(utxos, feeRate) : 0;
// Handle Send Max
const handleSendMax = () => {
if (bitcoinMaxAmount > 0) {
setBitcoinAmount(bitcoinMaxAmount.toString());
}
};
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
@@ -226,129 +227,6 @@ export function CashuWallet() {
// Ref to track if we've fetched npub.cash user info
const hasCheckedNpubCashRef = useRef(false);
// ============================================================================
// BITCOIN HANDLERS
// ============================================================================
const handleBitcoinSend = async () => {
if (!hasNsecAccess || !bitcoinAmount || !pendingBitcoinRecipient || !bitcoinAddress) {
toast({
variant: "destructive",
title: "Bitcoin Send Error",
description: "Missing required information for Bitcoin transaction",
});
return;
}
try {
const privateKey = getPrivateKey();
if (!privateKey) {
throw new Error('Unable to access private key');
}
const amountSats = parseInt(bitcoinAmount);
if (isNaN(amountSats) || amountSats <= 0) {
throw new Error('Invalid amount');
}
// Determine if the recipient is a Bitcoin address or npub
let recipientAddress: string;
if (pendingBitcoinRecipient.startsWith('bc1') || pendingBitcoinRecipient.startsWith('1') || pendingBitcoinRecipient.startsWith('3')) {
// It's already a Bitcoin address
recipientAddress = pendingBitcoinRecipient;
} else if (pendingBitcoinRecipient.startsWith('npub')) {
// It's an npub, convert to Bitcoin address
recipientAddress = npubToBitcoinAddress(pendingBitcoinRecipient);
} else {
// Assume it's a hex pubkey
recipientAddress = nostrPubkeyToBitcoinAddress(pendingBitcoinRecipient);
}
// Fetch UTXOs and fee rates
const [utxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
// Check if this is a Send Max transaction
const isSendMax = amountSats === bitcoinMaxAmount && bitcoinMaxAmount > 0;
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
recipientAddress,
amountSats,
utxos,
feeRates.fastestFee,
isSendMax
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
toast({
title: "Bitcoin Sent!",
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
});
// Reset form and refresh balance
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
refetchBitcoinBalance();
setShowSendModal(false);
} catch (error) {
console.error('Bitcoin send error:', error);
toast({
variant: "destructive",
title: "Bitcoin Send Failed",
description: error instanceof Error ? error.message : 'Unknown error occurred',
});
}
};
const handleBitcoinReceive = async () => {
if (!bitcoinAddress) return;
try {
const qr = await generateQRCode(bitcoinAddress);
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
} catch (error) {
console.error('QR generation error:', error);
toast({
variant: "destructive",
title: "QR Code Error",
description: "Failed to generate QR code",
});
}
};
// Fetch UTXOs for Bitcoin mode
const fetchBitcoinUtxos = async () => {
if (!bitcoinAddress || mode !== 'bitcoin') return;
setIsLoadingUtxos(true);
try {
const [fetchedUtxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
setUtxos(fetchedUtxos);
setFeeRate(feeRates.fastestFee);
} catch (error) {
console.error('Error fetching UTXOs:', error);
toast({
variant: "destructive",
title: "UTXO Error",
description: "Failed to fetch Bitcoin UTXOs",
});
} finally {
setIsLoadingUtxos(false);
}
};
// ============================================================================
// COMPUTED VALUES
// ============================================================================
@@ -449,11 +327,8 @@ export function CashuWallet() {
useEffect(() => {
if (mode === 'bitcoin' && bitcoinAddress) {
fetchBitcoinUtxos();
} else {
// Clear UTXOs when not in Bitcoin mode
setUtxos([]);
}
}, [mode, bitcoinAddress]);
}, [mode, bitcoinAddress, fetchBitcoinUtxos]);
// ============================================================================
// EFFECTS - Cleanup
@@ -514,8 +389,8 @@ export function CashuWallet() {
utxos={utxos}
utxoDropdownOpen={utxoDropdownOpen}
setUtxoDropdownOpen={setUtxoDropdownOpen}
selectedUtxo={selectedUtxo}
setSelectedUtxo={setSelectedUtxo}
onShowConsolidationModal={() => setShowConsolidationModal(true)}
isConsolidating={isConsolidating}
/>
@@ -567,6 +442,11 @@ export function CashuWallet() {
mintToRemove={mintToRemove}
onConfirmRemoveMint={handleConfirmRemoveMint}
isLoading={isLoading || isNpubCashLoading}
showConsolidationModal={showConsolidationModal}
setShowConsolidationModal={setShowConsolidationModal}
utxos={utxos}
onConfirmConsolidation={handleConsolidateUtxos}
isConsolidating={isConsolidating}
showLightningAddressQR={showLightningAddressQR}
setShowLightningAddressQR={setShowLightningAddressQR}
lightningAddressQRCode={lightningAddressQRCode}
@@ -614,7 +494,14 @@ export function CashuWallet() {
activeMintUrl={activeMintUrl}
onSend={() => {
if (mode === 'bitcoin') {
handleBitcoinSend();
handleBitcoinSend(
bitcoinAmount,
pendingBitcoinRecipient,
setBitcoinAmount,
setBitcoinRecipient,
setPendingBitcoinRecipient,
setShowSendModal
);
} else {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
@@ -638,9 +525,8 @@ export function CashuWallet() {
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={handleSendMax}
onSendMax={() => handleSendMax(setBitcoinAmount)}
/>
</div>
</DrawerContent>
@@ -677,7 +563,7 @@ export function CashuWallet() {
onSend={() => {}}
onReceive={() => {
if (mode === 'bitcoin') {
handleBitcoinReceive();
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
setShowReceiveModal(false);
} else {
handleReceive();
@@ -694,7 +580,6 @@ export function CashuWallet() {
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
+33 -74
View File
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button';
import { ChevronDown, Wallet, Check } from 'lucide-react';
import { ChevronDown, ArrowRightLeft } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
@@ -16,8 +16,8 @@ interface UTXOSelectorProps {
bitcoinAddress: string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
selectedUtxo: UTXO | null;
setSelectedUtxo: (utxo: UTXO | null) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
export function UTXOSelector({
@@ -26,8 +26,8 @@ export function UTXOSelector({
bitcoinAddress,
dropdownOpen,
setDropdownOpen,
selectedUtxo,
setSelectedUtxo,
onShowConsolidationModal,
isConsolidating,
}: UTXOSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
@@ -37,28 +37,6 @@ export function UTXOSelector({
.catch(() => setBtcUsdRate(null));
}, []);
// Auto-select first UTXO when UTXOs are loaded and none is selected
// Also handle case where selected UTXO is no longer available
useEffect(() => {
if (utxos.length > 0) {
if (!selectedUtxo) {
// No UTXO selected, select the first one
setSelectedUtxo(utxos[0]);
} else {
// Check if currently selected UTXO still exists in the list
const stillExists = utxos.some(utxo =>
utxo.txid === selectedUtxo.txid && utxo.vout === selectedUtxo.vout
);
if (!stillExists) {
// Selected UTXO no longer exists, select the first available one
setSelectedUtxo(utxos[0]);
}
}
} else {
// No UTXOs available, clear selection
setSelectedUtxo(null);
}
}, [utxos, selectedUtxo, setSelectedUtxo]);
const formatBalance = (sats: number): string => {
if (showSats) {
@@ -93,21 +71,12 @@ export function UTXOSelector({
>
<div className="flex items-center justify-between w-full min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
{selectedUtxo ? (
<>
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">
{formatUTXOBlock(selectedUtxo)}
</span>
</>
) : (
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
)}
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{selectedUtxo ? formatBalance(selectedUtxo.value) : formatBalance(totalBalance)}
{formatBalance(totalBalance)}
</span>
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
@@ -120,50 +89,40 @@ export function UTXOSelector({
No UTXOs available
</DropdownMenuItem>
) : (
utxos.map((utxo, index) => {
const isSelected = selectedUtxo &&
selectedUtxo.txid === utxo.txid &&
selectedUtxo.vout === utxo.vout;
return (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
onClick={() => setSelectedUtxo(isSelected ? null : utxo)}
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isSelected && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOBlock(utxo)}
</div>
utxos.map((utxo, index) => (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOBlock(utxo)}
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
);
})
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
))
)}
</div>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex flex-col gap-1">
{onShowConsolidationModal && (
<button
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Bitcoin wallet"
onClick={onShowConsolidationModal}
disabled={isConsolidating}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
title="Consolidate UTXOs"
>
<Wallet className="h-4 w-4" />
<ArrowRightLeft className="h-4 w-4" />
</button>
</div>
)}
</div>
);
}
+6 -6
View File
@@ -44,8 +44,8 @@ interface WalletHeaderProps {
utxos: UTXO[];
utxoDropdownOpen: boolean;
setUtxoDropdownOpen: (open: boolean) => void;
selectedUtxo: UTXO | null;
setSelectedUtxo: (utxo: UTXO | null) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
// Helper functions to prevent syntax errors in complex expressions
@@ -134,8 +134,8 @@ export function WalletHeader({
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
selectedUtxo,
setSelectedUtxo,
onShowConsolidationModal,
isConsolidating,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
@@ -342,8 +342,8 @@ export function WalletHeader({
bitcoinAddress={userPubkey ? nostrPubkeyToBitcoinAddress(userPubkey) : ''}
dropdownOpen={utxoDropdownOpen}
setDropdownOpen={setUtxoDropdownOpen}
selectedUtxo={selectedUtxo}
setSelectedUtxo={setSelectedUtxo}
onShowConsolidationModal={onShowConsolidationModal}
isConsolidating={isConsolidating}
/>
</div>
)}
+85 -1
View File
@@ -1,10 +1,11 @@
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 } from 'lucide-react';
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft } 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';
// Helper function to prevent complex template literals
const getLightningAddress = (userPubkey?: string, npubCashUserInfo?: { name?: string } | null): string => {
@@ -37,6 +38,13 @@ interface WalletModalProps {
onConfirmRemoveMint: () => void;
isLoading: boolean;
// Consolidation Modal
showConsolidationModal: boolean;
setShowConsolidationModal: (show: boolean) => void;
utxos: UTXO[];
onConfirmConsolidation: () => void;
isConsolidating: boolean;
// QR Modals
showLightningAddressQR: boolean;
setShowLightningAddressQR: (show: boolean) => void;
@@ -74,6 +82,11 @@ export function WalletModals({
mintToRemove,
onConfirmRemoveMint,
isLoading,
showConsolidationModal,
setShowConsolidationModal,
utxos,
onConfirmConsolidation,
isConsolidating,
showLightningAddressQR,
setShowLightningAddressQR,
lightningAddressQRCode,
@@ -213,6 +226,77 @@ export function WalletModals({
</div>
)}
{/* Consolidation Modal */}
{showConsolidationModal && (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4"
onClick={() => setShowConsolidationModal(false)}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={() => setShowConsolidationModal(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<ArrowRightLeft className="h-5 w-5 mr-2 text-primary" />
Consolidate UTXOs
</CardTitle>
<CardDescription>
Combine multiple UTXOs into a single transaction
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="text-center">
<div className="text-2xl font-bold text-primary mb-2">
{utxos.length} UTXO{utxos.length !== 1 ? 's' : ''}
</div>
<div className="text-sm text-muted-foreground">
Total Value: {utxos.reduce((sum, utxo) => sum + utxo.value, 0).toLocaleString()} sats
</div>
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>🔄 <strong>What this does:</strong> Combines all your UTXOs into a single transaction, sending the total amount (minus fees) back to your own address.</div>
<div>💰 <strong>Benefits:</strong> Reduces transaction fees for future payments and simplifies your UTXO management.</div>
<div>⚠️ <strong>Note:</strong> This will create a new transaction on the Bitcoin network and may take some time to confirm.</div>
</div>
<div className="flex justify-center">
<Button
onClick={() => {
onConfirmConsolidation();
setShowConsolidationModal(false);
}}
disabled={isConsolidating || utxos.length <= 1}
>
{isConsolidating ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Consolidating...
</>
) : (
<>
<ArrowRightLeft className="h-4 w-4 mr-2" />
Consolidate UTXOs
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* QR Modals */}
<QRModal
isOpen={showLightningAddressQR}