diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index ac1a6b3..ad1a31e 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -12,7 +12,7 @@ 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, UTXO } from '@/lib/bitcoin'; +import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, UTXO } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; import { TransactionCard } from './PaymentCard'; @@ -183,6 +183,17 @@ export function CashuWallet() { const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false); const [selectedUtxo, setSelectedUtxo] = useState(null); const [isLoadingUtxos, setIsLoadingUtxos] = useState(false); + const [feeRate, setFeeRate] = useState(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) => { @@ -259,13 +270,17 @@ export function CashuWallet() { 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 + feeRates.fastestFee, + isSendMax ); // Broadcast transaction @@ -316,8 +331,12 @@ export function CashuWallet() { setIsLoadingUtxos(true); try { - const fetchedUtxos = await fetchUTXOs(bitcoinAddress); + const [fetchedUtxos, feeRates] = await Promise.all([ + fetchUTXOs(bitcoinAddress), + getFeeRates() + ]); setUtxos(fetchedUtxos); + setFeeRate(feeRates.fastestFee); } catch (error) { console.error('Error fetching UTXOs:', error); toast({ @@ -529,9 +548,10 @@ export function CashuWallet() {
@@ -619,6 +639,8 @@ export function CashuWallet() { pendingBitcoinRecipient={pendingBitcoinRecipient} setPendingBitcoinRecipient={setPendingBitcoinRecipient} hasNsecAccess={hasNsecAccess} + bitcoinMaxAmount={bitcoinMaxAmount} + onSendMax={handleSendMax} /> diff --git a/src/components/wallet/PaymentCard.tsx b/src/components/wallet/PaymentCard.tsx index 5c16830..4df26b7 100644 --- a/src/components/wallet/PaymentCard.tsx +++ b/src/components/wallet/PaymentCard.tsx @@ -56,6 +56,8 @@ interface TransactionCardProps { pendingBitcoinRecipient?: string | null; setPendingBitcoinRecipient?: (value: string | null) => void; hasNsecAccess?: boolean; + bitcoinMaxAmount?: number; + onSendMax?: () => void; } export function TransactionCard({ @@ -93,11 +95,14 @@ export function TransactionCard({ pendingBitcoinRecipient, setPendingBitcoinRecipient, hasNsecAccess, + bitcoinMaxAmount, + onSendMax, }: TransactionCardProps) { // Slider state for confirmation const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]); const [addressSliderValue, setAddressSliderValue] = useState([0]); const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]); + const [sendMaxEnabled, setSendMaxEnabled] = useState(false); // Handle slider value changes and auto-submit at 100% const handleInvoiceSliderChange = (value: number[]) => { @@ -121,6 +126,14 @@ export function TransactionCard({ } }; + const handleSendMaxToggle = () => { + const newState = !sendMaxEnabled; + setSendMaxEnabled(newState); + if (newState && onSendMax) { + onSendMax(); + } + }; + const handleSliderMouseUp = (sliderId: string) => { // Reset the slider if it hasn't reached 100 if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) { @@ -148,6 +161,7 @@ export function TransactionCard({ useEffect(() => { if (!pendingBitcoinRecipient) { setBitcoinSliderValue([0]); + setSendMaxEnabled(false); } }, [pendingBitcoinRecipient]); @@ -162,7 +176,24 @@ export function TransactionCard({ : mode === 'bitcoin' && !pendingBitcoinRecipient ? 'Send Bitcoin on-chain' : mode === 'bitcoin' && pendingBitcoinRecipient - ? '' + ? ( +
+ + Sending to:{' '} + {pendingBitcoinRecipient} + + +
+ ) : pendingInvoice && decodedInvoiceAmount ? (
@@ -230,34 +261,32 @@ export function TransactionCard({ ) : pendingBitcoinRecipient ? ( // Step 2: Amount Input with Slider
-
- - Sending to:{' '} - {pendingBitcoinRecipient} - -
- setBitcoinAmount?.(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter' && bitcoinAmount && pendingBitcoinRecipient && !isLoading) { - onSend(); - } - }} - className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]" - />
diff --git a/src/lib/bitcoin.ts b/src/lib/bitcoin.ts index 8837763..6e011c8 100644 --- a/src/lib/bitcoin.ts +++ b/src/lib/bitcoin.ts @@ -133,6 +133,7 @@ export async function broadcastTransaction(txHex: string): Promise { * @param amountSats - Amount to send in satoshis * @param utxos - Available UTXOs * @param feeRate - Fee rate in sat/vB + * @param sendMax - If true, sends all UTXOs to recipient with no change output * @returns Signed transaction hex */ export async function createBitcoinTransaction( @@ -140,7 +141,8 @@ export async function createBitcoinTransaction( toAddress: string, amountSats: number, utxos: UTXO[], - feeRate: number + feeRate: number, + sendMax: boolean = false ): Promise<{ txHex: string; fee: number }> { // Create key pair from private key const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex'); @@ -182,33 +184,51 @@ export async function createBitcoinTransaction( totalInput += utxo.value; } - // Estimate transaction size + // Estimate transaction size based on sendMax mode // P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes - const estimatedSize = utxos.length * 57.5 + 2 * 43 + 10.5; // 2 outputs (recipient + change) + overhead + const outputCount = sendMax ? 1 : 2; // Send Max = 1 output, Regular = 2 outputs (recipient + change) + const estimatedSize = utxos.length * 57.5 + outputCount * 43 + 10.5; const estimatedFee = Math.ceil(estimatedSize * feeRate); - // Calculate change - const change = totalInput - amountSats - estimatedFee; + if (sendMax) { + // For Send Max: send all UTXOs to recipient, no change + const maxAmount = totalInput - estimatedFee; + + if (maxAmount <= 0) { + throw new Error( + `Insufficient funds for Send Max. Total: ${totalInput} sats, Fee: ${estimatedFee} sats` + ); + } - if (change < 0) { - throw new Error( - `Insufficient funds. Need ${amountSats + estimatedFee} sats, have ${totalInput} sats` - ); - } - - // Add output for recipient - psbt.addOutput({ - address: toAddress, - value: BigInt(amountSats), - }); - - // Add change output if significant (> dust limit) - const dustLimit = 546; // Standard dust limit for Bitcoin - if (change > dustLimit) { + // Add single output for recipient with max amount psbt.addOutput({ - address: changeAddress, - value: BigInt(change), + address: toAddress, + value: BigInt(maxAmount), }); + } else { + // Regular transaction: calculate change + const change = totalInput - amountSats - estimatedFee; + + if (change < 0) { + throw new Error( + `Insufficient funds. Need ${amountSats + estimatedFee} sats, have ${totalInput} sats` + ); + } + + // Add output for recipient + psbt.addOutput({ + address: toAddress, + value: BigInt(amountSats), + }); + + // Add change output if significant (> dust limit) + const dustLimit = 546; // Standard dust limit for Bitcoin + if (change > dustLimit) { + psbt.addOutput({ + address: changeAddress, + value: BigInt(change), + }); + } } // Create a Taproot signer @@ -245,3 +265,31 @@ export function satsToBTC(sats: number): string { export function btcToSats(btc: number): number { return Math.round(btc * 100000000); } + +/** + * Calculate the maximum amount that can be sent from available UTXOs + * This accounts for fees and dust limits + * @param utxos - Available UTXOs + * @param feeRate - Fee rate in sat/vB + * @returns Maximum amount in satoshis that can be sent + */ +export function calculateMaxSendAmount(utxos: UTXO[], feeRate: number): number { + if (utxos.length === 0) { + return 0; + } + + // Calculate total input value + const totalInput = utxos.reduce((sum, utxo) => sum + utxo.value, 0); + + // Estimate transaction size for a single output (no change) + // P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes + const estimatedSize = utxos.length * 57.5 + 43 + 10.5; // Single output + overhead + const estimatedFee = Math.ceil(estimatedSize * feeRate); + + // 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); +} \ No newline at end of file