Files
mkstack/src/components/wallet/BitcoinWallet.tsx
T

413 lines
15 KiB
TypeScript

import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/wallet/useBitcoin';
import { useNsecAccess } from '@/hooks/useNsecAccess';
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
import { QRModal } from '@/components/ui/qr-modal';
import { TransactionCard } from './PaymentCard';
import { ConsolidationModal } from './ConsolidationModal';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
interface BitcoinWalletProps {
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
generateQRCode: (text: string) => Promise<string>;
copyToClipboard: (text: string) => Promise<void>;
user?: { pubkey: string };
onRequestQRScanner: () => void;
onQRResult?: (result: QRScanResult) => void;
onWalletHeaderPropsChange?: (props: any) => void;
}
export function BitcoinWallet({
toast,
generateQRCode,
copyToClipboard,
user,
onRequestQRScanner,
onQRResult,
onWalletHeaderPropsChange,
}: BitcoinWalletProps) {
const { hasNsecAccess } = useNsecAccess();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
const {
utxos,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
const {
data: bitcoinTransactions = [],
isLoading: isBitcoinTransactionsLoading
} = useBitcoinTransactionHistory(bitcoinAddress);
// 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('');
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
// UTXO state
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
// Fetch UTXOs when component mounts
useEffect(() => {
if (bitcoinAddress) {
fetchBitcoinUtxos();
}
}, [bitcoinAddress, fetchBitcoinUtxos]);
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
if (!open) {
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
}
};
const handleReceiveDrawerClose = (open: boolean) => {
setShowReceiveModal(open);
};
// Handle focus management when drawers open
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// Handle QR scan results (called from parent WalletContainer)
useEffect(() => {
if (!onQRResult) return;
const handleQRResult = (result: QRScanResult) => {
if (result.type === 'bitcoin_address') {
setBitcoinRecipient(result.value);
setPendingBitcoinRecipient(result.value);
setShowSendModal(true);
toast({
title: "Bitcoin Address Scanned",
description: "Enter amount to send",
});
} else if (result.type === 'npub') {
try {
const decoded = nip19.decode(result.value);
if (decoded.type === 'npub') {
const address = nostrPubkeyToBitcoinAddress(decoded.data);
setBitcoinRecipient(address);
setPendingBitcoinRecipient(address);
setShowSendModal(true);
toast({
title: "Nostr npub Scanned",
description: "Enter amount to send",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Invalid npub",
description: "Could not decode npub",
});
}
}
};
// Store handler for parent to call
(window as any).__bitcoinWalletQRHandler = handleQRResult;
return () => {
delete (window as any).__bitcoinWalletQRHandler;
};
}, [onQRResult, toast]);
const totalBalance = bitcoinBalanceData?.balance || 0;
// Expose WalletHeader props to parent WalletContainer
// Use ref to track previous values and prevent infinite loops
const prevPropsRef = useRef<{
utxosLength?: number;
utxoDropdownOpen?: boolean;
isConsolidating?: boolean;
}>({});
useEffect(() => {
if (!onWalletHeaderPropsChange) return;
// Check if values actually changed
const currentProps = {
utxosLength: utxos?.length,
utxoDropdownOpen,
isConsolidating,
};
const prevProps = prevPropsRef.current;
const hasChanged =
prevProps.utxosLength !== currentProps.utxosLength ||
prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen ||
prevProps.isConsolidating !== currentProps.isConsolidating;
if (!hasChanged && Object.keys(prevProps).length > 0) {
// Values haven't changed, skip update
return;
}
// Update ref
prevPropsRef.current = currentProps;
// Send updated props
onWalletHeaderPropsChange({
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
onShowConsolidationModal: () => setShowConsolidationModal(true),
isConsolidating,
onShowBitcoinAddressQR: async (qr: string) => {
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
},
});
}, [
onWalletHeaderPropsChange,
utxos?.length,
utxoDropdownOpen,
isConsolidating,
// Note: Functions (setUtxoDropdownOpen, etc.) are not in deps
// because they're stable setters or we accept they may change
// The ref-based change detection ensures we only update when primitives change
]);
return (
<>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={onRequestQRScanner}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<ScanLine className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
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>
{/* Modals */}
<>
{/* Consolidation Modal */}
<ConsolidationModal
isOpen={showConsolidationModal}
onClose={() => setShowConsolidationModal(false)}
utxos={utxos}
onConfirm={handleConsolidateUtxos}
isConsolidating={isConsolidating}
/>
{/* 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"
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="send"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {
handleBitcoinSend(
bitcoinAmount,
pendingBitcoinRecipient,
setBitcoinAmount,
setBitcoinRecipient,
setPendingBitcoinRecipient,
setShowSendModal
);
}}
onReceive={() => {}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount={bitcoinAmount}
setBitcoinAmount={setBitcoinAmount}
bitcoinRecipient={bitcoinRecipient}
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={() => handleSendMax(setBitcoinAmount)}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {}}
onReceive={() => {
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount=""
setBitcoinAmount={() => {}}
bitcoinRecipient=""
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your Bitcoin transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={[]}
isLoading={isBitcoinTransactionsLoading}
bitcoinTransactions={bitcoinTransactions}
isBitcoinLoading={isBitcoinTransactionsLoading}
showSats={true}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</>
);
}