From 4672413b04c3d2866118cdc5b80fd1c79ea67141 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Mon, 6 Oct 2025 13:24:03 -0700 Subject: [PATCH] cashu vibes --- AGENTS.md | 43 +- docs/AI_CHAT.md | 33 -- docs/CASHU_ZAP_INTEGRATION.md | 218 ++++++++++ src/components/WalletModal.tsx | 68 ++- src/components/ZapButton.tsx | 549 +++++++++++++++++++++++- src/components/ZapDialog.tsx | 89 +++- src/components/auth/AccountSwitcher.tsx | 8 +- src/hooks/useWallet.ts | 28 +- src/hooks/useZaps.ts | 55 ++- 9 files changed, 1002 insertions(+), 89 deletions(-) create mode 100644 docs/CASHU_ZAP_INTEGRATION.md diff --git a/AGENTS.md b/AGENTS.md index bf0d117..317838f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/ui/`: shadcn/ui components (48+ components available) - `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.) - - Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments + - Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration - `useAuthor`: Fetch user profile data by pubkey @@ -33,8 +33,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `useLoggedInAccounts`: Manage multiple accounts - `useLoginActions`: Authentication actions - `useIsMobile`: Responsive design helper - - `useZaps`: Lightning zap functionality with payment processing - - `useWallet`: Unified wallet detection (WebLN + NWC) + - `useZaps`: Lightning zap functionality with Cashu integration and payment processing + - `useCashu`: Cashu wallet management (balances, mints, melt quotes) + - `useLightningAddress`: Lightning address validation and LNURL endpoint discovery + - `useWallet`: Unified wallet detection (Cashu + WebLN + NWC) with intelligent payment method selection - `useNWC`: Nostr Wallet Connect connection management - `useNWCContext`: Access NWC context provider - `useShakespeare`: AI chat completions with Shakespeare AI API @@ -109,6 +111,8 @@ The project includes a **`docs/`** directory containing specialized documentatio - **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences. +- **`docs/CASHU_ZAP_INTEGRATION.md`**: Read when implementing zap functionality, integrating Cashu wallet payments, or building Lightning payment features. Essential for understanding the unified ZapButton architecture and Cashu-powered Lightning zaps. + ## System Prompt Management The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines: @@ -970,6 +974,39 @@ When users specify color schemes: - Implement responsive design with Tailwind breakpoints - Add hover and focus states for interactive elements +### Dialog Component Patterns + +When using Dialog components, always ensure accessibility compliance by including required elements: + +```tsx +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"; + +// ✅ Correct - Always include DialogHeader with DialogTitle + + + + Dialog Title + + Optional description for screen readers + + + {/* Dialog content */} + + +``` + +**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility: + +```tsx +import { VisuallyHidden } from "@radix-ui/react-visually-hidden"; + + + + Hidden Title for Screen Readers + + +``` + ## Writing Tests vs Running Tests There is an important distinction between **writing new tests** and **running existing tests**: diff --git a/docs/AI_CHAT.md b/docs/AI_CHAT.md index 66759d1..c7e4a24 100644 --- a/docs/AI_CHAT.md +++ b/docs/AI_CHAT.md @@ -88,39 +88,6 @@ const handleStreaming = async (content: string) => { ## Implementation Patterns and Best Practices -### Dialog Component Patterns - -When using Dialog components, always ensure accessibility compliance by including required elements: - -```tsx -import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"; - -// ✅ Correct - Always include DialogHeader with DialogTitle - - - - Dialog Title - - Optional description for screen readers - - - {/* Dialog content */} - - -``` - -**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility: - -```tsx -import { VisuallyHidden } from "@radix-ui/react-visually-hidden"; - - - - Hidden Title for Screen Readers - - -``` - ### Streaming Response Handling When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss: diff --git a/docs/CASHU_ZAP_INTEGRATION.md b/docs/CASHU_ZAP_INTEGRATION.md new file mode 100644 index 0000000..a2e060e --- /dev/null +++ b/docs/CASHU_ZAP_INTEGRATION.md @@ -0,0 +1,218 @@ +# Unified ZapButton for AI Agents + +This document explains how AI agents can easily integrate intelligent Lightning zaps into Nostr clients using the unified MKStack `ZapButton` component. + +## Overview + +The `ZapButton` component automatically prioritizes Cashu wallet balances for NIP-57 Lightning zaps when available, with intelligent fallback to traditional Lightning payments (WebLN → NWC → Manual QR). This provides a seamless user experience where users can zap directly from their Cashu token balance or use traditional Lightning methods. + +## Key Features + +- **Unified Component**: Single `ZapButton` handles all zap scenarios +- **Intelligent Payment Selection**: Automatically chooses the best available payment method +- **Cashu Integration**: Uses Cashu wallet balance when available and sufficient +- **Smart Fallbacks**: Falls back to WebLN → NWC → Manual QR code +- **NIP-57 Compliant**: Full compliance with Lightning zap standards +- **Zero Configuration**: Works out of the box with existing Nostr infrastructure +- **Mobile Optimized**: Responsive design with drawer/modal patterns + +## Basic Usage + +### Simple Integration + +```tsx +import { ZapButton } from '@/components/ZapButton'; +import type { Event } from 'nostr-tools'; + +function PostCard({ event }: { event: Event }) { + return ( +
+

{event.content}

+ +
+ ); +} +``` + +### With Custom Styling + +```tsx + +``` + +## Component Props + +```tsx +interface ZapButtonProps { + target: Event; // Required: The Nostr event to zap + className?: string; // Optional: CSS classes for styling + showCount?: boolean; // Optional: Show zap count (default: true) + zapData?: { // Optional: External zap data to avoid refetching + count: number; + totalSats: number; + isLoading?: boolean; + }; +} +``` + +## How It Works + +### Automatic Wallet Detection + +The `ZapButton` automatically detects if the user has: +1. A Cashu wallet with available balance +2. Traditional Lightning wallet (WebLN/NWC) + +### Payment Flow + +The unified `ZapButton` uses an intelligent payment selection system: + +1. **Cashu Available & Sufficient**: Uses Cashu tokens → Lightning invoice conversion +2. **Cashu Insufficient/Unavailable**: Falls back to WebLN payment +3. **WebLN Unavailable**: Falls back to NWC payment +4. **NWC Unavailable**: Shows manual Lightning invoice with QR code + +### Cashu Integration Details + +When Cashu wallet is available and has sufficient balance: +- Creates a NIP-57 compliant zap request +- Gets Lightning invoice from recipient's zap endpoint +- Uses `createMeltQuote()` to convert Cashu tokens to Lightning payment +- Uses `payMeltQuote()` to execute the payment +- Burns Cashu tokens and sends Lightning payment + +## Required Dependencies + +Ensure these hooks are available in your app: + +```tsx +// Required for Cashu integration +import { useCashu } from '@/hooks/useCashu'; + +// Required for traditional Lightning zaps +import { useWallet } from '@/hooks/useWallet'; +import { useZaps } from '@/hooks/useZaps'; +``` + +## Complete Example + +```tsx +import { ZapButton } from '@/components/ZapButton'; +import { CashuWallet } from '@/components/CashuWallet'; +import type { Event } from 'nostr-tools'; + +function NostrApp() { + return ( +
+ {/* Cashu wallet for balance management */} + + + {/* Posts with zap buttons */} +
+ {events.map(event => ( +
+

{event.content}

+ +
+ ))} +
+
+ ); +} +``` + +## Advanced Usage + +### Custom Zap Data + +If you're already fetching zap data elsewhere, pass it to avoid duplicate requests: + +```tsx +const zapData = useZaps(event); + + +``` + +### Conditional Rendering + +The component automatically handles visibility based on: +- User login status +- Author Lightning address availability +- Cashu wallet availability + +```tsx +// Only shows if user can zap + +``` + +## Error Handling + +The component handles common error scenarios: +- Insufficient Cashu balance +- Lightning address not found +- Zap endpoint unavailable +- Payment failures + +All errors are displayed via toast notifications. + +## Mobile Optimization + +The component automatically uses: +- **Desktop**: Modal dialog +- **Mobile**: Bottom drawer + +No additional configuration needed. + +## Testing + +The component includes test IDs for easy testing: + +```tsx +// Unified zap modal +data-testid="zap-modal" +``` + +## Best Practices for AI Agents + +1. **Always include CashuWallet**: Let users manage their balance +2. **Use consistent styling**: Apply your app's design system +3. **Handle loading states**: The component manages its own loading states +4. **Trust the intelligence**: The component handles payment method selection automatically +5. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work + +## Troubleshooting + +### ZapButton Not Showing +- Check if user is logged in +- Verify author has Lightning address (lud06/lud16) +- Ensure Cashu wallet is initialized + +### Cashu Zaps Not Working +- Verify Cashu wallet has sufficient balance +- Check mint connectivity +- Ensure Lightning invoice is valid + +### Payment Method Fallbacks Not Working +- Verify WebLN/NWC connection +- Check Lightning wallet availability +- Ensure zap endpoint is accessible +- Test manual QR code fallback + +## Integration Checklist + +- [ ] Import unified `ZapButton` component +- [ ] Include `CashuWallet` for balance management +- [ ] Ensure `useCashu` hook is available +- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR +- [ ] Verify mobile responsiveness +- [ ] Test error handling scenarios + +This unified integration provides a seamless, intelligent zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments. diff --git a/src/components/WalletModal.tsx b/src/components/WalletModal.tsx index 280052c..0416b05 100644 --- a/src/components/WalletModal.tsx +++ b/src/components/WalletModal.tsx @@ -1,5 +1,5 @@ import { useState, forwardRef } from 'react'; -import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react'; +import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X, Coins } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Dialog, @@ -26,12 +26,13 @@ import { Badge } from '@/components/ui/badge'; import { Separator } from '@/components/ui/separator'; import { useNWC } from '@/hooks/useNWCContext'; import { useWallet } from '@/hooks/useWallet'; +import { useCashu } from '@/hooks/useCashu'; import { useToast } from '@/hooks/useToast'; import { useIsMobile } from '@/hooks/useIsMobile'; import type { NWCConnection, NWCInfo } from '@/hooks/useNWC'; import type { WebLNProvider } from "@webbtc/webln-types"; -interface WalletModalProps { +interface LightningWalletModalProps { children?: React.ReactNode; className?: string; } @@ -74,6 +75,8 @@ const WalletContent = forwardRef; activeConnection: string | null; + cashuBalance: number; + isCashuInitialized: boolean; handleSetActive: (cs: string) => void; handleRemoveConnection: (cs: string) => void; setAddDialogOpen: (open: boolean) => void; @@ -83,14 +86,49 @@ const WalletContent = forwardRef (
- {/* Current Status */} + {/* Primary Payment Method - Cashu */}
-

Current Status

+

Primary Payment Method

+
+
+ +
+

Cashu Wallet

+

+ {isCashuInitialized + ? `${cashuBalance.toLocaleString()} sats available` + : "Instant Bitcoin payments" + } +

+
+
+
+ {isCashuInitialized && } + + {isCashuInitialized ? "Active" : "Not Set Up"} + +
+
+
+ Cashu tokens are used first for Lightning zaps. Set up your Cashu wallet for instant payments. +
+
+ + + + {/* Lightning Fallback Methods */} +
+

Lightning Fallback Methods

+
+ Used when Cashu balance is insufficient or unavailable +
{/* WebLN */}
@@ -190,12 +228,12 @@ const WalletContent = forwardRef {/* Help */} - {!webln && connections.length === 0 && ( + {!isCashuInitialized && !webln && connections.length === 0 && ( <>

- Install a WebLN extension or connect a NWC wallet for zaps. + Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning fallback.

@@ -204,7 +242,7 @@ const WalletContent = forwardRef 0 && connections.some(c => c.isConnected); + const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0); const { toast } = useToast(); const handleAddConnection = async () => { @@ -267,6 +307,8 @@ export function WalletModal({ children, className }: WalletModalProps) { connections, connectionInfo, activeConnection, + cashuBalance, + isCashuInitialized, handleSetActive, handleRemoveConnection, setAddDialogOpen, @@ -308,7 +350,7 @@ export function WalletModal({ children, className }: WalletModalProps) { {children || ( )} @@ -322,10 +364,10 @@ export function WalletModal({ children, className }: WalletModalProps) { - Lightning Wallet + Payment Settings - Connect your lightning wallet to send zaps instantly. + Manage Cashu wallet and Lightning fallback methods for zaps.
@@ -370,7 +412,7 @@ export function WalletModal({ children, className }: WalletModalProps) { {children || ( )} @@ -378,10 +420,10 @@ export function WalletModal({ children, className }: WalletModalProps) { - Lightning Wallet + Payment Settings - Connect your lightning wallet to send zaps instantly. + Manage Cashu wallet and Lightning fallback methods for zaps. diff --git a/src/components/ZapButton.tsx b/src/components/ZapButton.tsx index bb3bbd8..5cd6fb4 100644 --- a/src/components/ZapButton.tsx +++ b/src/components/ZapButton.tsx @@ -1,10 +1,40 @@ -import { ZapDialog } from '@/components/ZapDialog'; -import { useZaps } from '@/hooks/useZaps'; -import { useWallet } from '@/hooks/useWallet'; +import { useState, useEffect, useRef, forwardRef } from 'react'; +import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { cn } from '@/lib/utils'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { + Drawer, + DrawerContent, + DrawerDescription, + DrawerHeader, + DrawerTitle, + DrawerTrigger, + DrawerClose, +} from '@/components/ui/drawer'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { Card, CardContent } from '@/components/ui/card'; +import { Separator } from '@/components/ui/separator'; +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAuthor } from '@/hooks/useAuthor'; -import { Zap } from 'lucide-react'; +import { useToast } from '@/hooks/useToast'; +import { useZaps } from '@/hooks/useZaps'; +import { useWallet } from '@/hooks/useWallet'; +import { useCashu } from '@/hooks/useCashu'; +import { useIsMobile } from '@/hooks/useIsMobile'; import type { Event } from 'nostr-tools'; +import QRCode from 'qrcode'; +import type { WebLNProvider } from "@webbtc/webln-types"; interface ZapButtonProps { target: Event; @@ -13,15 +43,276 @@ interface ZapButtonProps { zapData?: { count: number; totalSats: number; isLoading?: boolean }; } +const presetAmounts = [ + { amount: 1, icon: Sparkle }, + { amount: 50, icon: Sparkles }, + { amount: 100, icon: Zap }, + { amount: 250, icon: Star }, + { amount: 1000, icon: Rocket }, +]; + +interface ZapContentProps { + invoice: string | null; + amount: number | string; + comment: string; + isZapping: boolean; + qrCodeUrl: string; + copied: boolean; + webln: WebLNProvider | null; + canPayWithCashu: boolean; + cashuBalance: number; + handleZap: () => void; + handleCopy: () => void; + openInWallet: () => void; + setAmount: (amount: number | string) => void; + setComment: (comment: string) => void; + inputRef: React.RefObject; + zap: (amount: number, comment: string) => void; +} + +const ZapContent = forwardRef(({ + invoice, + amount, + comment, + isZapping, + qrCodeUrl, + copied, + webln, + canPayWithCashu, + cashuBalance, + handleZap, + handleCopy, + openInWallet, + setAmount, + setComment, + inputRef, + zap, +}, ref) => ( +
+ {invoice ? ( +
+ {/* Payment amount display */} +
+
{amount} sats
+
+ + + +
+ {/* QR Code */} +
+ + + {qrCodeUrl ? ( + Lightning Invoice QR Code + ) : ( +
+ )} + + +
+ + {/* Invoice input */} +
+ +
+ e.currentTarget.select()} + /> + +
+
+ + {/* Payment buttons */} +
+ {/* Primary Lightning payment button - powered by Cashu when available */} + + + {/* WebLN fallback button */} + {webln && ( + + )} + + + +
+ {canPayWithCashu + ? "Pay Lightning invoice using your Cashu token balance, or scan QR code manually." + : "Scan the QR code or copy the invoice to pay with any Lightning wallet." + } +
+
+
+
+ ) : ( + <> + {/* Cashu balance indicator */} + {canPayWithCashu && ( +
+
+ + Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats +
+
+ )} + +
+ { + if (value) { + setAmount(parseInt(value, 10)); + } + }} + className="grid grid-cols-5 gap-1 w-full" + > + {presetAmounts.map(({ amount: presetAmount, icon: Icon }) => ( + cashuBalance} + > + + {presetAmount} + + ))} + +
+
+ OR +
+
+ setAmount(e.target.value)} + className="w-full text-sm" + max={canPayWithCashu ? cashuBalance : undefined} + /> +