fixed send card for on-chain and added pay to pubkey

This commit is contained in:
lemonknowsall committed 2025-10-19 21:54:27 -07:00
1 parent 617edd1784
commit 722b1a743f
7 files changed
+731 -40

No files matched your search

+168 -10
View File
@@ -10,6 +10,9 @@ import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
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 } from '@/hooks/useBitcoinBalance';
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin';
import { QRModal } from '@/components/ui/qr-modal';
import { WalletHeader } from './WalletHeader';
import { TransactionCard } from './PaymentCard';
@@ -43,6 +46,11 @@ export function CashuWallet() {
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// Bitcoin hooks
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
const {
setMint: setNpubCashMint,
@@ -152,7 +160,7 @@ export function CashuWallet() {
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('lightning');
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
@@ -168,6 +176,13 @@ export function CashuWallet() {
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
@@ -180,6 +195,10 @@ export function CashuWallet() {
setPendingLightningAddress(null);
setDecodedInvoiceAmount(null);
setPendingInvoice(null);
// Reset Bitcoin state
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
}
};
@@ -195,11 +214,108 @@ 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()
]);
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
recipientAddress,
amountSats,
utxos,
feeRates.fastestFee
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
toast({
title: "Bitcoin Sent!",
description: `Transaction ${txId.slice(0, 8)}... confirmed`,
});
// 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",
});
}
};
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
const totalBalance: number = mode === 'bitcoin'
? (bitcoinBalanceData?.balance || 0)
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// EFFECTS - Error Handling
@@ -322,6 +438,10 @@ export function CashuWallet() {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
}}
onShowBitcoinAddressQR={(qr) => {
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
}}
generateQRCode={generateQRCode}
// MintSelector props
activeMintUrl={activeMintUrl}
@@ -432,10 +552,14 @@ export function CashuWallet() {
setQuoteAmount={() => {}}
activeMintUrl={activeMintUrl}
onSend={() => {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
if (mode === 'bitcoin') {
handleBitcoinSend();
} else {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
}
}
}}
onReceive={() => {}}
@@ -444,7 +568,16 @@ export function CashuWallet() {
setShowSendModal(false);
}}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading || isNpubCashLoading}
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
// Bitcoin props
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount={bitcoinAmount}
setBitcoinAmount={setBitcoinAmount}
bitcoinRecipient={bitcoinRecipient}
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
@@ -480,11 +613,25 @@ export function CashuWallet() {
activeMintUrl={activeMintUrl}
onSend={() => {}}
onReceive={() => {
handleReceive();
setShowReceiveModal(false);
if (mode === 'bitcoin') {
handleBitcoinReceive();
setShowReceiveModal(false);
} else {
handleReceive();
setShowReceiveModal(false);
}
}}
isResolvingAddress={false}
isLoading={isLoading || isNpubCashLoading}
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
// Bitcoin props
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount=""
setBitcoinAmount={() => {}}
bitcoinRecipient=""
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
@@ -503,6 +650,17 @@ export function CashuWallet() {
</ScrollArea>
</DrawerContent>
</Drawer>
{/* Bitcoin Address QR Modal */}
<QRModal
isOpen={showBitcoinAddressQR}
onClose={() => setShowBitcoinAddressQR(false)}
title="Bitcoin Address"
description="Scan this QR code to send Bitcoin to your address"
qrCodeUrl={bitcoinAddressQRCode}
content={bitcoinAddress || ''}
icon="qr"
/>
</>
</div>
</>
+149 -4
View File
@@ -5,7 +5,7 @@ import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react';
import { useState, useEffect } from 'react';
interface TransactionCardProps {
mode: 'tokens' | 'lightning';
mode: 'tokens' | 'lightning' | 'bitcoin';
operation: 'send' | 'receive';
// Send props
sendAmount: string;
@@ -34,6 +34,15 @@ interface TransactionCardProps {
onConfirmInvoice?: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
// Bitcoin props
bitcoinAddress?: string;
bitcoinAmount?: string;
setBitcoinAmount?: (value: string) => void;
bitcoinRecipient?: string;
setBitcoinRecipient?: (value: string) => void;
pendingBitcoinRecipient?: string | null;
setPendingBitcoinRecipient?: (value: string | null) => void;
hasNsecAccess?: boolean;
}
export function TransactionCard({
@@ -63,10 +72,19 @@ export function TransactionCard({
onConfirmInvoice,
isResolvingAddress,
isLoading,
bitcoinAddress,
bitcoinAmount,
setBitcoinAmount,
bitcoinRecipient,
setBitcoinRecipient,
pendingBitcoinRecipient,
setPendingBitcoinRecipient,
hasNsecAccess,
}: TransactionCardProps) {
// Slider state for confirmation
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
const [addressSliderValue, setAddressSliderValue] = useState([0]);
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
// Handle slider value changes and auto-submit at 100%
const handleInvoiceSliderChange = (value: number[]) => {
@@ -83,6 +101,13 @@ export function TransactionCard({
}
};
const handleBitcoinSliderChange = (value: number[]) => {
setBitcoinSliderValue(value);
if (value[0] === 100) {
onSend();
}
};
// Reset sliders when states change
const resetSliders = () => {
setInvoiceSliderValue([0]);
@@ -102,6 +127,12 @@ export function TransactionCard({
}
}, [pendingLightningAddress]);
useEffect(() => {
if (!pendingBitcoinRecipient) {
setBitcoinSliderValue([0]);
}
}, [pendingBitcoinRecipient]);
return (
<div className="space-y-8">
{/* Title */}
@@ -110,6 +141,10 @@ export function TransactionCard({
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: mode === 'bitcoin' && !pendingBitcoinRecipient
? 'Send Bitcoin on-chain'
: mode === 'bitcoin' && pendingBitcoinRecipient
? ''
: 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">
@@ -148,6 +183,8 @@ export function TransactionCard({
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
: mode === 'bitcoin'
? 'Receive Bitcoin on-chain'
: 'Deposit funds with Lightning'
)}
</p>
@@ -155,7 +192,7 @@ export function TransactionCard({
{/* Content */}
<div className="space-y-8">
{!activeMintUrl && (
{!activeMintUrl && mode !== 'bitcoin' && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{operation === 'send'
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
@@ -166,7 +203,96 @@ export function TransactionCard({
{operation === 'send' ? (
// Send Mode
mode === 'tokens' ? (
mode === 'bitcoin' ? (
// Bitcoin Send
<div className="space-y-8">
{!hasNsecAccess ? (
<div className="flex justify-center items-center h-32">
<div className="text-sm text-destructive bg-destructive/10 border border-destructive/20 p-3 rounded text-center">
⚠️ Login with nsec required to send Bitcoin
</div>
</div>
) : 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?.('');
}}
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
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">
<Slider
value={bitcoinSliderValue}
onValueChange={handleBitcoinSliderChange}
max={100}
step={1}
className="w-full h-12"
disabled={!bitcoinAmount || isLoading}
/>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-sm font-medium text-muted-foreground">
{bitcoinSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
</span>
</div>
</div>
</div>
</div>
) : (
// Step 1: Recipient Input
<div className="space-y-8">
<Input
placeholder="Bitcoin address or npub..."
value={bitcoinRecipient || ''}
onChange={(e) => setBitcoinRecipient?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinRecipient && !isLoading) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6">
<Button
onClick={() => {
if (bitcoinRecipient) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
disabled={!bitcoinRecipient || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)}
</div>
) : mode === 'tokens' ? (
// Cashu Token Send
<div className="space-y-8">
<Input
@@ -286,7 +412,26 @@ export function TransactionCard({
)
) : (
// Receive Mode
mode === 'tokens' ? (
mode === 'bitcoin' ? (
// Bitcoin Receive
<div className="space-y-8">
<div className="text-center">
<div className="font-mono text-sm bg-muted p-3 rounded border break-all">
{bitcoinAddress}
</div>
</div>
<div className="flex justify-center mt-6">
<Button
onClick={onReceive}
disabled={isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : mode === 'tokens' ? (
// Cashu Token Receive
<div className="space-y-8">
<Input
+83 -26
View File
@@ -1,11 +1,12 @@
import { useState, useEffect } from 'react';
import { nip19 } from 'nostr-tools';
import { Zap, Coins, Copy, Check, QrCode } from 'lucide-react';
import { Zap, Coins, Copy, Check, QrCode, Link } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { useToast } from '@/hooks/useToast';
import { LoginIcon } from '@/components/auth/LoginIcon';
import { MintSelector } from './MintSelector';
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
interface CashuMint {
url: string;
@@ -17,12 +18,13 @@ interface WalletHeaderProps {
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning';
setMode: (mode: 'tokens' | 'lightning') => void;
mode: 'tokens' | 'lightning' | 'bitcoin';
setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void;
userPubkey?: string;
npubCashUsername?: string;
onCopyToClipboard: (text: string) => Promise<void>;
onShowLightningAddressQR: (qrCode: string) => void;
onShowBitcoinAddressQR: (qrCode: string) => void;
generateQRCode: (text: string) => Promise<string>;
// MintSelector props
activeMintUrl: string | null;
@@ -49,6 +51,7 @@ export function WalletHeader({
npubCashUsername,
onCopyToClipboard,
onShowLightningAddressQR,
onShowBitcoinAddressQR,
generateQRCode,
// MintSelector props
activeMintUrl,
@@ -64,6 +67,7 @@ export function WalletHeader({
setDropdownOpen,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
const { toast } = useToast();
@@ -74,14 +78,24 @@ export function WalletHeader({
}, []);
const toggleMode = () => {
const newMode = mode === 'tokens' ? 'lightning' : 'tokens';
let newMode: 'tokens' | 'lightning' | 'bitcoin';
if (mode === 'lightning') {
newMode = 'tokens';
} else if (mode === 'tokens') {
newMode = 'bitcoin';
} else {
newMode = 'lightning';
}
setMode(newMode);
toast({
title: `${newMode === 'tokens' ? 'Cashu' : 'Lightning'} Enabled!`,
title: `${newMode === 'tokens' ? 'Cashu' : newMode === 'lightning' ? 'Lightning' : 'Bitcoin'} Enabled!`,
description: newMode === 'tokens'
? 'Send and receive with Cashu eCash'
: 'Send and receive with Lightning',
: newMode === 'lightning'
? 'Send and receive with Lightning'
: 'Send and receive with on-chain Bitcoin',
});
};
@@ -93,12 +107,14 @@ export function WalletHeader({
<button
onClick={toggleMode}
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={mode === 'tokens' ? 'Switch to Lightning' : 'Switch to Cashu Tokens'}
title={mode === 'tokens' ? 'Switch to Lightning' : mode === 'lightning' ? 'Switch to Bitcoin' : 'Switch to Cashu Tokens'}
>
{mode === 'tokens' ? (
<Coins className="h-6 w-6" />
) : (
) : mode === 'lightning' ? (
<Zap className="h-6 w-6" />
) : (
<Link className="h-6 w-6" />
)}
</button>
</div>
@@ -128,7 +144,7 @@ export function WalletHeader({
<div className="w-full max-w-[400px] mx-auto">
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && (
{userPubkey && mode !== 'bitcoin' && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
@@ -167,25 +183,66 @@ export function WalletHeader({
</button>
</div>
)}
{/* Bitcoin Address Row */}
{userPubkey && mode === 'bitcoin' && (() => {
const bitcoinAddress = nostrPubkeyToBitcoinAddress(userPubkey);
return bitcoinAddress ? (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
await onCopyToClipboard(bitcoinAddress);
setBitcoinAddressCopied(true);
setTimeout(() => setBitcoinAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Bitcoin address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{bitcoinAddress}
</span>
</div>
{bitcoinAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const qr = await generateQRCode(bitcoinAddress);
onShowBitcoinAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
) : null;
})()}
{/* Mint Selector Row */}
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
{mode !== 'bitcoin' && (
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
)}
</div>
</div>
</div>