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

+243 -1
View File
@@ -1,6 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { fetchUTXOs, type UTXO } from '@/lib/bitcoin';
import { useState } from 'react';
import { fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, npubToBitcoinAddress, nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useNsecAccess } from '@/hooks/useNsecAccess';
/**
* Fetch Bitcoin transaction history for an address from Blockstream API
@@ -104,3 +108,241 @@ export function useBitcoinTransactionHistory(address: string | null) {
staleTime: 10000, // Consider data stale after 10 seconds
});
}
/**
* Hook for Bitcoin operations (send, receive, consolidate, etc.)
*/
export function useBitcoinOperations(bitcoinAddress: string | null) {
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
const { refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
// State for Bitcoin operations
const [utxos, setUtxos] = useState<UTXO[]>([]);
const [isLoadingUtxos, setIsLoadingUtxos] = useState(false);
const [feeRate, setFeeRate] = useState<number>(1);
const [isConsolidating, setIsConsolidating] = useState(false);
// Calculate max send amount
const bitcoinMaxAmount = utxos.length > 0 ? calculateMaxSendAmount(utxos, feeRate) : 0;
// Fetch UTXOs for Bitcoin mode
const fetchBitcoinUtxos = async () => {
if (!bitcoinAddress) 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);
}
};
// Handle Send Max
const handleSendMax = (setBitcoinAmount: (amount: string) => void) => {
if (bitcoinMaxAmount > 0) {
setBitcoinAmount(bitcoinMaxAmount.toString());
}
};
// Handle Bitcoin Send
const handleBitcoinSend = async (
bitcoinAmount: string,
pendingBitcoinRecipient: string | null,
setBitcoinAmount: (amount: string) => void,
setBitcoinRecipient: (recipient: string) => void,
setPendingBitcoinRecipient: (recipient: string | null) => void,
setShowSendModal: (show: boolean) => void
) => {
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',
});
}
};
// Handle Bitcoin Receive
const handleBitcoinReceive = async (
setBitcoinAddressQRCode: (qr: string) => void,
setShowBitcoinAddressQR: (show: boolean) => void
) => {
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",
});
}
};
// Handle UTXO Consolidation
const handleConsolidateUtxos = async () => {
if (!hasNsecAccess || !bitcoinAddress || utxos.length <= 1) {
toast({
variant: "destructive",
title: "Consolidation Error",
description: "Cannot consolidate UTXOs",
});
return;
}
setIsConsolidating(true);
try {
const privateKey = getPrivateKey();
if (!privateKey) {
throw new Error('Unable to access private key');
}
// For consolidation, we send all UTXOs to our own address (self-send)
const consolidationAmount = calculateMaxSendAmount(utxos, feeRate);
if (consolidationAmount <= 0) {
throw new Error('Insufficient funds for consolidation');
}
// Fetch current UTXOs and fee rates
const [fetchedUtxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
// Create consolidation transaction (self-send with all UTXOs)
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
bitcoinAddress, // Send to our own address
consolidationAmount,
fetchedUtxos,
feeRates.fastestFee,
true // sendMax = true
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
toast({
title: "UTXOs Consolidated!",
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
});
// Refresh UTXOs and balance
refetchBitcoinBalance();
fetchBitcoinUtxos();
} catch (error) {
console.error('UTXO consolidation error:', error);
toast({
variant: "destructive",
title: "Consolidation Failed",
description: error instanceof Error ? error.message : 'Unknown error occurred',
});
} finally {
setIsConsolidating(false);
}
};
return {
// State
utxos,
isLoadingUtxos,
feeRate,
isConsolidating,
bitcoinMaxAmount,
// Functions
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
};
}