mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 08:47:23 +00:00
cashu vibes
This commit is contained in:
1 parent
62282ade4d
commit
4672413b04
9 files changed
+992
-79
No files matched your search
@@ -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 components including NostrProvider for Nostr integration
|
||||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
- `/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:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `useNostr`: Core Nostr protocol integration
|
||||||
- `useAuthor`: Fetch user profile data by pubkey
|
- `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
|
- `useLoggedInAccounts`: Manage multiple accounts
|
||||||
- `useLoginActions`: Authentication actions
|
- `useLoginActions`: Authentication actions
|
||||||
- `useIsMobile`: Responsive design helper
|
- `useIsMobile`: Responsive design helper
|
||||||
- `useZaps`: Lightning zap functionality with payment processing
|
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
||||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
- `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
|
- `useNWC`: Nostr Wallet Connect connection management
|
||||||
- `useNWCContext`: Access NWC context provider
|
- `useNWCContext`: Access NWC context provider
|
||||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
- `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/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
|
## 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:
|
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
|
- Implement responsive design with Tailwind breakpoints
|
||||||
- Add hover and focus states for interactive elements
|
- 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 open={isOpen} onOpenChange={onClose}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Dialog Title</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Optional description for screen readers
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{/* Dialog content */}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
```
|
||||||
|
|
||||||
|
**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";
|
||||||
|
|
||||||
|
<DialogHeader>
|
||||||
|
<VisuallyHidden>
|
||||||
|
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
|
||||||
|
</VisuallyHidden>
|
||||||
|
</DialogHeader>
|
||||||
|
```
|
||||||
|
|
||||||
## Writing Tests vs Running Tests
|
## Writing Tests vs Running Tests
|
||||||
|
|
||||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
There is an important distinction between **writing new tests** and **running existing tests**:
|
||||||
|
|||||||
@@ -88,39 +88,6 @@ const handleStreaming = async (content: string) => {
|
|||||||
|
|
||||||
## Implementation Patterns and Best Practices
|
## 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 open={isOpen} onOpenChange={onClose}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Dialog Title</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Optional description for screen readers
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
{/* Dialog content */}
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
```
|
|
||||||
|
|
||||||
**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";
|
|
||||||
|
|
||||||
<DialogHeader>
|
|
||||||
<VisuallyHidden>
|
|
||||||
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
|
|
||||||
</VisuallyHidden>
|
|
||||||
</DialogHeader>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Streaming Response Handling
|
### 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:
|
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div className="post-card">
|
||||||
|
<p>{event.content}</p>
|
||||||
|
<ZapButton target={event} showCount={true} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### With Custom Styling
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<ZapButton
|
||||||
|
target={event}
|
||||||
|
className="text-sm hover:text-yellow-500 transition-colors"
|
||||||
|
showCount={true}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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 (
|
||||||
|
<div className="app">
|
||||||
|
{/* Cashu wallet for balance management */}
|
||||||
|
<CashuWallet />
|
||||||
|
|
||||||
|
{/* Posts with zap buttons */}
|
||||||
|
<div className="posts">
|
||||||
|
{events.map(event => (
|
||||||
|
<div key={event.id} className="post">
|
||||||
|
<p>{event.content}</p>
|
||||||
|
<ZapButton target={event} showCount={true} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Usage
|
||||||
|
|
||||||
|
### Custom Zap Data
|
||||||
|
|
||||||
|
If you're already fetching zap data elsewhere, pass it to avoid duplicate requests:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const zapData = useZaps(event);
|
||||||
|
|
||||||
|
<ZapButton
|
||||||
|
target={event}
|
||||||
|
zapData={zapData}
|
||||||
|
showCount={true}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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
|
||||||
|
<ZapButton target={event} />
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, forwardRef } from 'react';
|
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 { Button } from '@/components/ui/button';
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -26,12 +26,13 @@ import { Badge } from '@/components/ui/badge';
|
|||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
import { useNWC } from '@/hooks/useNWCContext';
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
import { useWallet } from '@/hooks/useWallet';
|
||||||
|
import { useCashu } from '@/hooks/useCashu';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||||
|
|
||||||
interface WalletModalProps {
|
interface LightningWalletModalProps {
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
@@ -74,6 +75,8 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
connections: NWCConnection[];
|
connections: NWCConnection[];
|
||||||
connectionInfo: Record<string, NWCInfo>;
|
connectionInfo: Record<string, NWCInfo>;
|
||||||
activeConnection: string | null;
|
activeConnection: string | null;
|
||||||
|
cashuBalance: number;
|
||||||
|
isCashuInitialized: boolean;
|
||||||
handleSetActive: (cs: string) => void;
|
handleSetActive: (cs: string) => void;
|
||||||
handleRemoveConnection: (cs: string) => void;
|
handleRemoveConnection: (cs: string) => void;
|
||||||
setAddDialogOpen: (open: boolean) => void;
|
setAddDialogOpen: (open: boolean) => void;
|
||||||
@@ -83,14 +86,49 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
connections,
|
connections,
|
||||||
connectionInfo,
|
connectionInfo,
|
||||||
activeConnection,
|
activeConnection,
|
||||||
|
cashuBalance,
|
||||||
|
isCashuInitialized,
|
||||||
handleSetActive,
|
handleSetActive,
|
||||||
handleRemoveConnection,
|
handleRemoveConnection,
|
||||||
setAddDialogOpen
|
setAddDialogOpen
|
||||||
}, ref) => (
|
}, ref) => (
|
||||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||||
{/* Current Status */}
|
{/* Primary Payment Method - Cashu */}
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<h3 className="font-medium">Current Status</h3>
|
<h3 className="font-medium">Primary Payment Method</h3>
|
||||||
|
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Coins className="h-4 w-4 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">Cashu Wallet</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{isCashuInitialized
|
||||||
|
? `${cashuBalance.toLocaleString()} sats available`
|
||||||
|
: "Instant Bitcoin payments"
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isCashuInitialized && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||||
|
<Badge variant={isCashuInitialized ? "default" : "secondary"} className="text-xs">
|
||||||
|
{isCashuInitialized ? "Active" : "Not Set Up"}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground text-center">
|
||||||
|
Cashu tokens are used first for Lightning zaps. Set up your Cashu wallet for instant payments.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
{/* Lightning Fallback Methods */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
<h3 className="font-medium">Lightning Fallback Methods</h3>
|
||||||
|
<div className="text-xs text-muted-foreground mb-3">
|
||||||
|
Used when Cashu balance is insufficient or unavailable
|
||||||
|
</div>
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
{/* WebLN */}
|
{/* WebLN */}
|
||||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||||
@@ -190,12 +228,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{/* Help */}
|
{/* Help */}
|
||||||
{!webln && connections.length === 0 && (
|
{!isCashuInitialized && !webln && connections.length === 0 && (
|
||||||
<>
|
<>
|
||||||
<Separator />
|
<Separator />
|
||||||
<div className="text-center py-4 space-y-2">
|
<div className="text-center py-4 space-y-2">
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
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.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -204,7 +242,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
));
|
));
|
||||||
WalletContent.displayName = 'WalletContent';
|
WalletContent.displayName = 'WalletContent';
|
||||||
|
|
||||||
export function WalletModal({ children, className }: WalletModalProps) {
|
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||||
const [connectionUri, setConnectionUri] = useState('');
|
const [connectionUri, setConnectionUri] = useState('');
|
||||||
@@ -222,8 +260,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
} = useNWC();
|
} = useNWC();
|
||||||
|
|
||||||
const { webln } = useWallet();
|
const { webln } = useWallet();
|
||||||
|
const { balances, isInitialized: isCashuInitialized } = useCashu();
|
||||||
|
|
||||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||||
|
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
const handleAddConnection = async () => {
|
const handleAddConnection = async () => {
|
||||||
@@ -267,6 +307,8 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
connections,
|
connections,
|
||||||
connectionInfo,
|
connectionInfo,
|
||||||
activeConnection,
|
activeConnection,
|
||||||
|
cashuBalance,
|
||||||
|
isCashuInitialized,
|
||||||
handleSetActive,
|
handleSetActive,
|
||||||
handleRemoveConnection,
|
handleRemoveConnection,
|
||||||
setAddDialogOpen,
|
setAddDialogOpen,
|
||||||
@@ -308,7 +350,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
{children || (
|
{children || (
|
||||||
<Button variant="outline" size="sm" className={className}>
|
<Button variant="outline" size="sm" className={className}>
|
||||||
<Wallet className="h-4 w-4 mr-2" />
|
<Wallet className="h-4 w-4 mr-2" />
|
||||||
Wallet Settings
|
Payment Settings
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</DrawerTrigger>
|
</DrawerTrigger>
|
||||||
@@ -322,10 +364,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
</DrawerClose>
|
</DrawerClose>
|
||||||
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
||||||
<Wallet className="h-5 w-5" />
|
<Wallet className="h-5 w-5" />
|
||||||
Lightning Wallet
|
Payment Settings
|
||||||
</DrawerTitle>
|
</DrawerTitle>
|
||||||
<DrawerDescription>
|
<DrawerDescription>
|
||||||
Connect your lightning wallet to send zaps instantly.
|
Manage Cashu wallet and Lightning fallback methods for zaps.
|
||||||
</DrawerDescription>
|
</DrawerDescription>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
<div className="overflow-y-auto">
|
<div className="overflow-y-auto">
|
||||||
@@ -370,7 +412,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
{children || (
|
{children || (
|
||||||
<Button variant="outline" size="sm" className={className}>
|
<Button variant="outline" size="sm" className={className}>
|
||||||
<Wallet className="h-4 w-4 mr-2" />
|
<Wallet className="h-4 w-4 mr-2" />
|
||||||
Wallet Settings
|
Payment Settings
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -378,10 +420,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
<Wallet className="h-5 w-5" />
|
<Wallet className="h-5 w-5" />
|
||||||
Lightning Wallet
|
Payment Settings
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Connect your lightning wallet to send zaps instantly.
|
Manage Cashu wallet and Lightning fallback methods for zaps.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<WalletContent {...walletContentProps} />
|
<WalletContent {...walletContentProps} />
|
||||||
|
|||||||
+518
-11
@@ -1,10 +1,40 @@
|
|||||||
import { ZapDialog } from '@/components/ZapDialog';
|
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||||
import { useZaps } from '@/hooks/useZaps';
|
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
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 { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
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 type { Event } from 'nostr-tools';
|
||||||
|
import QRCode from 'qrcode';
|
||||||
|
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||||
|
|
||||||
interface ZapButtonProps {
|
interface ZapButtonProps {
|
||||||
target: Event;
|
target: Event;
|
||||||
@@ -13,15 +43,276 @@ interface ZapButtonProps {
|
|||||||
zapData?: { count: number; totalSats: number; isLoading?: boolean };
|
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<HTMLInputElement>;
|
||||||
|
zap: (amount: number, comment: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||||
|
invoice,
|
||||||
|
amount,
|
||||||
|
comment,
|
||||||
|
isZapping,
|
||||||
|
qrCodeUrl,
|
||||||
|
copied,
|
||||||
|
webln,
|
||||||
|
canPayWithCashu,
|
||||||
|
cashuBalance,
|
||||||
|
handleZap,
|
||||||
|
handleCopy,
|
||||||
|
openInWallet,
|
||||||
|
setAmount,
|
||||||
|
setComment,
|
||||||
|
inputRef,
|
||||||
|
zap,
|
||||||
|
}, ref) => (
|
||||||
|
<div ref={ref}>
|
||||||
|
{invoice ? (
|
||||||
|
<div className="flex flex-col h-full min-h-0">
|
||||||
|
{/* Payment amount display */}
|
||||||
|
<div className="text-center pt-4">
|
||||||
|
<div className="text-2xl font-bold">{amount} sats</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator className="my-4" />
|
||||||
|
|
||||||
|
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
|
||||||
|
{/* QR Code */}
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
|
||||||
|
<CardContent className="p-0 flex justify-center">
|
||||||
|
{qrCodeUrl ? (
|
||||||
|
<img
|
||||||
|
src={qrCodeUrl}
|
||||||
|
alt="Lightning Invoice QR Code"
|
||||||
|
className="w-full h-auto aspect-square max-w-full object-contain"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Invoice input */}
|
||||||
|
<div className="space-y-2 mt-4">
|
||||||
|
<Label htmlFor="invoice">Lightning Invoice</Label>
|
||||||
|
<div className="flex gap-2 min-w-0">
|
||||||
|
<Input
|
||||||
|
id="invoice"
|
||||||
|
value={invoice}
|
||||||
|
readOnly
|
||||||
|
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
|
||||||
|
onClick={(e) => e.currentTarget.select()}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={handleCopy}
|
||||||
|
className="shrink-0"
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="h-4 w-4 text-green-600" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Payment buttons */}
|
||||||
|
<div className="space-y-3 mt-4">
|
||||||
|
{/* Primary Lightning payment button - powered by Cashu when available */}
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
|
zap(finalAmount, comment);
|
||||||
|
}}
|
||||||
|
disabled={isZapping}
|
||||||
|
className="w-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
{canPayWithCashu ? (
|
||||||
|
<>
|
||||||
|
<Coins className="h-4 w-4 mr-2" />
|
||||||
|
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Zap className="h-4 w-4 mr-2" />
|
||||||
|
{isZapping ? "Processing..." : "Pay with Lightning"}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* WebLN fallback button */}
|
||||||
|
{webln && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
|
zap(finalAmount, comment);
|
||||||
|
}}
|
||||||
|
disabled={isZapping}
|
||||||
|
className="w-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
<Zap className="h-4 w-4 mr-2" />
|
||||||
|
{isZapping ? "Processing..." : "Pay with WebLN"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={openInWallet}
|
||||||
|
className="w-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-4 w-4 mr-2" />
|
||||||
|
Open in Lightning Wallet
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||||
|
{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."
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Cashu balance indicator */}
|
||||||
|
{canPayWithCashu && (
|
||||||
|
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
|
||||||
|
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Coins className="h-4 w-4" />
|
||||||
|
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||||
|
<ToggleGroup
|
||||||
|
type="single"
|
||||||
|
value={String(amount)}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
if (value) {
|
||||||
|
setAmount(parseInt(value, 10));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="grid grid-cols-5 gap-1 w-full"
|
||||||
|
>
|
||||||
|
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
|
||||||
|
<ToggleGroupItem
|
||||||
|
key={presetAmount}
|
||||||
|
value={String(presetAmount)}
|
||||||
|
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||||
|
disabled={canPayWithCashu && presetAmount > cashuBalance}
|
||||||
|
>
|
||||||
|
<Icon className="h-4 w-4 mb-1" />
|
||||||
|
<span className="truncate">{presetAmount}</span>
|
||||||
|
</ToggleGroupItem>
|
||||||
|
))}
|
||||||
|
</ToggleGroup>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="h-px flex-1 bg-muted" />
|
||||||
|
<span className="text-xs text-muted-foreground">OR</span>
|
||||||
|
<div className="h-px flex-1 bg-muted" />
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
ref={inputRef}
|
||||||
|
id="custom-amount"
|
||||||
|
type="number"
|
||||||
|
placeholder="Custom amount"
|
||||||
|
value={amount}
|
||||||
|
onChange={(e) => setAmount(e.target.value)}
|
||||||
|
className="w-full text-sm"
|
||||||
|
max={canPayWithCashu ? cashuBalance : undefined}
|
||||||
|
/>
|
||||||
|
<Textarea
|
||||||
|
id="custom-comment"
|
||||||
|
placeholder="Add a comment (optional)"
|
||||||
|
value={comment}
|
||||||
|
onChange={(e) => setComment(e.target.value)}
|
||||||
|
className="w-full resize-none text-sm"
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="px-4 pb-4">
|
||||||
|
<Button
|
||||||
|
onClick={handleZap}
|
||||||
|
className="w-full"
|
||||||
|
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
|
||||||
|
size="default"
|
||||||
|
>
|
||||||
|
{isZapping ? (
|
||||||
|
'Creating Lightning invoice...'
|
||||||
|
) : canPayWithCashu ? (
|
||||||
|
<>
|
||||||
|
<Coins className="h-4 w-4 mr-2" />
|
||||||
|
Zap {amount} sats (Cashu → Lightning)
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Zap className="h-4 w-4 mr-2" />
|
||||||
|
Zap {amount} sats
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
));
|
||||||
|
ZapContent.displayName = 'ZapContent';
|
||||||
|
|
||||||
export function ZapButton({
|
export function ZapButton({
|
||||||
target,
|
target,
|
||||||
className = "text-xs ml-1",
|
className = "text-xs ml-1",
|
||||||
showCount = true,
|
showCount = true,
|
||||||
zapData: externalZapData
|
zapData: externalZapData
|
||||||
}: ZapButtonProps) {
|
}: ZapButtonProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { data: author } = useAuthor(target?.pubkey || '');
|
const { data: author } = useAuthor(target?.pubkey || '');
|
||||||
|
const { toast } = useToast();
|
||||||
const { webln, activeNWC } = useWallet();
|
const { webln, activeNWC } = useWallet();
|
||||||
|
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||||
|
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||||
|
const [amount, setAmount] = useState<number | string>(100);
|
||||||
|
const [comment, setComment] = useState<string>('');
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
// Check if Cashu wallet is available and has balance
|
||||||
|
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||||
|
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||||
|
|
||||||
// Only fetch data if not provided externally
|
// Only fetch data if not provided externally
|
||||||
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
||||||
@@ -30,18 +321,138 @@ export function ZapButton({
|
|||||||
activeNWC
|
activeNWC
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Use external data if provided, otherwise use fetched data
|
||||||
|
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
||||||
|
const showLoading = externalZapData?.isLoading || isLoading;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (target) {
|
||||||
|
setComment('Zapped with MKStack!');
|
||||||
|
}
|
||||||
|
}, [target]);
|
||||||
|
|
||||||
|
// Generate QR code
|
||||||
|
useEffect(() => {
|
||||||
|
let isCancelled = false;
|
||||||
|
|
||||||
|
const generateQR = async () => {
|
||||||
|
if (!invoice) {
|
||||||
|
setQrCodeUrl('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
|
||||||
|
width: 512,
|
||||||
|
margin: 2,
|
||||||
|
color: {
|
||||||
|
dark: '#000000',
|
||||||
|
light: '#FFFFFF',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isCancelled) {
|
||||||
|
setQrCodeUrl(url);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!isCancelled) {
|
||||||
|
console.error('Failed to generate QR code:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
generateQR();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isCancelled = true;
|
||||||
|
};
|
||||||
|
}, [invoice]);
|
||||||
|
|
||||||
|
const handleCopy = async () => {
|
||||||
|
if (invoice) {
|
||||||
|
await navigator.clipboard.writeText(invoice);
|
||||||
|
setCopied(true);
|
||||||
|
toast({
|
||||||
|
title: 'Invoice copied',
|
||||||
|
description: 'Lightning invoice copied to clipboard',
|
||||||
|
});
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openInWallet = () => {
|
||||||
|
if (invoice) {
|
||||||
|
const lightningUrl = `lightning:${invoice}`;
|
||||||
|
window.open(lightningUrl, '_blank');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
setAmount(100);
|
||||||
|
setInvoice(null);
|
||||||
|
setCopied(false);
|
||||||
|
setQrCodeUrl('');
|
||||||
|
} else {
|
||||||
|
setAmount(100);
|
||||||
|
setInvoice(null);
|
||||||
|
setCopied(false);
|
||||||
|
setQrCodeUrl('');
|
||||||
|
}
|
||||||
|
}, [open, setInvoice]);
|
||||||
|
|
||||||
|
const handleZap = () => {
|
||||||
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
|
if (canPayWithCashu && finalAmount > cashuBalance) {
|
||||||
|
toast({
|
||||||
|
title: 'Insufficient Cashu balance',
|
||||||
|
description: `You only have ${cashuBalance} sats available.`,
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
zap(finalAmount, comment);
|
||||||
|
};
|
||||||
|
|
||||||
|
const contentProps = {
|
||||||
|
invoice,
|
||||||
|
amount,
|
||||||
|
comment,
|
||||||
|
isZapping,
|
||||||
|
qrCodeUrl,
|
||||||
|
copied,
|
||||||
|
webln,
|
||||||
|
canPayWithCashu,
|
||||||
|
cashuBalance,
|
||||||
|
handleZap,
|
||||||
|
handleCopy,
|
||||||
|
openInWallet,
|
||||||
|
setAmount,
|
||||||
|
setComment,
|
||||||
|
inputRef,
|
||||||
|
zap,
|
||||||
|
};
|
||||||
|
|
||||||
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
||||||
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use external data if provided, otherwise use fetched data
|
if (isMobile) {
|
||||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
|
||||||
const showLoading = externalZapData?.isLoading || isLoading;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ZapDialog target={target}>
|
<Drawer
|
||||||
<div className={`flex items-center gap-1 ${className}`}>
|
open={open}
|
||||||
|
onOpenChange={setOpen}
|
||||||
|
dismissible={true}
|
||||||
|
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
|
||||||
|
activeSnapPoint={invoice ? 0.98 : 0.98}
|
||||||
|
modal={true}
|
||||||
|
shouldScaleBackground={false}
|
||||||
|
fadeFromIndex={0}
|
||||||
|
>
|
||||||
|
<DrawerTrigger asChild>
|
||||||
|
<div className={`cursor-pointer ${className || ''}`}>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
<Zap className="h-4 w-4" />
|
<Zap className="h-4 w-4" />
|
||||||
<span className="text-xs">
|
<span className="text-xs">
|
||||||
{showLoading ? (
|
{showLoading ? (
|
||||||
@@ -53,6 +464,102 @@ export function ZapButton({
|
|||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</ZapDialog>
|
</div>
|
||||||
|
</DrawerTrigger>
|
||||||
|
<DrawerContent
|
||||||
|
key={invoice ? 'payment' : 'form'}
|
||||||
|
className={cn(
|
||||||
|
"transition-all duration-300",
|
||||||
|
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
|
||||||
|
)}
|
||||||
|
data-testid="zap-modal"
|
||||||
|
>
|
||||||
|
<DrawerHeader className="text-center relative">
|
||||||
|
{/* Back button when showing invoice */}
|
||||||
|
{invoice && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setInvoice(null);
|
||||||
|
setQrCodeUrl('');
|
||||||
|
}}
|
||||||
|
className="absolute left-4 top-4 flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Close button */}
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="absolute right-4 top-4"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
|
||||||
|
<DrawerTitle className="text-lg break-words pt-2">
|
||||||
|
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||||
|
</DrawerTitle>
|
||||||
|
<DrawerDescription className="text-sm break-words text-center">
|
||||||
|
{invoice ? (
|
||||||
|
'Pay with Bitcoin Lightning Network'
|
||||||
|
) : (
|
||||||
|
canPayWithCashu
|
||||||
|
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||||
|
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||||
|
)}
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
<div className="flex-1 overflow-y-auto px-4 pb-4">
|
||||||
|
<ZapContent {...contentProps} />
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<div className={`cursor-pointer ${className || ''}`}>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Zap className="h-4 w-4" />
|
||||||
|
<span className="text-xs">
|
||||||
|
{showLoading ? (
|
||||||
|
'...'
|
||||||
|
) : showCount && totalSats > 0 ? (
|
||||||
|
`${totalSats.toLocaleString()}`
|
||||||
|
) : (
|
||||||
|
'Zap'
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-lg break-words">
|
||||||
|
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className="text-sm text-center break-words">
|
||||||
|
{invoice ? (
|
||||||
|
'Pay with Bitcoin Lightning Network'
|
||||||
|
) : (
|
||||||
|
canPayWithCashu
|
||||||
|
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||||
|
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||||
|
)}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="overflow-y-auto">
|
||||||
|
<ZapContent {...contentProps} />
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
|
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import {
|
import {
|
||||||
@@ -30,6 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
|
|||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useZaps } from '@/hooks/useZaps';
|
import { useZaps } from '@/hooks/useZaps';
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
import { useWallet } from '@/hooks/useWallet';
|
||||||
|
import { useCashu } from '@/hooks/useCashu';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import type { Event } from 'nostr-tools';
|
import type { Event } from 'nostr-tools';
|
||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
@@ -57,6 +58,9 @@ interface ZapContentProps {
|
|||||||
qrCodeUrl: string;
|
qrCodeUrl: string;
|
||||||
copied: boolean;
|
copied: boolean;
|
||||||
webln: WebLNProvider | null;
|
webln: WebLNProvider | null;
|
||||||
|
// Cashu-related props
|
||||||
|
canPayWithCashu: boolean;
|
||||||
|
cashuBalance: number;
|
||||||
handleZap: () => void;
|
handleZap: () => void;
|
||||||
handleCopy: () => void;
|
handleCopy: () => void;
|
||||||
openInWallet: () => void;
|
openInWallet: () => void;
|
||||||
@@ -75,6 +79,8 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
qrCodeUrl,
|
qrCodeUrl,
|
||||||
copied,
|
copied,
|
||||||
webln,
|
webln,
|
||||||
|
canPayWithCashu,
|
||||||
|
cashuBalance,
|
||||||
handleZap,
|
handleZap,
|
||||||
handleCopy,
|
handleCopy,
|
||||||
openInWallet,
|
openInWallet,
|
||||||
@@ -139,8 +145,33 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
|
|
||||||
{/* Payment buttons */}
|
{/* Payment buttons */}
|
||||||
<div className="space-y-3 mt-4">
|
<div className="space-y-3 mt-4">
|
||||||
|
{/* Primary Lightning payment button - powered by Cashu when available */}
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
|
zap(finalAmount, comment);
|
||||||
|
}}
|
||||||
|
disabled={isZapping}
|
||||||
|
className="w-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
{canPayWithCashu ? (
|
||||||
|
<>
|
||||||
|
<Coins className="h-4 w-4 mr-2" />
|
||||||
|
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Zap className="h-4 w-4 mr-2" />
|
||||||
|
{isZapping ? "Processing..." : "Pay with Lightning"}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* WebLN fallback button */}
|
||||||
{webln && (
|
{webln && (
|
||||||
<Button
|
<Button
|
||||||
|
variant="outline"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
zap(finalAmount, comment);
|
zap(finalAmount, comment);
|
||||||
@@ -165,13 +196,26 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||||
Scan the QR code or copy the invoice to pay with any Lightning wallet.
|
{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."
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
{/* Cashu balance indicator */}
|
||||||
|
{canPayWithCashu && (
|
||||||
|
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
|
||||||
|
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Coins className="h-4 w-4" />
|
||||||
|
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||||
<ToggleGroup
|
<ToggleGroup
|
||||||
type="single"
|
type="single"
|
||||||
@@ -188,6 +232,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
key={presetAmount}
|
key={presetAmount}
|
||||||
value={String(presetAmount)}
|
value={String(presetAmount)}
|
||||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||||
|
disabled={canPayWithCashu && presetAmount > cashuBalance}
|
||||||
>
|
>
|
||||||
<Icon className="h-4 w-4 mb-1" />
|
<Icon className="h-4 w-4 mb-1" />
|
||||||
<span className="truncate">{presetAmount}</span>
|
<span className="truncate">{presetAmount}</span>
|
||||||
@@ -207,6 +252,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
value={amount}
|
value={amount}
|
||||||
onChange={(e) => setAmount(e.target.value)}
|
onChange={(e) => setAmount(e.target.value)}
|
||||||
className="w-full text-sm"
|
className="w-full text-sm"
|
||||||
|
max={canPayWithCashu ? cashuBalance : undefined}
|
||||||
/>
|
/>
|
||||||
<Textarea
|
<Textarea
|
||||||
id="custom-comment"
|
id="custom-comment"
|
||||||
@@ -218,9 +264,19 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="px-4 pb-4">
|
<div className="px-4 pb-4">
|
||||||
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
|
<Button
|
||||||
|
onClick={handleZap}
|
||||||
|
className="w-full"
|
||||||
|
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
|
||||||
|
size="default"
|
||||||
|
>
|
||||||
{isZapping ? (
|
{isZapping ? (
|
||||||
'Creating invoice...'
|
'Creating Lightning invoice...'
|
||||||
|
) : canPayWithCashu ? (
|
||||||
|
<>
|
||||||
|
<Coins className="h-4 w-4 mr-2" />
|
||||||
|
Zap {amount} sats (Cashu → Lightning)
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Zap className="h-4 w-4 mr-2" />
|
<Zap className="h-4 w-4 mr-2" />
|
||||||
@@ -242,6 +298,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { webln, activeNWC } = useWallet();
|
const { webln, activeNWC } = useWallet();
|
||||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||||
|
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||||
const [amount, setAmount] = useState<number | string>(100);
|
const [amount, setAmount] = useState<number | string>(100);
|
||||||
const [comment, setComment] = useState<string>('');
|
const [comment, setComment] = useState<string>('');
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
@@ -249,6 +306,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
// Check if Cashu wallet is available and has balance
|
||||||
|
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||||
|
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (target) {
|
if (target) {
|
||||||
setComment('Zapped with MKStack!');
|
setComment('Zapped with MKStack!');
|
||||||
@@ -328,6 +389,14 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
|
|
||||||
const handleZap = () => {
|
const handleZap = () => {
|
||||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
|
if (canPayWithCashu && finalAmount > cashuBalance) {
|
||||||
|
toast({
|
||||||
|
title: 'Insufficient Cashu balance',
|
||||||
|
description: `You only have ${cashuBalance} sats available.`,
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
zap(finalAmount, comment);
|
zap(finalAmount, comment);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -339,6 +408,8 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
qrCodeUrl,
|
qrCodeUrl,
|
||||||
copied,
|
copied,
|
||||||
webln,
|
webln,
|
||||||
|
canPayWithCashu,
|
||||||
|
cashuBalance,
|
||||||
handleZap,
|
handleZap,
|
||||||
handleCopy,
|
handleCopy,
|
||||||
openInWallet,
|
openInWallet,
|
||||||
@@ -420,7 +491,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
{invoice ? (
|
{invoice ? (
|
||||||
'Pay with Bitcoin Lightning Network'
|
'Pay with Bitcoin Lightning Network'
|
||||||
) : (
|
) : (
|
||||||
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
canPayWithCashu
|
||||||
|
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||||
|
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||||
)}
|
)}
|
||||||
</DrawerDescription>
|
</DrawerDescription>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
@@ -448,9 +521,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
{invoice ? (
|
{invoice ? (
|
||||||
'Pay with Bitcoin Lightning Network'
|
'Pay with Bitcoin Lightning Network'
|
||||||
) : (
|
) : (
|
||||||
<>
|
canPayWithCashu
|
||||||
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
|
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||||
</>
|
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||||
)}
|
)}
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu.tsx';
|
} from '@/components/ui/dropdown-menu.tsx';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
import { RelaySelector } from '@/components/RelaySelector';
|
||||||
import { WalletModal } from '@/components/WalletModal';
|
import { LightningWalletModal } from '@/components/WalletModal';
|
||||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
|
||||||
@@ -64,15 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<WalletModal>
|
<LightningWalletModal>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||||
onSelect={(e) => e.preventDefault()}
|
onSelect={(e) => e.preventDefault()}
|
||||||
>
|
>
|
||||||
<Wallet className='w-4 h-4' />
|
<Wallet className='w-4 h-4' />
|
||||||
<span>Wallet Settings</span>
|
<span>Payment Settings</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</WalletModal>
|
</LightningWalletModal>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={onAddAccountClick}
|
onClick={onAddAccountClick}
|
||||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||||
|
|||||||
+24
-4
@@ -1,16 +1,22 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
import { useNWC } from '@/hooks/useNWCContext';
|
||||||
|
import { useCashu } from '@/hooks/useCashu';
|
||||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||||
|
|
||||||
export interface WalletStatus {
|
export interface WalletStatus {
|
||||||
hasNWC: boolean;
|
hasNWC: boolean;
|
||||||
webln: WebLNProvider | null;
|
webln: WebLNProvider | null;
|
||||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
preferredMethod: 'cashu' | 'nwc' | 'webln' | 'manual';
|
||||||
|
// Cashu integration
|
||||||
|
hasCashu: boolean;
|
||||||
|
cashuBalance: number;
|
||||||
|
isCashuInitialized: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useWallet() {
|
export function useWallet() {
|
||||||
const { connections, getActiveConnection } = useNWC();
|
const { connections, getActiveConnection } = useNWC();
|
||||||
|
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||||
|
|
||||||
// Get the active connection directly - no memoization to avoid stale state
|
// Get the active connection directly - no memoization to avoid stale state
|
||||||
const activeNWC = getActiveConnection();
|
const activeNWC = getActiveConnection();
|
||||||
@@ -18,13 +24,24 @@ export function useWallet() {
|
|||||||
// Access WebLN directly from browser global scope
|
// Access WebLN directly from browser global scope
|
||||||
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
||||||
|
|
||||||
// Calculate status values reactively
|
// Calculate Cashu status
|
||||||
|
const hasCashu = useMemo(() => {
|
||||||
|
return isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||||
|
}, [isCashuInitialized, mints, balances]);
|
||||||
|
|
||||||
|
const cashuBalance = useMemo(() => {
|
||||||
|
return Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||||
|
}, [balances]);
|
||||||
|
|
||||||
|
// Calculate Lightning status values reactively
|
||||||
const hasNWC = useMemo(() => {
|
const hasNWC = useMemo(() => {
|
||||||
return connections.length > 0 && connections.some(c => c.isConnected);
|
return connections.length > 0 && connections.some(c => c.isConnected);
|
||||||
}, [connections]);
|
}, [connections]);
|
||||||
|
|
||||||
// Determine preferred payment method
|
// Determine preferred payment method - Cashu first, then Lightning fallbacks
|
||||||
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
|
const preferredMethod: WalletStatus['preferredMethod'] = hasCashu
|
||||||
|
? 'cashu'
|
||||||
|
: activeNWC
|
||||||
? 'nwc'
|
? 'nwc'
|
||||||
: webln
|
: webln
|
||||||
? 'webln'
|
? 'webln'
|
||||||
@@ -35,6 +52,9 @@ export function useWallet() {
|
|||||||
webln,
|
webln,
|
||||||
activeNWC,
|
activeNWC,
|
||||||
preferredMethod,
|
preferredMethod,
|
||||||
|
hasCashu,
|
||||||
|
cashuBalance,
|
||||||
|
isCashuInitialized,
|
||||||
};
|
};
|
||||||
|
|
||||||
return status;
|
return status;
|
||||||
|
|||||||
+52
-3
@@ -4,6 +4,7 @@ import { useAuthor } from '@/hooks/useAuthor';
|
|||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
import { useNWC } from '@/hooks/useNWCContext';
|
||||||
|
import { useCashu } from '@/hooks/useCashu';
|
||||||
import type { NWCConnection } from '@/hooks/useNWC';
|
import type { NWCConnection } from '@/hooks/useNWC';
|
||||||
import { nip57 } from 'nostr-tools';
|
import { nip57 } from 'nostr-tools';
|
||||||
import type { Event } from 'nostr-tools';
|
import type { Event } from 'nostr-tools';
|
||||||
@@ -29,6 +30,7 @@ export function useZaps(
|
|||||||
|
|
||||||
const author = useAuthor(actualTarget?.pubkey);
|
const author = useAuthor(actualTarget?.pubkey);
|
||||||
const { sendPayment, getActiveConnection } = useNWC();
|
const { sendPayment, getActiveConnection } = useNWC();
|
||||||
|
const { createMeltQuote, payMeltQuote, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||||
const [isZapping, setIsZapping] = useState(false);
|
const [isZapping, setIsZapping] = useState(false);
|
||||||
const [invoice, setInvoice] = useState<string | null>(null);
|
const [invoice, setInvoice] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -203,11 +205,11 @@ export function useZaps(
|
|||||||
|
|
||||||
const zapRequest = nip57.makeZapRequest({
|
const zapRequest = nip57.makeZapRequest({
|
||||||
profile: actualTarget.pubkey,
|
profile: actualTarget.pubkey,
|
||||||
event: event,
|
event: event as Event,
|
||||||
amount: zapAmount,
|
amount: zapAmount,
|
||||||
relays: [config.relayUrl],
|
relays: [config.relayUrl],
|
||||||
comment
|
comment
|
||||||
});
|
} as Parameters<typeof nip57.makeZapRequest>[0]);
|
||||||
|
|
||||||
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
|
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
|
||||||
if (!user.signer) {
|
if (!user.signer) {
|
||||||
@@ -228,10 +230,57 @@ export function useZaps(
|
|||||||
throw new Error('Lightning service did not return a valid invoice');
|
throw new Error('Lightning service did not return a valid invoice');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if Cashu wallet is available and has sufficient balance
|
||||||
|
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) >= amount);
|
||||||
|
|
||||||
|
if (canPayWithCashu) {
|
||||||
|
try {
|
||||||
|
// Find a mint with sufficient balance
|
||||||
|
const mintWithBalance = mints.find(mint => {
|
||||||
|
const balance = balances[mint.url] || 0;
|
||||||
|
return balance >= amount;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (mintWithBalance) {
|
||||||
|
// Create melt quote to convert Cashu tokens to Lightning payment
|
||||||
|
const meltQuote = await createMeltQuote(mintWithBalance.url, newInvoice);
|
||||||
|
|
||||||
|
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
|
||||||
|
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
||||||
|
|
||||||
|
// Clear states immediately on success
|
||||||
|
setIsZapping(false);
|
||||||
|
setInvoice(null);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Zap successful!',
|
||||||
|
description: `You sent ${amount} sats from your Cashu wallet to the author.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Invalidate zap queries to refresh counts
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||||
|
|
||||||
|
// Close dialog last to ensure clean state
|
||||||
|
onZapSuccess?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (cashuError) {
|
||||||
|
console.error('Cashu payment failed, falling back:', cashuError);
|
||||||
|
|
||||||
|
// Show specific Cashu error to user for debugging
|
||||||
|
const errorMessage = cashuError instanceof Error ? cashuError.message : 'Unknown Cashu error';
|
||||||
|
toast({
|
||||||
|
title: 'Cashu payment failed',
|
||||||
|
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Get the current active NWC connection dynamically
|
// Get the current active NWC connection dynamically
|
||||||
const currentNWCConnection = getActiveConnection();
|
const currentNWCConnection = getActiveConnection();
|
||||||
|
|
||||||
// Try NWC first if available and properly connected
|
// Try NWC if Cashu failed or unavailable
|
||||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||||
try {
|
try {
|
||||||
await sendPayment(currentNWCConnection, newInvoice);
|
await sendPayment(currentNWCConnection, newInvoice);
|
||||||
|
|||||||
Reference in new issue
Block a user