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>