Author SHA1 Message Date
lemonknowsall 4c21a4147c added push notification hook 2025-09-22 21:01:06 -07:00
44 changed files with 2151 additions and 7595 deletions

No files matched your search

+168 -77
View File
@@ -15,11 +15,10 @@ 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.)
- Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
@@ -33,13 +32,11 @@ 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 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
- `useZaps`: Lightning zap functionality with payment processing
- `useWallet`: Unified wallet detection (WebLN + NWC)
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `useShakespeare`: AI chat completions with Shakespeare AI API
- `usePush`: Push notifications via Nostr RPC
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext, NWCContext)
@@ -101,40 +98,6 @@ 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:
@@ -420,7 +383,71 @@ function usePosts() {
}
```
### Efficient Query Design
### Infinite Scroll for Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam, signal }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
const posts = data?.pages.flat() || [];
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
@@ -460,7 +487,7 @@ const [notes, reposts, genericReposts] = await Promise.all([
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
### Event Validation
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
@@ -531,7 +558,7 @@ function Post({ event }: { event: NostrEvent }) {
}
```
### `NostrMetadata` type
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
@@ -816,6 +843,48 @@ const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Push Notifications
The project includes `usePush` hook for managing push notifications via Nostr RPC. This enables users to receive browser notifications for Nostr events.
#### Basic Usage
```tsx
import { usePush } from '@/hooks/usePush';
function NotificationButton({ authorPubkey }: { authorPubkey: string }) {
const { subscribeToAuthor, isLoading, error } = usePush();
const handleEnableNotifications = async () => {
try {
await subscribeToAuthor(authorPubkey);
} catch (error) {
console.error('Failed to enable notifications:', error);
}
};
return (
<Button onClick={handleEnableNotifications} disabled={isLoading}>
{isLoading ? 'Enabling...' : 'Enable Notifications'}
</Button>
);
}
```
#### Available Methods
- **`subscribeToAuthor`**: Get notifications for new posts from a specific user
- **`subscribeToMentions`**: Get notifications when mentioned in posts
- **`subscribeToHashtag`**: Get notifications for posts with specific hashtags
- **`registerSubscription`**: Create custom notification subscriptions
- **`deleteSubscription`**: Remove notification subscriptions
#### Requirements
- User must be logged in with NIP-44 encryption support
- Browser must support push notifications
- VAPID public key is included by default
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
@@ -836,6 +905,61 @@ export function Post(/* ...props */) {
}
```
### Adding 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.
#### Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
#### Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
#### Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
@@ -996,39 +1120,6 @@ When users specify color schemes:
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
### Dialog Component Patterns
When using Dialog components, always ensure accessibility compliance by including required elements:
```tsx
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
// ✅ Correct - Always include DialogHeader with DialogTitle
<Dialog 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**:
-170
View File
@@ -1,170 +0,0 @@
### 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
@@ -1,393 +0,0 @@
# 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.
-54
View File
@@ -1,54 +0,0 @@
# 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.
## Basic Usage
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
</div>
);
}
```
## Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
## Commenting on URLs
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
-72
View File
@@ -1,72 +0,0 @@
### Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam, signal }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
import { useMemo } from 'react';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
// Remove duplicate events by ID
const posts = useMemo(() => {
const seen = new Set();
return data?.pages.flat().filter(event => {
if (!event.id || seen.has(event.id)) return false;
seen.add(event.id);
return true;
}) || [];
}, [data?.pages]);
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
-612
View File
@@ -1,612 +0,0 @@
# npub.cash Lightning Address Integration
This document explains how to integrate npub.cash Lightning addresses into your Nostr application, allowing users to receive Lightning payments without any setup.
## Overview
npub.cash is a Lightning address service powered by Cashu and Nostr. It provides instant Lightning addresses for any Nostr public key, with no registration required. Payments are stored as Cashu quotes that users can later claim.
### How It Works
1. **Identity**: Your Nostr pubkey becomes your Lightning address (`[email protected]`)
2. **Receiving**: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey
3. **Claiming**: Authenticate with NIP-98 to fetch and redeem your paid quotes from the configured mint
## Key Features
- **Zero Setup**: Any Nostr pubkey is instantly a valid Lightning address
- **Nostr Identity**: Uses NIP-98 authentication (no separate account needed)
- **Privacy**: Cashu provides better privacy than plain Lightning
- **Flexible**: Set your preferred Cashu mint
- **Optional Locking**: Enable NUT-20 quote locking for enhanced security
## Basic Usage
### Get Your Lightning Address
```tsx
import { useNpubCash } from '@/hooks/useNpubCash';
function MyLightningAddress() {
const { lightningAddress, isLoading } = useNpubCash();
if (isLoading) return <p>Loading...</p>;
return (
<div>
<h3>My Lightning Address</h3>
<p className="font-mono">{lightningAddress}</p>
<button onClick={() => navigator.clipboard.writeText(lightningAddress)}>
Copy
</button>
</div>
);
}
```
### Display Unclaimed Balance
```tsx
function UnclaimedBalance() {
const { unclaimedAmount, quotes, refresh } = useNpubCash();
return (
<div>
<h3>Unclaimed Payments</h3>
<p>{unclaimedAmount} sats from {quotes.length} payments</p>
<button onClick={refresh}>Refresh</button>
</div>
);
}
```
### Fetch and Display Quotes
```tsx
function PaymentHistory() {
const { quotes, fetchQuotes, isLoading } = useNpubCash();
useEffect(() => {
fetchQuotes();
}, [fetchQuotes]);
return (
<div>
<h3>Received Payments</h3>
{quotes.map(quote => (
<div key={quote.quote_id} className="border p-4 rounded">
<p>Amount: {quote.amount} sats</p>
<p>Mint: {quote.mint_url}</p>
<p>Status: {quote.state}</p>
<p>Paid: {new Date(quote.paid_at * 1000).toLocaleString()}</p>
</div>
))}
</div>
);
}
```
## Advanced Features
### Set Username (Paid Feature)
Users can optionally purchase a custom username for a cleaner Lightning address:
```tsx
function UsernameSelector() {
const { userInfo, setUsername, isLoading } = useNpubCash();
const handleSetUsername = async () => {
try {
await setUsername('myusername');
// Address becomes: [email protected]
alert('Username set successfully!');
} catch (error) {
// Payment required - X-Cashu header returned
console.error(error);
}
};
return (
<div>
<p>Current: {userInfo?.name || 'Using npub'}</p>
<button onClick={handleSetUsername} disabled={isLoading}>
Set Username
</button>
</div>
);
}
```
### Configure Preferred Mint
```tsx
function MintSelector() {
const { userInfo, setMint, isLoading } = useNpubCash();
const [mintUrl, setMintUrl] = useState('');
const handleSetMint = async () => {
try {
await setMint(mintUrl);
alert('Mint updated successfully!');
} catch (error) {
console.error('Failed to set mint:', error);
}
};
return (
<div>
<p>Current Mint: {userInfo?.mint_url}</p>
<input
type="text"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
placeholder="https://mint.example.com"
/>
<button onClick={handleSetMint} disabled={isLoading}>
Update Mint
</button>
</div>
);
}
```
### Enable Quote Locking (NUT-20)
Lock quotes to your pubkey for enhanced security:
```tsx
function QuoteLocking() {
const { userInfo, setLockQuotes, isLoading } = useNpubCash();
const toggleLocking = async () => {
try {
await setLockQuotes(!userInfo?.lock_quote);
alert('Quote locking updated!');
} catch (error) {
console.error('Failed to update locking:', error);
}
};
return (
<div>
<label>
<input
type="checkbox"
checked={userInfo?.lock_quote || false}
onChange={toggleLocking}
disabled={isLoading}
/>
Lock quotes to my pubkey (NUT-20)
</label>
<p className="text-sm text-muted-foreground">
Requires wallet with NUT-20 support
</p>
</div>
);
}
```
## Complete Example: Receive Payment Widget
```tsx
import { useState } from 'react';
import { useNpubCash } from '@/hooks/useNpubCash';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
function ReceivePaymentWidget() {
const {
lightningAddress,
unclaimedAmount,
quotes,
isLoading,
refresh,
} = useNpubCash();
const [copied, setCopied] = useState(false);
const copyAddress = async () => {
if (!lightningAddress) return;
await navigator.clipboard.writeText(lightningAddress);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<Card>
<CardHeader>
<CardTitle>Receive Lightning Payments</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Lightning Address */}
<div>
<label className="text-sm font-medium">Your Lightning Address</label>
<div className="flex gap-2 items-center mt-1">
<code className="flex-1 bg-muted px-3 py-2 rounded text-sm">
{lightningAddress || 'Loading...'}
</code>
<Button
size="sm"
onClick={copyAddress}
disabled={!lightningAddress}
>
{copied ? 'Copied!' : 'Copy'}
</Button>
</div>
</div>
{/* Unclaimed Balance */}
<div className="flex justify-between items-center p-4 bg-muted rounded">
<span className="font-medium">Unclaimed Balance</span>
<Badge variant="secondary" className="text-lg">
{unclaimedAmount} sats
</Badge>
</div>
{/* Payment History */}
<div>
<div className="flex justify-between items-center mb-2">
<span className="text-sm font-medium">Recent Payments</span>
<Button
size="sm"
variant="outline"
onClick={refresh}
disabled={isLoading}
>
Refresh
</Button>
</div>
<div className="space-y-2 max-h-[300px] overflow-y-auto">
{quotes.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No payments received yet
</p>
) : (
quotes.map(quote => (
<div
key={quote.quote_id}
className="border rounded p-3 space-y-1"
>
<div className="flex justify-between items-center">
<span className="font-semibold">{quote.amount} sats</span>
<Badge
variant={quote.state === 'PAID' ? 'default' : 'secondary'}
>
{quote.state}
</Badge>
</div>
<p className="text-xs text-muted-foreground">
{new Date(quote.paid_at * 1000).toLocaleString()}
</p>
<p className="text-xs text-muted-foreground truncate">
{quote.mint_url}
</p>
</div>
))
)}
</div>
</div>
</CardContent>
</Card>
);
}
export default ReceivePaymentWidget;
```
## API Reference
### Hook: `useNpubCash()`
Returns an object with the following properties and methods:
#### State
- `isInitialized: boolean` - Whether the hook has loaded initial data
- `isLoading: boolean` - Whether an API request is in progress
- `error: string | null` - Error message if any operation failed
- `lightningAddress: string | null` - User's npub.cash Lightning address
- `userInfo: NpubCashUserInfo | null` - User settings (mint, username, locking)
- `quotes: NpubCashQuote[]` - Array of received payment quotes
- `unclaimedAmount: number` - Total sats in unclaimed paid quotes
#### Methods
##### `fetchQuotes(since?: number, limit?: number): Promise<NpubCashQuote[]>`
Fetch paid quotes from npub.cash.
- `since` - Optional Unix timestamp to only fetch quotes paid after this time
- `limit` - Maximum number of quotes to return (default: 50)
```tsx
const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours
```
##### `fetchUserInfo(): Promise<NpubCashUserInfo>`
Fetch current user settings.
```tsx
const info = await fetchUserInfo();
console.log('Preferred mint:', info.mint_url);
```
##### `setUsername(username: string): Promise<void>`
Set a custom username (paid feature via Cashu 402).
```tsx
await setUsername('alice'); // Address becomes [email protected]
```
##### `setMint(mintUrl: string): Promise<void>`
Set preferred Cashu mint for receiving payments.
```tsx
await setMint('https://mint.example.com');
```
##### `setLockQuotes(locked: boolean): Promise<void>`
Enable or disable quote locking to pubkey (NUT-20).
```tsx
await setLockQuotes(true); // Enable locking
```
##### `refresh(): Promise<void>`
Refresh all data (quotes and user info) from npub.cash.
```tsx
await refresh();
```
##### `clearAuth(): void`
Clear stored JWT token, forcing NIP-98 re-authentication on next request.
```tsx
clearAuth(); // Next API call will require NIP-98 signature
```
## Types
### `NpubCashQuote`
```tsx
interface NpubCashQuote {
created_at: number; // Unix timestamp when quote was created
paid_at: number; // Unix timestamp when invoice was paid
expires_at: number; // Unix timestamp when quote expires
mint_url: string; // Cashu mint URL for this quote
quote_id: string; // Unique quote identifier
request: string; // Original BOLT11 invoice
amount: number; // Amount in sats
state: 'PENDING' | 'PAID' | 'EXPIRED';
locked: boolean; // Whether quote is locked to pubkey
}
```
### `NpubCashUserInfo`
```tsx
interface NpubCashUserInfo {
pubkey: string; // User's Nostr public key (hex)
name: string | null; // Custom username (if set)
mint_url: string; // User's preferred Cashu mint
lock_quote: boolean; // Whether quote locking is enabled
}
```
## Authentication
The hook handles authentication automatically using two methods:
### NIP-98 HTTP Auth
For every API request, the hook can create a NIP-98 event (kind 27235) signed by the user's Nostr key. This is the primary authentication method.
### JWT Tokens
To avoid repeated signing requests (especially for browser extensions), the hook can obtain a JWT token using a single NIP-98 request. The token is cached in localStorage and automatically refreshed when expired.
```tsx
// JWT is obtained automatically on first API call
// Cached in localStorage as 'npubcash-jwt'
// Valid for 30 minutes
```
## Integration with Cashu Wallet
To claim the received funds, integrate with the existing `useCashu` hook:
```tsx
import { useNpubCash } from '@/hooks/useNpubCash';
import { useCashu } from '@/hooks/useCashu';
function ClaimFunds() {
const { quotes } = useNpubCash();
const { redeemMintQuote, addMint } = useCashu();
const claimQuote = async (quote: NpubCashQuote) => {
try {
// Add mint if not already added
await addMint(quote.mint_url);
// Redeem the quote to receive Cashu tokens
await redeemMintQuote(quote.mint_url, quote.quote_id);
alert(`Claimed ${quote.amount} sats!`);
} catch (error) {
console.error('Failed to claim:', error);
}
};
return (
<div>
{quotes.map(quote => (
<div key={quote.quote_id}>
<p>{quote.amount} sats</p>
<button onClick={() => claimQuote(quote)}>Claim</button>
</div>
))}
</div>
);
}
```
## Best Practices
### 1. Track Claimed Quotes
The hook stores `lastClaimedAt` timestamp in localStorage to track which quotes are new. Update this after claiming:
```tsx
const [lastClaimed, setLastClaimed] = useLocalStorage('npubcash-last-claimed', 0);
const claimAll = async () => {
for (const quote of quotes) {
await redeemMintQuote(quote.mint_url, quote.quote_id);
}
setLastClaimed(Date.now() / 1000);
};
```
### 2. Handle Expired Quotes
Quotes expire after a certain time. Filter expired quotes in your UI:
```tsx
const activeQuotes = quotes.filter(q =>
q.state === 'PAID' && q.expires_at > Date.now() / 1000
);
```
### 3. Poll for New Payments
Set up periodic polling to check for new payments:
```tsx
useEffect(() => {
const interval = setInterval(() => {
refresh();
}, 30000); // Every 30 seconds
return () => clearInterval(interval);
}, [refresh]);
```
### 4. Display QR Code for Address
Make it easy for users to receive payments by displaying a QR code:
```tsx
import QRCode from 'qrcode.react';
function AddressQR() {
const { lightningAddress } = useNpubCash();
return (
<div>
<QRCode value={`lightning:${lightningAddress}`} size={256} />
<p className="text-xs">{lightningAddress}</p>
</div>
);
}
```
## Error Handling
The hook provides error state for failed operations:
```tsx
function ErrorDisplay() {
const { error, clearAuth, refresh } = useNpubCash();
if (!error) return null;
const handleRetry = () => {
if (error.includes('Authentication')) {
clearAuth(); // Clear stale JWT
}
refresh(); // Try again
};
return (
<div className="bg-destructive/10 p-4 rounded">
<p className="text-sm text-destructive">{error}</p>
<button onClick={handleRetry}>Retry</button>
</div>
);
}
```
## Configuration
### Custom npub.cash Domain
If using a self-hosted npub.cash instance:
```tsx
// In useNpubCash.ts, modify:
const NPUBCASH_API_BASE = 'https://your-instance.com/api/v2';
const NPUBCASH_DOMAIN = 'your-instance.com';
```
## Troubleshooting
### "No user logged in" Error
Ensure the user is logged in via `useCurrentUser`:
```tsx
const { user } = useCurrentUser();
const npubCash = useNpubCash();
if (!user) {
return <p>Please log in first</p>;
}
```
### "NIP-98 validation failed"
Check that:
1. System clock is accurate (NIP-98 events must be recent)
2. URL matches exactly (no query params in NIP-98 event URL)
3. User's signer is working properly
### JWT Token Issues
If JWT tokens aren't working, clear and re-authenticate:
```tsx
const { clearAuth, refresh } = useNpubCash();
clearAuth();
await refresh(); // Will create new NIP-98 auth
```
## Related Documentation
- [Cashu Zap Integration](./CASHU_ZAP_INTEGRATION.md)
- [Nostr Comments System](./NOSTR_COMMENTS.md)
- [AI Chat Integration](./AI_CHAT.md)
## Additional Resources
- [npub.cash Documentation](https://npubx.cash/docs)
- [NIP-98: HTTP Auth](https://github.com/nostr-protocol/nips/blob/master/98.md)
- [Cashu Protocol](https://docs.cashu.space/)
- [NUT-20: Locked Tokens](https://github.com/cashubtc/nuts/blob/main/20.md)
---
**Built with MKStack** - The complete framework for building Nostr applications with AI.
+1222 -1547
View File
File diff suppressed because it is too large. Load diff
+1 -4
View File
@@ -15,9 +15,6 @@
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@scure/bip39": "^2.0.0",
"coco-cashu-core": "1.0.0-rc5",
"coco-cashu-indexeddb": "0.8.0",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -68,6 +65,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
@@ -82,7 +80,6 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"@webbtc/webln-types": "^3.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
-2
View File
@@ -4,7 +4,6 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { CashuWallet } from "./components/CashuWallet";
export function AppRouter() {
return (
@@ -12,7 +11,6 @@ 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 */}
-771
View File
@@ -1,771 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { QRModal } from '@/components/ui/qr-modal';
import { LoadingModal } from '@/components/wallet/LoadingModal';
import { BalanceDisplay } from '@/components/wallet/BalanceDisplay';
import { ReceiveCard } from '@/components/wallet/ReceiveCard';
import { SendCard } from '@/components/wallet/SendCard';
import { TransactionHistory } from '@/components/wallet/TransactionHistory';
import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal';
import { RemoveMintModal } from '@/components/wallet/RemoveMintModal';
export function CashuWallet() {
// ============================================================================
// HOOKS
// ============================================================================
const {
isInitialized,
isLoading,
error,
balances,
mints,
receive,
send,
getProofs,
addMint,
removeMint,
createMintQuote,
createMeltQuote,
payMeltQuote,
redeemMintQuote,
addMintQuote,
on,
refreshBalances,
refreshMints,
clearError,
getHistory,
} = useCashu();
const { getCleanMintLabel } = useCashuMints(null);
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// ============================================================================
// STATE - Input Values
// ============================================================================
const [tokenInput, setTokenInput] = useState('');
const [mintUrl, setMintUrl] = useState('');
const [sendAmount, setSendAmount] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
// ============================================================================
// STATE - UI State
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
// ============================================================================
// STATE - Transaction State
// ============================================================================
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
// ============================================================================
// STATE - History
// ============================================================================
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
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 [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
const [mintToRemove, setMintToRemove] = useState<{
url: string;
name?: string;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// HELPER FUNCTIONS - QR Code Generation
// ============================================================================
// Generate QR code for sent token
const generateSentTokenQRCode = async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
};
// ============================================================================
// HELPER FUNCTIONS - Mint Management
// ============================================================================
/**
* Set active mint
*/
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
}, []);
// ============================================================================
// HELPER FUNCTIONS - History
// ============================================================================
const loadHistory = useCallback(async () => {
try {
setIsLoadingHistory(true);
const entries = await getHistory(50, 0); //TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [getHistory]);
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
const handleReceive = async () => {
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
await receive(tokenInput);
setTokenInput('');
console.log('✅ Token received successfully!');
toast({
title: "Token Received",
description: "Cashu token redeemed successfully!",
});
} catch (err) {
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Receive Failed",
description: errorMessage,
});
}
} else {
// Lightning mode - create mint quote
if (!quoteAmount || !activeMintUrl) return;
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const quote = await 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);
console.log('✅ Mint quote created:', quote);
console.log('🔗 Lightning Invoice:', quote.request);
console.log('💡 Wallet will automatically redeem when payment is detected');
toast({
title: "Lightning Invoice Created",
description: "Wallet will automatically claim tokens when payment is detected.",
});
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event (note: hyphenated!)
console.log('🔔 Setting up payment listener for quote:', quote.quote);
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
console.log('🔔 Mint quote redeemed event received:', redeemedQuote);
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
console.log('✅ Our quote was redeemed! Payment detected:', redeemedQuote);
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) {
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Quote Creation Failed",
description: errorMessage,
});
}
}
};
// ============================================================================
// EVENT HANDLERS - Send
// ============================================================================
const handleSend = async () => {
if (mode === 'tokens') {
if (!sendAmount || !activeMintUrl) return;
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const encodedToken = await send(activeMintUrl, amount);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
console.log('✅ Token created successfully!');
console.log('📤 Encoded token:', encodedToken);
setSendAmount('');
} catch (err) {
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Send Failed",
description: errorMessage,
});
}
} else {
// Lightning mode
if (!activeMintUrl) return;
// 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;
}
console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount);
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
console.log('🔄 Creating melt quote for invoice:', invoice);
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
console.log('🔄 Paying melt quote:', meltQuote.quote);
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning payment sent successfully!');
toast({
title: "Payment Sent",
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Payment Failed",
description: errorMessage,
});
}
} 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('@')) {
console.log('📧 Detected Lightning address:', input);
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice
try {
console.log('🔄 Creating melt quote for invoice:', input);
const meltQuote = await createMeltQuote(activeMintUrl, input);
console.log('🔄 Paying melt quote:', meltQuote.quote);
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning invoice paid successfully!');
toast({
title: "Invoice Paid",
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
});
setLightningInvoice('');
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Invoice Payment Failed",
description: errorMessage,
});
}
}
}
}
};
// ============================================================================
// EVENT HANDLERS - Utility
// ============================================================================
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove) return;
try {
await removeMint(mintToRemove.url);
// Manually refresh mints since there's no mint:removed event
await refreshMints();
// If the removed mint was the active mint, select the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(m => m.url !== mintToRemove.url);
if (remainingMints.length > 0) {
setActiveMintUrl(remainingMints[0].url);
} else {
setActiveMintUrl(null);
}
}
toast({
title: "Mint Removed",
description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`,
});
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: "destructive",
title: "Remove Failed",
description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`,
});
}
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
const handleAddMint = async () => {
if (!mintUrl.trim()) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
normalizedUrl = `https://${normalizedUrl}`;
}
await addMint(normalizedUrl);
setMintUrl('');
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint added successfully:', normalizedUrl);
toast({
title: "Mint Added",
description: "Mint added successfully!",
});
} catch (err) {
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Add Mint Failed",
description: errorMessage,
});
}
};
// ============================================================================
// EVENT HANDLERS - Quote Management
// ============================================================================
const handleShowDenominations = async (mintUrl: string) => {
try {
console.log('🔍 Getting token denominations for mint:', mintUrl);
// Get proofs from the wallet for this specific mint
const proofs = await getProofs(mintUrl);
console.log('💰 Raw proofs for mint:', proofs);
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) {
console.error('Failed to get denominations:', err);
toast({
variant: "destructive",
title: "Failed to Get Denominations",
description: "Failed to get token denominations. Check console for details.",
});
}
};
// ============================================================================
// EFFECTS
// ============================================================================
// Show error toasts when errors occur
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
handleSetActiveMint(mints[0].url);
}
}, [mints, activeMintUrl, handleSetActiveMint]);
// Load transaction history when wallet is initialized
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh transaction history on new transactions
useEffect(() => {
if (!isInitialized) return;
console.log('📜 Setting up history auto-refresh listeners...');
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = on('history:updated', () => {
console.log('📜 History updated event, refreshing...');
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = on('melt-quote:created', () => {
console.log('📜 Melt quote created, refreshing history...');
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
console.log('📜 Melt quote paid, refreshing history...');
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
console.log('📜 Mint quote redeemed (invoice paid), refreshing history...');
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, on, loadHistory]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (component unmount)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================
// RENDER - Main UI
// ============================================================================
return (
<>
<LoadingModal isLoading={isLoading || !isInitialized} />
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
SECTION: Balance Display
======================================================================== */}
<BalanceDisplay
totalBalance={totalBalance}
balances={balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMint}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={handleShowDenominations}
getCleanMintLabel={getCleanMintLabel}
/>
{/* ========================================================================
SECTION: Receive & Send Cards
======================================================================== */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<ReceiveCard
mode={mode}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onReceive={handleReceive}
isLoading={isLoading}
/>
<SendCard
mode={mode}
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
activeMintUrl={activeMintUrl}
onSend={handleSend}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading}
/>
</div>
{/* ========================================================================
SECTION: Sent Token Display
======================================================================== */}
{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"
/>
)}
{/* ========================================================================
SECTION: Transaction History
======================================================================== */}
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
isExpanded={isHistoryExpanded}
setIsExpanded={setIsHistoryExpanded}
/>
{/* ========================================================================
SECTION: Modals
======================================================================== */}
<>
<ProofBreakdownModal
isOpen={showProofBreakdown}
onClose={() => setShowProofBreakdown(false)}
breakdown={proofBreakdown}
/>
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={''}
icon="qr"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
// Clean up event listener when modal is closed manually
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (modal closed)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
// Clean up event listener when invoice expires
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (invoice expired)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Show destructive toast
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}
/>
)}
<RemoveMintModal
isOpen={showRemoveMintModal}
onClose={() => setShowRemoveMintModal(false)}
mint={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading}
/>
</>
</div>
</>
);
}
+23 -63
View File
@@ -1,5 +1,5 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X, Coins } from 'lucide-react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -26,13 +26,11 @@ import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
import type { WebLNProvider } from "@webbtc/webln-types";
interface LightningWalletModalProps {
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
@@ -70,65 +68,30 @@ AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
webln: WebLNProvider | null;
hasWebLN: boolean;
isDetecting: boolean;
hasNWC: boolean;
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;
}>(({
webln,
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Primary Payment Method - Cashu */}
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Primary Payment Method</h3>
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
<div className="flex items-center gap-3">
<Coins className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Cashu Wallet</p>
<p className="text-xs text-muted-foreground">
{isCashuInitialized
? `${cashuBalance.toLocaleString()} sats available`
: "Instant Bitcoin payments"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isCashuInitialized && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={isCashuInitialized ? "default" : "secondary"} className="text-xs">
{isCashuInitialized ? "Active" : "Not Set Up"}
</Badge>
</div>
</div>
<div className="text-xs text-muted-foreground text-center">
Cashu tokens are used first for Lightning zaps. Set up your Cashu wallet for instant payments.
</div>
</div>
<Separator />
{/* Lightning Fallback Methods */}
<div className="space-y-3">
<h3 className="font-medium">Lightning Fallback Methods</h3>
<div className="text-xs text-muted-foreground mb-3">
Used when Cashu balance is insufficient or unavailable
</div>
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
@@ -140,9 +103,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
</div>
</div>
<div className="flex items-center gap-2">
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
{webln ? "Ready" : "Not Found"}
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
@@ -228,12 +191,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!isCashuInitialized && !webln && connections.length === 0 && (
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning fallback.
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
@@ -242,7 +205,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
));
WalletContent.displayName = 'WalletContent';
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
@@ -259,11 +222,9 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
setActiveConnection
} = useNWC();
const { webln } = useWallet();
const { balances, isInitialized: isCashuInitialized } = useCashu();
const { hasWebLN, isDetecting } = useWallet();
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 () => {
@@ -302,13 +263,12 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
};
const walletContentProps = {
webln,
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
@@ -350,7 +310,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
Wallet Settings
</Button>
)}
</DrawerTrigger>
@@ -364,10 +324,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Payment Settings
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Manage Cashu wallet and Lightning fallback methods for zaps.
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
@@ -412,7 +372,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Payment Settings
Wallet Settings
</Button>
)}
</DialogTrigger>
@@ -420,10 +380,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Payment Settings
Lightning Wallet
</DialogTitle>
<DialogDescription>
Manage Cashu wallet and Lightning fallback methods for zaps.
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
+21 -528
View File
@@ -1,40 +1,10 @@
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 { useToast } from '@/hooks/useToast';
import { ZapDialog } from '@/components/ZapDialog';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapButtonProps {
target: Event;
@@ -43,276 +13,15 @@ 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(
@@ -321,245 +30,29 @@ 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;
}
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>
);
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
<div className="flex items-center gap-1">
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
canPayWithCashu
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
<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>
);
}
+21 -98
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
@@ -30,11 +30,9 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapDialogProps {
target: Event;
@@ -57,10 +55,7 @@ interface ZapContentProps {
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
// Cashu-related props
canPayWithCashu: boolean;
cashuBalance: number;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
@@ -78,9 +73,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
@@ -145,33 +138,8 @@ 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 && (
{hasWebLN && (
<Button
variant="outline"
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
@@ -196,26 +164,13 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
</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."
}
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"
@@ -232,7 +187,6 @@ 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>
@@ -252,7 +206,6 @@ 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"
@@ -264,19 +217,9 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
/>
</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"
>
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
{isZapping ? (
'Creating Lightning invoice...'
) : canPayWithCashu ? (
<>
<Coins className="h-4 w-4 mr-2" />
Zap {amount} sats (Cashu → Lightning)
</>
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
@@ -291,14 +234,14 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC } = useWallet();
const { webln, activeNWC, hasWebLN, detectWebLN } = 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);
@@ -306,16 +249,19 @@ 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!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
@@ -389,25 +335,6 @@ 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);
};
@@ -418,9 +345,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
isZapping,
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
@@ -502,9 +427,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{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!'
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
@@ -532,9 +455,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
{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!'
<>
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
</>
)}
</DialogDescription>
</DialogHeader>
+4 -4
View File
@@ -11,7 +11,7 @@ import {
} 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 { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -64,15 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<LightningWalletModal>
<WalletModal>
<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>
<span>Wallet Settings</span>
</DropdownMenuItem>
</LightningWalletModal>
</WalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
-143
View File
@@ -1,143 +0,0 @@
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 > 20 ? `${content.substring(0, 20)}...` : 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
View File
@@ -47,7 +47,6 @@ const Toast = React.forwardRef<
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
duration={5000}
{...props}
/>
)
-192
View File
@@ -1,192 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Wallet, ChevronDown, Plus, X, Zap, Coins, HelpCircle } from 'lucide-react';
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
interface CashuMint {
url: string;
name?: string;
}
interface BalanceDisplayProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning';
setMode: (mode: 'tokens' | 'lightning') => void;
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;
}
export function BalanceDisplay({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
}: BalanceDisplayProps) {
const { convertCurrency } = useCashuBalances(null);
return (
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-5xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
>
{convertCurrency(totalBalance, showSats)}
</button>
</div>
{/* Main Mode Toggle */}
<div className="mt-4 flex items-center justify-center">
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setMode('tokens')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-4 w-4" />
Cashu
</button>
<button
onClick={() => setMode('lightning')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-4 w-4" />
Lightning
</button>
</div>
</div>
{/* Active Mint Dropdown and Balance */}
<div className="mt-3 flex items-center justify-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
<Wallet className="h-4 w-4" />
{activeMintUrl ? getCleanMintLabel({ url: activeMintUrl }) : 'Select Mint'}
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="w-72">
{mints.length === 0 && (
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
)}
{mints
.filter((mint) => mint.url)
.map((mint, index) => (
<DropdownMenuItem
key={`dd-mint-${mint.url || `unknown-${index}`}`}
className="flex items-center justify-between"
onClick={() => setActiveMintUrl(mint.url)}
>
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint)}</span>
</div>
<Button
size="sm"
variant="ghost"
className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
>
<X className="h-3 w-3" />
</Button>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<div className="px-2 py-1.5">
<div className="flex gap-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="h-8"
/>
<Button size="sm" onClick={onAddMint} disabled={!mintUrl.trim()}>
<Plus className="h-3.5 w-3.5 mr-1" />
Add
</Button>
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
{/* Active Mint Balance */}
{activeMintUrl && (
<div className="flex items-center gap-2">
<button
onClick={() => activeMintUrl && onShowDenominations(activeMintUrl)}
className="text-sm font-semibold tabular-nums hover:opacity-80 transition-opacity cursor-pointer text-muted-foreground hover:text-foreground"
title="Click to see proof breakdown"
>
{convertCurrency(balances[activeMintUrl] || 0, showSats)}
</button>
{/* Help button */}
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground">
<HelpCircle className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
What is a Mint?
</DialogTitle>
<DialogDescription className="space-y-3 text-left">
<p>
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
</p>
<p>
<strong>Key features:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-4">
<li>Issues tokens when you deposit Lightning payments</li>
<li>Redeems tokens when you receive them</li>
<li>Manages your token balance</li>
<li>Enables Lightning ↔ Cashu conversions</li>
</ul>
<p>
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
</p>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
)}
</div>
</div>
);
}
-21
View File
@@ -1,21 +0,0 @@
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
interface LoadingModalProps {
isLoading: boolean;
}
export function LoadingModal({ isLoading }: LoadingModalProps) {
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" />
<span className="text-lg font-medium">Loading</span>
</CardContent>
</Card>
</div>
);
}
@@ -1,82 +0,0 @@
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 } from 'lucide-react';
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface ProofBreakdownModalProps {
isOpen: boolean;
onClose: () => void;
breakdown: ProofBreakdown | null;
}
export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) {
const { convertCurrency } = useCashuBalances(null);
if (!isOpen || !breakdown) return null;
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">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(breakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{convertCurrency(breakdown.totalBalance)}
</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(breakdown.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>
);
}
-98
View File
@@ -1,98 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Download, Zap } from 'lucide-react';
interface ReceiveCardProps {
mode: 'tokens' | 'lightning';
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
activeMintUrl: string | null;
onReceive: () => void;
isLoading: boolean;
}
export function ReceiveCard({
mode,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onReceive,
isLoading,
}: ReceiveCardProps) {
return (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
</CardTitle>
<CardDescription className="min-h-[2.5rem] flex items-center">
{mode === 'tokens'
? 'Enter Cashu token to redeem'
: 'Deposit funds with Lightning'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to receive tokens
</div>
)}
<div className="flex gap-2">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button onClick={onReceive} disabled={!tokenInput.trim() || !activeMintUrl || isLoading}>
<Download className="h-4 w-4 mr-2" />
Receive
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to create Lightning invoice
</div>
)}
<div className="flex gap-2">
<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}
/>
<Button onClick={onReceive} disabled={!quoteAmount || !activeMintUrl || isLoading}>
<Zap className="h-4 w-4 mr-2" />
Quote
</Button>
</div>
</>
)}
</CardContent>
</Card>
);
}
-83
View File
@@ -1,83 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertTriangle, X, RefreshCw } from 'lucide-react';
interface MintToRemove {
url: string;
name?: string;
}
interface RemoveMintModalProps {
isOpen: boolean;
onClose: () => void;
mint: MintToRemove | null;
onConfirm: () => void;
isLoading: boolean;
}
export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }: RemoveMintModalProps) {
if (!isOpen || !mint) return null;
return (
<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={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">
<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">{mint.name || new URL(mint.url).hostname}</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{mint.url}
</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={onClose}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
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>
);
}
-183
View File
@@ -1,183 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Send, Zap, Loader2, X } from 'lucide-react';
interface SendCardProps {
mode: 'tokens' | 'lightning';
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;
activeMintUrl: string | null;
onSend: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
}
export function SendCard({
mode,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
activeMintUrl,
onSend,
isResolvingAddress,
isLoading,
}: SendCardProps) {
return (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
</CardTitle>
<CardDescription className="min-h-[2.5rem] flex items-center">
{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 Lightning invoices or addresses from balance'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to send tokens
</div>
)}
<div className="flex gap-2">
<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}
/>
<Button onClick={onSend} disabled={!sendAmount || !activeMintUrl || isLoading}>
<Send className="h-4 w-4 mr-2" />
Send
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to pay Lightning invoices
</div>
)}
{pendingLightningAddress ? (
// Step 2: Show amount input for Lightning address
<div className="space-y-3">
<div className="flex gap-2">
<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();
}
}}
autoFocus
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
>
{isResolvingAddress ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending...
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
)}
</Button>
<Button
variant="outline"
size="icon"
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="h-10 w-10"
title="Cancel"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
) : (
// Step 1: Show invoice/address input
<div className="flex gap-2">
<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();
}
}}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
>
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
</Button>
</div>
)}
</>
)}
</CardContent>
</Card>
);
}
@@ -1,173 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
import type { HistoryEntry } from '@/hooks/useCashu';
interface TransactionHistoryProps {
entries: HistoryEntry[];
isLoading: boolean;
isExpanded: boolean;
setIsExpanded: (expanded: boolean) => void;
}
export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpanded }: 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':
return 'Mint Tokens';
case 'melt':
return 'Melt Tokens';
case 'send':
return 'Send Tokens';
case 'receive':
return 'Receive Tokens';
default:
return type;
}
};
const getHistoryStateColor = (state?: string) => {
if (!state) return 'bg-gray-500';
switch (state) {
case 'PAID':
return 'bg-green-500';
case 'UNPAID':
return 'bg-yellow-500';
case 'PENDING':
return 'bg-blue-500';
default:
return 'bg-gray-500';
}
};
return (
<Card className="mt-6 border-0 shadow-none">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<History className="h-5 w-5 mr-2" />
Transaction History
</div>
{entries.length > 3 && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsExpanded(!isExpanded)}
className="gap-1"
>
{isExpanded ? (
<>
<ChevronUp className="h-4 w-4" />
Hide
</>
) : (
<>
<ChevronDown className="h-4 w-4" />
Show
</>
)}
</Button>
)}
</CardTitle>
<CardDescription>
View your recent transactions
</CardDescription>
</CardHeader>
<CardContent>
{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 transaction history yet
</div>
) : (
<div className="space-y-2">
{(isExpanded ? entries : entries.slice(0, 3)).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>
{entry.state && entry.type !== 'mint' && entry.type !== 'melt' && (
<Badge
variant="secondary"
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
>
{entry.state}
</Badge>
)}
</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>
)}
</CardContent>
</Card>
);
}
-25
View File
@@ -1,25 +0,0 @@
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;
}
-102
View File
@@ -1,102 +0,0 @@
import { useMemo } from 'react';
import { useCashuManager } from './useCashuManager';
import { useCashuBalances } from './useCashuBalances';
import { useCashuMints } from './useCashuMints';
import { useCashuQuotes } from './useCashuQuotes';
import { useCashuWallet } from './useCashuWallet';
import { useCashuHistory } from './useCashuHistory';
import { useCashuSubscriptions } from './useCashuSubscriptions';
import { useCashuManagerOperations } from './useCashuManagerOperations';
import { UseCashuReturn, CashuWalletError } from './types';
export function useCashu(): UseCashuReturn {
const manager = useCashuManager();
const balances = useCashuBalances(manager.manager);
const mints = useCashuMints(manager.manager);
const quotes = useCashuQuotes(manager.manager, manager.repositories);
const wallet = useCashuWallet(manager.manager, manager.repositories);
const history = useCashuHistory(manager.manager);
const subscriptions = useCashuSubscriptions(manager.manager);
const managerOperations = useCashuManagerOperations(manager.manager);
// Combine all errors into a single error state
const combinedError = useMemo(() => {
const errors = [
manager.error,
balances.error,
mints.error,
quotes.error,
wallet.error,
history.error,
subscriptions.error,
managerOperations.error,
].filter(Boolean) as CashuWalletError[];
return errors.length > 0 ? errors[0] : null;
}, [manager.error, balances.error, mints.error, quotes.error, wallet.error, history.error, subscriptions.error, managerOperations.error]);
// Combine all loading states
const combinedIsLoading = useMemo(() => {
return manager.isLoading || balances.isLoading || mints.isLoading || quotes.isLoading || wallet.isLoading || history.isLoading || subscriptions.isLoading || managerOperations.isLoading;
}, [manager.isLoading, balances.isLoading, mints.isLoading, quotes.isLoading, wallet.isLoading, history.isLoading, subscriptions.isLoading, managerOperations.isLoading]);
return {
// State
isInitialized: manager.isInitialized,
isLoading: combinedIsLoading,
error: combinedError,
balances: balances.balances,
mints: mints.mints,
mnemonic: manager.mnemonic,
// Actions
// Wallet operations
receive: wallet.receive,
send: wallet.send,
getBalances: balances.getBalances,
getProofs: wallet.getProofs,
// Mint operations
addMint: mints.addMint,
removeMint: mints.removeMint,
getMints: mints.getMints,
// Quote operations
createMintQuote: quotes.createMintQuote,
redeemMintQuote: quotes.redeemMintQuote,
createMeltQuote: quotes.createMeltQuote,
payMeltQuote: quotes.payMeltQuote,
addMintQuote: quotes.addMintQuote,
// Subscription operations
awaitMintQuotePaid: subscriptions.awaitMintQuotePaid,
awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid,
// Manager operations
enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher,
disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher,
enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor,
disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor,
waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor,
enableProofStateWatcher: managerOperations.enableProofStateWatcher,
disableProofStateWatcher: managerOperations.disableProofStateWatcher,
// Event operations
on: managerOperations.on,
once: managerOperations.once,
off: managerOperations.off,
// Mnemonic operations
setMnemonic: manager.setMnemonic,
generateMnemonic: manager.generateMnemonic,
getMnemonic: manager.getMnemonic,
// History operations
getHistory: history.getHistory,
// Utility operations
refreshBalances: balances.refreshBalances,
refreshMints: mints.refreshMints,
clearError: manager.clearError,
};
}
-142
View File
@@ -1,142 +0,0 @@
// Error types that align with coco-cashu patterns
export class CashuWalletError extends Error {
constructor(message: string, public code: string, public details?: unknown) {
super(message);
this.name = 'CashuWalletError';
}
}
export class CashuInitializationError extends CashuWalletError {
constructor(message: string, details?: unknown) {
super(message, 'INITIALIZATION_ERROR', details);
}
}
export class CashuMintError extends CashuWalletError {
constructor(message: string, mintUrl: string, details?: unknown) {
super(message, 'MINT_ERROR', details);
this.mintUrl = mintUrl;
}
public mintUrl: string;
}
export class CashuQuoteError extends CashuWalletError {
constructor(message: string, quoteId: string, details?: unknown) {
super(message, 'QUOTE_ERROR', details);
this.quoteId = quoteId;
}
public quoteId: string;
}
export class CashuTokenError extends CashuWalletError {
constructor(message: string, token?: string, details?: unknown) {
super(message, 'TOKEN_ERROR', details);
this.token = token;
}
public token?: string;
}
// Core types
export interface CashuBalance {
[mintUrl: string]: number;
}
export interface CashuMint {
url: string;
name?: string;
info?: Record<string, unknown>;
}
export interface CashuMintQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuMeltQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuToken {
mint: string;
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
}
export interface HistoryEntry {
id: string;
type: 'mint' | 'melt' | 'send' | 'receive';
mintUrl: string;
amount: number;
unit: string;
createdAt: number;
metadata?: Record<string, unknown>;
quoteId?: string;
state?: string;
paymentRequest?: string;
token?: CashuToken;
}
// Hook state types
export interface CashuState {
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
balances: CashuBalance;
mints: CashuMint[];
mnemonic: string | null;
}
export interface CashuActions {
// Wallet operations
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getBalances: () => Promise<CashuBalance>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
// Mint operations
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getMints: () => Promise<CashuMint[]>;
// Quote operations
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
// Subscription operations (NEW)
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
// Manager operations (NEW)
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
disableMintQuoteWatcher: () => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
disableMintQuoteProcessor: () => Promise<void>;
waitForMintQuoteProcessor: () => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
disableProofStateWatcher: () => Promise<void>;
// Event operations (NEW)
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
// Mnemonic operations
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
// History operations
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
// Utility operations
refreshBalances: () => Promise<void>;
refreshMints: () => Promise<void>;
clearError: () => void;
}
export type UseCashuReturn = CashuState & CashuActions;
-204
View File
@@ -1,204 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { CashuBalance, CashuWalletError } from './types';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { toast } from '../useToast';
export interface UseCashuBalancesReturn {
balances: CashuBalance;
isLoading: boolean;
error: CashuWalletError | null;
refreshBalances: () => Promise<void>;
getBalances: () => Promise<CashuBalance>;
convertCurrency: (sats: number, showSats?: boolean) => string;
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
}
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
const [balances, setBalances] = useState<CashuBalance>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 200;
const refreshBalances = useCallback(async () => {
if (!manager) return;
// Prevent concurrent calls
if (isRefreshingRef.current) {
console.log('⏭️ refreshBalances: Skipping (already in progress)');
return;
}
// Throttle rapid successive calls
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
console.log('⏭️ refreshBalances: Skipping (throttled)');
return;
}
isRefreshingRef.current = true;
lastRefreshTimeRef.current = now;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
// Only update state if balances actually changed (deep comparison)
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ refreshBalances: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balances';
setError(new CashuWalletError(errorMessage, 'BALANCE_REFRESH_ERROR', { originalError: err }));
} finally {
isRefreshingRef.current = false;
}
}, [manager]);
const getBalances = useCallback(async (): Promise<CashuBalance> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
return await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
const cashuError = new CashuWalletError(errorMessage, 'GET_BALANCES_ERROR', { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
// Set up event listeners for automatic balance updates using coco events
useEffect(() => {
if (!manager) return;
const unsubscribeProofsSaved = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:saved', () => {
console.log('📨 Proofs saved, refreshing balances...');
refreshBalances();
});
const unsubscribeProofsStateChanged = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:state-changed', () => {
console.log('🔄 Proofs state changed, refreshing balances...');
refreshBalances();
});
const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => {
console.log('📤 Send created, refreshing balances...');
// Bypass throttling for send operations to ensure immediate balance update
setTimeout(async () => {
if (!manager) return;
try {
console.log('🔄 send:created: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 send:created: Raw balances from wallet:', newBalances);
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ send:created: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ send:created: Failed to refresh balances:', err);
}
}, 100);
});
const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('receive:created', () => {
console.log('📥 Receive created, refreshing balances...');
refreshBalances();
});
return () => {
unsubscribeProofsSaved();
unsubscribeProofsStateChanged();
unsubscribeSendCreated();
unsubscribeReceiveCreated();
};
}, [manager, refreshBalances]);
// Initial balance load
useEffect(() => {
if (manager && Object.keys(balances).length === 0) {
refreshBalances();
}
}, [manager, balances, refreshBalances]);
// Fetch exchange rate on mount for fallback
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setFallbackRate(rate))
.catch(error => {
console.warn('Failed to fetch initial exchange rate:', error);
// Keep fallbackRate as null to show sats instead of USD
});
}, []);
const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
// Only show USD if we have a valid exchange rate
if (fallbackRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * fallbackRate;
return `$${usd.toFixed(2)}`;
} else {
// If no exchange rate available, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, [fallbackRate]);
const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise<string> => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
try {
const usd = await exchangeRateService.satsToUsd(sats);
return `$${usd.toFixed(2)}`;
} catch (error) {
console.warn('Failed to fetch exchange rate:', error);
// If exchange rate fails, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, []);
return {
balances,
isLoading,
error,
refreshBalances,
getBalances,
convertCurrency,
convertCurrencyAsync,
};
}
-42
View File
@@ -1,42 +0,0 @@
import { useState, useCallback } from 'react';
import { HistoryEntry, CashuWalletError } from './types';
export interface UseCashuHistoryReturn {
isLoading: boolean;
error: CashuWalletError | null;
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
}
export function useCashuHistory(manager: unknown | null): UseCashuHistoryReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise<HistoryEntry[]> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('📜 Getting transaction history...');
const entries = await (manager as { history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> } }).history.getPaginatedHistory(offset, limit);
console.log(`✅ Found ${entries.length} history entries`);
return entries as unknown as HistoryEntry[];
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
console.error('❌ Error getting history:', err);
const cashuError = new CashuWalletError(errorMessage, 'GET_HISTORY_ERROR', { limit, offset, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
return {
isLoading,
error,
getHistory,
};
}
-167
View File
@@ -1,167 +0,0 @@
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 { CashuInitializationError, CashuWalletError } from './types';
// Dynamic imports for coco-cashu packages
let Manager: unknown = null;
let IndexedDbRepositories: unknown = null;
let ConsoleLogger: unknown = null;
let getEncodedToken: unknown = null;
let _getDecodedToken: unknown = null;
// Lazy load coco-cashu packages
const loadCocoCashu = async () => {
if (Manager) return; // Already loaded
try {
const coreModule = await import('coco-cashu-core');
const indexedDbModule = await import('coco-cashu-indexeddb');
Manager = coreModule.Manager;
ConsoleLogger = coreModule.ConsoleLogger;
getEncodedToken = coreModule.getEncodedToken;
_getDecodedToken = coreModule.getDecodedToken;
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
} catch (error) {
console.error('Failed to load coco-cashu packages:', error);
throw new CashuInitializationError(
'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb',
{ error }
);
}
};
export interface UseCashuManagerReturn {
manager: unknown | null;
repositories: unknown | null;
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
clearError: () => void;
}
export function useCashuManager(): UseCashuManagerReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance refs
const managerRef = useRef<unknown>(null);
const repositoriesRef = useRef<unknown>(null);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const getMnemonic = useCallback(() => {
return mnemonic;
}, [mnemonic]);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the manager
const initializeManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
await loadCocoCashu();
// 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
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
await repositories.init();
repositoriesRef.current = repositories;
// Initialize manager
const manager = new (Manager as new (
repositories: unknown,
seedGetter: () => Promise<Uint8Array>,
logger?: unknown
) => {
wallet: { getBalances: () => Promise<Record<string, number>>; receive: (token: string | unknown) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<unknown> };
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<unknown>; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>; createMeltQuote: (mintUrl: string, invoice: string) => Promise<unknown>; payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> };
history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> };
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
})(
repositories,
async () => seed,
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
);
managerRef.current = manager;
// Enable built-in services for automatic quote processing and state watching
try {
await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true });
await manager.enableMintQuoteProcessor();
await manager.enableProofStateWatcher();
console.log('✅ Enabled coco-cashu watcher services');
} catch (err) {
console.warn('⚠️ Failed to enable some watcher services:', err);
// Don't fail initialization if watchers can't be enabled
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err });
setError(cashuError);
console.error('Cashu initialization error:', err);
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeManager();
}, [initializeManager]);
return {
manager: managerRef.current,
repositories: repositoriesRef.current,
isInitialized,
isLoading,
error,
mnemonic,
setMnemonic,
generateMnemonic,
getMnemonic,
clearError,
};
}
@@ -1,147 +0,0 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuManagerOperationsReturn {
isLoading: boolean;
error: CashuWalletError | null;
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
disableMintQuoteWatcher: () => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
disableMintQuoteProcessor: () => Promise<void>;
waitForMintQuoteProcessor: () => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
disableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
}
export function useCashuManagerOperations(manager: unknown | null): UseCashuManagerOperationsReturn {
const isLoading = false; // Manager operations are typically async but don't have loading states
const error = null; // Errors are handled per-operation
const enableMintQuoteWatcher = useCallback(async (options?: { watchExistingPendingOnStart?: boolean }) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void> }).enableMintQuoteWatcher(options);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteWatcher', originalError: err });
}
}, [manager]);
const disableMintQuoteWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableMintQuoteWatcher: () => Promise<void> }).disableMintQuoteWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteWatcher', originalError: err });
}
}, [manager]);
const enableMintQuoteProcessor = useCallback(async (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void> }).enableMintQuoteProcessor(options);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteProcessor', originalError: err });
}
}, [manager]);
const disableMintQuoteProcessor = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableMintQuoteProcessor: () => Promise<void> }).disableMintQuoteProcessor();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteProcessor', originalError: err });
}
}, [manager]);
const waitForMintQuoteProcessor = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { waitForMintQuoteProcessor: () => Promise<void> }).waitForMintQuoteProcessor();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to wait for mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'waitForMintQuoteProcessor', originalError: err });
}
}, [manager]);
const enableProofStateWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableProofStateWatcher: () => Promise<void> }).enableProofStateWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable proof state watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableProofStateWatcher', originalError: err });
}
}, [manager]);
const disableProofStateWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableProofStateWatcher: () => Promise<void> }).disableProofStateWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable proof state watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableProofStateWatcher', originalError: err });
}
}, [manager]);
const on = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'on', event, originalError: err });
}
}, [manager]);
const once = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).once(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add one-time event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'once', event, originalError: err });
}
}, [manager]);
const off = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
(manager as { off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void }).off(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to remove event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'off', event, originalError: err });
}
}, [manager]);
return {
isLoading,
error,
enableMintQuoteWatcher,
disableMintQuoteWatcher,
enableMintQuoteProcessor,
disableMintQuoteProcessor,
waitForMintQuoteProcessor,
enableProofStateWatcher,
disableProofStateWatcher,
on,
once,
off,
};
}
-174
View File
@@ -1,174 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { CashuMint, CashuWalletError } from './types';
export interface UseCashuMintsReturn {
mints: CashuMint[];
isLoading: boolean;
error: CashuWalletError | null;
refreshMints: () => Promise<void>;
getMints: () => Promise<CashuMint[]>;
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
}
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
const [mints, setMints] = useState<CashuMint[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const refreshMints = useCallback(async () => {
if (!manager) return;
try {
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
const formattedMints = mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
// If no mints exist, add the default mint
if (formattedMints.length === 0) {
console.log('🔧 No mints found, adding default mint: mint.chorus.community');
try {
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint('https://mint.chorus.community');
// The mint:added event will trigger refreshMints again, so we don't need to set mints here
return;
} catch (err) {
console.warn('⚠️ Failed to add default mint:', err);
// Continue with empty mints if default mint fails
}
}
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh mints';
setError(new CashuWalletError(errorMessage, 'MINT_REFRESH_ERROR', { originalError: err }));
}
}, [manager]);
const getMints = useCallback(async (): Promise<CashuMint[]> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
return mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get mints';
const cashuError = new CashuWalletError(errorMessage, 'GET_MINTS_ERROR', { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const addMint = useCallback(async (mintUrl: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint(mintUrl);
// No need to manually refresh - events will handle it automatically
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
const cashuError = new CashuWalletError(errorMessage, 'ADD_MINT_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const removeMint = useCallback(async (mintUrl: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
// Access the mintService directly through the manager to use deleteMint
// The manager has a private mintService property that we can access
const mintService = (manager as any).mintService;
if (!mintService || typeof mintService.deleteMint !== 'function') {
throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR');
}
await mintService.deleteMint(mintUrl);
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint removed successfully:', mintUrl);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint';
const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
// Set up event listeners for automatic mint updates using coco events
useEffect(() => {
if (!manager) return;
const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:added', () => {
console.log('➕ Mint added, refreshing mints...');
refreshMints();
});
const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:updated', () => {
console.log('🔄 Mint updated, refreshing mints...');
refreshMints();
});
return () => {
unsubscribeMintAdded();
unsubscribeMintUpdated();
};
}, [manager, refreshMints]);
// Initial mints load
useEffect(() => {
if (manager && mints.length === 0) {
refreshMints();
}
}, [manager, mints.length, refreshMints]);
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
// If name looks like a URL, strip protocol as well
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host; // host excludes protocol and preserves port if any
} catch {
// Fallback: manual strip
return mint.url.replace(/^https?:\/\//, '');
}
}, []);
return {
mints,
isLoading,
error,
refreshMints,
getMints,
addMint,
removeMint,
getCleanMintLabel,
};
}
-156
View File
@@ -1,156 +0,0 @@
import { useState, useCallback } from 'react';
import { CashuMintQuote, CashuMeltQuote, CashuWalletError, CashuQuoteError } from './types';
export interface UseCashuQuotesReturn {
isLoading: boolean;
error: CashuWalletError | null;
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
}
export function useCashuQuotes(manager: unknown | null, repositories: unknown | null): UseCashuQuotesReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const quote = await (manager as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote> } }).quotes.createMintQuote(mintUrl, amount);
return {
quote: quote.quote,
request: quote.request,
expiry: quote.expiry
};
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote';
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, amount, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length);
console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl);
await (manager as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
console.log('✅ redeemMintQuote: Quote redeemed successfully');
} catch (err) {
console.error('❌ redeemMintQuote: Error details:', {
message: err instanceof Error ? err.message : 'Unknown error',
mintUrl,
quoteId,
quoteIdType: typeof quoteId,
quoteIdLength: quoteId.length
});
const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote';
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId });
// Access the mint quote repository
const mintQuoteRepo = (repositories as {
mintQuoteRepository?: {
addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise<void>
}
})?.mintQuoteRepository;
if (!mintQuoteRepo) {
throw new CashuWalletError('Mint quote repository not available', 'REPOSITORY_NOT_AVAILABLE');
}
// Add the quote to the repository with UNPAID state
// The mint processor will check and redeem it
await mintQuoteRepo.addMintQuote({
quote: quoteId,
mintUrl: mintUrl,
state: 'UNPAID', // Mark as UNPAID so coco will check it
});
console.log('✅ Mint quote added to repository successfully');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote';
console.error('❌ Error adding mint quote:', err);
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager, repositories]);
const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise<CashuMeltQuote> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const quote = await (manager as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote> } }).quotes.createMeltQuote(mintUrl, invoice);
return {
quote: quote.quote,
request: quote.request,
expiry: quote.expiry
};
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote';
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, invoice, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.payMeltQuote(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
return {
isLoading,
error,
createMintQuote,
redeemMintQuote,
createMeltQuote,
payMeltQuote,
addMintQuote,
};
}
-43
View File
@@ -1,43 +0,0 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuSubscriptionsReturn {
isLoading: boolean;
error: CashuWalletError | null;
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
}
export function useCashuSubscriptions(manager: unknown | null): UseCashuSubscriptionsReturn {
const isLoading = false; // Subscription operations are typically async but don't have loading states
const error = null; // Errors are handled per-operation
const awaitMintQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMintQuotePaid(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to await mint quote payment';
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
}
}, [manager]);
const awaitMeltQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMeltQuotePaid(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to await melt quote payment';
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
}
}, [manager]);
return {
isLoading,
error,
awaitMintQuotePaid,
awaitMeltQuotePaid,
};
}
-108
View File
@@ -1,108 +0,0 @@
import { useState, useCallback } from 'react';
import { CashuToken, CashuWalletError, CashuTokenError } from './types';
// Dynamic import for getEncodedToken
let getEncodedToken: unknown = null;
const loadGetEncodedToken = async () => {
if (getEncodedToken) return;
try {
const coreModule = await import('coco-cashu-core');
getEncodedToken = coreModule.getEncodedToken;
} catch (error) {
console.error('Failed to load getEncodedToken:', error);
}
};
export interface UseCashuWalletReturn {
isLoading: boolean;
error: CashuWalletError | null;
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
}
export function useCashuWallet(manager: unknown | null, repositories: unknown | null): UseCashuWalletReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const receive = useCallback(async (token: string | CashuToken) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).wallet.receive(token);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
const cashuError = new CashuTokenError(errorMessage, typeof token === 'string' ? token : undefined, { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const send = useCallback(async (mintUrl: string, amount: number): Promise<string> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
// Load getEncodedToken if not already loaded
await loadGetEncodedToken();
const token = await (manager as { wallet: { send: (mintUrl: string, amount: number) => Promise<CashuToken> } }).wallet.send(mintUrl, amount);
// Encode the token into a Cashu token string
const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token);
return encodedToken;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
const cashuError = new CashuWalletError(errorMessage, 'SEND_ERROR', { mintUrl, amount, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const getProofs = useCallback(async (mintUrl: string): Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
// Access the proof repository
const proofRepo = (repositories as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise<Array<Record<string, unknown>>> } })?.proofRepository;
if (!proofRepo) {
throw new CashuWalletError('Proof repository not available', 'REPOSITORY_NOT_AVAILABLE');
}
// Get ready proofs for this mint (proofs available to spend)
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`);
return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
console.error('❌ Error getting proofs:', err);
const cashuError = new CashuWalletError(errorMessage, 'GET_PROOFS_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager, repositories]);
return {
isLoading,
error,
receive,
send,
getProofs,
};
}
-17
View File
@@ -1,17 +0,0 @@
// Re-export the new modular useCashu hook and types
export { useCashu } from './cashu/index';
export type {
UseCashuReturn,
CashuBalance,
CashuMint,
CashuMintQuote,
CashuMeltQuote,
CashuToken,
HistoryEntry,
CashuWalletError,
CashuInitializationError,
CashuMintError,
CashuQuoteError,
CashuTokenError
} from './cashu/types';
-52
View File
@@ -1,52 +0,0 @@
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,
};
}
-159
View File
@@ -1,159 +0,0 @@
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}`;
const lnurlResponse = await fetch(lnurlEndpoint, {
headers: { 'Accept': 'application/json' },
});
if (!lnurlResponse.ok) {
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status}`);
}
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
if (lnurlData.status !== 'OK') {
throw new Error('LNURL endpoint returned error status');
}
if (lnurlData.tag !== 'payRequest') {
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
}
// Validate amount against min/max bounds
const minSats = lnurlData.minSendable / 1000;
const maxSats = lnurlData.maxSendable / 1000;
if (amountSats < minSats) {
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
}
if (amountSats > 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);
}
const invoiceResponse = await fetch(callbackUrl.toString(), {
headers: { 'Accept': 'application/json' },
});
if (!invoiceResponse.ok) {
throw new Error(`Failed to get invoice: ${invoiceResponse.status}`);
}
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
if (invoiceData.status !== 'OK') {
throw new Error(invoiceData.reason || 'Invoice generation failed');
}
if (!invoiceData.pr) {
throw new Error('No invoice returned from provider');
}
setIsLoading(false);
return invoiceData.pr;
} 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 };
+615
View File
@@ -0,0 +1,615 @@
import { useState, useCallback } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
// Your VAPID public key
const VAPID_PUBLIC_KEY = 'BIur4J9v796yU2ZUhaka6exwLAKUhAnDv0zJhrf_T1yuFs4jh4g8IaYygGAJ7u1KxZdu2Dwxh1ae5ob8yClHamc';
/**
* Push subscription configuration for Web Push API
*/
export interface PushSubscription {
endpoint: string;
p256dh_key: string;
auth_key: string;
}
/**
* Nostr event filter for push notifications
*/
export interface NotificationFilter {
kinds?: number[];
authors?: string[];
"#p"?: string[];
"#t"?: string[];
since?: number;
until?: number;
limit?: number;
}
/**
* Notification content configuration
*/
export interface NotificationConfig {
title: string;
body: string;
icon?: string;
badge?: string;
data?: Record<string, unknown>;
}
/**
* Complete subscription object for push notifications
*/
export interface PushNotificationSubscription {
subscription_id: string;
domain: string;
filter: NotificationFilter;
notification: NotificationConfig;
push_subscription: PushSubscription;
}
/**
* RPC request structure for push notification server
*/
interface RPCRequest {
method: 'register_subscription' | 'update_subscription' | 'delete_subscription' | 'list_subscriptions' | 'get_subscription';
params: Record<string, unknown>;
request_id: string;
}
/**
* Hook for managing push notifications via Nostr RPC
* Sends encrypted RPC events to a push notification worker
*/
export function usePush(workerPubkey?: string) {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Default worker pubkey - your actual push notification server
const defaultWorkerPubkey = workerPubkey || '7c3be2769c76eecd6c6e27276722dfae0d8ad201825253452153b90093c41654';
const clearError = useCallback(() => {
setError(null);
}, []);
/**
* Send an encrypted RPC request to the push notification worker
*/
const sendRPCRequest = useCallback(async (
method: RPCRequest['method'],
params: Record<string, unknown>
): Promise<void> => {
if (!user?.signer) {
throw new Error('User must be logged in to manage push notifications');
}
if (!user.signer.nip44) {
throw new Error('Signer must support NIP-44 encryption for push notifications');
}
// Decode worker pubkey if it's in npub format
let workerHex = defaultWorkerPubkey;
if (defaultWorkerPubkey.startsWith('npub1')) {
const decoded = nip19.decode(defaultWorkerPubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid worker pubkey format');
}
workerHex = decoded.data;
}
const requestId = `req_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
const request: RPCRequest = {
method,
params,
request_id: requestId,
};
try {
// Encrypt the request using NIP-44
const payload = JSON.stringify(request);
console.log('Encrypting RPC request payload:', payload);
const encryptedRequest = await user.signer.nip44.encrypt(workerHex, payload);
console.log('Encrypted request:', encryptedRequest);
// Create unsigned RPC event (kind 25742)
const unsignedEvent = {
kind: 25742,
content: encryptedRequest,
tags: [
['p', workerHex],
['rpc', requestId],
['method', method],
],
created_at: Math.floor(Date.now() / 1000),
};
console.log('Signing RPC event:', unsignedEvent);
console.log('Target worker pubkey:', workerHex);
// Sign the event using the user's signer
const signedEvent = await user.signer.signEvent(unsignedEvent);
console.log('Signed RPC event:', signedEvent);
// Send the signed RPC event
const result = await nostr.event(signedEvent);
console.log('RPC event sent result:', result);
return;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error('RPC send error:', err);
throw new Error(`Failed to send push notification request: ${errorMessage}`);
}
}, [user, nostr, defaultWorkerPubkey]);
/**
* Register a new push notification subscription
*/
const registerSubscription = useCallback(async (
subscriptionId: string,
domain: string,
filter: NotificationFilter,
notification: NotificationConfig,
pushSubscription: PushSubscription
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('register_subscription', {
subscription_id: subscriptionId,
domain,
filter,
notification,
push_subscription: pushSubscription,
});
toast({
title: 'Push notifications enabled',
description: 'You will now receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to register subscription';
setError(errorMessage);
toast({
title: 'Failed to enable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Update an existing push notification subscription
*/
const updateSubscription = useCallback(async (
subscriptionId: string,
domain: string,
updates: Partial<Pick<PushNotificationSubscription, 'filter' | 'notification' | 'push_subscription'> & { is_active: boolean }>
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('update_subscription', {
subscription_id: subscriptionId,
domain,
updates,
});
toast({
title: 'Subscription updated',
description: 'Your push notification settings have been updated.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to update subscription';
setError(errorMessage);
toast({
title: 'Failed to update notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Delete a push notification subscription
*/
const deleteSubscription = useCallback(async (
subscriptionId: string,
domain: string
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('delete_subscription', {
subscription_id: subscriptionId,
domain,
});
toast({
title: 'Push notifications disabled',
description: 'You will no longer receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to delete subscription';
setError(errorMessage);
toast({
title: 'Failed to disable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* List all subscriptions for a domain
*/
const listSubscriptions = useCallback(async (domain: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('list_subscriptions', { domain });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to list subscriptions';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Get a specific subscription
*/
const getSubscription = useCallback(async (subscriptionId: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('get_subscription', { subscription_id: subscriptionId });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get subscription';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Request browser permission for push notifications
*/
const requestNotificationPermission = useCallback(async (): Promise<NotificationPermission> => {
if (!('Notification' in window)) {
throw new Error('This browser does not support push notifications');
}
if (Notification.permission === 'granted') {
return 'granted';
}
if (Notification.permission === 'denied') {
throw new Error('Push notifications are blocked. Please enable them in your browser settings.');
}
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
throw new Error('Push notification permission was denied');
}
return permission;
}, []);
/**
* Convert npub to hex format for use in filters
*/
const convertNpubToHex = useCallback((pubkey: string): string => {
if (pubkey.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
return decoded.data;
} catch (error) {
throw new Error(`Failed to decode npub: ${error instanceof Error ? error.message : String(error)}`);
}
}
// If it's already hex format, return as-is
return pubkey;
}, []);
/**
* Convert VAPID key from base64url string to Uint8Array (matches working implementation)
*/
const convertVapidKey = useCallback((key: string): Uint8Array => {
try {
// Add padding if needed
const padding = '='.repeat((4 - (key.length % 4)) % 4);
const base64 = (key + padding).replace(/-/g, '+').replace(/_/g, '/');
// Decode base64 to binary string
const rawData = window.atob(base64);
// Convert binary string to Uint8Array
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
console.log('VAPID key converted:', {
originalLength: key.length,
base64Length: base64.length,
outputLength: outputArray.length,
firstBytes: Array.from(outputArray.slice(0, 10))
});
return outputArray;
} catch (err) {
throw new Error(`Invalid VAPID key format: ${err instanceof Error ? err.message : String(err)}`);
}
}, []);
/**
* Subscribe to browser push notifications and get subscription details
*/
const subscribeToPush = useCallback(async (vapidPublicKey: string = VAPID_PUBLIC_KEY): Promise<PushSubscription> => {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
throw new Error('Push notifications are not supported in this browser');
}
await requestNotificationPermission();
// Register service worker and wait for it to be ready
const registration = await navigator.serviceWorker.ready;
console.log('Service worker ready:', registration);
console.log('Service worker scope:', registration.scope);
console.log('Service worker active:', !!registration.active);
// Check if already subscribed
const existingSubscription = await registration.pushManager.getSubscription();
console.log('Existing subscription:', existingSubscription);
// Convert VAPID key to proper format
console.log('VAPID public key (base64):', vapidPublicKey);
const applicationServerKey = convertVapidKey(vapidPublicKey);
console.log('VAPID key converted to Uint8Array, length:', applicationServerKey.length);
let subscription;
try {
console.log('Attempting to subscribe to push manager...');
// Subscribe to push notifications
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey,
});
console.log('Push subscription successful:', subscription);
} catch (pushError: any) {
console.error('Push subscription failed with error:', pushError);
console.error('Error name:', pushError.name);
console.error('Error message:', pushError.message);
// Provide specific error messages based on error type
if (pushError.name === 'InvalidStateError') {
throw new Error('Push subscription failed: Invalid state (possibly already subscribed)');
} else if (pushError.name === 'NotAllowedError') {
throw new Error('Push subscription failed: Permission denied by user');
} else if (pushError.name === 'NotSupportedError') {
throw new Error('Push subscription failed: Push not supported by this browser/service');
} else if (pushError.name === 'AbortError') {
throw new Error('Push subscription failed: Request was aborted (VAPID key mismatch?)');
} else {
throw new Error(`Push subscription failed: ${pushError.name} - ${pushError.message}`);
}
}
// Extract keys safely
const subscriptionJson = subscription.toJSON();
const keys = subscriptionJson.keys;
if (!keys?.p256dh || !keys?.auth) {
throw new Error('Invalid subscription keys received');
}
// Convert to our format
return {
endpoint: subscription.endpoint,
p256dh_key: keys.p256dh,
auth_key: keys.auth,
};
}, [requestNotificationPermission, convertVapidKey]);
/**
* Helper function to create a subscription for following an author
*/
const subscribeToAuthor = useCallback(async (
authorPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const authorHex = convertNpubToHex(authorPubkey);
const subscriptionId = `follow-${authorHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
authors: [authorHex], // Use hex format
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} posted something!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'new_post',
author: authorHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for mentions
*/
const subscribeToMentions = useCallback(async (
userPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const userHex = convertNpubToHex(userPubkey);
const subscriptionId = `mentions-${userHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#p": [userHex], // Mentions of the user (use hex format)
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} mentioned you!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'mention',
user: userHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for hashtags
*/
const subscribeToHashtag = useCallback(async (
hashtag: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
const subscriptionId = `hashtag-${hashtag}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#t": [hashtag], // Posts with the hashtag
limit: 50,
};
const notification: NotificationConfig = {
title: `{{author_name}} posted about #${hashtag}`,
body: `{{content}}`,
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'hashtag',
hashtag,
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription]);
return {
// Core RPC methods
registerSubscription,
updateSubscription,
deleteSubscription,
listSubscriptions,
getSubscription,
// Browser push notification helpers
requestNotificationPermission,
subscribeToPush,
// Convenience methods for common use cases
subscribeToAuthor,
subscribeToMentions,
subscribeToHashtag,
// State
isLoading,
error,
clearError,
// Config
workerPubkey: defaultWorkerPubkey,
};
}
/**
* Example usage:
*
* ```tsx
* import { usePush } from '@/hooks/usePush';
*
* function MyComponent() {
* const {
* subscribeToAuthor,
* subscribeToMentions,
* isLoading,
* error
* } = usePush('npub1yourpushworkerpubkey');
*
* const handleFollowNotifications = async (authorPubkey: string) => {
* try {
* await subscribeToAuthor(authorPubkey, 'myapp.com');
* } catch (error) {
* console.error('Failed to enable notifications:', error);
* }
* };
*
* return (
* <Button
* onClick={() => handleFollowNotifications('npub1author...')}
* disabled={isLoading}
* >
* {isLoading ? 'Enabling...' : 'Enable Notifications'}
* </Button>
* );
* }
* ```
*/
-62
View File
@@ -1,62 +0,0 @@
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,
};
}
-372
View File
@@ -1,372 +0,0 @@
import { useCallback, useState } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NUser } from '@nostrify/react/login';
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
export interface ChatMessage {
role: 'user' | 'assistant' | 'system';
content: string | Array<{
type: 'text' | 'image_url';
text?: string;
image_url?: {
url: string;
};
}>;
}
export interface ChatCompletionRequest {
model: string;
messages: ChatMessage[];
stream?: boolean;
temperature?: number;
max_tokens?: number;
}
export interface ChatCompletionResponse {
id: string;
object: string;
created: number;
model: string;
choices: Array<{
index: number;
message: ChatMessage;
finish_reason: string;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
export interface Model {
id: string;
name: string;
description: string;
object: string;
owned_by: string;
created: number;
context_window: number;
pricing: {
prompt: string;
completion: string;
};
}
export interface ModelsResponse {
object: string;
data: Model[];
}
// Configuration
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
// Helper function to create NIP-98 token
async function createNIP98Token(
method: string,
url: string,
body?: unknown,
user?: NUser
): Promise<string> {
if (!user?.signer) {
throw new Error('User signer is required for NIP-98 authentication');
}
// Create the tags array
const tags: string[][] = [
['u', url],
['method', method]
];
// Add payload hash for requests with body (following NIP-98 spec)
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 the HTTP request event
const event = await user.signer.signEvent({
kind: 27235, // NIP-98 HTTP Auth
content: '',
tags,
created_at: Math.floor(Date.now() / 1000)
});
// Return the token (base64 encoded event)
return btoa(JSON.stringify(event));
}
// Helper function to handle API errors with user-friendly messages
async function handleAPIError(response: Response) {
if (response.status === 401) {
throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
} else if (response.status === 402) {
throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
} else if (response.status === 400) {
try {
const error = await response.json();
if (error.error?.type === 'invalid_request_error') {
// Handle specific validation errors
if (error.error.code === 'minimum_amount_not_met') {
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
} else if (error.error.code === 'unsupported_method') {
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
} else if (error.error.code === 'invalid_url') {
throw new Error('Invalid redirect URL provided for Stripe payment.');
}
}
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
} catch {
throw new Error('Invalid request. Please check your parameters and try again.');
}
} else if (response.status === 404) {
throw new Error('Resource not found. Please check the payment ID or try again.');
} else if (response.status >= 500) {
throw new Error('Server error. Please try again in a few moments.');
} else if (!response.ok) {
try {
const errorData = await response.json();
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
} catch {
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
}
}
}
export function useShakespeare() {
const { user } = useCurrentUser();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Clear error helper
const clearError = useCallback(() => {
setError(null);
}, []);
// Chat completion function
const sendChatMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
options?: Partial<ChatCompletionRequest>
): Promise<ChatCompletionResponse> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
return await response.json();
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
}, [user]);
// Streaming chat completion function
const sendStreamingMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
onChunk: (chunk: string) => void,
options?: Partial<ChatCompletionRequest>
): Promise<void> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
stream: true,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
if (!response.body) {
throw new Error('No response body');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
onChunk(content);
}
} catch {
// Ignore parsing errors for incomplete chunks
}
}
}
}
} finally {
reader.releaseLock();
}
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
}, [user]);
// Get available models
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const token = await createNIP98Token(
'GET',
`${SHAKESPEARE_API_URL}/models`,
undefined,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
method: 'GET',
headers: {
'Authorization': `Nostr ${token}`,
},
});
await handleAPIError(response);
return await response.json();
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage);
} finally {
setIsLoading(false);
}
}, [user]);
return {
// State
isLoading,
error,
isAuthenticated: !!user,
// Actions
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
clearError,
};
}
+1 -1
View File
@@ -6,7 +6,7 @@ import type {
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
+60 -27
View File
@@ -1,61 +1,94 @@
import { useMemo } from 'react';
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/useCashu';
import type { WebLNProvider } from '@webbtc/webln-types';
import type { WebLNProvider } from 'webln';
import { requestProvider } from 'webln';
export interface WalletStatus {
hasWebLN: boolean;
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
preferredMethod: 'cashu' | 'nwc' | 'webln' | 'manual';
// Cashu integration
hasCashu: boolean;
cashuBalance: number;
isCashuInitialized: boolean;
isDetecting: boolean;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const [webln, setWebln] = useState<WebLNProvider | null>(null);
const [isDetecting, setIsDetecting] = useState(false);
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
const { connections, getActiveConnection } = useNWC();
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
// Access WebLN directly from browser global scope
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
// Detect WebLN
const detectWebLN = useCallback(async () => {
if (webln || isDetecting) return webln;
// Calculate Cashu status
const hasCashu = useMemo(() => {
return isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
}, [isCashuInitialized, mints, balances]);
setIsDetecting(true);
try {
const provider = await requestProvider();
setWebln(provider);
setHasAttemptedDetection(true);
return provider;
} catch (error) {
// Only log the error if it's not the common "no provider" error
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
console.warn('WebLN detection error:', error);
}
setWebln(null);
setHasAttemptedDetection(true);
return null;
} finally {
setIsDetecting(false);
}
}, [webln, isDetecting]);
const cashuBalance = useMemo(() => {
return Object.values(balances).reduce((sum, balance) => sum + balance, 0);
}, [balances]);
// Only auto-detect once on mount
useEffect(() => {
if (!hasAttemptedDetection) {
detectWebLN();
}
}, [detectWebLN, hasAttemptedDetection]);
// Calculate Lightning status values reactively
// Test WebLN connection
const testWebLN = useCallback(async (): Promise<boolean> => {
if (!webln) return false;
try {
await webln.enable();
return true;
} catch (error) {
console.error('WebLN test failed:', error);
return false;
}
}, [webln]);
// Calculate status values reactively
const hasNWC = useMemo(() => {
return connections.length > 0 && connections.some(c => c.isConnected);
}, [connections]);
// Determine preferred payment method - Cashu first, then Lightning fallbacks
const preferredMethod: WalletStatus['preferredMethod'] = hasCashu
? 'cashu'
: activeNWC
// Determine preferred payment method
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
? 'nwc'
: webln
? 'webln'
: 'manual';
const status: WalletStatus = {
hasWebLN: !!webln,
hasNWC,
webln,
activeNWC,
isDetecting,
preferredMethod,
hasCashu,
cashuBalance,
isCashuInitialized,
};
return status;
return {
...status,
hasAttemptedDetection,
detectWebLN,
testWebLN,
};
}
+15 -93
View File
@@ -4,11 +4,10 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/useCashu';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
import type { WebLNProvider } from '@webbtc/webln-types';
import type { WebLNProvider } from 'webln';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
@@ -30,7 +29,6 @@ export function useZaps(
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const { createMeltQuote, payMeltQuote, balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
@@ -133,13 +131,7 @@ export function useZaps(
}, [zapEvents, actualTarget]);
const zap = async (amount: number, comment: string) => {
if (amount <= 0 || isNaN(amount)) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
setIsZapping(false);
if (amount <= 0) {
return;
}
@@ -166,17 +158,6 @@ 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({
@@ -211,18 +192,18 @@ 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({
event: actualTarget,
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
comment
@@ -247,57 +228,10 @@ 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) {
// Create melt quote to convert Cashu tokens to Lightning payment
const meltQuote = await createMeltQuote(mintWithBalance.url, newInvoice);
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats from your Cashu wallet to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
return;
}
} catch (cashuError) {
console.error('Cashu payment failed, falling back:', cashuError);
// Show specific Cashu error to user for debugging
const errorMessage = cashuError instanceof Error ? cashuError.message : 'Unknown Cashu error';
toast({
title: 'Cashu payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
}
}
// Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection();
// Try NWC if Cashu failed or unavailable
// Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
@@ -329,22 +263,10 @@ export function useZaps(
});
}
}
if (webln) { // Try WebLN next
try {
// For native WebLN, we may need to enable it first
let webLnProvider = webln;
if (webln.enable && typeof webln.enable === 'function') {
const enabledProvider = await webln.enable();
// Some implementations return the provider, others return void
// Cast to WebLNProvider to handle both cases
const provider = enabledProvider as WebLNProvider | undefined;
if (provider) {
webLnProvider = provider;
}
}
await webLnProvider.sendPayment(newInvoice);
await webln.sendPayment(newInvoice);
// Clear states immediately on success
setIsZapping(false);
@@ -361,7 +283,7 @@ export function useZaps(
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('WebLN payment failed, falling back:', weblnError);
console.error('webln payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
-131
View File
@@ -1,131 +0,0 @@
/**
* 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();