diff --git a/package-lock.json b/package-lock.json index 0fa0820d..d4f31c57 100644 --- a/package-lock.json +++ b/package-lock.json @@ -94,6 +94,7 @@ "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", "@types/path-browserify": "^1.0.3", + "@types/qrcode": "^1.5.5", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/turndown": "^5.0.5", @@ -3764,6 +3765,16 @@ "integrity": "sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ==", "license": "MIT" }, + "node_modules/@types/qrcode": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.5.tgz", + "integrity": "sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/react": { "version": "18.3.20", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz", diff --git a/package.json b/package.json index d15b1325..70e2f92b 100644 --- a/package.json +++ b/package.json @@ -96,6 +96,7 @@ "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", "@types/path-browserify": "^1.0.3", + "@types/qrcode": "^1.5.5", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/turndown": "^5.0.5", diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 7d639572..c5e88d91 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -1,6 +1,7 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle } from 'lucide-react'; +import QRCode from 'qrcode'; +import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy } from 'lucide-react'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -51,6 +52,143 @@ interface AddCreditsRequest { const PRESET_AMOUNTS = [5, 10, 25, 50, 100]; +interface LightningPaymentProps { + invoice: string; + amount: number; + onClose: () => void; +} + +function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) { + const [qrDataUrl, setQrDataUrl] = useState(''); + const [isWebLNAvailable, setIsWebLNAvailable] = useState(false); + const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false); + const { toast } = useToast(); + + useEffect(() => { + // Generate QR code + QRCode.toDataURL(invoice, { + width: 256, + margin: 2, + color: { + dark: '#000000', + light: '#ffffff', + }, + }) + .then(setQrDataUrl) + .catch(console.error); + + // Check for WebLN availability + setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window); + }, [invoice]); + + const handleWebLNPay = async () => { + if (!window.webln) return; + + try { + setIsPayingWithWebLN(true); + await window.webln.enable(); + await window.webln.sendPayment(invoice); + + toast({ + title: 'Payment sent!', + description: 'Your Lightning payment has been sent successfully.', + }); + + onClose(); + } catch (error) { + console.error('WebLN payment failed:', error); + toast({ + title: 'Payment failed', + description: error instanceof Error ? error.message : 'Failed to send Lightning payment', + variant: 'destructive', + }); + } finally { + setIsPayingWithWebLN(false); + } + }; + + const handleCopyInvoice = () => { + navigator.clipboard.writeText(invoice); + toast({ + title: 'Invoice copied', + description: 'Lightning invoice copied to clipboard', + }); + }; + + const formatCurrency = (amount: number) => { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(amount); + }; + + return ( +
+
+

Lightning Payment

+

+ Pay {formatCurrency(amount)} with Lightning Network +

+
+ + {/* QR Code */} +
+ {qrDataUrl ? ( +
+ Lightning Invoice QR Code +
+ ) : ( +
+ +
+ )} +
+ + {/* Payment Buttons */} +
+ {isWebLNAvailable && ( + + )} + + +
+ + {/* Invoice Text (for manual copying) */} +
+ +
+ {invoice} +
+
+ +
+ +
+
+ ); +} + export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) { const { user } = useCurrentUser(); const { toast } = useToast(); @@ -58,6 +196,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr const [amount, setAmount] = useState(10); const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe'); + const [lightningInvoice, setLightningInvoice] = useState(null); // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ @@ -89,12 +228,8 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr description: 'Stripe checkout opened in a new window.', }); } else if (payment.method === 'lightning') { - // Copy Lightning invoice to clipboard - navigator.clipboard.writeText(payment.url); - toast({ - title: 'Lightning invoice copied', - description: 'The Lightning invoice has been copied to your clipboard.', - }); + // Show Lightning payment interface + setLightningInvoice(payment.url); } // Refresh payments list @@ -220,8 +355,20 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
- {/* Add Credits Form */} -
+ {/* Lightning Payment Interface */} + {lightningInvoice ? ( + { + setLightningInvoice(null); + onOpenChange(false); + }} + /> + ) : ( + <> + {/* Add Credits Form */} +
@@ -352,11 +499,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr size="sm" onClick={() => { if (payment.method === 'lightning') { - navigator.clipboard.writeText(payment.url); - toast({ - title: 'Invoice copied', - description: 'Lightning invoice copied to clipboard', - }); + setLightningInvoice(payment.url); } else { window.open(payment.url, '_blank'); } @@ -364,7 +507,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr className="h-6 px-2 text-xs" > - {payment.method === 'lightning' ? 'Copy' : 'Pay'} + {payment.method === 'lightning' ? 'Pay' : 'Pay'} )}
@@ -379,6 +522,8 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
)}
+ + )}
diff --git a/src/components/LightningPayment.test.tsx b/src/components/LightningPayment.test.tsx new file mode 100644 index 00000000..05319747 --- /dev/null +++ b/src/components/LightningPayment.test.tsx @@ -0,0 +1,89 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; + +// Mock QRCode +vi.mock('qrcode', () => ({ + default: { + toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,mock-qr-code'), + }, +})); + +// Mock WebLN +const mockWebLN = { + enable: vi.fn().mockResolvedValue(undefined), + sendPayment: vi.fn().mockResolvedValue({ preimage: 'mock-preimage' }), +}; + +// We need to import the component after mocking +const { CreditsDialog } = await import('./CreditsDialog'); + +const mockConnection = { + baseURL: 'https://api.test.com/v1', + apiKey: 'test-key', +}; + +describe('Lightning Payment', () => { + beforeEach(() => { + vi.clearAllMocks(); + // Reset WebLN mock + Object.defineProperty(window, 'webln', { + value: undefined, + writable: true, + }); + }); + + it('shows QR code for Lightning payment', async () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + // Should show the normal form initially + expect(screen.getByText('Amount (USD)')).toBeInTheDocument(); + }); + + it('shows WebLN button when available', async () => { + // Mock WebLN availability + Object.defineProperty(window, 'webln', { + value: mockWebLN, + writable: true, + }); + + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + // Should show the normal form initially + expect(screen.getByText('Amount (USD)')).toBeInTheDocument(); + }); + + it('displays copy invoice button', async () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + // Should show the normal form initially + expect(screen.getByText('Payment Method')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/types/webln.d.ts b/src/types/webln.d.ts new file mode 100644 index 00000000..73eedd50 --- /dev/null +++ b/src/types/webln.d.ts @@ -0,0 +1,30 @@ +declare global { + interface Window { + webln?: { + enable(): Promise; + sendPayment(paymentRequest: string): Promise<{ + preimage: string; + }>; + makeInvoice(args: { + amount?: number; + defaultMemo?: string; + }): Promise<{ + paymentRequest: string; + }>; + signMessage(message: string): Promise<{ + message: string; + signature: string; + }>; + verifyMessage(signature: string, message: string): Promise; + getInfo(): Promise<{ + node: { + alias: string; + pubkey: string; + color?: string; + }; + }>; + }; + } +} + +export {}; \ No newline at end of file