This commit is contained in:
lemonknowsall committed 2025-10-23 09:34:15 -07:00
1 parent e3cebf3a34
commit fabbb0b50e
3 files changed
+151 -52

No files matched your search

+26 -4
View File
@@ -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<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) => {
@@ -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() {
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex justify-center border-t border-muted hover:bg-muted/30 transition-colors"
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground font-medium">History</span>
</button>
</div>
</div>
@@ -619,6 +639,8 @@ export function CashuWallet() {
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={handleSendMax}
/>
</div>
</DrawerContent>
+55 -26
View File
@@ -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
? ''
? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending to:</span>{' '}
<span className="font-semibold text-foreground">{pendingBitcoinRecipient}</span>
</span>
<button
onClick={() => {
setPendingBitcoinRecipient?.(null);
setBitcoinAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
)
: pendingInvoice && decodedInvoiceAmount ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
@@ -230,34 +261,32 @@ export function TransactionCard({
) : pendingBitcoinRecipient ? (
// Step 2: Amount Input with Slider
<div className="space-y-8">
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending to:</span>{' '}
<span className="font-semibold text-foreground">{pendingBitcoinRecipient}</span>
</span>
<button
onClick={() => {
setPendingBitcoinRecipient?.(null);
setBitcoinAmount?.('');
<div className="flex items-center gap-3">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinAmount || ''}
onChange={(e) => setBitcoinAmount?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (bitcoinAmount || sendMaxEnabled) && pendingBitcoinRecipient && !isLoading) {
onSend();
}
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
disabled={sendMaxEnabled}
className="flex-1 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]"
/>
<button
onClick={handleSendMaxToggle}
disabled={!bitcoinMaxAmount}
className={`px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
sendMaxEnabled
? 'bg-orange-500 text-white border-orange-500 hover:bg-orange-600'
: 'bg-gray-100 text-gray-600 border-gray-300 hover:bg-gray-200'
} ${!bitcoinMaxAmount ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
>
<X className="h-4 w-4 text-muted-foreground" />
Send Max
</button>
</div>
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinAmount || ''}
onChange={(e) => 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]"
/>
<div className="mt-6">
<div className="relative w-full">
<div
@@ -271,7 +300,7 @@ export function TransactionCard({
max={100}
step={1}
className="w-full h-12"
disabled={!bitcoinAmount || isLoading}
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
/>
</div>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
+70 -22
View File
@@ -133,6 +133,7 @@ export async function broadcastTransaction(txHex: string): Promise<string> {
* @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);
}