Author SHA1 Message Date
lemonknowsall 7390dd6c19 fixed npubx.cash payments 2025-10-18 11:41:10 -07:00
lemonknowsall 6d35028424 header spacing and styling 2025-10-18 11:04:24 -07:00
lemonknowsall bea63c75aa transaction history drawer and separate mint display 2025-10-18 00:22:50 -07:00
lemonknowsall e4ee51335e upgraded mobile styling 2025-10-17 13:39:29 -07:00
lemonknowsall 8ef018df8a moved cards to drawers for mobile view 2025-10-16 23:32:07 -07:00
lemonknowsall 56bdebff5d updated transactions look 2025-10-16 22:20:18 -07:00
lemonknowsall 6162217ce9 silent return bug on lnaddress payments 2025-10-16 17:26:46 -07:00
lemonknowsall ea57135d1e npubxcash lnaddress subscriptions working 2025-10-16 17:05:39 -07:00
lemonknowsall b5bc571aa7 refactor the refactor 2025-10-16 13:03:59 -07:00
lemonknowsall 77803dda38 implement mint removal 2025-10-15 23:12:01 -07:00
lemonknowsall 73c68f2655 remove scroll bar from login modal 2025-10-15 22:13:37 -07:00
lemonknowsall f78013b083 npubxcash lightning address redemption working 2025-10-15 21:29:39 -07:00
lemonknowsall bd956cef3f implement npubcash-sdk to simplify code 2025-10-15 01:22:12 -07:00
lemonknowsall 2ac097d8de code cleanup round 2 2025-10-15 00:10:24 -07:00
lemonknowsall aaf12120e6 move files together 2025-10-13 19:57:15 -07:00
lemonknowsall 5ce402105c code cleanup 2025-10-13 16:52:25 -07:00
lemonknowsall dd3f4465c5 put lightning address in balance card 2025-10-13 16:27:15 -07:00
lemonknowsall c8ad3b1a36 get user info from npubxcash 2025-10-13 13:10:02 -07:00
lemonknowsall 1701cce6b0 add lightning address and qr modal 2025-10-13 12:46:17 -07:00
lemonknowsall 346ba70710 set mint with npubxcash 2025-10-13 12:33:02 -07:00
lemonknowsall 5dc19e857f click outside to close breakdown modal 2025-10-13 00:32:39 -07:00
lemonknowsall 8bc8a41910 remove npubx cash reference for now 2025-10-12 22:36:50 -07:00
lemonknowsall c3b1adc375 wallet and card resizing 2025-10-12 14:26:34 -07:00
lemonknowsall 4f2bfa4d5b updated qrcode bg color and truncated text 2025-10-12 14:13:07 -07:00
lemonknowsall 7af7aee47c history event listeners to update transactions live 2025-10-12 14:07:59 -07:00
lemonknowsall 2569f0dd0d transaction history formatting 2025-10-12 13:57:31 -07:00
lemonknowsall fd684a40a8 toast dismissal 2025-10-12 13:39:16 -07:00
lemonknowsall 7ba3d7f8c5 added expiry timer 2025-10-12 13:28:11 -07:00
lemonknowsall 45918e86e2 detect lightning payment and toast 2025-10-12 13:01:18 -07:00
lemonknowsall 967bdca369 solid cashu foundation 2025-10-11 00:34:32 -07:00
lemonknowsall a8faa03b49 modals and mint removal 2025-10-09 21:19:02 -07:00
lemonknowsall 22d3675f2b modular cashu hooks, wallet toggle, qr code modals 2025-10-08 00:23:26 -07:00
lemonknowsall ec465d9892 addMintQuote addition 2025-10-07 21:35:07 -07:00
lemonknowsall 579cd3584b add npubxCash lightning address 2025-10-07 00:48:29 -07:00
lemonknowsall 565305a592 added cashu context to prevent repeated invocation 2025-10-06 20:47:01 -07:00
lemonknowsall 669a911d59 balance refresh infinite loop example 2025-10-06 20:22:08 -07:00
lemonknowsall 39796c293a nip57 event type mismatch error (toString) 2025-10-06 20:14:10 -07:00
lemonknowsall e14d4e887f infinite loop initialization, wallet endpoint structure, zapdialog debug 2025-10-06 17:27:30 -07:00
lemonknowsall 4672413b04 cashu vibes 2025-10-06 13:24:03 -07:00
lemonknowsall 62282ade4d updated coco to npm packages from local 2025-10-06 00:41:41 -07:00
lemonknowsall af1cbaeacc address test errors 2025-10-06 00:15:20 -07:00
lemonknowsall 6dacd3d964 cashu wallet integration 2025-10-05 23:02:14 -07:00
80 changed files with 7667 additions and 6396 deletions

No files matched your search

-337
View File
@@ -1,337 +0,0 @@
---
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
```tsx
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
const {
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
isLoading,
error,
isAuthenticated
} = useShakespeare();
```
#### Model Selector Component
```tsx
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
const { getAvailableModels, isLoading } = useShakespeare();
const [models, setModels] = useState<Model[]>([]);
const [selectedModel, setSelectedModel] = useState<string>('');
useEffect(() => {
const fetchModels = async () => {
try {
const response = await getAvailableModels();
// Sort models by total cost (cheapest first)
const sortedModels = response.data.sort((a, b) => {
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
return costA - costB;
});
setModels(sortedModels);
// Select the cheapest model by default
if (sortedModels.length > 0) {
const cheapestModel = sortedModels[0];
setSelectedModel(cheapestModel.id);
onModelSelect(cheapestModel.id);
}
} catch (err) {
console.error('Failed to fetch models:', err);
}
};
fetchModels();
}, [getAvailableModels, onModelSelect]);
const handleModelChange = (modelId: string) => {
setSelectedModel(modelId);
onModelSelect(modelId);
};
return (
<div>
<label htmlFor="model-select">Choose Model:</label>
<select
id="model-select"
value={selectedModel}
onChange={(e) => handleModelChange(e.target.value)}
disabled={isLoading}
>
<option value="">Select a model...</option>
{models.map((model, index) => {
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
const isCheapest = index === 0;
return (
<option key={model.id} value={model.id}>
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
</option>
);
})}
</select>
</div>
);
}
```
#### Basic Chat Example
```tsx
function AIChat() {
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleSend = async () => {
if (!input.trim() || !selectedModel) return;
const newMessages = [...messages, { role: 'user', content: input }];
setMessages(newMessages);
setInput('');
try {
const response = await sendChatMessage(newMessages, selectedModel);
setMessages(prev => [...prev, {
role: 'assistant',
content: response.choices[0].message.content as string
}]);
} catch (err) {
console.error('Chat error:', err);
}
};
if (!isAuthenticated) return <div>Please log in to use AI</div>;
return (
<div className="max-w-2xl mx-auto p-4">
{error && <div className="text-red-500 mb-4">{error}</div>}
{/* Model Selection */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
<div className="space-y-2 mb-4">
{messages.map((msg, i) => (
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<div className="flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
className="flex-1 p-2 border rounded"
disabled={isLoading || !selectedModel}
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
/>
<button
onClick={handleSend}
disabled={isLoading || !selectedModel}
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
>
Send
</button>
</div>
</div>
);
}
```
#### Streaming Chat Example
```tsx
function StreamingChat() {
const { sendStreamingMessage } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [currentResponse, setCurrentResponse] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleStreaming = async (content: string) => {
if (!selectedModel) return;
setCurrentResponse('');
const newMessages = [...messages, { role: 'user', content }];
setMessages(newMessages);
try {
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
setCurrentResponse(prev => prev + chunk);
});
// Add the complete response to messages
if (currentResponse.trim()) {
setMessages(prev => [...prev, {
role: 'assistant',
content: currentResponse
}]);
}
} catch (err) {
console.error('Streaming error:', err);
} finally {
setCurrentResponse('');
}
};
return (
<div>
{/* Model selection UI */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
{/* Chat interface */}
{/* ... rest of your chat UI */}
</div>
);
}
```
#### Model Information
Models are dynamically fetched from the Shakespeare API and include:
- **Model ID**: Unique identifier for the model
- **Name**: Human-readable model name
- **Description**: Model capabilities and use cases
- **Context Window**: Maximum token limit for conversations
- **Pricing**: Cost per token for prompt and completion
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
#### Key Points
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
- **Authentication Required**: User must be logged in with Nostr account
- **Free vs Premium**: Check pricing to determine if model requires credits
- **Error Handling**: Handle `isLoading` and `error` states appropriately
- **Model Selection**: Provide UI for users to choose between available models
## 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
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
```tsx
const handleStreamingResponse = async () => {
let streamedContent = ''; // ✅ Use local variable to accumulate content
try {
await sendStreamingMessage(messages, model, (chunk) => {
streamedContent += chunk; // ✅ Accumulate in local variable
setCurrentStreamingMessage(streamedContent); // Update UI
});
// ✅ Save accumulated content to persistent state
if (streamedContent.trim()) {
const assistantMessage: MessageDisplay = {
id: Date.now().toString(),
role: 'assistant',
content: streamedContent, // ✅ Use accumulated content
timestamp: new Date()
};
setMessages(prev => [...prev, assistantMessage]);
}
} finally {
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
}
};
```
### Error Boundary Patterns
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
```tsx
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { Alert, AlertDescription } from '@/components/ui/alert';
function AIChatWithErrorBoundary() {
return (
<ErrorBoundary
fallback={
<div className="p-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Something went wrong with the AI chat. Please refresh the page and try again.
</AlertDescription>
</Alert>
</div>
}
>
<AIChat />
</ErrorBoundary>
);
}
// In your AI component, handle specific error types gracefully:
function useAIWithErrorHandling() {
const { sendChatMessage, error, clearError } = useShakespeare();
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
try {
await sendChatMessage(messages, modelId);
} catch (err) {
// Handle specific error types with user-friendly messages
if (err.message.includes('401')) {
throw new Error('Authentication failed. Please log in again.');
} else if (err.message.includes('402')) {
throw new Error('Insufficient credits. Please add credits to use premium features.');
} else if (err.message.includes('network')) {
throw new Error('Network error. Please check your internet connection.');
}
throw err; // Re-throw for error boundary
}
};
return { sendMessage, error, clearError };
}
```
@@ -1,478 +0,0 @@
---
name: nostr-direct-messages
description: Implement Nostr direct messaging features, build chat interfaces, or work with encrypted peer-to-peer communication (NIP-04 and NIP-17).
---
# Direct Messaging on Nostr
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, more private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent cache-first local storage.
**The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
## Setup Instructions
### 1. Add DMProvider to Your App
First, add the `DMProvider` to your app's provider tree in `src/App.tsx`:
```tsx
// Add these imports at the top of src/App.tsx
import { DMProvider, type DMConfig } from '@/components/DMProvider';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
// Add this configuration before your App component
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to true to enable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP17_ONLY, // Recommended for new apps
};
// Then wrap your app components with DMProvider:
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
);
}
```
### 2. Configure DM Settings
The `DMConfig` object supports the following options:
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
- `PROTOCOL_MODE.NIP04_OR_NIP17` - Support both protocols (for backwards compatibility)
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
## Quick Start
### 1. Send Messages
```tsx
import { useDMContext } from '@/hooks/useDMContext';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
const [content, setContent] = useState('');
const handleSend = async () => {
await sendMessage({
recipientPubkey,
content,
protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
});
setContent('');
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<button type="submit">Send</button>
</form>
);
}
```
### 2. Display Conversations
```tsx
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
const { conversations, isLoading } = useDMContext();
if (isLoading) {
return <div>Loading conversations...</div>;
}
return (
<div className="space-y-2">
{conversations.map((conversation) => (
<ConversationItem
key={conversation.pubkey}
conversation={conversation}
onClick={() => onSelectConversation(conversation.pubkey)}
/>
))}
</div>
);
}
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
onClick: () => void;
}) {
const author = useAuthor(conversation.pubkey);
const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
const avatarUrl = author.data?.metadata?.picture;
return (
<button onClick={onClick} className="w-full p-3 hover:bg-accent rounded-lg">
<div className="flex items-center gap-3">
<Avatar>
<AvatarImage src={avatarUrl} />
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 text-left">
<div className="font-medium">{displayName}</div>
<div className="text-sm text-muted-foreground truncate">
{conversation.lastMessage?.decryptedContent || 'No messages yet'}
</div>
</div>
</div>
</button>
);
}
```
### 3. Display Messages in a Conversation
```tsx
import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useCurrentUser } from '@/hooks/useCurrentUser';
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
const { user } = useCurrentUser();
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
return (
<div className="flex flex-col space-y-2">
{hasMoreMessages && (
<button onClick={loadEarlierMessages} className="text-sm text-muted-foreground">
Load earlier messages
</button>
)}
{messages.map((message) => {
const isFromMe = message.pubkey === user?.pubkey;
return (
<div
key={message.id}
className={cn(
"flex",
isFromMe ? "justify-end" : "justify-start"
)}
>
<div className={cn(
"max-w-[70%] rounded-lg px-4 py-2",
isFromMe ? "bg-primary text-primary-foreground" : "bg-muted"
)}>
{message.error ? (
<span className="text-red-500">🔒 {message.error}</span>
) : (
<p className="whitespace-pre-wrap break-words">
{message.decryptedContent}
</p>
)}
{message.isSending && (
<span className="text-xs opacity-50">Sending...</span>
)}
</div>
</div>
);
})}
</div>
);
}
```
## Using the Complete Messaging Interface
For a fully-featured messaging UI out of the box, use the `DMMessagingInterface` component:
```tsx
import { DMMessagingInterface } from "@/components/dm/DMMessagingInterface";
function MessagesPage() {
return (
<div className="container mx-auto p-4 h-screen">
<DMMessagingInterface />
</div>
);
}
```
The `DMMessagingInterface` component provides a complete messaging UI with:
- Conversation list with Active/Requests tabs
- Message thread view with pagination
- Compose area with file upload support
- Real-time message updates
- Mobile-responsive layout (shows one panel at a time on mobile)
It requires no props and works automatically when wrapped in `DMProvider`.
**For custom layouts**, see the "Building Custom Messaging UIs" section below for individual components (`DMConversationList`, `DMChatArea`, `DMStatusInfo`).
## Sending Files with Messages
```tsx
import { useDMContext } from '@/hooks/useDMContext';
import { useUploadFile } from '@/hooks/useUploadFile';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import type { FileAttachment } from '@/contexts/DMContext';
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const [content, setContent] = useState('');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const handleSend = async () => {
let attachments: FileAttachment[] | undefined;
// Upload file if one is selected
if (selectedFile) {
const tags = await uploadFile(selectedFile);
attachments = [{
url: tags[0][1], // URL from first tag
mimeType: selectedFile.type,
size: selectedFile.size,
name: selectedFile.name,
tags: tags
}];
}
await sendMessage({
recipientPubkey,
content,
protocol: MESSAGE_PROTOCOL.NIP17,
attachments,
});
setContent('');
setSelectedFile(null);
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<input
type="file"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
/>
{selectedFile && <div>Selected: {selectedFile.name}</div>}
<button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Send'}
</button>
</form>
);
}
```
## Protocol Comparison
### NIP-04 (Legacy)
- **Encryption**: NIP-04 (simpler, older)
- **Metadata**: Sender and recipient visible to relays
- **Event Kind**: Kind 4
- **Use When**: Compatibility with older clients
### NIP-17 (Modern & Private)
- **Encryption**: NIP-44 (stronger)
- **Metadata**: Hidden via gift wrapping (NIP-59)
- **Event Kinds**: Kind 14 (text), Kind 15 (files)
- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
- **Use When**: Maximum privacy (recommended)
**Key Privacy Features of NIP-17:**
- Sender identity hidden (uses random ephemeral keys)
- Timestamps randomized (±2 days) to hide send time
- Dual gift wraps (recipient + sender) for message history
## Advanced Features
### Conversation Categorization
The system automatically categorizes conversations:
```tsx
const { conversations } = useDMContext();
// Filter by category
const knownConversations = conversations.filter(c => c.isKnown);
const requestConversations = conversations.filter(c => c.isRequest);
// isKnown = true if user has sent at least one message
// isRequest = true if only received messages, never replied
```
### Loading States
```tsx
const { isLoading, loadingPhase, scanProgress } = useDMContext();
// Check overall loading state
if (isLoading) {
console.log('Current phase:', loadingPhase);
// LOADING_PHASES.CACHE - Loading from local cache
// LOADING_PHASES.RELAYS - Querying relays
// LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
// LOADING_PHASES.READY - Fully loaded
}
// Display scan progress for large message histories
if (scanProgress.nip17) {
console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
}
```
### Clear Cache and Refresh
```tsx
import { useDMContext } from '@/hooks/useDMContext';
function SettingsButton() {
const { clearCacheAndRefetch } = useDMContext();
const handleClearCache = async () => {
await clearCacheAndRefetch();
// Clears IndexedDB cache and reloads all messages from relays
};
return (
<button onClick={handleClearCache}>
Clear Message Cache
</button>
);
}
```
## Architecture Notes
### Data Flow
1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
2. **Background Sync**: New messages fetched from relays in parallel
3. **Real-time Updates**: WebSocket subscriptions for live messages
4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
### Storage
- **IndexedDB**: All messages stored locally with NIP-44 encryption
- **Per-User Storage**: Separate encrypted store for each logged-in user
- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
### Performance
- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
- **Pagination**: Conversation messages paginated (25/page)
- **Deduplication**: Automatic filtering of duplicate messages by ID
### Security
- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
- **No Plaintext**: Decrypted content never persisted unencrypted
- **Domain Isolation**: IndexedDB databases are namespaced by hostname to prevent data conflicts
## Building Custom Messaging UIs
For advanced use cases, you can use the individual DM components to build custom layouts:
### Available Components
**`DMConversationList`** - Conversation sidebar with tabs
```tsx
import { DMConversationList } from '@/components/dm/DMConversationList';
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={(pubkey) => setSelectedPubkey(pubkey)}
onStatusClick={() => setShowStatus(true)} // optional
className="h-full"
/>
```
**`DMChatArea`** - Message thread and compose area
```tsx
import { DMChatArea } from '@/components/dm/DMChatArea';
<DMChatArea
pubkey={selectedPubkey}
onBack={() => setSelectedPubkey(null)} // optional, for mobile back button
className="h-full"
/>
```
**`DMStatusInfo`** - Debug/status panel
```tsx
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
```
### Custom Layout Example
```tsx
import { useState } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea';
function CustomMessagingLayout() {
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
return (
<div className="flex h-screen">
{/* Custom sidebar */}
<aside className="w-64 border-r">
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={setSelectedPubkey}
/>
</aside>
{/* Custom main area */}
<main className="flex-1">
{selectedPubkey ? (
<DMChatArea pubkey={selectedPubkey} />
) : (
<div className="flex items-center justify-center h-full">
<p>Select a conversation to start messaging</p>
</div>
)}
</main>
</div>
);
}
```
+1
View File
@@ -0,0 +1 @@
../.mcp.json
-2
View File
@@ -7,13 +7,11 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.ai/
yarn.lock
# Editor directories and files
.idea
+1
View File
@@ -0,0 +1 @@
@jsr:registry=https://npm.jsr.io
+107 -208
View File
@@ -15,11 +15,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
## Project Structure
- `/docs/`: Specialized documentation for implementation patterns and features
- `/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.)
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
- 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,23 +33,21 @@ 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
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
- `useConversationMessages`: Hook exported from DMContext for paginated messages
- `/src/contexts/`: React context providers (AppContext, NWCContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup (**CRITICAL**: this file is **already configured** with `QueryClientProvider`, `NostrProvider`, `UnheadProvider` and other important providers - **read this file before making changes**. Changes are usually not necessary unless adding new providers. Changing this file may break the application)
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
**CRITICAL**: Always read the files mentioned above before making changes, as they contain important setup and configuration for the application. Never directly write to these files without first reading their contents.
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
@@ -103,6 +101,40 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## Documentation
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
- **`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. **CRITICAL**: Follow the two-component architecture - `CashuWallet` for standalone wallet management, `ZapButton` for content integration.
## Cashu Integration Architecture
**IMPORTANT**: The Cashu wallet integration follows a **two-component architecture** that must be preserved:
### Component Separation
- **`CashuWallet`**: Standalone wallet management interface (dedicated page/route)
- **`ZapButton`**: Integrated zap functionality within content feeds
### Why This Architecture?
- **Clean UX**: Users manage wallet separately from consuming content
- **Performance**: Wallet operations don't interfere with feed rendering
- **Security**: Sensitive wallet operations are isolated
- **Mobile Optimization**: Wallet can use full-screen layouts
### Integration Rules
- ✅ **CORRECT**: `CashuWallet` as separate route/page
- ✅ **CORRECT**: `ZapButton` embedded in content feeds
- ❌ **INCORRECT**: Embedding `CashuWallet` in content feeds
- ❌ **INCORRECT**: Mixing wallet management with content consumption
**Always read `docs/CASHU_ZAP_INTEGRATION.md` before implementing any Cashu-related features.**
## 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:
@@ -110,6 +142,10 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
@@ -143,7 +179,6 @@ When implementing features that could use existing NIPs, follow this decision fr
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
- If you have a tool available to generate a kind, you **MUST** call the tool to generate a new kind rather than picking an arbitrary number
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
@@ -220,7 +255,7 @@ const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}]);
}], { signal });
```
### Kind Ranges
@@ -270,104 +305,6 @@ The file `NIP.md` is used by this project to define a custom Nostr protocol docu
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### Nostr Security Model
**CRITICAL**: Nostr is permissionless - **anyone can publish any event**. When implementing admin/moderation systems or any feature that should only trust specific users, you MUST filter queries by the `authors` field. Without author filtering, anyone can publish events claiming to be admin actions, moderator decisions, or trusted content.
#### Using the `authors` Filter
**Always filter by authors when querying:**
- **Admin/moderator actions** - MUST filter by trusted admin pubkeys
- **Addressable events (kinds 30000-39999)** - MUST include author to prevent anyone from publishing events with the same d-tag
- **Any privileged operations** - Filter by trusted pubkeys only
**✅ Secure - Filtering by trusted authors:**
```typescript
import { ADMIN_PUBKEYS } from '@/lib/admins';
// Query organizer appointments - ONLY accept events from admins
const events = await nostr.query([{
kinds: [30078],
authors: ADMIN_PUBKEYS, // CRITICAL: Only trust admin authors
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**❌ INSECURE - No author filtering:**
```typescript
// DANGER: This accepts events from ANYONE who publishes kind 30078
// An attacker could appoint themselves as an organizer
const events = await nostr.query([{
kinds: [30078],
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**Addressable Events Example:**
```typescript
// For addressable events, ALWAYS include the author in your filter
// This prevents attackers from publishing events with the same d-tag
const article = await nostr.query([{
kinds: [30023], // Long-form article
authors: [authorPubkey], // CRITICAL: Verify the author
'#d': ['my-article-slug'],
limit: 1
}]);
```
**URL Routing for Addressable/Replaceable Events:**
When creating URL paths for addressable or replaceable events, always include the author in the URL structure:
```typescript
// ❌ INSECURE: Missing author - anyone could publish an event with this d-tag
<Route path="/article/:slug" element={<Article />} />
// URL: /article/hello-world
// ✅ SECURE: Includes author - can safely filter by both author and d-tag
<Route path="/article/:npub/:slug" element={<Article />} />
// URL: /article/npub1abc.../hello-world
```
This ensures your route parameters provide both the author pubkey and the d-tag identifier needed to create a secure query filter.
**NIP-72 Community Moderation Example:**
When implementing moderated communities (NIP-72), you must query the community definition to get the moderator list, then filter approval events by those moderators:
```typescript
// Step 1: Query the community definition to get moderators
const communityEvents = await nostr.query([{
kinds: [34550],
authors: [communityOwnerPubkey], // CRITICAL: Only trust the community owner
'#d': [communityId],
limit: 1,
}]);
if (communityEvents.length === 0) return [];
// Step 2: Extract moderator pubkeys from p tags
const moderatorPubkeys = communityEvents[0].tags
.filter(([name, _, __, role]) => name === 'p' && role === 'moderator')
.map(([_, pubkey]) => pubkey);
// Step 3: Query approval events - ONLY from trusted moderators
const approvals = await nostr.query([{
kinds: [4550],
authors: moderatorPubkeys, // CRITICAL: Only accept approvals from moderators
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
limit: 100,
}]);
```
Without filtering approvals by the moderator list, anyone could publish kind 4550 events claiming to approve posts for the community.
#### When Author Filtering Is NOT Required
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -400,7 +337,7 @@ function useSpecificRelay() {
const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }]);
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
@@ -425,7 +362,7 @@ function useRelayGroup() {
]);
// Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }]);
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
@@ -475,7 +412,8 @@ function usePosts() {
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const events = await nostr.query([{ kinds: [1], limit: 20 }]);
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
@@ -495,7 +433,7 @@ const events = await nostr.query([
'#e': [eventId],
limit: 150,
}
]);
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
@@ -507,9 +445,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }]),
nostr.query([{ kinds: [6], '#e': [eventId] }]),
nostr.query([{ kinds: [16], '#e': [eventId] }]),
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
@@ -563,7 +501,8 @@ function useCalendarEvents() {
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]);
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
@@ -764,6 +703,7 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
@@ -791,6 +731,7 @@ const events = await nostr.query(
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
@@ -897,46 +838,16 @@ export function Post(/* ...props */) {
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
relayUrl: "wss://relay.nostr.band",
};
```
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
### Relay Management
The project includes a complete NIP-65 relay management system:
- **RelayListManager**: Component for managing multiple relays with read/write permissions
- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in
- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in
Use the `RelayListManager` component to provide relay management interfaces:
```tsx
import { RelayListManager } from '@/components/RelayListManager';
function SettingsPage() {
return (
<div>
<h2>Relay Settings</h2>
<RelayListManager />
</div>
);
}
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
@@ -990,9 +901,10 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface.
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
@@ -1001,61 +913,24 @@ import { Card, CardContent } from '@/components/ui/card';
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try checking your relay connections or wait a moment for content to load.
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## CRITICAL Design Standards
## Design Customization
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
**Tailor the site's look and feel based on the user's specific request.** This includes:
### Design Principles
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- **Generate custom images liberally** when image generation tools are available - this is ALWAYS preferred over stock photography for creating unique, brand-specific visuals that perfectly match the design intent
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
### Avoid Generic Design
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
### Interaction Patterns
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
### Technical Requirements
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
### Components
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
@@ -1120,14 +995,45 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
- When using negative z-index (e.g., `-z-10`) for background images or decorative elements, **always add `isolate` to the parent container** to create a local stacking context. Without `isolate`, negative z-index pushes elements behind the page's background color, making them invisible.
### 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
There is an important distinction between **writing new tests** and **running existing tests**:
### Writing Tests (Creating New Test Files)
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
@@ -1141,7 +1047,6 @@ There is an important distinction between **writing new tests** and **running ex
- Existing functionality needs verification
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes
@@ -1200,10 +1105,4 @@ Run available tools in this priority order:
- Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
### Using Git
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
When your changes are complete and validated, create a git commit with a descriptive message summarizing your changes.
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
+170
View File
@@ -0,0 +1,170 @@
### AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
```tsx
import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
```
#### Basic Chat Example
```tsx
function AIChat() {
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const handleSend = async () => {
if (!input.trim()) return;
const newMessages = [...messages, { role: 'user', content: input }];
setMessages(newMessages);
setInput('');
const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
setMessages(prev => [...prev, {
role: 'assistant',
content: response.choices[0].message.content as string
}]);
};
if (!isAuthenticated) return <div>Please log in to use AI</div>;
return (
<div className="max-w-2xl mx-auto p-4">
{error && <div className="text-red-500 mb-4">{error}</div>}
<div className="space-y-2 mb-4">
{messages.map((msg, i) => (
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<div className="flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
className="flex-1 p-2 border rounded"
disabled={isLoading}
/>
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
Send
</button>
</div>
</div>
);
}
```
#### Streaming Chat
```tsx
const [currentResponse, setCurrentResponse] = useState('');
const handleStreaming = async (content: string) => {
setCurrentResponse('');
await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
setCurrentResponse(prev => prev + chunk);
});
};
```
#### Models
- **`tybalt`**: Free model for development
- **`shakespeare`**: Premium model (requires credits)
#### Key Points
- User must be logged in with Nostr account
- Use `tybalt` for free testing
- Handle `isLoading` and `error` states
- Check `isAuthenticated` before API calls
## Implementation Patterns and Best Practices
### 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:
```tsx
const handleStreamingResponse = async () => {
let streamedContent = ''; // ✅ Use local variable to accumulate content
try {
await sendStreamingMessage(messages, model, (chunk) => {
streamedContent += chunk; // ✅ Accumulate in local variable
setCurrentStreamingMessage(streamedContent); // Update UI
});
// ✅ Save accumulated content to persistent state
if (streamedContent.trim()) {
const assistantMessage: MessageDisplay = {
id: Date.now().toString(),
role: 'assistant',
content: streamedContent, // ✅ Use accumulated content
timestamp: new Date()
};
setMessages(prev => [...prev, assistantMessage]);
}
} finally {
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
}
};
```
### Error Boundary Patterns
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
```tsx
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { Alert, AlertDescription } from '@/components/ui/alert';
function AIChatWithErrorBoundary() {
return (
<ErrorBoundary
fallback={
<div className="p-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Something went wrong with the AI chat. Please refresh the page and try again.
</AlertDescription>
</Alert>
</div>
}
>
<AIChat />
</ErrorBoundary>
);
}
// In your AI component, handle specific error types gracefully:
function useAIWithErrorHandling() {
const { sendChatMessage, error, clearError } = useShakespeare();
const sendMessage = async (messages: ChatMessage[]) => {
try {
await sendChatMessage(messages, 'tybalt');
} catch (err) {
// Handle specific error types with user-friendly messages
if (err.message.includes('401')) {
throw new Error('Authentication failed. Please log in again.');
} else if (err.message.includes('402')) {
throw new Error('Insufficient credits. Please add credits to use premium features.');
} else if (err.message.includes('network')) {
throw new Error('Network error. Please check your internet connection.');
}
throw err; // Re-throw for error boundary
}
};
return { sendMessage, error, clearError };
}
```
+393
View File
@@ -0,0 +1,393 @@
# 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
**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops!
### Setup CashuContext (Required!)
Create `src/contexts/CashuContext.tsx`:
```tsx
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashu(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashu must be used within a CashuProvider');
}
return context;
}
```
### Wrap Your App
Add `CashuProvider` to your App.tsx:
```tsx
import { CashuProvider } from '@/contexts/CashuContext';
export function App() {
return (
<SomeProvider>
<CashuProvider>
{/* Your app */}
</CashuProvider>
</SomeProvider>
);
}
```
### Import from Context
**Always** import from the context, not the hook:
```tsx
// ✅ CORRECT
import { useCashu } from '@/contexts/CashuContext';
// ❌ WRONG - Will cause infinite loops!
import { useCashu } from '@/hooks/useCashu';
```
This ensures all components share the same Cashu wallet instance, preventing:
- Multiple wallet initializations
- Infinite refresh loops
- Performance issues
## Architecture Overview
**IMPORTANT**: The Cashu integration uses a **two-component architecture**:
1. **`CashuWallet`** - Standalone wallet management interface (separate page/route)
2. **`ZapButton`** - Integrated zap functionality within content feeds
### Component Separation
The `CashuWallet` component is designed as a **standalone wallet management interface** and should remain separate from content feeds. This separation provides:
- **Clean UX**: Users manage their wallet separately from consuming content
- **Performance**: Wallet operations don't interfere with feed rendering
- **Security**: Sensitive wallet operations are isolated
- **Mobile Optimization**: Wallet can use full-screen layouts on mobile
### Integration Pattern
```tsx
// ✅ CORRECT: Separate wallet management
function App() {
return (
<Router>
<Routes>
<Route path="/wallet" element={<CashuWallet />} />
<Route path="/" element={<FeedPage />} />
</Routes>
</Router>
);
}
// ✅ CORRECT: ZapButton integrated in content
function FeedPage() {
return (
<div className="posts">
{events.map(event => (
<div key={event.id} className="post">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
))}
</div>
);
}
// ❌ INCORRECT: Don't embed CashuWallet in content feeds
function FeedPage() {
return (
<div className="posts">
<CashuWallet /> {/* Don't do this */}
{events.map(event => (
<div key={event.id} className="post">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
))}
</div>
);
}
```
## 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. **Maintain Component Separation**: Keep `CashuWallet` as a standalone page/route, not embedded in content feeds
2. **Always include CashuWallet**: Provide a dedicated route/page for wallet management
3. **Use consistent styling**: Apply your app's design system
4. **Handle loading states**: The component manages its own loading states
5. **Trust the intelligence**: The component handles payment method selection automatically
6. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work
7. **Follow the architecture**: Use `ZapButton` for content integration, `CashuWallet` for wallet management
8. **Avoid Infinite Loops**: The `useCashu` hook includes throttling and deep comparison to prevent infinite refresh loops. Do NOT:
- Call `refreshBalances()` in `useEffect` that depends on `balances`
- Create circular dependencies between state updates and effects
- Override the built-in throttling mechanisms
## 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
### Infinite Loop: `refreshBalances` Repeatedly Called
If you see continuous console logs like `🔄 refreshBalances: Getting balances from wallet...`, the issue is likely:
**Root Cause #1 (MOST COMMON)**: Multiple components are calling `useCashu()` directly from the hook instead of from the Context Provider. This creates multiple wallet instances that all try to initialize and refresh balances.
**Solution**: Ensure you:
1. Created `CashuContext.tsx` as shown in the Required Dependencies section
2. Wrapped your app with `<CashuProvider>`
3. Import `useCashu` from `@/contexts/CashuContext` in ALL components (not from `@/hooks/useCashu`)
**Root Cause #2**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency.
**Built-in Protections**: The `useCashu` hook includes:
- **Throttling**: Prevents calls more than once every 500ms
- **Deep Comparison**: Only updates state if balance values actually changed
- **Stable References**: Returns the same object reference when values are unchanged
**Common Mistakes to Avoid**:
```tsx
// ❌ INCORRECT: Creates infinite loop
useEffect(() => {
refreshBalances();
}, [balances, refreshBalances]);
// ❌ INCORRECT: Calls refreshBalances on every balance change
useEffect(() => {
if (balances) {
refreshBalances();
}
}, [balances]);
// ✅ CORRECT: Only call on mount or user action
useEffect(() => {
refreshBalances(); // Called once on mount
}, []); // Empty dependency array
// ✅ CORRECT: Call on user action
<Button onClick={() => refreshBalances()}>
Refresh
</Button>
```
**If Issue Persists**: Check your implementation for:
1. Effects that call `refreshBalances` and depend on `balances`
2. Custom hooks that wrap `useCashu` and create circular dependencies
3. Component re-renders that trigger unintended effect runs
## Integration Checklist
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
- [ ] Import unified `ZapButton` component
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
- [ ] Verify mobile responsiveness
- [ ] Test error handling scenarios
- [ ] Verify component separation (wallet management vs content integration)
- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly)
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,8 +1,3 @@
---
name: nostr-comments
description: Implement Nostr comment systems, add discussion features to posts/articles, or build community interaction features.
---
# Adding Nostr Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
@@ -1,9 +1,4 @@
---
name: nostr-infinite-scroll
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
---
# Infinite Scroll for Nostr Feeds
### Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
+1
View File
@@ -17,6 +17,7 @@ export default tseslint.config(
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+1729 -1494
View File
File diff suppressed because it is too large. Load diff
+14 -11
View File
@@ -4,16 +4,17 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i --silent && vite",
"dev": "npm i --legacy-peer-deps --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'"
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^7.0.0",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -41,24 +42,26 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@scure/bip39": "^2.0.0",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"coco-cashu-core": "1.0.0-rc10",
"coco-cashu-indexeddb": "0.8.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.21.0",
"nostr-tools": "^2.13.0",
"npubcash-sdk": "^0.2.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.71.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -66,7 +69,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^4.3.6"
"zod": "^3.25.71"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
+1 -2
View File
@@ -1,2 +1 @@
/assets/* /assets/:splat 200
/* /index.html 200
/* /index.html 200
-2
View File
@@ -1,2 +0,0 @@
User-agent: *
Allow: /
+10 -12
View File
@@ -6,7 +6,6 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
@@ -32,25 +31,24 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "light",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
theme: "system",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<TooltipProvider>
<Toaster />
+2
View File
@@ -4,6 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { CashuWallet } from "./components/wallet/CashuWallet";
export function AppRouter() {
return (
@@ -11,6 +12,7 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/wallet" element={<CashuWallet />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+14 -22
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
@@ -9,54 +9,46 @@ interface AppProviderProps {
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for RelayMetadata validation
const RelayMetadataSchema = z.object({
relays: z.array(z.object({
url: z.url(),
read: z.boolean(),
write: z.boolean(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayMetadata: RelayMetadataSchema,
}) satisfies z.ZodType<AppConfig>;
relayUrl: z.string().url(),
});
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
{},
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.partial().parse(parsed);
return AppConfigSchema.parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
setConfig(updater);
};
const config = { ...defaultConfig, ...rawConfig };
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
@@ -96,11 +88,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
File diff suppressed because it is too large. Load diff
+19 -25
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -10,7 +10,7 @@ interface NostrProviderProps {
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config } = useAppContext();
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayMetadata = useRef(config.relayMetadata);
const relayUrl = useRef<string>(config.relayUrl);
// Invalidate Nostr queries when relay metadata changes
// Update refs when config changes
useEffect(() => {
relayMetadata.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayMetadata, queryClient]);
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
@@ -32,27 +32,21 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters: NostrFilter[]) {
const routes = new Map<string, NostrFilter[]>();
// Route to all read relays
const readRelays = relayMetadata.current.relays
.filter(r => r.read)
.map(r => r.url);
for (const url of readRelays) {
routes.set(url, filters);
}
return routes;
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
},
eventRouter(_event: NostrEvent) {
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
const allRelays = new Set<string>(writeRelays);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
},
-62
View File
@@ -1,62 +0,0 @@
import { useEffect } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
/**
* NostrSync - Syncs user's Nostr data
*
* This component runs globally to sync various Nostr data when the user logs in.
* Currently syncs:
* - NIP-65 relay list (kind 10002)
*/
export function NostrSync() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { config, updateConfig } = useAppContext();
useEffect(() => {
if (!user) return;
const syncRelaysFromNostr = async () => {
try {
const events = await nostr.query(
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
if (events.length > 0) {
const event = events[0];
// Only update if the event is newer than our stored data
if (event.created_at > config.relayMetadata.updatedAt) {
const fetchedRelays = event.tags
.filter(([name]) => name === 'r')
.map(([_, url, marker]) => ({
url,
read: !marker || marker === 'read',
write: !marker || marker === 'write',
}));
if (fetchedRelays.length > 0) {
console.log('Syncing relay list from Nostr:', fetchedRelays);
updateConfig((current) => ({
...current,
relayMetadata: {
relays: fetchedRelays,
updatedAt: event.created_at,
},
}));
}
}
}
} catch (error) {
console.error('Failed to sync relays from Nostr:', error);
}
};
syncRelaysFromNostr();
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
return null;
}
+2 -7
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline break-all"
className="text-blue-500 hover:underline"
>
{url}
</a>
@@ -61,18 +61,13 @@ export function NoteContent({
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else if (decoded.type === 'nprofile') {
const pubkey = decoded.data.pubkey;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline break-all"
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
-286
View File
@@ -1,286 +0,0 @@
import { useState, useEffect } from 'react';
import { Plus, X, Wifi, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
interface Relay {
url: string;
read: boolean;
write: boolean;
}
export function RelayListManager() {
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const { toast } = useToast();
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync)
useEffect(() => {
setRelays(config.relayMetadata.relays);
}, [config.relayMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
return new URL(url).toString();
} catch {
try {
return new URL(`wss://${url}`).toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: 'Invalid relay URL',
description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)',
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (relays.some(r => r.url === normalized)) {
toast({
title: 'Relay already exists',
description: 'This relay is already in your list.',
variant: 'destructive',
});
return;
}
const newRelays = [...relays, { url: normalized, read: true, write: true }];
setRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = relays.filter(r => r.url !== url);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleRead = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, read: !r.read } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleWrite = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, write: !r.write } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: Relay[]) => {
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
relayMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP65RelayList(newRelays);
}
};
const publishNIP65RelayList = (relayList: Relay[]) => {
const tags = relayList.map(relay => {
if (relay.read && relay.write) {
return ['r', relay.url];
} else if (relay.read) {
return ['r', relay.url, 'read'];
} else if (relay.write) {
return ['r', relay.url, 'write'];
}
// If neither read nor write, don't include (shouldn't happen)
return null;
}).filter((tag): tag is string[] => tag !== null);
publishEvent(
{
kind: 10002,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: 'Relay list published',
description: 'Your relay list has been published to Nostr.',
});
},
onError: (error) => {
console.error('Failed to publish relay list:', error);
toast({
title: 'Failed to publish relay list',
description: 'There was an error publishing your relay list to Nostr.',
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.protocol === 'wss:') {
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} else {
return parsed.href;
}
} catch {
return url;
}
}
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{relays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
>
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
{/* Settings Popover */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
>
<Settings className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="end">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
Read
</Label>
<Switch
id={`read-${relay.url}`}
checked={relay.read}
onCheckedChange={() => handleToggleRead(relay.url)}
className="data-[state=checked]:bg-green-500 scale-75"
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
Write
</Label>
<Switch
id={`write-${relay.url}`}
checked={relay.write}
onCheckedChange={() => handleToggleWrite(relay.url)}
className="data-[state=checked]:bg-blue-500 scale-75"
/>
</div>
</div>
</PopoverContent>
</Popover>
{/* Remove Button */}
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={relays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-relay-url" className="sr-only">
Relay URL
</Label>
<Input
id="new-relay-url"
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
Add Relay
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
Log in to sync your relay list with Nostr
</p>
)}
</div>
);
}
+174
View File
@@ -0,0 +1,174 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
interface RelaySelectorProps {
className?: string;
}
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url: string) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("justify-between", className)}
>
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue && isValidRelayInput(inputValue) ? (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{inputValue ? "Invalid relay URL" : "No relay found."}
</div>
)}
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
.map((option) => (
<CommandItem
key={option.url}
value={option.url}
onSelect={(currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedRelay === option.url ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span className="font-medium">{option.name}</span>
<span className="text-xs text-muted-foreground">{option.url}</span>
</div>
</CommandItem>
))}
{inputValue && isValidRelayInput(inputValue) && (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer border-t"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+49 -13
View File
@@ -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/cashu/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<HTMLDivElement, {
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
cashuBalance: number;
isCashuInitialized: boolean;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
@@ -83,14 +86,43 @@ const WalletContent = forwardRef<HTMLDivElement, {
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
{/* Primary Payment Method - Cashu */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<h3 className="font-medium">Primary Wallet</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>
<Separator />
{/* Lightning Fallback Methods */}
<div className="space-y-3">
<h3 className="font-medium">Other Options</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
@@ -190,12 +222,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!webln && connections.length === 0 && (
{!isCashuInitialized && !webln && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<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
</p>
</div>
</>
@@ -204,7 +236,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
@@ -222,8 +254,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
} = useNWC();
const { webln } = useWallet();
const { balances, isInitialized: isCashuInitialized } = useCashu();
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 handleAddConnection = async () => {
@@ -267,6 +301,8 @@ export function WalletModal({ children, className }: WalletModalProps) {
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
@@ -308,7 +344,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
Payment Settings
</Button>
)}
</DrawerTrigger>
@@ -322,10 +358,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
Payment Settings
</DrawerTitle>
<DrawerDescription>
Connect your lightning wallet to send zaps instantly.
Manage wallet methods for zaps
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
@@ -370,7 +406,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
Payment Settings
</Button>
)}
</DialogTrigger>
@@ -378,10 +414,10 @@ export function WalletModal({ children, className }: WalletModalProps) {
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
Payment Settings
</DialogTitle>
<DialogDescription>
Connect your lightning wallet to send zaps instantly.
Manage wallet methods for zaps
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
+528 -21
View File
@@ -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/cashu/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<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({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { toast } = useToast();
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
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
@@ -30,29 +321,245 @@ export function ZapButton({
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
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
if (isMobile) {
return (
<Drawer
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" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</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 (
<ZapDialog target={target}>
<div className={`flex items-center gap-1 ${className}`}>
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</ZapDialog>
<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>
);
}
+92 -8
View File
@@ -1,5 +1,5 @@
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 { cn } from '@/lib/utils';
import {
@@ -30,6 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
@@ -57,6 +58,9 @@ interface ZapContentProps {
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
// Cashu-related props
canPayWithCashu: boolean;
cashuBalance: number;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
@@ -75,6 +79,8 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
@@ -139,8 +145,33 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
{/* 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);
@@ -165,13 +196,26 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
</Button>
<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>
) : (
<>
{/* 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"
@@ -188,6 +232,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
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>
@@ -207,6 +252,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
max={canPayWithCashu ? cashuBalance : undefined}
/>
<Textarea
id="custom-comment"
@@ -218,9 +264,19 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
/>
</div>
<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 ? (
'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" />
@@ -242,6 +298,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
const { toast } = useToast();
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);
@@ -249,6 +306,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
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);
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
@@ -328,6 +389,25 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
// Validate the amount
if (isNaN(finalAmount) || finalAmount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
return;
}
if (canPayWithCashu && finalAmount > cashuBalance) {
toast({
title: 'Insufficient Cashu balance',
description: `You only have ${cashuBalance} sats available.`,
variant: 'destructive',
});
return;
}
zap(finalAmount, comment);
};
@@ -339,6 +419,8 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
@@ -420,7 +502,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{invoice ? (
'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>
</DrawerHeader>
@@ -448,9 +532,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{invoice ? (
'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!'
)}
</DialogDescription>
</DialogHeader>
+15 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,6 +10,8 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { LightningWalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -41,6 +43,9 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
@@ -59,6 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<LightningWalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Payment Settings</span>
</DropdownMenuItem>
</LightningWalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+5 -1
View File
@@ -2,6 +2,7 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
@@ -33,13 +34,15 @@ export function LoginArea({ className }: LoginAreaProps) {
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<span>Sign up</span>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button>
</div>
)}
@@ -48,6 +51,7 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
+187 -151
View File
@@ -2,20 +2,20 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useLoginActions } from '@/hooks/useLoginActions';
import { DialogTitle } from '@radix-ui/react-dialog';
import { cn } from '@/lib/utils';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
@@ -26,7 +26,7 @@ const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
@@ -170,167 +170,203 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
reader.readAsText(file);
};
const hasExtension = 'nostr' in window;
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const renderTabs = () => (
<Tabs defaultValue="key" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="key" className="flex items-center gap-2">
<span>Secret Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<span>Remote Signer</span>
</TabsTrigger>
</TabsList>
<TabsContent value='key' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleKeyLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
type="submit"
size="lg"
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
type="button"
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleBunkerLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
type="submit"
size="lg"
className='w-full'
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Log in'}
</Button>
</form>
</TabsContent>
</Tabs>
);
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
Log in
</DialogTitle>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1 min-h-0'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
<div className='px-6 pb-6 space-y-4 overflow-y-auto'>
{/* Extension Login Button - shown if extension is available */}
{hasExtension && (
<div className="space-y-4">
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<Button
className="w-full h-12 px-9"
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Log in with Extension'}
</Button>
</div>
)}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
{hasExtension ? (
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<CollapsibleTrigger asChild>
<button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
<span>More Options</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
</button>
</CollapsibleTrigger>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent>
</Tabs>
</div>
</DialogContent>
</Dialog>
+50
View File
@@ -0,0 +1,50 @@
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
export function LoginIcon() {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
if (currentUser) {
return (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
);
}
return (
<>
<Button
onClick={() => setLoginDialogOpen(true)}
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
title="Log in"
>
<User className="!h-6 !w-6" />
</Button>
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</>
);
}
+435 -88
View File
@@ -2,26 +2,35 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Upload, Eye, EyeOff } from 'lucide-react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
const sanitizeFilename = (filename: string) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showKey, setShowKey] = useState(false);
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -34,9 +43,34 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('download');
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
};
const downloadKey = () => {
@@ -45,14 +79,8 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
@@ -66,9 +94,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Continue to profile step
login.nsec(nsec);
setStep('profile');
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
@@ -78,6 +110,21 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
}
};
const finishKeySetup = () => {
try {
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
}
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
@@ -111,6 +158,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
@@ -122,6 +173,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -134,6 +188,30 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} catch {
toast({
@@ -141,111 +219,372 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
} finally {
// Still proceed to completion even if profile failed
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'generate') return 'Sign up';
if (step === 'download') return 'Secret Key';
if (step === 'profile') return 'Create Your Profile';
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('generate');
setStep('welcome');
setIsLoading(false);
setNsec('');
setShowKey(false);
setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
{/* Generate Step */}
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
{/* Benefits */}
<div className='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<Button className="w-full h-12 px-9" onClick={generateKey}>
Generate key
</Button>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Download Step */}
{step === 'download' && (
<div className='space-y-4'>
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
{/* Generate Step - Enhanced with animations */}
{step === 'generate' && (
<div className='text-center space-y-4'>
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
{/* Animated background elements */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
</div>
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono text-sm"
/>
{!isLoading && (
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={generateKey}
disabled={isLoading}
>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
</div>
)}
{/* Download Step - Whimsical and magical */}
{step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
</div>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
</Button>
</div>
</div>
)}
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</Button>
{/* Profile Step - Optional profile setup */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='mx-auto max-w-sm'>
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
<p className='text-xs text-amber-900 dark:text-amber-300'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
</div>
</div>
)}
{/* Profile Step */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Publishing status indicator */}
{isPublishing && (
<div className='p-4 rounded-lg bg-muted border'>
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
Publishing your profile...
</span>
</div>
@@ -263,6 +602,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
@@ -276,7 +616,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='resize-none'
className='rounded-lg resize-none'
rows={3}
disabled={isPublishing}
/>
@@ -292,7 +632,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='flex-1'
className='rounded-lg flex-1'
disabled={isPublishing}
/>
<input
@@ -308,6 +648,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
@@ -323,7 +664,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full'
className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
@@ -333,18 +674,24 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
Creating Profile...
</>
) : (
'Create profile'
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)}
</Button>
<Button
variant='outline'
className='w-full'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
'Setting up account...'
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
) : (
'Skip for now'
)}
-409
View File
@@ -1,409 +0,0 @@
import { useState, useRef, useEffect, useCallback, memo } from 'react';
import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useDMContext } from '@/hooks/useDMContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { ArrowLeft, Send, Loader2, AlertTriangle, Key, ShieldCheck } from 'lucide-react';
import { cn } from '@/lib/utils';
import { NoteContent } from '@/components/NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
interface DMChatAreaProps {
pubkey: string | null;
onBack?: () => void;
className?: string;
}
const MessageBubble = memo(({
message,
isFromCurrentUser
}: {
message: {
id: string;
pubkey: string;
kind: number;
tags: string[][];
decryptedContent?: string;
decryptedEvent?: NostrEvent;
error?: string;
created_at: number;
isSending?: boolean;
};
isFromCurrentUser: boolean;
}) => {
// For NIP-17, use inner message kind (14/15); for NIP-04, use message kind (4)
const actualKind = message.decryptedEvent?.kind || message.kind;
const isNIP4Message = message.kind === 4;
const isFileAttachment = actualKind === 15; // Kind 15 = files/attachments
// Create a NostrEvent object for NoteContent (only used for kind 15)
// For NIP-17 file attachments, use the decryptedEvent which has the actual tags
const messageEvent: NostrEvent = message.decryptedEvent || {
id: message.id,
pubkey: message.pubkey,
created_at: message.created_at,
kind: message.kind,
tags: message.tags,
content: message.decryptedContent || '',
sig: '', // Not needed for display
};
return (
<div className={cn("flex mb-4", isFromCurrentUser ? "justify-end" : "justify-start")}>
<div className={cn(
"max-w-[70%] rounded-lg px-4 py-2",
isFromCurrentUser
? "bg-primary text-primary-foreground"
: "bg-muted"
)}>
{message.error ? (
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<p className="text-sm italic opacity-70 cursor-help">🔒 Failed to decrypt</p>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{message.error}</p>
</TooltipContent>
</Tooltip>
) : isFileAttachment ? (
// Kind 15: Use NoteContent to render files/media with imeta tags
<div className="text-sm">
<NoteContent event={messageEvent} className="whitespace-pre-wrap break-words" />
</div>
) : (
// Kind 4 (NIP-04) and Kind 14 (NIP-17 text): Display plain text
<p className="text-sm whitespace-pre-wrap break-words">
{message.decryptedContent}
</p>
)}
<div className="flex items-center gap-2 mt-1">
<TooltipProvider>
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<span className={cn(
"text-xs opacity-70 cursor-default",
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
)}>
{formatConversationTime(message.created_at)}
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{formatFullDateTime(message.created_at)}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<TooltipProvider>
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<span className={cn(
"flex-shrink-0 opacity-50",
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
)}>
{message.kind === 4 ? (
<Key className="h-3 w-3" />
) : (
<ShieldCheck className="h-3 w-3" />
)}
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{message.kind === 4 && "NIP-04 Kind 4 (Legacy DM)"}
{message.kind === 14 && "NIP-17 Kind 14 (Private Message)"}
{message.kind === 15 && "NIP-17 Kind 15 (Media)"}
{message.kind !== 4 && message.kind !== 14 && message.kind !== 15 && `Kind ${message.kind}`}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
{isNIP4Message && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex-shrink-0">
<AlertTriangle className="h-3 w-3 text-yellow-600 dark:text-yellow-500" />
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">Uses outdated NIP-04 encryption</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{message.isSending && (
<Loader2 className="h-3 w-3 animate-spin opacity-70" />
)}
</div>
</div>
</div>
);
});
MessageBubble.displayName = 'MessageBubble';
const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => {
const author = useAuthor(pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name || genUserName(pubkey);
const avatarUrl = metadata?.picture;
const initials = displayName.slice(0, 2).toUpperCase();
return (
<div className="p-4 border-b flex items-center gap-3">
{onBack && (
<Button
variant="ghost"
size="icon"
onClick={onBack}
className="md:hidden"
>
<ArrowLeft className="h-5 w-5" />
</Button>
)}
<Avatar className="h-10 w-10">
<AvatarImage src={avatarUrl} alt={displayName} />
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<h2 className="font-semibold truncate">{displayName}</h2>
{metadata?.nip05 && (
<p className="text-xs text-muted-foreground truncate">{metadata.nip05}</p>
)}
</div>
</div>
);
};
const EmptyState = ({ isLoading }: { isLoading: boolean }) => {
return (
<div className="h-full flex items-center justify-center p-8">
<div className="text-center text-muted-foreground max-w-sm">
{isLoading ? (
<>
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
<p className="text-sm">Loading conversations...</p>
<p className="text-xs mt-2">
Fetching encrypted messages from relays
</p>
</>
) : (
<>
<p className="text-sm">Select a conversation to start messaging</p>
<p className="text-xs mt-2">
Your messages are encrypted and stored locally
</p>
</>
)}
</div>
</div>
);
};
export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => {
const { user } = useCurrentUser();
const { sendMessage, protocolMode, isLoading } = useDMContext();
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey || '');
const [messageText, setMessageText] = useState('');
const [isSending, setIsSending] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
// Determine default protocol based on mode
const getDefaultProtocol = () => {
if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04;
if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17;
if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17;
// Fallback to NIP-17 for any unexpected mode
return MESSAGE_PROTOCOL.NIP17;
};
const [selectedProtocol, setSelectedProtocol] = useState<MessageProtocol>(getDefaultProtocol());
const scrollAreaRef = useRef<HTMLDivElement>(null);
// Determine if selection is allowed
const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17;
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
if (scrollAreaRef.current) {
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
if (scrollContainer) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
}
}, [messages.length]);
const handleSend = useCallback(async () => {
if (!messageText.trim() || !pubkey || !user) return;
setIsSending(true);
try {
await sendMessage({
recipientPubkey: pubkey,
content: messageText.trim(),
protocol: selectedProtocol,
});
setMessageText('');
} catch (error) {
console.error('Failed to send message:', error);
} finally {
setIsSending(false);
}
}, [messageText, pubkey, user, sendMessage, selectedProtocol]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
const handleLoadMore = useCallback(async () => {
if (!scrollAreaRef.current || isLoadingMore) return;
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
if (!scrollContainer) return;
// Store current scroll position and height
const previousScrollHeight = scrollContainer.scrollHeight;
const previousScrollTop = scrollContainer.scrollTop;
setIsLoadingMore(true);
// Load more messages
loadEarlierMessages();
// Wait for DOM to update, then restore relative scroll position
setTimeout(() => {
if (scrollContainer) {
const newScrollHeight = scrollContainer.scrollHeight;
const heightDifference = newScrollHeight - previousScrollHeight;
scrollContainer.scrollTop = previousScrollTop + heightDifference;
}
setIsLoadingMore(false);
}, 0);
}, [loadEarlierMessages, isLoadingMore]);
if (!pubkey) {
return (
<Card className={cn("h-full", className)}>
<EmptyState isLoading={isLoading} />
</Card>
);
}
if (!user) {
return (
<Card className={cn("h-full flex items-center justify-center", className)}>
<div className="text-center text-muted-foreground">
<p className="text-sm">Please log in to view messages</p>
</div>
</Card>
);
}
return (
<Card className={cn("h-full flex flex-col", className)}>
<ChatHeader pubkey={pubkey} onBack={onBack} />
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4">
{messages.length === 0 ? (
<div className="h-full flex items-center justify-center">
<div className="text-center text-muted-foreground">
<p className="text-sm">No messages yet</p>
<p className="text-xs mt-1">Send a message to start the conversation</p>
</div>
</div>
) : (
<div>
{hasMoreMessages && (
<div className="flex justify-center mb-4">
<Button
variant="outline"
size="sm"
onClick={handleLoadMore}
disabled={isLoadingMore}
className="text-xs"
>
{isLoadingMore ? (
<>
<Loader2 className="h-3 w-3 animate-spin mr-2" />
Loading...
</>
) : (
'Load Earlier Messages'
)}
</Button>
</div>
)}
{messages.map((message) => (
<MessageBubble
key={message.id}
message={message}
isFromCurrentUser={message.pubkey === user.pubkey}
/>
))}
</div>
)}
</ScrollArea>
<div className="p-4 border-t">
<div className="flex gap-2">
<Textarea
value={messageText}
onChange={(e) => setMessageText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
className="min-h-[80px] resize-none"
disabled={isSending}
/>
<div className="flex flex-col gap-2">
<Button
onClick={handleSend}
disabled={!messageText.trim() || isSending}
size="icon"
className="h-[44px] w-[90px]"
>
{isSending ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Send className="h-5 w-5" />
)}
</Button>
<Select
value={selectedProtocol}
onValueChange={(value) => setSelectedProtocol(value as MessageProtocol)}
disabled={!allowSelection}
>
<SelectTrigger className="h-[32px] w-[90px] text-xs px-2">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={MESSAGE_PROTOCOL.NIP17} className="text-xs">
NIP-17
</SelectItem>
<SelectItem value={MESSAGE_PROTOCOL.NIP04} className="text-xs">
NIP-04
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</Card>
);
};
-266
View File
@@ -1,266 +0,0 @@
import { useMemo, useState, memo } from 'react';
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { LOADING_PHASES } from '@/lib/dmConstants';
interface DMConversationListProps {
selectedPubkey: string | null;
onSelectConversation: (pubkey: string) => void;
className?: string;
onStatusClick?: () => void;
}
interface ConversationItemProps {
pubkey: string;
isSelected: boolean;
onClick: () => void;
lastMessage: { decryptedContent?: string; error?: string } | null;
lastActivity: number;
hasNIP4Messages: boolean;
}
const ConversationItemComponent = ({
pubkey,
isSelected,
onClick,
lastMessage,
lastActivity,
hasNIP4Messages
}: ConversationItemProps) => {
const author = useAuthor(pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name || genUserName(pubkey);
const avatarUrl = metadata?.picture;
const initials = displayName.slice(0, 2).toUpperCase();
const lastMessagePreview = lastMessage?.error
? '🔒 Encrypted message'
: lastMessage?.decryptedContent || 'No messages yet';
// Show skeleton only for name/avatar while loading (we already have message data)
const isLoadingProfile = author.isLoading && !metadata;
return (
<button
onClick={onClick}
className={cn(
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent block overflow-hidden",
isSelected && "bg-accent"
)}
>
<div className="flex items-start gap-3 max-w-full">
{isLoadingProfile ? (
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
) : (
<Avatar className="h-10 w-10 flex-shrink-0">
<AvatarImage src={avatarUrl} alt={displayName} />
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2 mb-1">
<div className="flex items-center gap-1.5 min-w-0 flex-1">
{isLoadingProfile ? (
<Skeleton className="h-[1.25rem] w-24" />
) : (
<span className="font-medium text-sm truncate">{displayName}</span>
)}
{hasNIP4Messages && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex-shrink-0">
<AlertTriangle className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-500" />
</div>
</TooltipTrigger>
<TooltipContent side="left">
<p className="text-xs max-w-[200px]">Some messages use outdated NIP-04 encryption</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0 cursor-default">
{formatConversationTime(lastActivity)}
</span>
</TooltipTrigger>
<TooltipContent side="left">
<p className="text-xs">{formatFullDateTime(lastActivity)}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<p className="text-sm text-muted-foreground truncate">
{lastMessagePreview}
</p>
</div>
</div>
</button>
);
};
const ConversationItem = memo(ConversationItemComponent);
ConversationItem.displayName = 'ConversationItem';
const ConversationListSkeleton = () => {
return (
<div className="space-y-2 p-4">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-start gap-3 p-3">
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
<div className="flex-1 space-y-2">
<div className="flex justify-between">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-12" />
</div>
<Skeleton className="h-3 w-full" />
</div>
</div>
))}
</div>
);
};
export const DMConversationList = ({
selectedPubkey,
onSelectConversation,
className,
onStatusClick
}: DMConversationListProps) => {
const { conversations, isLoading, loadingPhase } = useDMContext();
const [activeTab, setActiveTab] = useState<'known' | 'requests'>('known');
// Filter conversations by type
const { knownConversations, requestConversations } = useMemo(() => {
return {
knownConversations: conversations.filter(c => c.isKnown),
requestConversations: conversations.filter(c => c.isRequest),
};
}, [conversations]);
// Get the current list based on active tab
const currentConversations = activeTab === 'known' ? knownConversations : requestConversations;
// Show skeleton during initial load (cache + relays) if we have no conversations yet
const isInitialLoad = (loadingPhase === LOADING_PHASES.CACHE || loadingPhase === LOADING_PHASES.RELAYS) && conversations.length === 0;
return (
<Card className={cn("h-full flex flex-col overflow-hidden", className)}>
{/* Header - always visible */}
<div className="p-4 border-b flex-shrink-0 flex items-center justify-between">
<div className="flex items-center gap-2">
<h2 className="font-semibold text-lg">Messages</h2>
{(loadingPhase === LOADING_PHASES.CACHE ||
loadingPhase === LOADING_PHASES.RELAYS ||
loadingPhase === LOADING_PHASES.SUBSCRIPTIONS) && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
{loadingPhase === LOADING_PHASES.CACHE && 'Loading from cache...'}
{loadingPhase === LOADING_PHASES.RELAYS && 'Querying relays for new messages...'}
{loadingPhase === LOADING_PHASES.SUBSCRIPTIONS && 'Setting up subscriptions...'}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
{onStatusClick && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={onStatusClick}
aria-label="View messaging status"
>
<Info className="h-4 w-4" />
</Button>
)}
</div>
{/* Tab buttons - always visible */}
<div className="px-2 pt-2 flex-shrink-0">
<div className="grid grid-cols-2 gap-1 bg-muted p-1 rounded-lg">
<button
onClick={() => setActiveTab('known')}
className={cn(
"text-xs py-2 px-3 rounded-md transition-colors",
activeTab === 'known'
? "bg-background shadow-sm font-medium"
: "text-muted-foreground hover:text-foreground"
)}
>
Active {knownConversations.length > 0 && `(${knownConversations.length})`}
</button>
<button
onClick={() => setActiveTab('requests')}
className={cn(
"text-xs py-2 px-3 rounded-md transition-colors",
activeTab === 'requests'
? "bg-background shadow-sm font-medium"
: "text-muted-foreground hover:text-foreground"
)}
>
Requests {requestConversations.length > 0 && `(${requestConversations.length})`}
</button>
</div>
</div>
{/* Content area - show skeleton during initial load, otherwise show conversations */}
<div className="flex-1 min-h-0 mt-2 overflow-hidden">
{(isLoading || isInitialLoad) ? (
<ConversationListSkeleton />
) : conversations.length === 0 ? (
<div className="flex items-center justify-center h-full text-center text-muted-foreground px-4">
<div>
<p className="text-sm">No conversations yet</p>
<p className="text-xs mt-1">Start a new conversation to get started</p>
</div>
</div>
) : currentConversations.length === 0 ? (
<div className="flex items-center justify-center h-32 text-center text-muted-foreground px-4">
<p className="text-sm">No {activeTab} conversations</p>
</div>
) : (
<ScrollArea className="h-full block">
<div className="block w-full px-2 py-2 space-y-1">
{currentConversations.map((conversation) => (
<ConversationItem
key={conversation.pubkey}
pubkey={conversation.pubkey}
isSelected={selectedPubkey === conversation.pubkey}
onClick={() => onSelectConversation(conversation.pubkey)}
lastMessage={conversation.lastMessage}
lastActivity={conversation.lastActivity}
hasNIP4Messages={conversation.hasNIP4Messages}
/>
))}
</div>
</ScrollArea>
)}
</div>
</Card>
);
};
@@ -1,84 +0,0 @@
import { useState, useCallback } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea';
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
import { useDMContext } from '@/hooks/useDMContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
interface DMMessagingInterfaceProps {
className?: string;
}
export const DMMessagingInterface = ({ className }: DMMessagingInterfaceProps) => {
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
const [statusModalOpen, setStatusModalOpen] = useState(false);
const isMobile = useIsMobile();
const { clearCacheAndRefetch } = useDMContext();
// On mobile, show only one panel at a time
const showConversationList = !isMobile || !selectedPubkey;
const showChatArea = !isMobile || selectedPubkey;
const handleSelectConversation = useCallback((pubkey: string) => {
setSelectedPubkey(pubkey);
}, []);
const handleBack = useCallback(() => {
setSelectedPubkey(null);
}, []);
return (
<>
{/* Status Modal */}
<Dialog open={statusModalOpen} onOpenChange={setStatusModalOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Messaging Status</DialogTitle>
<DialogDescription>
View loading status, cache info, and connection details
</DialogDescription>
</DialogHeader>
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
</DialogContent>
</Dialog>
<div className={cn("flex gap-4 overflow-hidden", className)}>
{/* Conversation List - Left Sidebar */}
<div className={cn(
"md:w-80 md:flex-shrink-0",
isMobile && !showConversationList && "hidden",
isMobile && showConversationList && "w-full"
)}>
<DMConversationList
selectedPubkey={selectedPubkey}
onSelectConversation={handleSelectConversation}
className="h-full"
onStatusClick={() => setStatusModalOpen(true)}
/>
</div>
{/* Chat Area - Right Panel */}
<div className={cn(
"flex-1 md:min-w-0",
isMobile && !showChatArea && "hidden",
isMobile && showChatArea && "w-full"
)}>
<DMChatArea
pubkey={selectedPubkey}
onBack={isMobile ? handleBack : undefined}
className="h-full"
/>
</div>
</div>
</>
);
};
-214
View File
@@ -1,214 +0,0 @@
import { useState } from 'react';
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
import { useDMContext } from '@/hooks/useDMContext';
import { LOADING_PHASES } from '@/lib/dmConstants';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/useToast';
interface DMStatusInfoProps {
clearCacheAndRefetch?: () => Promise<void>;
}
export const DMStatusInfo = ({ clearCacheAndRefetch }: DMStatusInfoProps) => {
const [isClearing, setIsClearing] = useState(false);
const { toast } = useToast();
const {
loadingPhase,
subscriptions,
scanProgress,
isDoingInitialLoad,
lastSync,
conversations,
} = useDMContext();
const handleClearCache = async () => {
if (!clearCacheAndRefetch) return;
setIsClearing(true);
try {
await clearCacheAndRefetch();
toast({
title: 'Cache cleared',
description: 'Refetching messages from relays...',
});
setIsClearing(false);
} catch (error) {
console.error('Error clearing cache:', error);
toast({
title: 'Error',
description: 'Failed to clear cache. Please try again.',
variant: 'destructive',
});
setIsClearing(false);
}
};
const getLoadingPhaseInfo = () => {
switch (loadingPhase) {
case LOADING_PHASES.IDLE:
return { label: 'Idle', description: 'Not yet initialized', icon: Loader2, color: 'text-muted-foreground' };
case LOADING_PHASES.CACHE:
return { label: 'Loading from cache', description: 'Reading cached messages...', icon: Database, color: 'text-blue-500' };
case LOADING_PHASES.RELAYS:
return { label: 'Loading from relays', description: 'Fetching messages from Nostr relays...', icon: Wifi, color: 'text-yellow-500' };
case LOADING_PHASES.SUBSCRIPTIONS:
return { label: 'Connecting subscriptions', description: 'Setting up real-time message sync...', icon: RefreshCw, color: 'text-orange-500' };
case LOADING_PHASES.READY:
return { label: 'Ready', description: 'All systems operational', icon: CheckCircle2, color: 'text-green-500' };
default:
return { label: 'Unknown', description: 'Status unknown', icon: Loader2, color: 'text-muted-foreground' };
}
};
const phaseInfo = getLoadingPhaseInfo();
const PhaseIcon = phaseInfo.icon;
const formatTimestamp = (timestamp: number | null) => {
if (!timestamp) return 'Never';
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
return date.toLocaleDateString();
};
return (
<div className="space-y-4">
{/* Loading Phase */}
<Card>
<CardContent className="pt-6">
<div className="flex items-start gap-3">
<PhaseIcon className={`h-5 w-5 ${phaseInfo.color} ${loadingPhase !== LOADING_PHASES.READY ? 'animate-pulse' : ''}`} />
<div className="flex-1 space-y-1">
<div className="flex items-center gap-2">
<p className="font-medium">{phaseInfo.label}</p>
{isDoingInitialLoad && (
<Badge variant="secondary" className="text-xs">
Initial Load
</Badge>
)}
</div>
<p className="text-sm text-muted-foreground">{phaseInfo.description}</p>
</div>
</div>
</CardContent>
</Card>
{/* Scan Progress */}
{(scanProgress.nip4 !== null || scanProgress.nip17 !== null) && (
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Scanning Messages</p>
{scanProgress.nip4 !== null && (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">NIP-4 (Legacy)</span>
<span className="text-muted-foreground">{scanProgress.nip4.current} events</span>
</div>
<p className="text-xs text-muted-foreground">{scanProgress.nip4.status}</p>
</div>
)}
{scanProgress.nip17 !== null && (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">NIP-17 (Private)</span>
<span className="text-muted-foreground">{scanProgress.nip17.current} events</span>
</div>
<p className="text-xs text-muted-foreground">{scanProgress.nip17.status}</p>
</div>
)}
</div>
</CardContent>
</Card>
)}
{/* Subscriptions */}
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Real-time Subscriptions</p>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">NIP-4 (Legacy DMs)</span>
<Badge variant={subscriptions.isNIP4Connected ? 'default' : 'secondary'}>
{subscriptions.isNIP4Connected ? 'Connected' : 'Disconnected'}
</Badge>
</div>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">NIP-17 (Private DMs)</span>
<Badge variant={subscriptions.isNIP17Connected ? 'default' : 'secondary'}>
{subscriptions.isNIP17Connected ? 'Connected' : 'Disconnected'}
</Badge>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Cache Info */}
<Card>
<CardContent className="pt-6">
<div className="space-y-3">
<p className="text-sm font-medium">Cache Information</p>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Conversations</span>
<span className="font-medium">{conversations.length}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Last NIP-4 sync</span>
<span className="font-medium">{formatTimestamp(lastSync.nip4)}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Last NIP-17 sync</span>
<span className="font-medium">{formatTimestamp(lastSync.nip17)}</span>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Actions */}
{clearCacheAndRefetch && (
<>
<Separator />
<div className="space-y-3">
<div className="space-y-1">
<p className="text-sm font-medium">Cache Management</p>
<p className="text-xs text-muted-foreground">
Clear all cached messages and refetch from relays. This will force a fresh sync.
</p>
</div>
<Button
onClick={handleClearCache}
disabled={isClearing}
variant="outline"
className="w-full"
>
{isClearing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Clearing...
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
Clear Cache & Refetch
</>
)}
</Button>
</div>
</>
)}
</div>
);
};
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="size-5" />
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
+20
View File
@@ -0,0 +1,20 @@
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
interface LoadingScreenProps {
isLoading: boolean;
}
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
if (!isLoading) return null;
return (
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
<Card className="border-0 shadow-lg bg-background">
<CardContent className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin mr-3" />
</CardContent>
</Card>
</div>
);
}
+145
View File
@@ -0,0 +1,145 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, Copy, Check, QrCode, Zap, Clock } from 'lucide-react';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useEffect, useState } from 'react';
interface QRModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
description: string;
qrCodeUrl: string;
content: string;
icon?: 'qr' | 'zap';
expiryTimestamp?: number;
onExpiry?: () => void;
}
export function QRModal({
isOpen,
onClose,
title,
description,
qrCodeUrl,
content,
icon = 'qr',
expiryTimestamp,
onExpiry,
}: QRModalProps) {
const { copy, copied } = useCopyToClipboard();
const [timeRemaining, setTimeRemaining] = useState<number | null>(null);
const handleCopy = () => {
copy(content);
};
// Countdown timer effect
useEffect(() => {
if (!isOpen || !expiryTimestamp) return;
const updateTimer = () => {
const now = Math.floor(Date.now() / 1000); // Current time in seconds
const remaining = expiryTimestamp - now;
if (remaining <= 0) {
setTimeRemaining(0);
// Call expiry callback
if (onExpiry) {
onExpiry();
}
onClose();
} else {
setTimeRemaining(remaining);
}
};
// Update immediately
updateTimer();
// Then update every second
const interval = setInterval(updateTimer, 1000);
return () => clearInterval(interval);
}, [isOpen, expiryTimestamp, onExpiry, onClose]);
// Format time remaining as MM:SS
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
if (!isOpen) return null;
const IconComponent = icon === 'zap' ? Zap : QrCode;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<IconComponent className="h-5 w-5 mr-2" />
{title}
</CardTitle>
<CardDescription>
{description}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{expiryTimestamp && timeRemaining !== null && timeRemaining <= 3600 && (
<div className="flex items-center justify-center gap-2 text-sm">
<Clock className="h-4 w-4" />
<span className={timeRemaining < 60 ? "text-destructive font-semibold" : "text-muted-foreground"}>
Expires in {formatTime(timeRemaining)}
</span>
</div>
)}
<div className="flex justify-center">
<div className="bg-white p-4 rounded-lg border shadow-sm">
<img
src={qrCodeUrl}
alt={`${title} QR Code`}
className="w-64 h-64 object-contain"
/>
</div>
</div>
<div className="text-center">
<div
className="bg-muted p-3 rounded-lg border font-mono text-sm cursor-pointer hover:bg-muted/80 transition-colors relative group"
onClick={handleCopy}
title="Click to copy full content"
>
{content.length > 33
? `${content.substring(0, 15)}...${content.substring(content.length - 15)}`
: content}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
+1
View File
@@ -47,6 +47,7 @@ const Toast = React.forwardRef<
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
duration={5000}
{...props}
/>
)
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useMintManager } from '@/hooks/cashu/useMintManager';
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
import { QRModal } from '@/components/ui/qr-modal';
import { WalletHeader } from './WalletHeader';
import { TransactionCard } from './PaymentCard';
import { WalletModals } from './MintModals';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
export function CashuWallet() {
// ============================================================================
// CORE HOOKS
// ============================================================================
const {
coco,
repositories,
isInitialized,
isLoading,
error,
balances,
mints,
getEncodedToken,
clearError,
refreshMints,
} = useCashu();
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
const {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
getAllQuotes,
refreshQuotes,
syncQuotesWithWallet,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
// Wrapper to handle return type mismatch
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
return setNpubCashMint(mintUrl);
};
// ============================================================================
// DOMAIN HOOKS
// ============================================================================
const {
activeMintUrl,
setActiveMintUrl,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
} = useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint: handleSetNpubCashMint,
refreshMints,
toast,
});
// Wrapper for setActiveMintUrl to handle the async nature
const handleSetActiveMintSync = (url: string | null) => {
setActiveMintUrl(url);
};
const {
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
sentToken,
setSentToken,
sentTokenQRCode,
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
handleReceive,
handleSend,
mintQuoteUnsubscribeRef,
} = useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
});
const {
historyEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
} = useHistoryManager({
coco,
isInitialized,
});
// ============================================================================
// UI STATE
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningQR, setShowLightningQR] = useState(false);
const [lightningQRCode, setLightningQRCode] = useState<string>('');
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
// Ref to track if we've fetched npub.cash user info
const hasCheckedNpubCashRef = useRef(false);
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// EFFECTS - Error Handling
// ============================================================================
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "Npub.cash Error",
description: npubCashError,
});
clearNpubCashError();
}
}, [npubCashError, clearNpubCashError, toast]);
// ============================================================================
// EFFECTS - NPub.cash Integration
// ============================================================================
useEffect(() => {
if (!isNpubCashLoggedIn) {
hasCheckedNpubCashRef.current = false;
setNpubCashUserInfo(null);
return;
}
if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return;
const fetchUserInfo = async () => {
hasCheckedNpubCashRef.current = true;
const userInfo = await getNpubCashUserInfo();
if (!userInfo) return;
setNpubCashUserInfo(userInfo);
// Sync mint from npub.cash if different from active mint
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
const mintExists = mints.some(m => m.url === userInfo.mint_url);
if (!mintExists && coco) {
try {
await coco.mint.addMint(userInfo.mint_url);
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
} catch {
// Silent failure - user can manually add mint if needed
}
} else if (mintExists) {
setActiveMintUrl(userInfo.mint_url, false);
}
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
// Set up automatic quote sync subscription when logged into npub.cash
useEffect(() => {
if (!isNpubCashLoggedIn || !coco || !isInitialized) return;
let unsubscribe: (() => void) | null = null;
const setupSync = async () => {
unsubscribe = await syncQuotesWithWallet(coco, toast);
};
setupSync();
return () => {
if (unsubscribe) {
unsubscribe();
}
};
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================
// RENDER
// ============================================================================
return (
<>
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
{/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */}
<WalletHeader
totalBalance={totalBalance}
balances={balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
userPubkey={user?.pubkey}
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
onCopyToClipboard={copyToClipboard}
onShowLightningAddressQR={(qr) => {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
}}
generateQRCode={generateQRCode}
// MintSelector props
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMintSync}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={mintDropdownOpen}
setDropdownOpen={setMintDropdownOpen}
/>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-20 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex justify-center border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
</button>
</div>
</div>
{/* Modals */}
<>
<WalletModals
showProofBreakdown={showProofBreakdown}
setShowProofBreakdown={setShowProofBreakdown}
proofBreakdown={proofBreakdown}
showRemoveMintModal={showRemoveMintModal}
setShowRemoveMintModal={setShowRemoveMintModal}
mintToRemove={mintToRemove}
onConfirmRemoveMint={handleConfirmRemoveMint}
isLoading={isLoading || isNpubCashLoading}
showLightningQR={showLightningQR}
setShowLightningQR={setShowLightningQR}
lightningQRCode={lightningQRCode}
showLightningAddressQR={showLightningAddressQR}
setShowLightningAddressQR={setShowLightningAddressQR}
lightningAddressQRCode={lightningAddressQRCode}
userPubkey={user?.pubkey}
npubCashUserInfo={npubCashUserInfo}
currentInvoice={currentInvoice}
showInvoiceModal={showInvoiceModal}
setShowInvoiceModal={setShowInvoiceModal}
mintQuoteUnsubscribeRef={mintQuoteUnsubscribeRef}
sentToken={sentToken}
setSentToken={setSentToken}
sentTokenQRCode={sentTokenQRCode}
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={setShowSendModal}>
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
</DrawerHeader>
<div className="px-4 pb-4">
<TransactionCard
mode={mode}
operation="send"
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={activeMintUrl}
onSend={() => {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
}
}}
onReceive={() => {}}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading || isNpubCashLoading}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={setShowReceiveModal}>
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
</DrawerHeader>
<div className="px-4 pb-4">
<TransactionCard
mode={mode}
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onSend={() => {}}
onReceive={() => {
handleReceive();
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isLoading || isNpubCashLoading}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[90vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
</DrawerHeader>
<ScrollArea className="h-[90vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</div>
</>
);
}
+274
View File
@@ -0,0 +1,274 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { X, Coins, AlertTriangle, RefreshCw } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface MintToRemove {
url: string;
name?: string;
}
interface WalletModalProps {
// Proof Breakdown Modal
showProofBreakdown: boolean;
setShowProofBreakdown: (show: boolean) => void;
proofBreakdown: ProofBreakdown | null;
// Remove Mint Modal
showRemoveMintModal: boolean;
setShowRemoveMintModal: (show: boolean) => void;
mintToRemove: MintToRemove | null;
onConfirmRemoveMint: () => void;
isLoading: boolean;
// QR Modals
showLightningQR: boolean;
setShowLightningQR: (show: boolean) => void;
lightningQRCode: string;
showLightningAddressQR: boolean;
setShowLightningAddressQR: (show: boolean) => void;
lightningAddressQRCode: string;
userPubkey?: string;
npubCashUserInfo?: { name?: string } | null;
// Invoice Modal
currentInvoice?: {
amount: number;
qrCodeUrl: string;
invoice: string;
expiry: number;
} | null;
showInvoiceModal: boolean;
setShowInvoiceModal: (show: boolean) => void;
mintQuoteUnsubscribeRef: React.MutableRefObject<(() => void) | null>;
// Sent Token Modal
sentToken: string | null;
setSentToken: (token: string | null) => void;
sentTokenQRCode: string;
}
export function WalletModals({
showProofBreakdown,
setShowProofBreakdown,
proofBreakdown,
showRemoveMintModal,
setShowRemoveMintModal,
mintToRemove,
onConfirmRemoveMint,
isLoading,
showLightningQR,
setShowLightningQR,
lightningQRCode,
showLightningAddressQR,
setShowLightningAddressQR,
lightningAddressQRCode,
userPubkey,
npubCashUserInfo,
currentInvoice,
showInvoiceModal,
setShowInvoiceModal,
mintQuoteUnsubscribeRef,
sentToken,
setSentToken,
sentTokenQRCode,
}: WalletModalProps) {
const { toast } = useToast();
return (
<>
{/* Proof Breakdown Modal */}
{showProofBreakdown && proofBreakdown && (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={() => setShowProofBreakdown(false)}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={() => setShowProofBreakdown(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(proofBreakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{proofBreakdown.totalBalance.toLocaleString()} sats
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(proofBreakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
)}
{/* Remove Mint Modal */}
{showRemoveMintModal && mintToRemove && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={() => setShowRemoveMintModal(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Are you sure you want to remove this mint from your wallet?
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => setShowRemoveMintModal(false)}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirmRemoveMint}
disabled={isLoading}
>
{isLoading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* QR Modals */}
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={''}
icon="qr"
/>
<QRModal
isOpen={showLightningAddressQR}
onClose={() => setShowLightningAddressQR(false)}
title="Lightning Address"
description="Scan this QR code to send payments to your Lightning address"
qrCodeUrl={lightningAddressQRCode}
content={userPubkey ? `${npubCashUserInfo?.name || nip19.npubEncode(userPubkey)}@npubx.cash` : ''}
icon="zap"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
{/* Sent Token Modal */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
</>
);
}
+190
View File
@@ -0,0 +1,190 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, X, Check, ChevronDown, Wallet } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
interface CashuMint {
url: string;
name?: string;
}
interface MintSelectorProps {
balances: { [key: string]: number };
showSats: boolean;
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function MintSelector({
balances,
showSats,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: MintSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const activeMint = mints.find(mint => mint.url === activeMintUrl);
const activeBalance = activeMint ? balances[activeMint.url] || 0 : 0;
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0">
<div className="flex items-center justify-between w-full min-w-0">
{activeMint ? (
<>
<div className="flex items-center gap-2 min-w-0 flex-1">
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">{getCleanMintLabel(activeMint)}</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(activeBalance)}
</span>
</>
) : (
<span className="text-muted-foreground truncate min-w-0 flex-1">Select a mint</span>
)}
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
{mints.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem asChild>
<div className="flex gap-2 p-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="flex-1"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Escape') {
setDropdownOpen(false);
} else if (e.key === 'Enter') {
e.preventDefault();
if (mintUrl.trim()) {
onAddMint();
}
}
}}
onKeyUp={(e) => e.stopPropagation()}
/>
<Button
onClick={(e) => {
e.stopPropagation();
onAddMint();
}}
disabled={!mintUrl.trim()}
size="sm"
>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{activeMint && (
<div className="flex flex-col gap-1">
<button
onClick={() => onShowDenominations(activeMint.url)}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="View token breakdown"
>
<Wallet className="h-4 w-4" />
</button>
</div>
)}
</div>
);
}
+256
View File
@@ -0,0 +1,256 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Send, Download, Zap, Loader2, X } from 'lucide-react';
interface TransactionCardProps {
mode: 'tokens' | 'lightning';
operation: 'send' | 'receive';
// Send props
sendAmount: string;
setSendAmount: (value: string) => void;
lightningInvoice: string;
setLightningInvoice: (value: string) => void;
lightningAddressInput: string;
setLightningAddressInput: (value: string) => void;
lightningAddressAmount: string;
setLightningAddressAmount: (value: string) => void;
pendingLightningAddress: string | null;
setPendingLightningAddress: (value: string | null) => void;
// Receive props
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
// Common props
activeMintUrl: string | null;
onSend: () => void;
onReceive: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
}
export function TransactionCard({
mode,
operation,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onSend,
onReceive,
isResolvingAddress,
isLoading,
}: TransactionCardProps) {
return (
<div className="space-y-8">
{/* Title */}
<div className="text-center">
<p className="text-base text-muted-foreground mt-2">
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: pendingLightningAddress ? (
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending to:</span>{' '}
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
</span>
) : 'Pay invoices or addresses'
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
: 'Deposit funds with Lightning'
)}
</p>
</div>
{/* Content */}
<div className="space-y-4">
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{operation === 'send'
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
: (mode === 'tokens' ? 'Select a mint to receive tokens' : 'Select a mint to create Lightning invoice')
}
</div>
)}
{operation === 'send' ? (
// Send Mode
mode === 'tokens' ? (
// Cashu Token Send
<div className="space-y-3">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-4">
<Button
onClick={onSend}
disabled={!sendAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingLightningAddress ? (
// Lightning Address Amount Input
<div className="space-y-3">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center gap-2 mt-4">
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
{isResolvingAddress ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Zap className="h-5 w-5" />
)}
</Button>
<Button
variant="outline"
size="icon"
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="h-12 w-12 rounded-full"
title="Cancel"
>
<X className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice/Address Input
<div className="space-y-3">
<Input
placeholder="lnbc... or [email protected]"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-4">
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
)
) : (
// Receive Mode
mode === 'tokens' ? (
// Cashu Token Receive
<div className="space-y-3">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-4">
<Button
onClick={onReceive}
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice Receive
<div className="space-y-3">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-4">
<Button
onClick={onReceive}
disabled={!quoteAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
)
)}
</div>
</div>
);
}
@@ -0,0 +1,111 @@
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
interface TransactionHistoryProps {
entries: HistoryEntry[];
isLoading: boolean;
}
export function TransactionHistory({ entries, isLoading }: TransactionHistoryProps) {
// Icon indicating transaction type (Lightning vs Cashu)
const getTransactionTypeIcon = (type: string) => {
switch (type) {
case 'mint':
case 'melt':
return <Zap className="h-4 w-4" />;
case 'send':
case 'receive':
return <Coins className="h-4 w-4" />;
default:
return <History className="h-4 w-4" />;
}
};
// Arrow indicating direction (next to amount)
const getDirectionIcon = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
case 'melt':
case 'send':
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
default:
return null;
}
};
const getHistoryLabel = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return 'Received';
case 'melt':
case 'send':
return 'Sent';
default:
return type;
}
};
return (
<div className="space-y-2">
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading history...</span>
</div>
) : entries.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transactions yet
</div>
) : (
<>
{entries.map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getTransactionTypeIcon(entry.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
{entry.type === 'melt' && (
<div className="text-xs text-muted-foreground mt-1">
+ fees
</div>
)}
</div>
<div className="mt-1">
{getDirectionIcon(entry.type)}
</div>
</div>
</div>
</div>
))}
</>
)}
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
import { useState, useEffect } from 'react';
import { nip19 } from 'nostr-tools';
import { Zap, Coins, Copy, Check, QrCode } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { useToast } from '@/hooks/useToast';
import { LoginIcon } from '@/components/auth/LoginIcon';
import { MintSelector } from './MintSelector';
interface CashuMint {
url: string;
name?: string;
}
interface WalletHeaderProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning';
setMode: (mode: 'tokens' | 'lightning') => void;
userPubkey?: string;
npubCashUsername?: string;
onCopyToClipboard: (text: string) => Promise<void>;
onShowLightningAddressQR: (qrCode: string) => void;
generateQRCode: (text: string) => Promise<string>;
// MintSelector props
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function WalletHeader({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
userPubkey,
npubCashUsername,
onCopyToClipboard,
onShowLightningAddressQR,
generateQRCode,
// MintSelector props
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
const { toast } = useToast();
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const toggleMode = () => {
const newMode = mode === 'tokens' ? 'lightning' : 'tokens';
setMode(newMode);
toast({
title: `${newMode === 'tokens' ? 'Cashu' : 'Lightning'} Enabled!`,
description: newMode === 'tokens'
? 'Send and receive with Cashu eCash'
: 'Send and receive with Lightning',
});
};
return (
<div className="flex flex-col items-center pt-10 space-y-2">
{/* Mode Toggle */}
<div className="absolute top-3 left-3 sm:left-4 z-10">
<button
onClick={toggleMode}
className="px-3 py-2 rounded-lg bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={mode === 'tokens' ? 'Switch to Lightning' : 'Switch to Cashu Tokens'}
>
{mode === 'tokens' ? (
<Coins className="h-6 w-6" />
) : (
<Zap className="h-6 w-6" />
)}
</button>
</div>
{/* Login Icon */}
<div className="absolute top-3 right-3 sm:right-4 z-10">
<LoginIcon />
</div>
{/* Balance Display */}
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-6xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
>
<span className="text-muted-foreground italic">
{showSats ? '₿' : '$'}
</span>
{showSats ? totalBalance.toLocaleString() : (btcUsdRate ? `${(totalBalance / 100000000 * btcUsdRate).toFixed(2)}` : totalBalance.toLocaleString())}
</button>
</div>
{/* Lightning Address and Mint Selector Grid */}
<div className="mt-3 px-4">
<div className="w-full max-w-[400px] mx-auto">
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && (
<div className="flex gap-2 items-center min-w-0">
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
await onCopyToClipboard(lightningAddress);
setLightningAddressCopied(true);
setTimeout(() => setLightningAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Lightning address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{npubCashUsername || ''}
</span>
<span className="flex-shrink-0 text-muted-foreground">
@npubx.cash
</span>
</div>
{lightningAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
const qr = await generateQRCode(lightningAddress);
onShowLightningAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
)}
{/* Mint Selector Row */}
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
</div>
</div>
</div>
</div>
);
}
+5 -10
View File
@@ -2,25 +2,20 @@ import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export interface RelayMetadata {
/** List of relays with read/write permissions */
relays: { url: string; read: boolean; write: boolean }[];
/** Unix timestamp of when the relay list was last updated */
updatedAt: number;
}
export interface AppConfig {
/** Current theme */
theme: Theme;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
/** Selected relay URL */
relayUrl: string;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
+25
View File
@@ -0,0 +1,25 @@
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/cashu/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashu(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashu must be used within a CashuProvider');
}
return context;
}
-138
View File
@@ -1,138 +0,0 @@
import { createContext } from 'react';
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
import { type NostrEvent } from '@nostrify/nostrify';
import type { MessageProtocol } from '@/lib/dmConstants';
// ============================================================================
// DM Types and Constants
// ============================================================================
interface ParticipantData {
messages: DecryptedMessage[];
lastActivity: number;
lastMessage: DecryptedMessage | null;
hasNIP4: boolean;
hasNIP17: boolean;
}
type MessagesState = Map<string, ParticipantData>;
interface LastSyncData {
nip4: number | null;
nip17: number | null;
}
interface SubscriptionStatus {
isNIP4Connected: boolean;
isNIP17Connected: boolean;
}
interface ScanProgress {
current: number;
status: string;
}
interface ScanProgressState {
nip4: ScanProgress | null;
nip17: ScanProgress | null;
}
interface ConversationSummary {
id: string;
pubkey: string;
lastMessage: DecryptedMessage | null;
lastActivity: number;
hasNIP4Messages: boolean;
hasNIP17Messages: boolean;
isKnown: boolean;
isRequest: boolean;
lastMessageFromUser: boolean;
}
interface DecryptedMessage extends NostrEvent {
decryptedContent?: string;
error?: string;
isSending?: boolean;
clientFirstSeen?: number;
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
}
/**
* File attachment for direct messages (NIP-92 compatible).
*
* All fields are required. Use with `useUploadFile` hook to upload files
* and generate the proper tags format.
*
* @example
* ```tsx
* import { useUploadFile } from '@/hooks/useUploadFile';
* import type { FileAttachment } from '@/contexts/DMContext';
*
* const { mutateAsync: uploadFile } = useUploadFile();
*
* const tags = await uploadFile(file);
* const attachment: FileAttachment = {
* url: tags[0][1],
* mimeType: file.type,
* size: file.size,
* name: file.name,
* tags: tags
* };
*
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Check out this file!',
* attachments: [attachment]
* });
* ```
*
* @property url - Blossom server URL where file is hosted
* @property mimeType - MIME type of the file (e.g., 'image/png')
* @property size - File size in bytes
* @property name - Original filename
* @property tags - NIP-94 file metadata tags (includes hashes)
*/
export interface FileAttachment {
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}
/**
* Direct Messaging context interface providing access to all DM functionality.
*
* @property messages - Raw message state (Map of pubkey -> participant data)
* @property isLoading - True during initial load phases
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
* @property lastSync - Unix timestamps of last successful sync for each protocol
* @property subscriptions - Connection status for real-time message subscriptions
* @property conversations - Array of conversation summaries sorted by last activity
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
* @property scanProgress - Progress info for large message history scans
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
*/
export interface DMContextType {
messages: MessagesState;
isLoading: boolean;
loadingPhase: LoadingPhase;
isDoingInitialLoad: boolean;
lastSync: LastSyncData;
subscriptions: SubscriptionStatus;
conversations: ConversationSummary[];
sendMessage: (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => Promise<void>;
protocolMode: ProtocolMode;
scanProgress: ScanProgressState;
clearCacheAndRefetch: () => Promise<void>;
}
export const DMContext = createContext<DMContextType | null>(null);
+251
View File
@@ -0,0 +1,251 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useLocalStorage } from '../useLocalStorage';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
import { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
// Types from coco-cashu-core
type CocoManager = Awaited<ReturnType<typeof initializeCoco>>;
// Singleton pattern to prevent multiple initializations
let globalCocoInstance: CocoManager | null = null;
let globalRepositories: Repositories | null = null;
let globalInitializationPromise: Promise<{ coco: CocoManager; repositories: Repositories }> | null = null;
export interface UseCashuReturn {
// The typed coco manager (direct library access)
coco: CocoManager | null;
// Repositories for direct access to proof data
repositories: Repositories | null;
// React state (for reactivity)
balances: { [mintUrl: string]: number };
mints: Array<{ url: string; name?: string; info?: unknown }>;
totalBalance: number;
// Status
isInitialized: boolean;
isLoading: boolean;
error: Error | null;
// Mnemonic management
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
// Utility functions
clearError: () => void;
getEncodedToken: typeof getEncodedToken;
refreshMints: () => Promise<void>;
}
export function useCashu(): UseCashuReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance ref
const cocoRef = useRef<CocoManager | null>(null);
const repositoriesRef = useRef<Repositories | null>(null);
// React state for UI reactivity
const [balances, setBalances] = useState<{ [mintUrl: string]: number }>({});
const [mints, setMints] = useState<Array<{ url: string; name?: string; info?: unknown }>>([]);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const refreshMints = useCallback(async () => {
const coco = cocoRef.current;
if (!coco) return;
try {
const mintList = await coco.mint.getAllMints();
setMints(mintList.map((m: any) => ({
url: m.mintUrl,
name: m.name,
info: m.mintInfo
})));
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new Error('Invalid mnemonic');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the coco manager
const initializeCocoManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
// Use singleton pattern to prevent multiple initializations
if (globalCocoInstance && globalRepositories) {
console.log('Using existing coco instance (singleton)');
cocoRef.current = globalCocoInstance;
repositoriesRef.current = globalRepositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// If there's already an initialization in progress, wait for it
if (globalInitializationPromise) {
console.log('Waiting for existing initialization...');
const { coco, repositories } = await globalInitializationPromise;
cocoRef.current = coco;
repositoriesRef.current = repositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// Generate or retrieve mnemonic
let currentMnemonic = mnemonic;
if (!currentMnemonic) {
currentMnemonic = bip39.generateMnemonic(wordlist);
setMnemonicState(currentMnemonic);
}
// Create seed from mnemonic
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories with proper initialization
const repo = new IndexedDbRepositories({ name: "cashu-wallet" });
await repo.init(); // Ensure repository is properly initialized
// Create initialization promise
globalInitializationPromise = (async () => {
const coco = await initializeCoco({
repo,
seedGetter: async () => seed,
logger: new ConsoleLogger("coco", { level: "debug" }) // Use debug level for better logging
});
return { coco, repositories: repo };
})();
// Initialize coco manager using the new API
const { coco, repositories } = await globalInitializationPromise;
// Store as singleton
console.log('Storing new coco instance as singleton');
globalCocoInstance = coco;
globalRepositories = repositories;
globalInitializationPromise = null;
cocoRef.current = coco;
repositoriesRef.current = repositories;
// Enable built-in services for automatic quote processing and state watching
try {
console.log('Enabling coco services...');
await coco.enableMintQuoteWatcher({ watchExistingPendingOnStart: false });
console.log('Mint quote watcher enabled');
await coco.enableMintQuoteProcessor();
console.log('Mint quote processor enabled');
await coco.enableProofStateWatcher();
console.log('Proof state watcher enabled');
console.log('All coco services enabled successfully');
} catch (err) {
// Don't fail initialization if watchers can't be enabled
console.warn('Failed to enable some coco services:', err);
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
setError(new Error(errorMessage));
globalInitializationPromise = null; // Reset on error
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeCocoManager();
}, [initializeCocoManager]);
// Auto-refresh balances and mints on manager events
useEffect(() => {
const coco = cocoRef.current;
if (!coco) return;
const refreshBalances = async () => {
try {
const newBalances = await coco.wallet.getBalances();
setBalances(newBalances);
} catch (err) {
// Silent failure - errors are handled by the manager
}
};
// Initial load
refreshBalances();
refreshMints();
// Listen to events
const unsubs = [
coco.on('proofs:saved', refreshBalances),
coco.on('proofs:state-changed', refreshBalances),
coco.on('send:created', refreshBalances),
coco.on('receive:created', refreshBalances),
coco.on('mint:added', refreshMints),
coco.on('mint:updated', refreshMints),
];
return () => unsubs.forEach(unsub => unsub());
}, [isInitialized, refreshMints]);
// Calculate total balance
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
return {
// The typed coco manager (direct library access)
coco: cocoRef.current,
// Repositories for direct access to proof data
repositories: repositoriesRef.current,
// React state (for reactivity)
balances,
mints,
totalBalance,
// Status
isInitialized,
isLoading,
error,
// Mnemonic management
mnemonic,
setMnemonic,
generateMnemonic,
// Utility functions
clearError,
getEncodedToken,
refreshMints,
};
}
+79
View File
@@ -0,0 +1,79 @@
import { useState, useCallback, useEffect } from 'react';
import type { HistoryEntry } from 'coco-cashu-core';
interface UseHistoryManagerProps {
coco: any; // Coco instance
isInitialized: boolean;
}
export function useHistoryManager({
coco,
isInitialized,
}: UseHistoryManagerProps) {
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
// Load history from wallet
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
const entries = await coco.history.getPaginatedHistory(0, 50); // TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [coco]);
// Load history on wallet initialization
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh on wallet events
useEffect(() => {
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, coco, loadHistory]);
return {
historyEntries,
setHistoryEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
loadHistory,
};
}
+219
View File
@@ -0,0 +1,219 @@
import { useState, useCallback, useEffect } from 'react';
import { getCleanMintLabel } from './walletUtils';
export interface CashuMint {
url: string;
name?: string;
}
interface UseMintManagerProps {
coco: any; // Coco instance
mints: CashuMint[];
repositories: any; // Repositories instance
isNpubCashLoggedIn: boolean;
setNpubCashMint: (mintUrl: string) => Promise<boolean>;
refreshMints: () => Promise<void>;
toast: any; // Toast function
}
export function useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint,
refreshMints,
toast,
}: UseMintManagerProps) {
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
const [mintUrl, setMintUrl] = useState('');
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
// Set active mint and optionally sync to npub.cash
const handleSetActiveMint = useCallback(
async (url: string | null, syncToNpubCash = true) => {
setActiveMintUrl(url);
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && url && syncToNpubCash) {
try {
await setNpubCashMint(url);
} catch (err) {
console.error('Failed to sync mint to npub.cash:', err);
}
}
},
[isNpubCashLoggedIn, setNpubCashMint]
);
// Add a new mint
const handleAddMint = useCallback(async () => {
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (
!normalizedUrl.startsWith('http://') &&
!normalizedUrl.startsWith('https://')
) {
normalizedUrl = `https://${normalizedUrl}`;
}
await coco.mint.addMint(normalizedUrl);
setMintUrl('');
toast({
title: 'Mint Added',
description: 'Mint added successfully!',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Add Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintUrl, coco, toast]);
// Show remove confirmation modal
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
// Confirm and remove mint
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove || !repositories) return;
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(
(mint) => mint.url !== mintToRemove.url
);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: 'Mint Removed',
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: 'destructive',
title: 'Remove Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [
mintToRemove,
mints,
activeMintUrl,
handleSetActiveMint,
repositories,
toast,
refreshMints,
]);
// Show denomination breakdown for a mint
const handleShowDenominations = useCallback(
async (
mintUrl: string,
setShowProofBreakdown: (show: boolean) => void,
setProofBreakdown: (breakdown: {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}) => void
) => {
if (!repositories) return;
try {
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(
mintUrl
);
if (!proofs || proofs.length === 0) {
toast({
variant: 'destructive',
title: 'No Tokens',
description: 'No tokens found for this mint',
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations).reduce(
(sum, [amount, count]) => sum + parseInt(amount) * count,
0
);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance,
});
setShowProofBreakdown(true);
} catch (err) {
toast({
variant: 'destructive',
title: 'Failed to Get Denominations',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
},
[repositories, toast]
);
// Auto-select first mint when mints change
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
// Don't sync to npub.cash on auto-select, only on manual changes
handleSetActiveMint(mints[0].url, false);
}
}, [mints, activeMintUrl, handleSetActiveMint]);
return {
activeMintUrl,
setActiveMintUrl: handleSetActiveMint,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
};
}
+386
View File
@@ -0,0 +1,386 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
interface UseWalletTransactionsProps {
coco: any; // Coco instance
activeMintUrl: string | null;
isNpubCashLoggedIn: boolean;
repositories: any; // Repositories instance
generateQRCode: (text: string) => Promise<string>;
toast: any; // Toast function
getEncodedToken: (token: any) => string;
getLightningInvoice: (params: {
lightningAddress: string;
amountSats: number;
}) => Promise<string>;
}
export function useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
}: UseWalletTransactionsProps) {
// Receive state
const [tokenInput, setTokenInput] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
// Send state
const [sendAmount, setSendAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<
string | null
>(null);
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
// Invoice modal state
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// Generate QR code for sent token
const generateSentTokenQRCode = useCallback(async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
}, [generateQRCode]);
// Handle unknown mint error by adding the mint and retrying
const handleUnknownMintError = useCallback(
async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Add the mint
await coco.mint.addMint(mintUrl);
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: 'destructive',
title: 'Receive Failed',
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
},
[coco, tokenInput, toast]
);
// Handle receive (token or Lightning)
const handleReceive = useCallback(async () => {
if (!coco) return;
// Receive Cashu token mode
if (!tokenInput && !quoteAmount) {
return;
}
if (tokenInput) {
// Receive token mode
try {
console.log(
'Attempting to receive token:',
tokenInput.substring(0, 20) + '...'
);
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: 'Cashu token redeemed successfully!',
});
} catch (err) {
console.error('Token receive error:', err);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: 'destructive',
title: 'Receive Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (quoteAmount && activeMintUrl) {
// Lightning quote mode
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry,
});
setShowInvoiceModal(true);
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
toast({
title: 'Payment Received',
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
toast({
variant: 'destructive',
title: 'Quote Creation Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}, [
coco,
tokenInput,
quoteAmount,
activeMintUrl,
toast,
generateQRCode,
handleUnknownMintError,
]);
// Handle send (token or Lightning)
const handleSend = useCallback(async () => {
if (!coco) return;
if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress) {
return;
}
// Send Cashu token mode
if (sendAmount && activeMintUrl) {
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Send Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (activeMintUrl) {
// Lightning mode
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
invoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Payment Sent',
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
} catch (err) {
console.error('Payment error:', err);
toast({
variant: 'destructive',
title: 'Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice
try {
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
input
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Invoice Paid',
description:
'Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.',
});
setLightningInvoice('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Invoice Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}
}
}, [
coco,
sendAmount,
lightningInvoice,
lightningAddressInput,
lightningAddressAmount,
pendingLightningAddress,
activeMintUrl,
toast,
getEncodedToken,
generateSentTokenQRCode,
getLightningInvoice,
]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
return {
// Receive state
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
// Send state
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
// Transaction output state
sentToken,
setSentToken,
sentTokenQRCode,
// Invoice modal state
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
// Handlers
handleReceive,
handleSend,
// Refs
mintQuoteUnsubscribeRef,
};
}
+23
View File
@@ -0,0 +1,23 @@
export const getCleanMintLabel = (mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host;
} catch {
return mint.url.replace(/^https?:\/\//, '');
}
};
export const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = (err as any)?.message || err?.toString() || '';
return (err as any)?.constructor?.name === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
export const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = (err as any)?.message || err?.toString() || '';
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
-1
View File
@@ -28,7 +28,6 @@ export function useAuthor(pubkey: string | undefined) {
return { event };
}
},
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
retry: 3,
});
}
+1 -1
View File
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
queryFn: async (c) => {
const filter: NostrFilter = { kinds: [1111] };
-87
View File
@@ -1,87 +0,0 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useDMContext } from "@/hooks/useDMContext";
const MESSAGES_PER_PAGE = 25;
/**
* Hook to access paginated messages for a specific conversation.
*
* Returns the most recent messages (default 25) with the ability to load earlier messages.
* Automatically resets to default page size when switching conversations.
*
* @example
* ```tsx
* import { useConversationMessages } from '@/contexts/DMContext';
*
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
* const {
* messages,
* hasMoreMessages,
* loadEarlierMessages,
* totalCount
* } = useConversationMessages(recipientPubkey);
*
* return (
* <div>
* {hasMoreMessages && (
* <button onClick={loadEarlierMessages}>
* Load Earlier ({totalCount - messages.length} more)
* </button>
* )}
* {messages.map(msg => (
* <div key={msg.id}>{msg.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @param conversationId - The pubkey of the conversation participant
* @returns Paginated message data with loading function
*/
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
const result = useMemo(() => {
const conversationData = allMessages.get(conversationId);
if (!conversationData) {
return {
messages: [],
hasMoreMessages: false,
totalCount: 0,
lastMessage: null,
lastActivity: 0,
};
}
const totalMessages = conversationData.messages.length;
const hasMore = totalMessages > visibleCount;
// Return the most recent N messages (slice from the end)
const visibleMessages = conversationData.messages.slice(-visibleCount);
return {
messages: visibleMessages,
hasMoreMessages: hasMore,
totalCount: totalMessages,
lastMessage: conversationData.lastMessage,
lastActivity: conversationData.lastActivity,
};
}, [allMessages, conversationId, visibleCount]);
const loadEarlierMessages = useCallback(() => {
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
}, []);
// Reset visible count when conversation changes
useEffect(() => {
setVisibleCount(MESSAGES_PER_PAGE);
}, [conversationId]);
return {
...result,
loadEarlierMessages,
};
}
+52
View File
@@ -0,0 +1,52 @@
import { useState, useCallback } from 'react';
import { useToast } from './useToast';
interface UseCopyToClipboardReturn {
copy: (text: string) => Promise<void>;
copied: boolean;
copyError: string | null;
}
/**
* Hook for copying text to clipboard with feedback
*
* @example
* ```tsx
* const { copy, copied, copyError } = useCopyToClipboard();
*
* await copy('cashuBo2Ft...');
* // copied will be true for 2 seconds
* ```
*/
export function useCopyToClipboard(): UseCopyToClipboardReturn {
const [copied, setCopied] = useState(false);
const [copyError, setCopyError] = useState<string | null>(null);
const { toast } = useToast();
const copy = useCallback(async (text: string): Promise<void> => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setCopyError(null);
// Auto-reset copied state after 2 seconds
setTimeout(() => setCopied(false), 2000);
} catch (err) {
const errorMessage = 'Failed to copy to clipboard';
console.error(errorMessage, err);
setCopyError(errorMessage);
toast({
variant: "destructive",
title: "Copy Failed",
description: errorMessage,
});
}
}, [toast]);
return {
copy,
copied,
copyError,
};
}
-45
View File
@@ -1,45 +0,0 @@
import { useContext } from "react";
import { DMContext, DMContextType } from "@/contexts/DMContext";
/**
* Hook to access the direct messaging system.
*
* Provides access to conversations, message sending, loading states, and cache management.
* Must be used within a DMProvider.
*
* @example
* ```tsx
* import { useDMContext } from '@/hooks/useDMContext';
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
*
* function MyComponent() {
* const { conversations, sendMessage, isLoading } = useDMContext();
*
* // Send a message
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!',
* protocol: MESSAGE_PROTOCOL.NIP17
* });
*
* // Display conversations
* return (
* <div>
* {isLoading ? 'Loading...' : conversations.map(c => (
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @returns DMContextType - The direct messaging context
* @throws Error if used outside DMProvider
*/
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
throw new Error('useDMContext must be used within DMProvider');
}
return context;
}
+250
View File
@@ -0,0 +1,250 @@
import { useState, useCallback } from 'react';
// LNURL Protocol Types
interface LNURLPayResponse {
status: 'OK' | 'ERROR';
tag: 'payRequest';
commentAllowed?: number;
minSendable: number; // millisats
maxSendable: number; // millisats
metadata: string;
callback: string;
}
interface LNURLInvoiceResponse {
status: 'OK' | 'ERROR';
reason?: string;
pr?: string; // BOLT11 invoice
}
interface GetInvoiceParams {
lightningAddress: string;
amountSats: number;
comment?: string;
}
interface UseLightningAddressReturn {
getInvoice: (params: GetInvoiceParams) => Promise<string>;
isLoading: boolean;
error: string | null;
}
/**
* Hook for resolving Lightning addresses to invoices
*
* @example
* ```tsx
* const { getInvoice, isLoading, error } = useLightningAddress();
*
* const invoice = await getInvoice({
* lightningAddress: '[email protected]',
* amountSats: 1000,
* comment: 'Thanks for the coffee!'
* });
* ```
*/
export function useLightningAddress(): UseLightningAddressReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/**
* Fetches a Lightning invoice for the given address and amount
*
* @param params - Lightning address, amount in sats, and optional comment
* @returns BOLT11 invoice string
* @throws Error if resolution fails
*/
const getInvoice = useCallback(async (params: GetInvoiceParams): Promise<string> => {
const { lightningAddress, amountSats, comment } = params;
setIsLoading(true);
setError(null);
try {
// Validate inputs
if (!lightningAddress || !lightningAddress.includes('@')) {
throw new Error('Invalid Lightning address format. Expected: [email protected]');
}
if (amountSats <= 0) {
throw new Error('Amount must be greater than 0');
}
// Parse Lightning address
const [username, domain] = lightningAddress.split('@');
if (!username || !domain) {
throw new Error('Invalid Lightning address format');
}
// Step 1: Fetch LNURL-pay info
const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`;
console.log('Resolving Lightning address:', {
lightningAddress,
lnurlEndpoint,
amountSats
});
const lnurlResponse = await fetch(lnurlEndpoint, {
headers: { 'Accept': 'application/json' },
});
if (!lnurlResponse.ok) {
console.error('LNURL Endpoint Error:', {
lightningAddress,
lnurlEndpoint,
status: lnurlResponse.status,
statusText: lnurlResponse.statusText
});
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status} ${lnurlResponse.statusText}`);
}
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
console.log('LNURL Response:', {
lightningAddress,
lnurlData
});
if (lnurlData.status && lnurlData.status !== 'OK') {
console.error('LNURL Status Error:', {
lightningAddress,
status: lnurlData.status,
response: lnurlData
});
throw new Error('LNURL endpoint returned error status');
}
if (lnurlData.tag !== 'payRequest') {
console.error('LNURL Tag Error:', {
lightningAddress,
expectedTag: 'payRequest',
actualTag: lnurlData.tag,
response: lnurlData
});
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
}
// Validate amount against min/max bounds
const minSats = lnurlData.minSendable / 1000;
const maxSats = lnurlData.maxSendable / 1000;
console.log('Amount validation:', {
lightningAddress,
amountSats,
minSats,
maxSats,
minSendable: lnurlData.minSendable,
maxSendable: lnurlData.maxSendable
});
if (amountSats < minSats) {
console.error('Amount below minimum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
}
if (amountSats > maxSats) {
console.error('Amount exceeds maximum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`);
}
// Step 2: Request invoice from callback URL
const amountMsats = amountSats * 1000;
const callbackUrl = new URL(lnurlData.callback);
callbackUrl.searchParams.set('amount', amountMsats.toString());
// Add comment if provided and allowed
if (comment && lnurlData.commentAllowed && comment.length <= lnurlData.commentAllowed) {
callbackUrl.searchParams.set('comment', comment);
}
console.log('Requesting invoice:', {
lightningAddress,
amountSats,
amountMsats,
callbackUrl: callbackUrl.toString(),
comment
});
const invoiceResponse = await fetch(callbackUrl.toString(), {
headers: { 'Accept': 'application/json' },
});
if (!invoiceResponse.ok) {
console.error('Invoice Request Error:', {
lightningAddress,
amountSats,
callbackUrl: callbackUrl.toString(),
status: invoiceResponse.status,
statusText: invoiceResponse.statusText
});
throw new Error(`Failed to get invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
}
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
console.log('Invoice Response:', {
lightningAddress,
amountSats,
invoiceData
});
// Check if we have a valid invoice (some providers return invoice directly without status field)
if (invoiceData.pr) {
console.log('Invoice generated successfully:', {
lightningAddress,
amountSats,
invoiceLength: invoiceData.pr.length
});
setIsLoading(false);
return invoiceData.pr;
}
// If no invoice but has status field, check for errors
if (invoiceData.status && invoiceData.status !== 'OK') {
const errorReason = invoiceData.reason || 'Invoice generation failed';
console.error('LNURL Invoice Error:', {
lightningAddress,
amountSats,
status: invoiceData.status,
reason: errorReason,
response: invoiceData
});
throw new Error(`Invoice generation failed: ${errorReason}`);
}
// If we get here, no invoice was provided
console.error('LNURL Invoice Missing PR:', {
lightningAddress,
amountSats,
response: invoiceData
});
throw new Error('No invoice returned from provider');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, []);
return {
getInvoice,
isLoading,
error,
};
}
export type { GetInvoiceParams };
+1 -1
View File
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
const { logins, setLogin, removeLogin } = useNostrLogin();
const { data: authors = [] } = useQuery({
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
queryKey: ['logins', logins.map((l) => l.id).join(';')],
queryFn: async ({ signal }) => {
const events = await nostr.query(
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
+74
View File
@@ -0,0 +1,74 @@
import { useCallback } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
export interface NIP98Options {
url: string;
method: string;
body?: unknown;
}
/**
* Hook for creating NIP-98 HTTP Authentication headers
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
*/
export function useNIP98() {
const { user } = useCurrentUser();
/**
* Create a NIP-98 authorization header for HTTP requests
* @param options - The request details (url, method, optional body)
* @returns Promise<string> - The "Nostr base64..." authorization header value
*/
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
if (!user) {
throw new Error('User must be logged in to create NIP-98 auth header');
}
const { url, method, body } = options;
// Parse URL to remove query parameters (per NIP-98 spec)
const urlObj = new URL(url);
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
const tags: string[][] = [
['u', urlWithoutQuery],
['method', method.toUpperCase()],
];
// If there's a request body (POST, PUT, PATCH), add payload hash
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create and sign the NIP-98 event (kind 27235)
const event = await user.signer.signEvent({
kind: 27235,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
}) as NostrEvent;
// Encode the event as base64
const eventJson = JSON.stringify(event);
const base64Event = btoa(eventJson);
return `Nostr ${base64Event}`;
}, [user]);
return {
createAuthHeader,
isLoggedIn: !!user,
pubkey: user?.pubkey,
signer: user?.signer,
};
}
+320
View File
@@ -0,0 +1,320 @@
import { useCallback, useState, useMemo, useEffect, useRef } from 'react';
import { useNIP98 } from './useNIP98';
import { NPCClient, JWTAuthProvider } from 'npubcash-sdk';
import type { User, Quote } from 'npubcash-types';
const NPUBCASH_BASE_URL = 'https://npubx.cash';
export interface NpubCashUserInfo {
pubkey: string;
name?: string;
mint_url: string;
lock_quote: boolean;
}
/**
* Hook for interacting with npub.cash API using the official SDK
*/
export function useNpubCash() {
const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Ref to track last sync timestamp for incremental updates
const lastSyncRef = useRef<number>(0);
// Create NPCClient instance using the SDK with JWTAuthProvider for proper WebSocket auth
const npcClient = useMemo(() => {
if (!isLoggedIn || !signer) return null;
// Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature
const signingFunc = async (eventTemplate: any) => {
return await signer.signEvent(eventTemplate);
};
const auth = new JWTAuthProvider(NPUBCASH_BASE_URL, signingFunc);
return new NPCClient(NPUBCASH_BASE_URL, auth);
}, [isLoggedIn, signer]);
// Generic wrapper for SDK calls with loading state
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
try {
setIsLoading(true);
setError(null);
return await operation();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
return null;
} finally {
setIsLoading(false);
}
}, []);
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setMintUrl(mintUrl));
return result !== null;
}, [npcClient, withLoading]);
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
if (!npcClient) return null;
// Since SDK doesn't have getUserInfo, we'll use manual implementation
// This could be enhanced if SDK adds this method
return withLoading(async () => {
const url = `${NPUBCASH_BASE_URL}/api/v2/user/info`;
const authHeader = await createAuthHeader({ url, method: 'GET' });
const response = await fetch(url, {
method: 'GET',
headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' },
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
}
const data = await response.json();
return data.data.user;
});
}, [npcClient, createAuthHeader, withLoading]);
const getAllQuotes = useCallback(async (): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getAllQuotes());
return result || [];
}, [npcClient, withLoading]);
const getQuotesSince = useCallback(async (since: number): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getQuotesSince(since));
return result || [];
}, [npcClient, withLoading]);
const setLockQuotes = useCallback(async (lockQuotes: boolean): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setLock(lockQuotes));
return result !== null;
}, [npcClient, withLoading]);
const subscribeToQuotes = useCallback((
onUpdate: (quoteId: string) => void,
onError?: (msg: string) => void
) => {
if (!npcClient) return () => {};
return npcClient.subscribe(onUpdate, onError);
}, [npcClient]);
const refreshQuotes = useCallback(async (coco: any, toast: any): Promise<void> => {
if (!npcClient || !coco) return;
try {
// Fetch all quotes from npub.cash
const quotes = await getAllQuotes();
if (quotes.length === 0) {
toast({
title: "No Quotes Found",
description: "No pending quotes found on npub.cash",
});
return;
}
// Group quotes by mint URL
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists, add if not
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
// Add quotes to the wallet (matching main.ts format)
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Refreshed",
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
});
} else {
toast({
title: "No New Quotes",
description: "All quotes from npub.cash are already processed",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Refresh Failed",
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
});
}
}, [npcClient, getAllQuotes]);
const clearError = useCallback(() => setError(null), []);
// Subscribe to quote updates and sync to wallet automatically
const syncQuotesWithWallet = useCallback(async (coco: any, toast: any): Promise<() => void> => {
if (!npcClient || !coco) return () => {};
try {
// Fetch and sync all quotes initially
const quotes = await getAllQuotes();
if (quotes.length > 0) {
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to sync quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Synced",
description: `Synced ${addedQuotes} quotes from npub.cash`,
});
lastSyncRef.current = Math.floor(Date.now() / 1000);
}
}
// Subscribe to real-time updates
const unsubscribe = subscribeToQuotes(
async (quoteId: string) => {
try {
// When a quote is updated, fetch newer quotes and sync
const recentQuotes = await getQuotesSince(lastSyncRef.current);
if (recentQuotes.length > 0) {
const quotesByMint = recentQuotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof recentQuotes>);
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
} catch (err) {
console.warn(`Failed to sync quote ${quoteId} for mint ${mintUrl}:`, err);
}
}
lastSyncRef.current = Math.floor(Date.now() / 1000);
}
} catch (err) {
console.error('Failed to sync quote update:', err);
}
},
(err: string) => {
console.error('Quote subscription error:', err);
toast({
variant: "destructive",
title: "Sync Error",
description: "Failed to sync quotes from npub.cash",
});
}
);
return unsubscribe;
} catch (err) {
console.error('Failed to set up quote sync:', err);
toast({
variant: "destructive",
title: "Sync Failed",
description: err instanceof Error ? err.message : 'Failed to set up quote sync',
});
return () => {};
}
}, [npcClient, getAllQuotes, getQuotesSince, subscribeToQuotes]);
return {
// Core methods
setMint,
getUserInfo,
// Quote management methods
getAllQuotes,
getQuotesSince,
setLockQuotes,
subscribeToQuotes,
refreshQuotes,
syncQuotesWithWallet,
// Status
isLoading,
error,
isLoggedIn,
pubkey,
clearError,
// SDK instance for advanced usage
npcClient,
};
}
+1 -1
View File
@@ -85,7 +85,7 @@ export function usePostComment() {
onSuccess: (_, { root }) => {
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
});
},
});
+62
View File
@@ -0,0 +1,62 @@
import { useState, useCallback } from 'react';
import QRCode from 'qrcode';
import { useToast } from './useToast';
interface UseQRCodeReturn {
generateQRCode: (text: string) => Promise<string>;
isGenerating: boolean;
error: string | null;
}
/**
* Hook for generating QR codes
*
* @example
* ```tsx
* const { generateQRCode, isGenerating, error } = useQRCode();
*
* const qrCodeUrl = await generateQRCode('cashuBo2Ft...');
* ```
*/
export function useQRCode(): UseQRCodeReturn {
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const { toast } = useToast();
const generateQRCode = useCallback(async (text: string): Promise<string> => {
setIsGenerating(true);
setError(null);
try {
const qrCodeUrl = await QRCode.toDataURL(text, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
setIsGenerating(false);
return qrCodeUrl;
} catch (err) {
const errorMessage = 'Failed to generate QR code';
console.error(errorMessage, err);
setError(errorMessage);
setIsGenerating(false);
toast({
variant: "destructive",
title: "QR Code Failed",
description: errorMessage,
});
return '';
}
}, [toast]);
return {
generateQRCode,
isGenerating,
error,
};
}
+1 -1
View File
@@ -6,7 +6,7 @@ import type {
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
const TOAST_REMOVE_DELAY = 1000
type ToasterToast = ToastProps & {
id: string
+24 -4
View File
@@ -1,16 +1,22 @@
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/cashu/useCashu';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
hasNWC: boolean;
webln: WebLNProvider | 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() {
const { connections, getActiveConnection } = useNWC();
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
@@ -18,13 +24,24 @@ export function useWallet() {
// Access WebLN directly from browser global scope
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(() => {
return connections.length > 0 && connections.some(c => c.isConnected);
}, [connections]);
// Determine preferred payment method
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
// Determine preferred payment method - Cashu first, then Lightning fallbacks
const preferredMethod: WalletStatus['preferredMethod'] = hasCashu
? 'cashu'
: activeNWC
? 'nwc'
: webln
? 'webln'
@@ -35,6 +52,9 @@ export function useWallet() {
webln,
activeNWC,
preferredMethod,
hasCashu,
cashuBalance,
isCashuInitialized,
};
return status;
+78 -12
View File
@@ -4,6 +4,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/cashu/useCashu';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
@@ -29,6 +30,7 @@ export function useZaps(
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
@@ -131,7 +133,13 @@ export function useZaps(
}, [zapEvents, actualTarget]);
const zap = async (amount: number, comment: string) => {
if (amount <= 0) {
if (amount <= 0 || isNaN(amount)) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
@@ -158,6 +166,17 @@ export function useZaps(
return;
}
// Additional validation to ensure actualTarget has required properties
if (!actualTarget.pubkey || !actualTarget.id) {
toast({
title: 'Invalid event',
description: 'The event is missing required properties.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
try {
if (!author.data || !author.data?.metadata || !author.data?.event ) {
toast({
@@ -192,20 +211,20 @@ export function useZaps(
return;
}
// Create zap request - use appropriate event format based on kind
// For addressable events (30000-39999), pass the object to get 'a' tag
// For all other events, pass the ID string to get 'e' tag
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
? actualTarget
: actualTarget.id;
const zapAmount = amount * 1000; // convert to millisats
// Validate zapAmount is a valid number
if (isNaN(zapAmount) || zapAmount <= 0) {
throw new Error('Invalid zap amount');
}
// Create zap request - always pass the full event object
// The nip57.makeZapRequest function will handle proper tag generation
// ('e' tag for regular events, 'a' tag for addressable events)
const zapRequest = nip57.makeZapRequest({
profile: actualTarget.pubkey,
event: event,
event: actualTarget,
amount: zapAmount,
relays: config.relayMetadata.relays.map(r => r.url),
relays: [config.relayUrl],
comment
});
@@ -228,10 +247,57 @@ export function useZaps(
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 && coco) {
// Create melt quote to convert Cashu tokens to Lightning payment
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
await coco.quotes.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
const currentNWCConnection = getActiveConnection();
// Try NWC first if available and properly connected
// Try NWC if Cashu failed or unavailable
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
+1 -1
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.75rem;
--radius: 0.5rem;
--sidebar-background: 0 0% 98%;
-86
View File
@@ -1,86 +0,0 @@
import type { NostrEvent } from '@nostrify/nostrify';
// ============================================================================
// Message Protocol Types
// ============================================================================
export const MESSAGE_PROTOCOL = {
NIP04: 'nip04',
NIP17: 'nip17',
UNKNOWN: 'unknown',
} as const;
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
// ============================================================================
// Protocol Mode (for user selection)
// ============================================================================
export const PROTOCOL_MODE = {
NIP04_ONLY: 'nip04_only',
NIP17_ONLY: 'nip17_only',
NIP04_OR_NIP17: 'nip04_or_nip17',
} as const;
export type ProtocolMode = typeof PROTOCOL_MODE[keyof typeof PROTOCOL_MODE];
// ============================================================================
// Loading Phases
// ============================================================================
export const LOADING_PHASES = {
IDLE: 'idle',
CACHE: 'cache',
RELAYS: 'relays',
SUBSCRIPTIONS: 'subscriptions',
READY: 'ready',
} as const;
export type LoadingPhase = typeof LOADING_PHASES[keyof typeof LOADING_PHASES];
// ============================================================================
// Protocol Configuration
// ============================================================================
export const PROTOCOL_CONFIG = {
[MESSAGE_PROTOCOL.NIP04]: {
label: 'NIP-04',
description: 'Legacy DMs',
kind: 4,
},
[MESSAGE_PROTOCOL.NIP17]: {
label: 'NIP-17',
description: 'Private DMs',
kind: 1059,
},
[MESSAGE_PROTOCOL.UNKNOWN]: {
label: 'Unknown',
description: 'Unknown protocol',
kind: 0,
},
} as const;
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Get the message protocol from an event kind
*/
export function getMessageProtocol(event: NostrEvent): MessageProtocol {
switch (event.kind) {
case 4:
return MESSAGE_PROTOCOL.NIP04;
case 1059:
return MESSAGE_PROTOCOL.NIP17;
default:
return MESSAGE_PROTOCOL.UNKNOWN;
}
}
/**
* Check if a protocol is valid for sending messages
*/
export function isValidSendProtocol(protocol: MessageProtocol): boolean {
return protocol === MESSAGE_PROTOCOL.NIP04 || protocol === MESSAGE_PROTOCOL.NIP17;
}
-117
View File
@@ -1,117 +0,0 @@
import { openDB, type IDBPDatabase } from 'idb';
import type { NostrEvent } from '@nostrify/nostrify';
// ============================================================================
// IndexedDB Schema
// ============================================================================
// Use domain-based naming to avoid conflicts between apps on same domain
const getDBName = () => {
// Use hostname for unique DB per app (e.g., 'nostr-dm-store-localhost', 'nostr-dm-store-myapp.com')
const hostname = typeof window !== 'undefined' ? window.location.hostname : 'default';
return `nostr-dm-store-${hostname}`;
};
const DB_NAME = getDBName();
const DB_VERSION = 1;
const STORE_NAME = 'messages';
interface StoredParticipant {
messages: NostrEvent[];
lastActivity: number;
hasNIP4: boolean;
hasNIP17: boolean;
}
export interface MessageStore {
participants: Record<string, StoredParticipant>;
lastSync: {
nip4: number | null;
nip17: number | null;
};
}
// ============================================================================
// Database Operations
// ============================================================================
/**
* Open the IndexedDB database
*/
async function openDatabase(): Promise<IDBPDatabase> {
return openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
// Create the messages store if it doesn't exist
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
},
});
}
/**
* Write messages to IndexedDB for a specific user
* Messages are stored in their original encrypted form (kind 4 or kind 13)
*/
export async function writeMessagesToDB(
userPubkey: string,
messageStore: MessageStore
): Promise<void> {
try {
const db = await openDatabase();
// Store messages in their original encrypted form (no NIP-44 wrapper needed)
// Each message content is already encrypted by the sender
await db.put(STORE_NAME, messageStore, userPubkey);
} catch (error) {
console.error('[MessageStore] ❌ Error writing to IndexedDB:', error);
throw error;
}
}
/**
* Read messages from IndexedDB for a specific user
* Messages are stored in their original encrypted form (kind 4 or kind 13)
*/
export async function readMessagesFromDB(
userPubkey: string
): Promise<MessageStore | undefined> {
try {
const db = await openDatabase();
const data = await db.get(STORE_NAME, userPubkey);
if (!data) {
return undefined;
}
return data as MessageStore;
} catch (error) {
console.error('[MessageStore] Error reading from IndexedDB:', error);
throw error;
}
}
/**
* Delete messages from IndexedDB for a specific user
*/
export async function deleteMessagesFromDB(userPubkey: string): Promise<void> {
try {
const db = await openDatabase();
await db.delete(STORE_NAME, userPubkey);
} catch (error) {
console.error('[MessageStore] Error deleting from IndexedDB:', error);
throw error;
}
}
/**
* Clear all messages from IndexedDB
*/
export async function clearAllMessages(): Promise<void> {
try {
const db = await openDatabase();
await db.clear(STORE_NAME);
} catch (error) {
console.error('[MessageStore] Error clearing IndexedDB:', error);
throw error;
}
}
-98
View File
@@ -1,98 +0,0 @@
import type { NostrEvent } from '@nostrify/nostrify';
/**
* Validate that an event is a proper DM event
*/
export function validateDMEvent(event: NostrEvent): boolean {
// Must be kind 4 (NIP-04 DM)
if (event.kind !== 4) return false;
// Must have a 'p' tag
const hasRecipient = event.tags?.some(([name]) => name === 'p');
if (!hasRecipient) return false;
// Must have content (even if encrypted)
if (!event.content) return false;
return true;
}
/**
* Get the recipient pubkey from a DM event
*/
export function getRecipientPubkey(event: NostrEvent): string | undefined {
return event.tags?.find(([name]) => name === 'p')?.[1];
}
/**
* Get the conversation partner pubkey from a DM event
* (the other person in the conversation, not the current user)
*/
export function getConversationPartner(event: NostrEvent, userPubkey: string): string | undefined {
const isFromUser = event.pubkey === userPubkey;
if (isFromUser) {
// If we sent it, the partner is the recipient
return getRecipientPubkey(event);
} else {
// If they sent it, the partner is the author
return event.pubkey;
}
}
/**
* Format timestamp for display (matches Signal/WhatsApp/Telegram pattern)
* Today: Show time (e.g., "2:45 PM")
* Yesterday: "Yesterday"
* This week: Day name (e.g., "Mon")
* This year: Month and day (e.g., "Jan 15")
* Older: Full date (e.g., "Jan 15, 2024")
*/
export function formatConversationTime(timestamp: number): string {
const date = new Date(timestamp * 1000);
const now = new Date();
// Start of today (midnight)
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// Start of yesterday
const yesterdayStart = new Date(todayStart);
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
// Start of this week (assuming week starts on Sunday, adjust if needed)
const weekStart = new Date(todayStart);
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
if (date >= todayStart) {
// Today: Show time (e.g., "2:45 PM")
return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
} else if (date >= yesterdayStart) {
// Yesterday
return 'Yesterday';
} else if (date >= weekStart) {
// This week: Show day name (e.g., "Monday")
return date.toLocaleDateString(undefined, { weekday: 'short' });
} else if (date.getFullYear() === now.getFullYear()) {
// This year: Show month and day (e.g., "Jan 15")
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
} else {
// Older: Show full date (e.g., "Jan 15, 2024")
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
}
/**
* Format timestamp as full date and time for tooltips
* e.g., "Mon, Jan 15, 2024, 2:45 PM"
*/
export function formatFullDateTime(timestamp: number): string {
const date = new Date(timestamp * 1000);
return date.toLocaleString(undefined, {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
});
}
+131
View File
@@ -0,0 +1,131 @@
/**
* Exchange rate service for fetching BTC/USD rates from Coinbase API
*/
export class ExchangeRateService {
private static readonly COINBASE_API_URL = "https://api.coinbase.com/v2/exchange-rates";
private static readonly CACHE_DURATION_MS = 60000; // 1 minute cache
private cachedRate: number | null = null;
private cacheTimestamp: number = 0;
/**
* Get the current BTC/USD exchange rate from Coinbase API
* Uses caching to avoid excessive API calls
*/
async getBtcUsdRate(): Promise<number> {
const now = Date.now();
// Return cached rate if still valid
if (this.cachedRate && (now - this.cacheTimestamp) < ExchangeRateService.CACHE_DURATION_MS) {
console.debug(`Using cached BTC/USD rate: ${this.cachedRate}`, {
cache_age_ms: now - this.cacheTimestamp,
});
return this.cachedRate;
}
try {
console.debug("Fetching BTC/USD rate from Coinbase API");
const response = await fetch(`${ExchangeRateService.COINBASE_API_URL}?currency=BTC`, {
method: "GET",
headers: {
"Accept": "application/json",
"User-Agent": "MKStack/1.0",
},
// Add timeout to prevent hanging
signal: AbortSignal.timeout(10000), // 10 second timeout
});
if (!response.ok) {
throw new Error(`Coinbase API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
// Validate response structure
if (!data?.data?.rates?.USD) {
throw new Error("Invalid response format from Coinbase API");
}
const rate = parseFloat(data.data.rates.USD);
if (isNaN(rate) || rate <= 0) {
throw new Error(`Invalid exchange rate received: ${data.data.rates.USD}`);
}
// Update cache
this.cachedRate = rate;
this.cacheTimestamp = now;
console.info(`Fetched BTC/USD rate from Coinbase: ${rate}`, { rate });
return rate;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Failed to fetch BTC/USD rate: ${errorMessage}`);
// If we have a cached rate, use it as fallback
if (this.cachedRate) {
const cacheAge = now - this.cacheTimestamp;
console.warn(`Using stale cached rate as fallback: ${this.cachedRate}`, {
cache_age_ms: cacheAge,
});
return this.cachedRate;
}
// If no cached rate available, throw error
throw new Error(`Unable to fetch BTC/USD exchange rate: ${errorMessage}`);
}
}
/**
* Convert BTC amount to USD using current exchange rate
*/
async btcToUsd(btcAmount: number): Promise<number> {
const rate = await this.getBtcUsdRate();
return btcAmount * rate;
}
/**
* Convert USD amount to BTC using current exchange rate
*/
async usdToBtc(usdAmount: number): Promise<number> {
const rate = await this.getBtcUsdRate();
return usdAmount / rate;
}
/**
* Convert sats to USD using current exchange rate
*/
async satsToUsd(sats: number): Promise<number> {
const btcAmount = sats / 100000000; // Convert sats to BTC
return this.btcToUsd(btcAmount);
}
/**
* Clear the cached exchange rate (useful for testing)
*/
clearCache(): void {
this.cachedRate = null;
this.cacheTimestamp = 0;
}
/**
* Get cache status for debugging
*/
getCacheStatus(): { rate: number | null; age_ms: number; is_valid: boolean } {
const now = Date.now();
const age = now - this.cacheTimestamp;
const isValid = this.cachedRate !== null && age < ExchangeRateService.CACHE_DURATION_MS;
return {
rate: this.cachedRate,
age_ms: age,
is_valid: isValid,
};
}
}
// Export a singleton instance
export const exchangeRateService = new ExchangeRateService();
-12
View File
@@ -1,15 +1,3 @@
import Buffer from 'buffer';
/**
* Polyfill for Buffer in browser environment
*
* Many Node.js libraries like isomorphic-git and bitcoinjs-lib expect Buffer to be globally available.
* This polyfill makes the buffer package's Buffer available globally.
*/
if (!globalThis.Buffer) {
globalThis.Buffer = Buffer.Buffer;
}
/**
* Polyfill for AbortSignal.any()
*
-24
View File
@@ -1,24 +0,0 @@
import { useSeoMeta } from '@unhead/react';
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
const Messages = () => {
useSeoMeta({
title: 'Messages',
description: 'Private encrypted messaging on Nostr',
});
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto p-4 h-screen flex flex-col">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-semibold">Messages</h1>
</div>
<DMMessagingInterface className="flex-1" />
</div>
</div>
);
};
export default Messages;
+1 -6
View File
@@ -23,12 +23,7 @@ export function TestApp({ children }: TestAppProps) {
const defaultConfig: AppConfig = {
theme: 'light',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
relayUrl: 'wss://relay.nostr.band',
};
return (
+19
View File
@@ -0,0 +1,19 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}
+1 -1
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,