mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 08:47:23 +00:00
Send Max
This commit is contained in:
1 parent
e3cebf3a34
commit
fabbb0b50e
3 files changed
+127
-28
No files matched your search
@@ -12,7 +12,7 @@ import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
|||||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||||
import { useBitcoinBalance, useBitcoinTransactionHistory } from '@/hooks/useBitcoinBalance';
|
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 { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { WalletHeader } from './WalletHeader';
|
import { WalletHeader } from './WalletHeader';
|
||||||
import { TransactionCard } from './PaymentCard';
|
import { TransactionCard } from './PaymentCard';
|
||||||
@@ -183,6 +183,17 @@ export function CashuWallet() {
|
|||||||
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
|
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
|
||||||
const [selectedUtxo, setSelectedUtxo] = useState<UTXO | null>(null);
|
const [selectedUtxo, setSelectedUtxo] = useState<UTXO | null>(null);
|
||||||
const [isLoadingUtxos, setIsLoadingUtxos] = useState(false);
|
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
|
// Handle drawer close with state reset
|
||||||
const handleSendDrawerClose = (open: boolean) => {
|
const handleSendDrawerClose = (open: boolean) => {
|
||||||
@@ -259,13 +270,17 @@ export function CashuWallet() {
|
|||||||
getFeeRates()
|
getFeeRates()
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Check if this is a Send Max transaction
|
||||||
|
const isSendMax = amountSats === bitcoinMaxAmount && bitcoinMaxAmount > 0;
|
||||||
|
|
||||||
// Create and sign transaction
|
// Create and sign transaction
|
||||||
const { txHex, fee } = await createBitcoinTransaction(
|
const { txHex, fee } = await createBitcoinTransaction(
|
||||||
privateKey,
|
privateKey,
|
||||||
recipientAddress,
|
recipientAddress,
|
||||||
amountSats,
|
amountSats,
|
||||||
utxos,
|
utxos,
|
||||||
feeRates.fastestFee
|
feeRates.fastestFee,
|
||||||
|
isSendMax
|
||||||
);
|
);
|
||||||
|
|
||||||
// Broadcast transaction
|
// Broadcast transaction
|
||||||
@@ -316,8 +331,12 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
setIsLoadingUtxos(true);
|
setIsLoadingUtxos(true);
|
||||||
try {
|
try {
|
||||||
const fetchedUtxos = await fetchUTXOs(bitcoinAddress);
|
const [fetchedUtxos, feeRates] = await Promise.all([
|
||||||
|
fetchUTXOs(bitcoinAddress),
|
||||||
|
getFeeRates()
|
||||||
|
]);
|
||||||
setUtxos(fetchedUtxos);
|
setUtxos(fetchedUtxos);
|
||||||
|
setFeeRate(feeRates.fastestFee);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching UTXOs:', error);
|
console.error('Error fetching UTXOs:', error);
|
||||||
toast({
|
toast({
|
||||||
@@ -529,9 +548,10 @@ export function CashuWallet() {
|
|||||||
<div className="max-w-4xl mx-auto">
|
<div className="max-w-4xl mx-auto">
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowHistoryModal(true)}
|
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" />
|
<ChevronUp className="h-5 w-5 text-muted-foreground" />
|
||||||
|
<span className="text-xs text-muted-foreground font-medium">History</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -619,6 +639,8 @@ export function CashuWallet() {
|
|||||||
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
||||||
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
||||||
hasNsecAccess={hasNsecAccess}
|
hasNsecAccess={hasNsecAccess}
|
||||||
|
bitcoinMaxAmount={bitcoinMaxAmount}
|
||||||
|
onSendMax={handleSendMax}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ interface TransactionCardProps {
|
|||||||
pendingBitcoinRecipient?: string | null;
|
pendingBitcoinRecipient?: string | null;
|
||||||
setPendingBitcoinRecipient?: (value: string | null) => void;
|
setPendingBitcoinRecipient?: (value: string | null) => void;
|
||||||
hasNsecAccess?: boolean;
|
hasNsecAccess?: boolean;
|
||||||
|
bitcoinMaxAmount?: number;
|
||||||
|
onSendMax?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TransactionCard({
|
export function TransactionCard({
|
||||||
@@ -93,11 +95,14 @@ export function TransactionCard({
|
|||||||
pendingBitcoinRecipient,
|
pendingBitcoinRecipient,
|
||||||
setPendingBitcoinRecipient,
|
setPendingBitcoinRecipient,
|
||||||
hasNsecAccess,
|
hasNsecAccess,
|
||||||
|
bitcoinMaxAmount,
|
||||||
|
onSendMax,
|
||||||
}: TransactionCardProps) {
|
}: TransactionCardProps) {
|
||||||
// Slider state for confirmation
|
// Slider state for confirmation
|
||||||
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
|
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
|
||||||
const [addressSliderValue, setAddressSliderValue] = useState([0]);
|
const [addressSliderValue, setAddressSliderValue] = useState([0]);
|
||||||
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
|
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
|
||||||
|
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
|
||||||
|
|
||||||
// Handle slider value changes and auto-submit at 100%
|
// Handle slider value changes and auto-submit at 100%
|
||||||
const handleInvoiceSliderChange = (value: number[]) => {
|
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) => {
|
const handleSliderMouseUp = (sliderId: string) => {
|
||||||
// Reset the slider if it hasn't reached 100
|
// Reset the slider if it hasn't reached 100
|
||||||
if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) {
|
if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) {
|
||||||
@@ -148,6 +161,7 @@ export function TransactionCard({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!pendingBitcoinRecipient) {
|
if (!pendingBitcoinRecipient) {
|
||||||
setBitcoinSliderValue([0]);
|
setBitcoinSliderValue([0]);
|
||||||
|
setSendMaxEnabled(false);
|
||||||
}
|
}
|
||||||
}, [pendingBitcoinRecipient]);
|
}, [pendingBitcoinRecipient]);
|
||||||
|
|
||||||
@@ -162,7 +176,24 @@ export function TransactionCard({
|
|||||||
: mode === 'bitcoin' && !pendingBitcoinRecipient
|
: mode === 'bitcoin' && !pendingBitcoinRecipient
|
||||||
? 'Send Bitcoin on-chain'
|
? 'Send Bitcoin on-chain'
|
||||||
: mode === 'bitcoin' && pendingBitcoinRecipient
|
: 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 ? (
|
: pendingInvoice && decodedInvoiceAmount ? (
|
||||||
<div className="flex items-center justify-center gap-2">
|
<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="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
||||||
@@ -230,34 +261,32 @@ export function TransactionCard({
|
|||||||
) : pendingBitcoinRecipient ? (
|
) : pendingBitcoinRecipient ? (
|
||||||
// Step 2: Amount Input with Slider
|
// Step 2: Amount Input with Slider
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<div className="flex items-center justify-center gap-2">
|
<div className="flex items-center gap-3">
|
||||||
<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>
|
|
||||||
<Input
|
<Input
|
||||||
placeholder="Amount (sats)"
|
placeholder="Amount (sats)"
|
||||||
type="number"
|
type="number"
|
||||||
value={bitcoinAmount || ''}
|
value={bitcoinAmount || ''}
|
||||||
onChange={(e) => setBitcoinAmount?.(e.target.value)}
|
onChange={(e) => setBitcoinAmount?.(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter' && bitcoinAmount && pendingBitcoinRecipient && !isLoading) {
|
if (e.key === 'Enter' && (bitcoinAmount || sendMaxEnabled) && pendingBitcoinRecipient && !isLoading) {
|
||||||
onSend();
|
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]"
|
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'}`}
|
||||||
|
>
|
||||||
|
Send Max
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<div
|
<div
|
||||||
@@ -271,7 +300,7 @@ export function TransactionCard({
|
|||||||
max={100}
|
max={100}
|
||||||
step={1}
|
step={1}
|
||||||
className="w-full h-12"
|
className="w-full h-12"
|
||||||
disabled={!bitcoinAmount || isLoading}
|
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||||
|
|||||||
+52
-4
@@ -133,6 +133,7 @@ export async function broadcastTransaction(txHex: string): Promise<string> {
|
|||||||
* @param amountSats - Amount to send in satoshis
|
* @param amountSats - Amount to send in satoshis
|
||||||
* @param utxos - Available UTXOs
|
* @param utxos - Available UTXOs
|
||||||
* @param feeRate - Fee rate in sat/vB
|
* @param feeRate - Fee rate in sat/vB
|
||||||
|
* @param sendMax - If true, sends all UTXOs to recipient with no change output
|
||||||
* @returns Signed transaction hex
|
* @returns Signed transaction hex
|
||||||
*/
|
*/
|
||||||
export async function createBitcoinTransaction(
|
export async function createBitcoinTransaction(
|
||||||
@@ -140,7 +141,8 @@ export async function createBitcoinTransaction(
|
|||||||
toAddress: string,
|
toAddress: string,
|
||||||
amountSats: number,
|
amountSats: number,
|
||||||
utxos: UTXO[],
|
utxos: UTXO[],
|
||||||
feeRate: number
|
feeRate: number,
|
||||||
|
sendMax: boolean = false
|
||||||
): Promise<{ txHex: string; fee: number }> {
|
): Promise<{ txHex: string; fee: number }> {
|
||||||
// Create key pair from private key
|
// Create key pair from private key
|
||||||
const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex');
|
const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex');
|
||||||
@@ -182,12 +184,29 @@ export async function createBitcoinTransaction(
|
|||||||
totalInput += utxo.value;
|
totalInput += utxo.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Estimate transaction size
|
// Estimate transaction size based on sendMax mode
|
||||||
// P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes
|
// 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);
|
const estimatedFee = Math.ceil(estimatedSize * feeRate);
|
||||||
|
|
||||||
// Calculate change
|
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`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add single output for recipient with max amount
|
||||||
|
psbt.addOutput({
|
||||||
|
address: toAddress,
|
||||||
|
value: BigInt(maxAmount),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Regular transaction: calculate change
|
||||||
const change = totalInput - amountSats - estimatedFee;
|
const change = totalInput - amountSats - estimatedFee;
|
||||||
|
|
||||||
if (change < 0) {
|
if (change < 0) {
|
||||||
@@ -210,6 +229,7 @@ export async function createBitcoinTransaction(
|
|||||||
value: BigInt(change),
|
value: BigInt(change),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Create a Taproot signer
|
// Create a Taproot signer
|
||||||
// For Taproot key-path spending, we need to tweak the private key
|
// For Taproot key-path spending, we need to tweak the private key
|
||||||
@@ -245,3 +265,31 @@ export function satsToBTC(sats: number): string {
|
|||||||
export function btcToSats(btc: number): number {
|
export function btcToSats(btc: number): number {
|
||||||
return Math.round(btc * 100000000);
|
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);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user