added qr code scanner

This commit is contained in:
lemonknowsall committed 2025-10-26 23:07:28 -07:00
1 parent 97613fc5b2
commit a432716f47
5 files changed
+285 -6

No files matched your search

+118 -4
View File
@@ -5,7 +5,7 @@ import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useQRCode, type QRScanResult } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useMintManager } from '@/hooks/cashu/useMintManager';
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
@@ -20,7 +20,7 @@ import { WalletModals } from './WalletModals';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download } from 'lucide-react';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
export function CashuWallet() {
@@ -44,7 +44,7 @@ export function CashuWallet() {
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { generateQRCode, isScanning, startScanning, stopScanning, error: qrError } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
const { hasNsecAccess } = useNsecAccess();
@@ -183,6 +183,7 @@ export function CashuWallet() {
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
const [showQRScanner, setShowQRScanner] = useState(false);
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
@@ -331,6 +332,16 @@ export function CashuWallet() {
}
}, [mode, bitcoinAddress, fetchBitcoinUtxos]);
// Start/stop QR scanner when modal opens/closes
useEffect(() => {
if (showQRScanner) {
startScanning(handleQRScanResult);
} else {
stopScanning();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showQRScanner, startScanning, stopScanning]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
@@ -344,6 +355,95 @@ export function CashuWallet() {
};
}, [mintQuoteUnsubscribeRef]);
// Handle QR scanner results
const handleQRScanResult = async (result: QRScanResult) => {
try {
await stopScanning();
setShowQRScanner(false);
switch (result.type) {
case 'lightning_invoice': {
setMode('lightning');
setLightningInvoice(result.value);
setPendingInvoice(result.value);
// Decode invoice amount
setDecodedInvoiceAmount(100); // Placeholder - would need actual decoding
setShowSendModal(true);
toast({
title: "Lightning Invoice Scanned",
description: "Invoice ready to pay",
});
break;
}
case 'lightning_address': {
setMode('lightning');
setLightningAddressInput(result.value);
setPendingLightningAddress(result.value);
setShowSendModal(true);
toast({
title: "Lightning Address Scanned",
description: "Enter amount to send",
});
break;
}
case 'cashu_token': {
setMode('tokens');
setTokenInput(result.value);
setShowReceiveModal(true);
toast({
title: "Cashu Token Scanned",
description: "Token ready to redeem",
});
break;
}
case 'bitcoin_address': {
setMode('bitcoin');
setBitcoinRecipient(result.value);
setPendingBitcoinRecipient(result.value);
setShowSendModal(true);
toast({
title: "Bitcoin Address Scanned",
description: "Enter amount to send",
});
break;
}
case 'npub': {
// Convert npub to bitcoin address
try {
const decoded = nip19.decode(result.value);
if (decoded.type === 'npub') {
const address = nostrPubkeyToBitcoinAddress(decoded.data);
setMode('bitcoin');
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",
});
}
break;
}
default: {
toast({
variant: "destructive",
title: "Unknown QR Code",
description: result.value,
});
}
}
} catch (err) {
console.error('Error handling QR scan:', err);
}
};
// ============================================================================
// RENDER
// ============================================================================
@@ -398,7 +498,7 @@ export function CashuWallet() {
{/* 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-20 justify-center py-8">
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
@@ -409,6 +509,16 @@ export function CashuWallet() {
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowQRScanner(true)}
disabled={isLoading || isNpubCashLoading}
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"
@@ -466,6 +576,10 @@ export function CashuWallet() {
isRestoring={isRestoring}
mints={mints}
activeMintUrl={activeMintUrl}
showQRScanner={showQRScanner}
setShowQRScanner={setShowQRScanner}
stopScanning={stopScanning}
qrError={qrError}
/>
{/* Bottom Drawer Modals */}
+33
View File
@@ -5,6 +5,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2 } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { UTXO } from '@/lib/bitcoin';
@@ -80,6 +81,12 @@ interface WalletModalProps {
isRestoring: boolean;
mints: Array<{ url: string; name?: string }>;
activeMintUrl: string | null;
// QR Scanner Modal
showQRScanner: boolean;
setShowQRScanner: (show: boolean) => void;
stopScanning: () => Promise<void>;
qrError: string | null;
}
export function WalletModals({
@@ -114,6 +121,10 @@ export function WalletModals({
isRestoring,
mints,
activeMintUrl,
showQRScanner,
setShowQRScanner,
stopScanning,
qrError,
}: WalletModalProps) {
const { toast } = useToast();
@@ -472,6 +483,28 @@ export function WalletModals({
</div>
</div>
)}
{/* QR Scanner Modal */}
{showQRScanner && (
<Dialog open={showQRScanner} onOpenChange={(open) => {
if (!open) {
setShowQRScanner(false);
stopScanning();
}
}}>
<DialogContent className="max-w-full h-screen flex flex-col items-center justify-center p-0 bg-black border-0 [&>button]:text-white [&>button]:hover:bg-black/70">
{/* Centered QR Scanner */}
<div className="flex-1 w-full relative flex items-center justify-center">
<div id="qr-reader" className="w-full h-full"></div>
{qrError && (
<div className="absolute top-4 left-4 right-4 p-3 bg-destructive text-destructive-foreground rounded">
{qrError}
</div>
)}
</div>
</DialogContent>
</Dialog>
)}
</>
);
}
+126 -2
View File
@@ -1,11 +1,24 @@
import { useState, useCallback } from 'react';
import { useState, useCallback, useRef } from 'react';
import QRCode from 'qrcode';
import { Html5Qrcode } from 'html5-qrcode';
import { useToast } from './useToast';
export type QRScanResult =
| { type: 'lightning_invoice'; value: string }
| { type: 'lightning_address'; value: string }
| { type: 'cashu_token'; value: string }
| { type: 'bitcoin_address'; value: string }
| { type: 'npub'; value: string }
| { type: 'unknown'; value: string };
interface UseQRCodeReturn {
generateQRCode: (text: string) => Promise<string>;
isGenerating: boolean;
error: string | null;
// Scanner functions
isScanning: boolean;
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
stopScanning: () => Promise<void>;
}
/**
@@ -21,6 +34,9 @@ interface UseQRCodeReturn {
export function useQRCode(): UseQRCodeReturn {
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isScanning, setIsScanning] = useState(false);
const [scanError, setScanError] = useState<string | null>(null);
const scannerRef = useRef<Html5Qrcode | null>(null);
const { toast } = useToast();
const generateQRCode = useCallback(async (text: string): Promise<string> => {
@@ -54,9 +70,117 @@ export function useQRCode(): UseQRCodeReturn {
}
}, [toast]);
const classifyQRCode = useCallback((decodedText: string): QRScanResult => {
// Lightning invoice: lnbc... (case insensitive)
if (/^lnbc[a-z0-9]+$/i.test(decodedText)) {
return { type: 'lightning_invoice', value: decodedText };
}
// Lightning address: [email protected]
if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(decodedText)) {
return { type: 'lightning_address', value: decodedText };
}
// Cashu token: cashu...
if (/^cashu[A-Za-z0-9+/=]+$/.test(decodedText)) {
return { type: 'cashu_token', value: decodedText };
}
// Bitcoin address: bc1... or legacy (1..., 3...)
if (/^(bc1|3|1)[a-zA-Z0-9]{25,62}$/.test(decodedText)) {
return { type: 'bitcoin_address', value: decodedText };
}
// Nostr npub: npub1...
if (/^npub1[a-z0-9]{58}$/.test(decodedText)) {
return { type: 'npub', value: decodedText };
}
return { type: 'unknown', value: decodedText };
}, []);
const startScanning = useCallback(async (onResult: (result: QRScanResult) => void): Promise<void> => {
try {
setScanError(null);
// Find available cameras
const devices = await Html5Qrcode.getCameras();
if (devices.length === 0) {
throw new Error('No cameras found');
}
// Use the back camera by default, or first available
const cameraId = devices.length > 1
? devices.find(d => d.label.includes('back'))?.id || devices[0].id
: devices[0].id;
// Initialize scanner
const scanner = new Html5Qrcode('qr-reader');
scannerRef.current = scanner;
// Start scanning
await scanner.start(
cameraId,
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
(decodedText) => {
const result = classifyQRCode(decodedText);
onResult(result);
},
(errorMessage) => {
// Ignore decoding errors, camera is still running
// Only log if it's not a "QR code not found" type error
if (!errorMessage.includes('qr')) {
console.debug('QR scan error:', errorMessage);
}
}
);
setIsScanning(true);
} catch (err) {
let errorMessage = 'Failed to start camera';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Provide more helpful error messages
if (errorMessage.includes('NotAllowedError') || errorMessage.includes('Permission denied')) {
errorMessage = 'Camera permission denied. Please allow camera access.';
} else if (errorMessage.includes('NotFoundError') || errorMessage.includes('No device')) {
errorMessage = 'No camera found. Please connect a camera.';
}
setScanError(errorMessage);
setIsScanning(false);
console.error('Camera error:', err);
}
}, [classifyQRCode]);
const stopScanning = useCallback(async (): Promise<void> => {
try {
if (scannerRef.current) {
await scannerRef.current.stop();
await scannerRef.current.clear();
scannerRef.current = null;
}
setIsScanning(false);
setScanError(null);
} catch (err) {
console.error('Error stopping scanner:', err);
setIsScanning(false);
}
}, []);
return {
generateQRCode,
isGenerating,
error,
error: scanError,
isScanning,
startScanning,
stopScanning,
};
}