diff --git a/package-lock.json b/package-lock.json
index 66f4635..5b36471 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -55,6 +55,7 @@
"date-fns": "^3.6.0",
"ecpair": "^3.0.0",
"embla-carousel-react": "^8.3.0",
+ "html5-qrcode": "^2.3.8",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
@@ -5947,6 +5948,12 @@
"node": ">=18"
}
},
+ "node_modules/html5-qrcode": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/html5-qrcode/-/html5-qrcode-2.3.8.tgz",
+ "integrity": "sha512-jsr4vafJhwoLVEDW3n1KvPnCCXWaQfRng0/EEYk1vNcQGcG/htAdhJX0be8YyqMoSz7+hZvOZSTAepsabiuhiQ==",
+ "license": "Apache-2.0"
+ },
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
diff --git a/package.json b/package.json
index b347088..c8337c5 100644
--- a/package.json
+++ b/package.json
@@ -57,6 +57,7 @@
"date-fns": "^3.6.0",
"ecpair": "^3.0.0",
"embla-carousel-react": "^8.3.0",
+ "html5-qrcode": "^2.3.8",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx
index 6e86dc3..1d9e81a 100644
--- a/src/components/wallet/CashuWallet.tsx
+++ b/src/components/wallet/CashuWallet.tsx
@@ -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 */}
{/* Action Buttons */}
-
+
+
+
{/* Bottom Drawer Modals */}
diff --git a/src/components/wallet/WalletModals.tsx b/src/components/wallet/WalletModals.tsx
index f5f46c4..fb48cce 100644
--- a/src/components/wallet/WalletModals.tsx
+++ b/src/components/wallet/WalletModals.tsx
@@ -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;
+ 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({
)}
+
+ {/* QR Scanner Modal */}
+ {showQRScanner && (
+
+ )}
>
);
}
diff --git a/src/hooks/useQRCode.ts b/src/hooks/useQRCode.ts
index 2043b06..0ac6143 100644
--- a/src/hooks/useQRCode.ts
+++ b/src/hooks/useQRCode.ts
@@ -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
;
isGenerating: boolean;
error: string | null;
+ // Scanner functions
+ isScanning: boolean;
+ startScanning: (onResult: (result: QRScanResult) => void) => Promise;
+ stopScanning: () => Promise;
}
/**
@@ -21,6 +34,9 @@ interface UseQRCodeReturn {
export function useQRCode(): UseQRCodeReturn {
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState(null);
+ const [isScanning, setIsScanning] = useState(false);
+ const [scanError, setScanError] = useState(null);
+ const scannerRef = useRef(null);
const { toast } = useToast();
const generateQRCode = useCallback(async (text: string): Promise => {
@@ -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: name@domain.tld
+ 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 => {
+ 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 => {
+ 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,
};
}