Author SHA1 Message Date
lemonknowsall 315989fc87 Update nostr-tools to ^2.21.0 and @getalby/sdk to ^7.0.0 2026-01-28 23:28:11 -08:00
Alex Gleason c1bd55108c Remove stray docs mentions from AGENTS.md 2026-01-24 21:21:09 -06:00
Alex Gleason 266e2c92d8 Replace docs with skills 2026-01-24 21:20:22 -06:00
Alex Gleason 8163f30011 You don't actually have to pass signal now 2026-01-24 00:02:15 -06:00
Alex Gleason b97db2ca77 Upgrade zod to v4 2026-01-23 23:59:13 -06:00
Alex Gleason cda1b903a9 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2026-01-21 16:52:45 -06:00
Alex Gleason ead11c31fe Remove stack.json 2026-01-21 16:52:23 -06:00
Alex Gleason a9bbb5ab84 Merge branch 'remove-nostr-band-relay' into 'main'
Replace dead relay.nostr.band with relay.primal.net

See merge request soapbox-pub/mkstack!29
2026-01-21 20:32:10 +00:00
Derek Ross f87510bc3a Replace dead relay.nostr.band with relay.primal.net 2026-01-21 15:29:02 -05:00
Alex Gleason fc010f9b91 Add Nostr Security Model to AGENTS.md 2026-01-21 12:14:24 -06:00
Alex Gleason 20f9ea9069 npm audit fix 2026-01-17 19:19:05 -06:00
Alex Gleason fc4c4deded Upgrade Nostrify 2026-01-17 19:18:43 -06:00
Alex Gleason b3dac352a4 Remove deploy script 2026-01-11 22:21:47 -06:00
Alex Gleason e94f53f0e2 Add -z-10 isolate hint 2026-01-10 11:37:12 -06:00
Alex Gleason 74449cf0d7 Add opencode.json with Nostr MCP server 2026-01-09 16:27:49 -06:00
Alex Gleason e26ab6a433 Fix URL wrapping in NoteContent 2025-12-30 18:19:20 -06:00
Alex Gleason 816051f5ea Greatly simplify the login and signup dialogs 2025-12-30 17:53:32 -06:00
Alex Gleason 413aa93e4f Generate custom images liberally 2025-12-23 05:54:11 -06:00
Alex Gleason 6941aad2f5 Upgrade Nostrify 2025-12-22 13:28:39 -06:00
Alex Gleason 28aba4b3a4 Revert "Fix happy-dom vuln"
This reverts commit e5b3f249f8.
2025-12-21 04:11:11 -06:00
Alex Gleason e5b3f249f8 Fix happy-dom vuln 2025-12-21 02:28:15 -06:00
Alex Gleason 12e6465912 npm audit fix 2025-12-21 02:02:24 -06:00
Alex Gleason 722d138f35 Remove "Vibed with MKStack" 2025-12-02 20:26:37 -06:00
Alex Gleason 84a15aa077 Revert "Try adding cashu deps"
This reverts commit 6534c5fcea.
2025-11-20 11:14:14 -06:00
Alex Gleason 8c7b595d22 Revert "Use nutstack package.json and package-lock.json"
This reverts commit 0bf1e0e85e.
2025-11-20 11:14:07 -06:00
Alex Gleason 0bf1e0e85e Use nutstack package.json and package-lock.json 2025-11-19 18:47:04 -06:00
Alex Gleason 6534c5fcea Try adding cashu deps 2025-11-19 18:42:35 -06:00
Alex Gleason e4ee998500 Fix posting a comment not invalidating comment cache 2025-11-17 19:44:34 -06:00
Alex Gleason 000be63075 Don't redirect /assets/* in Netlify redirects file 2025-11-13 22:11:57 -06:00
Alex Gleason 5f14ac11fc Remove DM stuff from App.tsx, add instructions on how to add it in docs 2025-11-11 17:36:32 -06:00
Alex Gleason 0b7d86a16f Remove DMProvider from App.tsx and update DM documentation
- Removed DMProvider, DMConfig imports and configuration from App.tsx
- Updated docs/NOSTR_DIRECT_MESSAGES.md with setup instructions
- DM functionality now requires manual setup as documented
- Preserved all existing intentional test errors
2025-11-11 17:34:45 -06:00
Alex Gleason 8496cb99e5 Disable DM functionality by default 2025-11-11 17:31:46 -06:00
Alex Gleason 386d664a33 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-11-10 17:49:28 -06:00
Alex Gleason 0a5e8fc9e0 Bully the robot to utilize git if it's available, and to always read files before writing to them 2025-11-10 17:45:42 -06:00
Alex Gleason 2ba510c54f Merge branch 'removeMessageRoute' into 'main'
Remove "/messages" route

See merge request soapbox-pub/mkstack!27
2025-11-07 12:19:29 +00:00
lemonknowsall eb0fd14e33 remove /messages route 2025-11-06 19:43:20 -08:00
Alex Gleason 0532d23b57 RelayListManager improved mobile support 2025-11-05 00:23:40 -06:00
Alex Gleason 8eddf49e61 Implement NIP-65 relay management
- Replace single relayUrl with NIP-65 compatible relayMetadata structure
- Add RelayListManager component for managing multiple relays with read/write permissions
- Add NostrSync component to automatically sync user's NIP-65 relay list on login
- Update NostrProvider to use relay list instead of single relay
- Remove RelaySelector component and update empty states
- Update AGENTS.md documentation to reflect relay management changes
- Automatically publish relay list changes as NIP-65 events when user is logged in
2025-11-04 23:58:32 -06:00
Alex Gleason d7dee81b1c Split DM context up into multiple files 2025-11-04 23:33:58 -06:00
Alex Gleason fbafc52992 Stronger guidance to call the generate_kind tool 2025-11-03 22:33:18 -06:00
84 changed files with 2640 additions and 13806 deletions

No files matched your search

@@ -1,4 +1,9 @@
### AI Integration with Shakespeare API
---
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
@@ -217,6 +222,39 @@ Models are dynamically fetched from the Shakespeare API and include:
## Implementation Patterns and Best Practices
### Dialog Component Patterns
When using Dialog components, always ensure accessibility compliance by including required elements:
```tsx
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
// ✅ Correct - Always include DialogHeader with DialogTitle
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
<DialogHeader>
<DialogTitle>Dialog Title</DialogTitle>
<DialogDescription>
Optional description for screen readers
</DialogDescription>
</DialogHeader>
{/* Dialog content */}
</DialogContent>
</Dialog>
```
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
```tsx
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
<DialogHeader>
<VisuallyHidden>
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
</VisuallyHidden>
</DialogHeader>
```
### Streaming Response Handling
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
@@ -1,3 +1,8 @@
---
name: nostr-comments
description: Implement Nostr comment systems, add discussion features to posts/articles, or build community interaction features.
---
# Adding Nostr Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
@@ -1,42 +1,81 @@
### Direct Messaging on Nostr
---
name: nostr-direct-messages
description: Implement Nostr direct messaging features, build chat interfaces, or work with encrypted peer-to-peer communication (NIP-04 and NIP-17).
---
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, - more - private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent - cache first - local storage.
# Direct Messaging on Nostr
## Quick Start
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, more private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent cache-first local storage.
### 1. Enable Direct Messaging
**The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
## Setup Instructions
### 1. Add DMProvider to Your App
First, add the `DMProvider` to your app's provider tree in `src/App.tsx`:
```tsx
import { DMProvider } from '@/contexts/DMContext';
// Add these imports at the top of src/App.tsx
import { DMProvider, type DMConfig } from '@/components/DMProvider';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
function App() {
// Add this configuration before your App component
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to true to enable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP17_ONLY, // Recommended for new apps
};
// Then wrap your app components with DMProvider:
export function App() {
return (
<DMProvider config={{
enabled: true, // Enable the DM system
protocolMode: PROTOCOL_MODE.NIP17_ONLY
}}>
{/* Your app components */}
</DMProvider>
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
);
}
```
**Config Options:**
### 2. Configure DM Settings
The `DMConfig` object supports the following options:
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
- `PROTOCOL_MODE.BOTH` - Support both protocols (for backwards compatibility)
- `PROTOCOL_MODE.NIP04_OR_NIP17` - Support both protocols (for backwards compatibility)
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
### 2. Send Messages
## Quick Start
### 1. Send Messages
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
@@ -54,8 +93,8 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
@@ -65,10 +104,10 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
}
```
### 3. Display Conversations
### 2. Display Conversations
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
@@ -82,7 +121,7 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
return (
<div className="space-y-2">
{conversations.map((conversation) => (
<ConversationItem
<ConversationItem
key={conversation.pubkey}
conversation={conversation}
onClick={() => onSelectConversation(conversation.pubkey)}
@@ -92,8 +131,8 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
);
}
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
onClick: () => void;
}) {
const author = useAuthor(conversation.pubkey);
@@ -119,10 +158,10 @@ function ConversationItem({ conversation, onClick }: {
}
```
### 4. Display Messages in a Conversation
### 3. Display Messages in a Conversation
```tsx
import { useConversationMessages } from '@/contexts/DMContext';
import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useCurrentUser } from '@/hooks/useCurrentUser';
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
@@ -136,12 +175,12 @@ function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
Load earlier messages
</button>
)}
{messages.map((message) => {
const isFromMe = message.pubkey === user?.pubkey;
return (
<div
<div
key={message.id}
className={cn(
"flex",
@@ -201,9 +240,10 @@ It requires no props and works automatically when wrapped in `DMProvider`.
## Sending Files with Messages
```tsx
import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useUploadFile } from '@/hooks/useUploadFile';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import type { FileAttachment } from '@/contexts/DMContext';
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
@@ -217,7 +257,7 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
// Upload file if one is selected
if (selectedFile) {
const tags = await uploadFile(selectedFile);
attachments = [{
url: tags[0][1], // URL from first tag
mimeType: selectedFile.type,
@@ -240,19 +280,19 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<input
type="file"
<input
type="file"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
/>
{selectedFile && <div>Selected: {selectedFile.name}</div>}
<button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Send'}
</button>
@@ -321,7 +361,7 @@ if (scanProgress.nip17) {
### Clear Cache and Refresh
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
function SettingsButton() {
const { clearCacheAndRefetch } = useDMContext();
@@ -1,4 +1,9 @@
### Infinite Scroll for Nostr Feeds
---
name: nostr-infinite-scroll
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
---
# Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
+161 -95
View File
@@ -15,7 +15,6 @@ 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.)
@@ -34,10 +33,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history) - See **`docs/CASHU_WALLET.md`** for comprehensive implementation guide
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing) - See **`docs/BITCOIN_WALLET.md`** for Bitcoin wallet architecture and operations
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider) - See **`docs/CASHU_WALLET.md`** for integration patterns
- `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
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
@@ -46,9 +45,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useConversationMessages`: Hook exported from DMContext for paginated messages
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `App.tsx`: Main app component with provider setup (**CRITICAL**: this file is **already configured** with `QueryClientProvider`, `NostrProvider`, `UnheadProvider` and other important providers - **read this file before making changes**. Changes are usually not necessary unless adding new providers. Changing this file may break the application)
- `AppRouter.tsx`: React Router configuration
**CRITICAL**: Always read the files mentioned above before making changes, as they contain important setup and configuration for the application. Never directly write to these files without first reading their contents.
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
@@ -102,22 +103,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/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
- **`docs/CASHU_WALLET.md`**: Read when implementing Cashu/eCash wallet features, Lightning payments, mint management, token operations, or working with the coco-cashu-core library. This guide covers architecture, component structure, hook patterns, and best practices for the Cashu wallet system.
- **`docs/BITCOIN_WALLET.md`**: Read when implementing on-chain Bitcoin wallet features, UTXO management, Bitcoin transactions, consolidation, or working with Bitcoin addresses derived from Nostr pubkeys. This guide covers the Bitcoin wallet architecture, transaction flows, and integration patterns.
## 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:
@@ -125,10 +110,6 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## "Vibed with NutStack"
When building the site for the first time, include "Vibed with NutStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
@@ -162,6 +143,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
- If you have a tool available to generate a kind, you **MUST** call the tool to generate a new kind rather than picking an arbitrary number
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
@@ -238,7 +220,7 @@ const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
}]);
```
### Kind Ranges
@@ -288,6 +270,104 @@ The file `NIP.md` is used by this project to define a custom Nostr protocol docu
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### Nostr Security Model
**CRITICAL**: Nostr is permissionless - **anyone can publish any event**. When implementing admin/moderation systems or any feature that should only trust specific users, you MUST filter queries by the `authors` field. Without author filtering, anyone can publish events claiming to be admin actions, moderator decisions, or trusted content.
#### Using the `authors` Filter
**Always filter by authors when querying:**
- **Admin/moderator actions** - MUST filter by trusted admin pubkeys
- **Addressable events (kinds 30000-39999)** - MUST include author to prevent anyone from publishing events with the same d-tag
- **Any privileged operations** - Filter by trusted pubkeys only
**✅ Secure - Filtering by trusted authors:**
```typescript
import { ADMIN_PUBKEYS } from '@/lib/admins';
// Query organizer appointments - ONLY accept events from admins
const events = await nostr.query([{
kinds: [30078],
authors: ADMIN_PUBKEYS, // CRITICAL: Only trust admin authors
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**❌ INSECURE - No author filtering:**
```typescript
// DANGER: This accepts events from ANYONE who publishes kind 30078
// An attacker could appoint themselves as an organizer
const events = await nostr.query([{
kinds: [30078],
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**Addressable Events Example:**
```typescript
// For addressable events, ALWAYS include the author in your filter
// This prevents attackers from publishing events with the same d-tag
const article = await nostr.query([{
kinds: [30023], // Long-form article
authors: [authorPubkey], // CRITICAL: Verify the author
'#d': ['my-article-slug'],
limit: 1
}]);
```
**URL Routing for Addressable/Replaceable Events:**
When creating URL paths for addressable or replaceable events, always include the author in the URL structure:
```typescript
// ❌ INSECURE: Missing author - anyone could publish an event with this d-tag
<Route path="/article/:slug" element={<Article />} />
// URL: /article/hello-world
// ✅ SECURE: Includes author - can safely filter by both author and d-tag
<Route path="/article/:npub/:slug" element={<Article />} />
// URL: /article/npub1abc.../hello-world
```
This ensures your route parameters provide both the author pubkey and the d-tag identifier needed to create a secure query filter.
**NIP-72 Community Moderation Example:**
When implementing moderated communities (NIP-72), you must query the community definition to get the moderator list, then filter approval events by those moderators:
```typescript
// Step 1: Query the community definition to get moderators
const communityEvents = await nostr.query([{
kinds: [34550],
authors: [communityOwnerPubkey], // CRITICAL: Only trust the community owner
'#d': [communityId],
limit: 1,
}]);
if (communityEvents.length === 0) return [];
// Step 2: Extract moderator pubkeys from p tags
const moderatorPubkeys = communityEvents[0].tags
.filter(([name, _, __, role]) => name === 'p' && role === 'moderator')
.map(([_, pubkey]) => pubkey);
// Step 3: Query approval events - ONLY from trusted moderators
const approvals = await nostr.query([{
kinds: [4550],
authors: moderatorPubkeys, // CRITICAL: Only accept approvals from moderators
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
limit: 100,
}]);
```
Without filtering approvals by the moderator list, anyone could publish kind 4550 events claiming to approve posts for the community.
#### When Author Filtering Is NOT Required
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -320,7 +400,7 @@ function useSpecificRelay() {
const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
const events = await relay.query([{ kinds: [1], limit: 20 }]);
// Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
@@ -345,7 +425,7 @@ function useRelayGroup() {
]);
// Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
const events = await relayGroup.query([{ kinds: [1], limit: 20 }]);
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
@@ -395,8 +475,7 @@ function usePosts() {
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
const events = await nostr.query([{ kinds: [1], limit: 20 }]);
return events; // these events could be transformed into another format
},
});
@@ -416,7 +495,7 @@ const events = await nostr.query([
'#e': [eventId],
limit: 150,
}
], { signal });
]);
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
@@ -428,9 +507,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [1], '#e': [eventId] }]),
nostr.query([{ kinds: [6], '#e': [eventId] }]),
nostr.query([{ kinds: [16], '#e': [eventId] }]),
]);
```
@@ -484,8 +563,7 @@ function useCalendarEvents() {
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]);
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
@@ -686,7 +764,6 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
@@ -714,7 +791,6 @@ const events = await nostr.query(
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
@@ -753,20 +829,6 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Direct Messaging (NIP-04 & NIP-17)
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols. **The system is disabled by default** - enable it by passing `enabled: true` in the `DMProvider` config.
For complete implementation guide including:
- Setup and configuration
- Sending messages and file attachments
- Using the `DMMessagingInterface` component
- Building custom messaging UIs
- Protocol comparison (NIP-04 vs NIP-17)
- Advanced features and architecture
See **`docs/NOSTR_DIRECT_MESSAGES.md`**
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
@@ -835,16 +897,46 @@ export function Post(/* ...props */) {
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
### Relay Management
The project includes a complete NIP-65 relay management system:
- **RelayListManager**: Component for managing multiple relays with read/write permissions
- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in
- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in
Use the `RelayListManager` component to provide relay management interfaces:
```tsx
import { RelayListManager } from '@/components/RelayListManager';
function SettingsPage() {
return (
<div>
<h2>Relay Settings</h2>
<RelayListManager />
</div>
);
}
```
## Routing
@@ -898,10 +990,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
@@ -910,9 +1001,8 @@ import { Card, CardContent } from '@/components/ui/card';
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
No results found. Try checking your relay connections or wait a moment for content to load.
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
@@ -931,7 +1021,7 @@ import { Card, CardContent } from '@/components/ui/card';
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
- **Generate custom images liberally** when image generation tools are available - this is ALWAYS preferred over stock photography for creating unique, brand-specific visuals that perfectly match the design intent
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
@@ -1030,45 +1120,14 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
### 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>
```
- When using negative z-index (e.g., `-z-10`) for background images or decorative elements, **always add `isolate` to the parent container** to create a local stacking context. Without `isolate`, negative z-index pushes elements behind the page's background color, making them invisible.
## Writing Tests vs Running Tests
There is an important distinction between **writing new tests** and **running existing tests**:
### Writing Tests (Creating New Test Files)
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message
@@ -1082,6 +1141,7 @@ There is an important distinction between **writing new tests** and **running ex
- Existing functionality needs verification
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes
@@ -1140,4 +1200,10 @@ Run available tools in this priority order:
- Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
### Using Git
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
When your changes are complete and validated, create a git commit with a descriptive message summarizing your changes.
-460
View File
@@ -1,460 +0,0 @@
# Bitcoin Wallet System for AI Agents (NutStack)
This document explains the Bitcoin wallet system architecture and provides guidance for AI agents to extend, modify, and build upon the existing implementation.
## Overview
The Bitcoin wallet system provides on-chain Bitcoin transaction capabilities including:
- **Send/Receive**: On-chain Bitcoin transactions using Taproot addresses
- **UTXO Management**: View and manage unspent transaction outputs
- **UTXO Consolidation**: Combine multiple UTXOs into a single transaction
- **Transaction History**: View past Bitcoin transactions with status tracking
- **QR Code Support**: Scan Bitcoin addresses and npubs
The wallet requires nsec login for transaction signing.
## Architecture
### Component Hierarchy
```
WalletContainer (parent)
└── BitcoinWallet
├── WalletHeader (balance, mode toggle, address display)
├── PaymentCard (send/receive forms)
├── TransactionHistory (transaction list)
├── UTXOSelector (UTXO dropdown with consolidation)
├── ConsolidationModal (UTXO consolidation confirmation)
├── QRScanner (QR code scanning)
└── QRModal (address QR code display)
```
### Key Components
#### `BitcoinWallet.tsx`
Main Bitcoin wallet component that orchestrates all Bitcoin operations:
- Manages Bitcoin send/receive state
- Handles QR scan results
- Coordinates UTXO management
- Provides action buttons (Send, Receive, Scan, History)
**Key State:**
- `bitcoinAmount`: Amount to send (in sats)
- `bitcoinRecipient`: Recipient address or npub
- `pendingBitcoinRecipient`: Confirmed recipient after validation
- `showSendModal`, `showReceiveModal`, `showHistoryModal`: Drawer visibility
**Key Props:**
- `user`: Current user with pubkey
- `toast`: Toast notification function
- `generateQRCode`: QR code generation function
- `onRequestQRScanner`: Request QR scanner modal
- `onQRResult`: Handle QR scan results
#### `WalletHeader.tsx`
Displays wallet balance, mode toggle, and address management:
- **Balance Display**: Shows total Bitcoin balance with USD/sats toggle
- **Address Display**: Shows Bitcoin address with copy/QR buttons
- **UTXO Selector**: Displays UTXO count and consolidation option
- **Custody Badge**: Indicates "Self-Custody" for Bitcoin mode
#### `PaymentCard.tsx`
Transaction card for Bitcoin operations:
- **Bitcoin Send**: Two-step process (recipient → amount)
- **Bitcoin Receive**: Shows address with QR generation
- **Send Max**: Toggle for sending all available funds
**Bitcoin Send Flow:**
1. User enters recipient address or npub
2. System validates and converts npub to Bitcoin address if needed
3. User enters amount (or clicks "Send Max")
4. Transaction is created, signed, and broadcast
#### `TransactionHistory.tsx`
Transaction history display:
- **Bitcoin Transactions**: On-chain transactions with status
- **Transaction Types**: `sent`, `received`, `consolidate`
- **Status Display**: `confirmed`, `unconfirmed`, `pending`
**Bitcoin Transaction Format:**
```typescript
interface BitcoinTransaction {
id: string;
txid: string;
type: 'sent' | 'received' | 'consolidate';
amount: number; // in satoshis
fee?: number; // in satoshis
address: string;
confirmations: number;
blockHeight?: number;
timestamp: number;
status: 'confirmed' | 'unconfirmed' | 'pending';
}
```
#### `UTXOSelector.tsx`
UTXO management dropdown:
- Shows UTXO count and total balance
- Lists individual UTXOs with block information
- Consolidation button for combining UTXOs
- Formatting supports sats/USD display
#### `ConsolidationModal.tsx`
Confirmation modal for UTXO consolidation:
- Shows number of UTXOs to be consolidated
- Displays total value
- Explains benefits (reduced fees, simplified management)
- Handles consolidation execution
#### `QRScanner.tsx`
QR code scanning interface:
- Camera-based scanning using Html5Qrcode
- Paste from clipboard support
- Classifies scanned codes (Bitcoin address, npub, etc.)
- Handles camera permissions and errors
### Core Hooks
#### `useBitcoin.ts`
Main Bitcoin operations hook:
- **`useBitcoinBalance`**: Fetches UTXOs and calculates balance
- **`useBitcoinTransactionHistory`**: Fetches transaction history from Blockstream API
- **`useBitcoinOperations`**: Manages send/receive/consolidate operations
**Key Functions:**
```typescript
// Fetch UTXOs and balance
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
// Fetch transaction history
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
// Get operations hook
const {
utxos,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
```
#### `useNsecAccess.ts`
Access to private key for transaction signing:
- **`hasNsecAccess`**: Checks if user logged in with nsec
- **`getPrivateKey`**: Returns private key in hex format
**Usage:**
```typescript
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
if (!hasNsecAccess) {
// Show error: nsec login required
return;
}
const privateKey = getPrivateKey();
// Use private key for transaction signing
```
#### `useQRCode.ts`
QR code generation and scanning:
- **`generateQRCode`**: Creates QR code from text
- **`startScanning`**: Starts camera scanner
- **`stopScanning`**: Stops scanner
- **`classifyQRCode`**: Classifies scanned text (Bitcoin address, npub, etc.)
**QR Code Types:**
- `bitcoin_address`: Bitcoin address (bc1..., 1..., 3...)
- `npub`: Nostr public key (npub1...)
- `unknown`: Unrecognized format
### Core Libraries
#### `bitcoin.ts`
Bitcoin utility functions:
- **Address Derivation**: `nostrPubkeyToBitcoinAddress()`, `npubToBitcoinAddress()`
- **Validation**: `isValidBitcoinAddress()`
- **UTXO Management**: `fetchUTXOs()`, `calculateMaxSendAmount()`
- **Transaction Building**: `createBitcoinTransaction()`, `broadcastTransaction()`
- **Fee Estimation**: `getFeeRates()`
**Key Functions:**
```typescript
// Convert Nostr pubkey to Bitcoin Taproot address
const address = nostrPubkeyToBitcoinAddress(user.pubkey);
// Fetch UTXOs from Blockstream API
const utxos = await fetchUTXOs(address);
// Get fee rates
const feeRates = await getFeeRates();
// Returns: { fastestFee, halfHourFee, hourFee, economyFee, minimumFee }
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKeyHex,
recipientAddress,
amountSats,
utxos,
feeRates.fastestFee,
sendMax // true for send max
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
```
#### `exchangeRateService.ts`
Exchange rate service for BTC/USD conversion:
- Fetches rates from Coinbase API
- 1-minute caching to reduce API calls
- Fallback to cached rate on API failure
- Methods: `getBtcUsdRate()`, `satsToUsd()`, `btcToUsd()`, `usdToBtc()`
## Key Features
### On-Chain Bitcoin Transactions
**Address Derivation:**
- Bitcoin addresses are derived from Nostr public keys
- Uses Taproot (P2TR) addresses (bc1p...)
- Supports conversion from npub format
**Transaction Flow:**
1. User enters recipient (Bitcoin address or npub)
2. System validates and converts npub if needed
3. User enters amount (or selects "Send Max")
4. System fetches UTXOs and fee rates
5. Transaction is built and signed
6. Transaction is broadcast to network
7. Balance is refreshed automatically
**Send Max:**
- Calculates maximum sendable amount (total - fees)
- No change output (sends all UTXOs)
- Useful for consolidating or emptying wallet
### UTXO Management
**UTXO Display:**
- Shows count and total value
- Lists individual UTXOs with block information
- Displays confirmation status
**UTXO Consolidation:**
- Combines multiple UTXOs into single transaction
- Sends all funds to own address (self-send)
- Reduces future transaction fees
- Requires nsec login for signing
**UTXO Selection:**
- Automatic selection for transactions
- Uses all available UTXOs for send max
- Optimizes for fee efficiency
### Transaction History
**Data Source:**
Blockstream API provides transaction history:
- Fetches transaction list from `/address/:address/txs`
- Fetches full transaction details for accurate sent/received detection
- Calculates transaction amounts and fees
**Transaction Detection:**
- **Received**: Address appears in outputs only
- **Sent**: Address appears in input prevouts
- **Consolidate**: Self-send where all outputs go to same address
**Display:**
- Transaction type with icon
- Amount with direction (sent/received)
- Fee information (for sent transactions)
- Confirmation count and status
- Block height and timestamp
### QR Code Integration
**QR Code Generation:**
- Bitcoin addresses for receiving payments
**QR Code Scanning:**
- Bitcoin addresses: Auto-fills recipient field
- npubs: Converts to Bitcoin address and auto-fills
**Supported Formats:**
- `bc1...` (Taproot addresses)
- `1...`, `3...` (Legacy addresses)
- `npub1...` (Nostr public keys)
## State Management
### Bitcoin State Flow
```
BitcoinWallet Component
├── Local State
│ ├── bitcoinAmount (send amount)
│ ├── bitcoinRecipient (recipient input)
│ ├── pendingBitcoinRecipient (validated recipient)
│ └── Modal visibility states
├── useBitcoinBalance Hook
│ ├── Fetches UTXOs from Blockstream API
│ ├── Calculates total balance
│ └── Auto-refreshes every 30 seconds
├── useBitcoinTransactionHistory Hook
│ ├── Fetches transaction history
│ └── Auto-refreshes every 30 seconds
└── useBitcoinOperations Hook
├── UTXO management
├── Send/receive operations
└── Consolidation handling
```
### React Query Integration
**Bitcoin Balance:**
```typescript
const { data: bitcoinBalanceData, refetch } = useBitcoinBalance(bitcoinAddress);
// Returns: { balance: number, utxos: UTXO[] }
```
**Transaction History:**
```typescript
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
// Returns: BitcoinTransaction[]
```
**Auto-Refresh:**
- Balance: Refetches every 30 seconds
- Transactions: Refetches every 30 seconds
- Stale time: 10 seconds (data considered fresh for 10s)
## Extension Points
### Adding New Features
#### 1. Custom Fee Selection
To allow users to select fee rates:
**Add Fee Selector Component:**
```typescript
const [selectedFeeRate, setSelectedFeeRate] = useState<'fastest' | 'halfHour' | 'hour' | 'economy'>('fastest');
const feeRates = await getFeeRates();
const feeRate = feeRates[`${selectedFeeRate}Fee`];
```
**Update `PaymentCard.tsx`:**
```typescript
// Add fee selector dropdown
<Select value={selectedFeeRate} onValueChange={setSelectedFeeRate}>
<SelectItem value="fastest">Fastest ({feeRates.fastestFee} sat/vB)</SelectItem>
<SelectItem value="halfHour">Half Hour ({feeRates.halfHourFee} sat/vB)</SelectItem>
// ...
</Select>
```
#### 2. Transaction Labels/Notes
To add labels or notes to transactions:
**Extend Transaction History:**
```typescript
interface BitcoinTransaction {
// ... existing fields
label?: string;
notes?: string;
}
```
**Store Labels:**
- Use local storage or IndexedDB
- Key by transaction ID
- Display in transaction history
### Modifying Existing Features
#### Change Address Format
**Modify `bitcoin.ts`:**
```typescript
// Change from Taproot to P2WPKH (bc1q...)
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
const { address } = bitcoin.payments.p2wpkh({
pubkey: pubkeyBuffer,
network: bitcoin.networks.bitcoin,
});
return address || '';
}
```
#### Change Fee Estimation
**Modify `bitcoin.ts`:**
```typescript
// Use different API or estimation method
export async function getFeeRates() {
return {
fastestFee: 10,
halfHourFee: 5,
hourFee: 3,
economyFee: 1,
minimumFee: 1,
};
}
```
## Troubleshooting
### Common Issues
#### 1. "Nsec login required" error
**Cause**: User not logged in with nsec
**Solution**: Check `hasNsecAccess` before showing Bitcoin features
#### 2. Transaction fails to broadcast
**Cause**: Invalid transaction or network error
**Solution**: Validate transaction before broadcasting, retry on network errors
#### 3. UTXOs not updating
**Cause**: Blockstream API rate limiting or network issues
**Solution**: Implement retry logic, show error to user
#### 4. Balance incorrect
**Cause**: UTXOs not fetched or cached data stale
**Solution**: Force refresh balance, check Blockstream API response
## API Dependencies
### Blockstream API
- **Base URL**: `https://blockstream.info/api`
- **Endpoints**:
- `/address/:address/utxo` - Fetch UTXOs
- `/address/:address/txs` - Fetch transaction list
- `/tx/:txid` - Fetch full transaction details
- `/fee-estimates` - Get fee rates
- `/tx` - Broadcast transaction (POST)
### Coinbase API
- **Base URL**: `https://api.coinbase.com/v2/exchange-rates`
- **Endpoint**: `?currency=BTC` - Get BTC/USD exchange rate
## Dependencies
Required packages:
```json
{
"bitcoinjs-lib": "^7.x",
"@bitcoinerlab/secp256k1": "^1.x",
"ecpair": "^2.x",
"qrcode": "^1.x",
"html5-qrcode": "^2.x"
}
```
-784
View File
@@ -1,784 +0,0 @@
# Cashu Wallet Implementation Guide
This document provides comprehensive instructions for AI agents working on the Cashu/Lightning wallet implementation. It covers architecture, patterns, and best practices for extending and maintaining the wallet system.
## Table of Contents
1. [Architecture Overview](#architecture-overview)
2. [Component Structure](#component-structure)
3. [Hook Patterns](#hook-patterns)
4. [Wallet Modes](#wallet-modes)
5. [Mint Management](#mint-management)
6. [Transaction Operations](#transaction-operations)
7. [Integration Points](#integration-points)
8. [Extension Guidelines](#extension-guidelines)
9. [Best Practices](#best-practices)
## Architecture Overview
The Cashu wallet is built on a **layered architecture** with clear separation of concerns:
```
┌─────────────────────────────────────────────────┐
│ CashuWallet (Orchestrator) │
│ - Coordinates all operations │
│ - Manages UI state and modals │
│ - Routes between modes (tokens/lightning) │
└─────────────────────────────────────────────────┘
│
┌───────────┼──────────┐
│ │ │
┌───────▼─────┐ ┌───▼───────┐ ┌▼─────────────┐
│ WalletHeader│ │PaymentCard│ │Modals/Drawers│
│ - Balance │ │- Send/ │ │ - QRScanner │
│ - Mint │ │ Receive │ │ - History │
│ - Mode │ │- Lightning│ │ - Breakdown │
└─────────────┘ └───────────┘ └──────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ Domain Hooks │
│ - useMintManager (mint operations) │
│ - useTokenOperations (Cashu tokens) │
│ - useLightningOperations (Lightning) │
│ - useHistoryManager (transaction history) │
└───────────────────────────────────────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ Core Hooks │
│ - useCashu (coco manager instance) │
│ - useNpubCash (npub.cash API) │
│ - useLightningAddress (LNURL resolution) │
│ - useQRCode (QR generation/scanning) │
└───────────────────────────────────────────────┘
│
│
┌───────▼───────────────────────────────────────┐
│ coco-cashu-core Library │
│ - Proof management │
│ - Mint operations │
│ - Quote processing │
└───────────────────────────────────────────────┘
```
### Key Principles
1. **Separation of Concerns**: UI components are separated from business logic hooks
2. **Single Responsibility**: Each hook handles one specific domain (mints, tokens, lightning)
3. **State Management**: React state for UI reactivity, coco instance for wallet operations
4. **Error Handling**: Centralized error handling with toast notifications
5. **Type Safety**: Full TypeScript coverage with proper types from coco-cashu-core
## Component Structure
### Main Components
#### `CashuWallet.tsx` - Main Orchestrator
**Purpose**: Coordinates all wallet operations and manages global state.
**Key Responsibilities**:
- Initializes and manages the `coco` wallet manager instance
- Coordinates between mint management, token operations, and lightning operations
- Manages modal/drawer state (send, receive, history, QR scanner)
- Handles QR scan results and routes to appropriate handlers
- Integrates with npub.cash API for Lightning addresses
- Exposes wallet header props to parent `WalletContainer`
**Key Patterns**:
```typescript
// Core hooks initialized first
const { coco, balances, mints, ... } = useCashu();
const { ... } = useNpubCash();
// Domain hooks use core hooks
const { activeMintUrl, ... } = useMintManager({ coco, mints, ... });
const { sendAmount, ... } = useTokenOperations({ coco, activeMintUrl, ... });
// Combined handlers route to appropriate domain
const handleSend = async () => {
if (sendAmount && activeMintUrl) {
return tokenOps.handleTokenSend();
}
if (pendingLightningAddress) {
return lightningOps.handleLightningAddressPayment();
}
// ...
};
```
**State Management**:
- Uses refs to track initialization state (`hasFetchedUserInfoRef`, `hasSetMintFromUserInfoRef`)
- Persists active mint URL to localStorage
- Manages drawer open/close state with cleanup
#### `WalletHeader.tsx` - Balance and Controls
**Purpose**: Displays wallet balance, mode switching, and mint/address selectors.
**Key Features**:
- Toggle between sats and USD display
- Mode switching button (tokens → lightning → bitcoin → tokens)
- Mint selector dropdown (when mode is tokens/lightning)
- Lightning address display (when mode is lightning)
- Bitcoin address display (when mode is bitcoin)
- Seed phrase display (when mode is tokens)
**Key Patterns**:
- Uses `exchangeRateService` for BTC/USD conversion
- Conditional rendering based on `mode` prop
- Copy-to-clipboard functionality with visual feedback
- QR code generation for addresses
#### `PaymentCard.tsx` - Send/Receive Interface
**Purpose**: Unified interface for all send/receive operations.
**Modes Supported**:
- **Send**: Token send, Lightning invoice payment, Lightning address payment, Bitcoin send, reverse swap
- **Receive**: Token receive, Lightning invoice creation, Bitcoin address display
**Key Patterns**:
- Single component handles multiple operation types
- Uses `operation` prop ('send' | 'receive') to determine UI
- Uses `mode` prop ('tokens' | 'lightning' | 'bitcoin') for context
- Progressive disclosure: shows pending state (e.g., "Sending to: address") before amount input
- Input validation with error messages
**State Flow**:
```typescript
// Send flow
1. User enters invoice/address → detectAndHandleLightningInput()
2. Sets pending state (pendingInvoice, pendingLightningAddress)
3. Shows confirmation UI with amount
4. User confirms → handleConfirmInvoicePayment() or handleLightningAddressPayment()
// Receive flow
1. User enters amount → handleLightningReceive()
2. Creates mint quote → shows invoice modal
3. Waits for payment via mint-quote:redeemed event
```
#### `MintSelector.tsx` - Mint Dropdown
**Purpose**: Select and manage Cashu mints.
**Features**:
- Dropdown showing all trusted mints with balances
- Add new mint input
- Remove mint button (with confirmation modal)
- Active mint indicator
- Denomination breakdown button
**Key Patterns**:
- Uses `DropdownMenu` from shadcn/ui
- Filters mints to only show trusted mints
- Format balance with sats/USD toggle
- Inline input for adding mints
### Modal Components
#### `QRScanner.tsx`
- Camera-based QR code scanning
- Paste from clipboard support
- Classifies QR codes (invoice, address, token, etc.)
- Uses `html5-qrcode` library
#### `ProofBreakdownModal.tsx`
- Shows token denomination breakdown for a mint
- Displays total balance and count of each denomination
- Useful for debugging payment issues
#### `RemoveMintModal.tsx`
- Confirmation dialog for removing mints
- Warns about data loss
- Shows mint name/URL
#### `SeedPhraseModal.tsx`
- Input for restoring tokens from seed phrase
- Validates mnemonic format
- Shows active mint context
#### `TransactionHistory.tsx`
- Displays transaction history from coco
- Filters out unpaid quotes (only shows completed)
- Supports both Cashu and Bitcoin transactions
- Shows transaction type, amount, timestamp, mint info
## Hook Patterns
### Core Hooks
#### `useCashu.ts` - Wallet Manager
**Purpose**: Manages the `coco` wallet manager instance and core wallet state.
**Key Features**:
- Singleton pattern to prevent multiple initializations
- Mnemonic generation and validation
- Balance and mint state management
- Event listeners for automatic balance updates
- Repository access for direct proof operations
**Usage Pattern**:
```typescript
const {
coco, // Manager instance (null until initialized)
repositories, // Direct repository access
balances, // Reactive balance state
mints, // Reactive mint list
isInitialized, // Initialization status
isLoading, // Loading state
error, // Error state
mnemonic, // Current mnemonic
refreshMints // Refresh mint list
} = useCashu();
```
**Important Notes**:
- `coco` is `null` until wallet is initialized
- Always check `isInitialized` before using `coco`
- Balance updates automatically via event listeners
- Repositories provide direct access to proofs, mints, history
#### `useNpubCash.ts` - npub.cash Integration
**Purpose**: Integrates with npub.cash API for Lightning addresses and quote sync.
**Key Features**:
- NIP-98 authentication with Nostr signer
- User info fetching (mint URL, Lightning address)
- Quote synchronization with wallet
- Real-time quote updates via WebSocket
- Automatic mint addition for quotes
**Usage Pattern**:
```typescript
const {
setMint, // Set mint URL in npub.cash
getUserInfo, // Get user info (mint URL, name)
syncQuotesWithWallet, // Subscribe to quote updates
isLoggedIn, // Login status
isLoading, // Loading state
error // Error state
} = useNpubCash();
```
**Quote Sync Flow**:
1. On login, `syncQuotesWithWallet()` is called
2. Fetches all quotes from npub.cash
3. Adds mints if needed (auto-trusts)
4. Adds quotes to wallet via `coco.quotes.addMintQuote()`
5. Subscribes to real-time updates
6. On quote update, fetches newer quotes and syncs
#### `useLightningAddress.ts` - LNURL Resolution
**Purpose**: Resolves Lightning addresses to invoices using LNURL-pay protocol.
**Key Features**:
- Two-step LNURL-pay resolution
- Amount validation (min/max)
- Comment support
- Error handling with descriptive messages
**Usage Pattern**:
```typescript
const { getInvoice, isLoading, error } = useLightningAddress();
const invoice = await getInvoice({
lightningAddress: '[email protected]',
amountSats: 1000,
comment: 'Optional comment'
});
```
**Resolution Flow**:
1. Parse Lightning address → `https://domain/.well-known/lnurlp/username`
2. Fetch LNURL-pay info (min/max, callback URL)
3. Validate amount against bounds
4. Request invoice from callback URL with amount
5. Return BOLT11 invoice
### Domain Hooks
#### `useMintManager.ts` - Mint Operations
**Purpose**: Manages mint selection, adding, removing, and denomination display.
**Key Features**:
- Active mint selection with npub.cash sync
- Mint addition with auto-trust
- Mint removal with confirmation
- Denomination breakdown calculation
- Mint URL normalization
**Key Functions**:
- `handleSetActiveMint()` - Set active mint, optionally sync to npub.cash
- `handleAddMint()` - Add new mint with validation
- `handleRemoveMintClick()` - Show removal confirmation
- `handleConfirmRemoveMint()` - Remove mint and switch active mint
- `handleShowDenominations()` - Calculate and show token breakdown
**Important Patterns**:
```typescript
// Always check if mint exists before adding
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (isKnown) {
// Ensure trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
} else {
// Add with trusted flag
await coco.mint.addMint(mintUrl, { trusted: true });
}
```
#### `useTokenOperations.ts` - Cashu Token Operations
**Purpose**: Handles sending and receiving Cashu tokens.
**Key Features**:
- Token send with amount validation
- Token receive with unknown mint handling
- QR code generation for sent tokens
- Automatic mint addition for unknown mints
**Key Functions**:
- `handleTokenSend()` - Send tokens, generate QR code
- `handleTokenReceive()` - Receive tokens, handle unknown mints
- `handleUnknownMintError()` - Add unknown mint and retry
**Error Handling**:
- Detects `UnknownMintError` from coco
- Extracts mint URL from error message
- Automatically adds and trusts the mint
- Retries the receive operation
#### `useLightningOperations.ts` - Lightning Operations
**Purpose**: Handles Lightning invoice creation, payment, and address resolution.
**Key Features**:
- Lightning invoice creation (mint quotes)
- Invoice payment (melt quotes)
- Lightning address payment flow
- Invoice amount decoding
- Real-time payment tracking
**Key Functions**:
- `handleLightningReceive()` - Create mint quote, show invoice modal
- `detectAndHandleLightningInput()` - Classify input (invoice vs address)
- `handleLightningAddressPayment()` - Resolve address, create invoice, pay
- `handleConfirmInvoicePayment()` - Pay pending invoice
**Payment Flow**:
```typescript
// Receive flow
1. User enters amount → handleLightningReceive()
2. coco.quotes.createMintQuote(mintUrl, amount)
3. Generate QR code for invoice
4. Show invoice modal
5. Listen for 'mint-quote:redeemed' event
6. On payment, close modal and show success
// Send flow (invoice)
1. User enters invoice → detectAndHandleLightningInput()
2. Decode amount from invoice
3. Set pendingInvoice state
4. User confirms → handleConfirmInvoicePayment()
5. coco.quotes.createMeltQuote() + payMeltQuote()
// Send flow (address)
1. User enters address → detectAndHandleLightningInput()
2. Set pendingLightningAddress state
3. User enters amount → handleLightningAddressPayment()
4. Resolve address to invoice → createMeltQuote() + payMeltQuote()
```
#### `useHistoryManager.ts` - Transaction History
**Purpose**: Manages transaction history loading and filtering.
**Key Features**:
- Paginated history loading
- Filters out unpaid quotes (only completed transactions)
- Auto-refresh on wallet events
- Event listeners for history updates
**Filtering Logic**:
- Mint quotes: only show `state === 'ISSUED'` (completed)
- Melt quotes: only show `state === 'PAID'` (completed)
- Send/Receive: show all (no state field)
**Event Listeners**:
- `history:updated` - General history updates
- `melt-quote:created` - Melt quote created (coco bug workaround)
- `melt-quote:paid` - Melt quote paid
- `mint-quote:redeemed` - Mint quote redeemed (invoice paid)
#### `useQRCode.ts` - QR Code Operations
**Purpose**: Generates QR codes and scans QR codes with camera.
**Key Features**:
- QR code generation with `qrcode` library
- Camera-based scanning with `html5-qrcode`
- QR code classification (invoice, address, token, npub, Bitcoin address)
- Paste from clipboard support
- Error handling for camera permissions
**Classification Logic**:
```typescript
// Lightning invoice: lnbc... or lightning:lnbc...
// Lightning address: [email protected] or lightning:[email protected]
// Cashu token: cashu...
// Bitcoin address: bc1..., 1..., 3...
// Nostr npub: npub1... or nostr:npub1...
```
## Wallet Modes
The wallet supports three modes, each with different UI and operations:
### Mode: 'tokens' (Cashu)
**Purpose**: Direct Cashu token operations.
**Features**:
- Mint selector for choosing active mint
- Send tokens (generates Cashu token)
- Receive tokens (redeems Cashu token)
- Seed phrase display
- Token denomination breakdown
**Operations**:
- Send: `coco.wallet.send(mintUrl, amount)` → generates token
- Receive: `coco.wallet.receive(token)` → redeems token
### Mode: 'lightning'
**Purpose**: Lightning Network operations via Cashu mints.
**Features**:
- Lightning address display (from npub.cash)
- Send: Pay Lightning invoices or addresses
- Receive: Create Lightning invoices (mint quotes)
- Mint selector for choosing active mint
- Reverse swap support (on-chain to Lightning)
**Operations**:
- Send: `createMeltQuote()` + `payMeltQuote()` to pay invoice
- Receive: `createMintQuote()` → generates Lightning invoice → wait for payment
### Mode: 'bitcoin'
**Purpose**: On-chain Bitcoin operations.
**Features**:
- Bitcoin address display (derived from Nostr pubkey)
- UTXO selector for managing UTXOs
- Send Bitcoin on-chain
- Receive Bitcoin on-chain
- Consolidation support
**Note**: Bitcoin mode is handled by `BitcoinWallet` component (not shown in attached files reference BITCOIN_WALLET.md for more information).
## Mint Management
### Mint Lifecycle
1. **Add Mint**: User enters URL → `coco.mint.addMint(url, { trusted: true })`
2. **Trust Mint**: Automatically trusted when added (or via `coco.mint.trustMint()`)
3. **Select Mint**: Set as active mint → `setActiveMintUrl(url)`
4. **Remove Mint**: Delete from repository → `repositories.mintRepository.deleteMint(url)`
### Mint States
- **Known**: Mint exists in repository (from `getAllMints()`)
- **Trusted**: Mint is trusted (from `isTrustedMint()`)
- **Active**: Currently selected mint (stored in state and localStorage)
### Mint Synchronization
- When user logs into npub.cash, mint URL is fetched and set as active
- When user manually selects a mint, it's synced to npub.cash (if logged in)
- Active mint URL is persisted to localStorage
## Transaction Operations
### Send Operations
#### Token Send
```typescript
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
// Show QR code modal with token
```
#### Lightning Invoice Payment
```typescript
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
```
#### Lightning Address Payment
```typescript
// 1. Resolve address to invoice
const invoice = await getLightningInvoice({ lightningAddress, amountSats });
// 2. Pay invoice
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
```
### Receive Operations
#### Token Receive
```typescript
await coco.wallet.receive(token);
// Automatically handles unknown mints
```
#### Lightning Invoice Creation
```typescript
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// quote.request is the Lightning invoice
// Show QR code modal
// Listen for 'mint-quote:redeemed' event
```
## Integration Points
### npub.cash Integration
**Purpose**: Provides Lightning addresses and quote synchronization.
**Flow**:
1. User logs in with Nostr → `useNIP98` provides signer
2. `useNpubCash` creates `NPCClient` with JWT auth
3. On login, fetch user info → get mint URL and Lightning address
4. Set mint URL as active mint (if not already set)
5. Subscribe to quote updates → sync quotes to wallet
**Key Files**:
- `useNpubCash.ts` - API client and sync logic
- `useNIP98.ts` - NIP-98 authentication (not shown, but referenced)
### QR Code Integration
**Flow**:
1. User clicks scan button → opens `QRScanner` modal
2. Camera starts → `html5-qrcode` scans
3. QR code detected → `classifyQRCode()` classifies type
4. Result routed to appropriate handler:
- `lightning_invoice` → `handleQRResult()` → sets invoice
- `lightning_address` → `handleQRResult()` → sets address
- `cashu_token` → `handleQRResult()` → sets token input
- `bitcoin_address` → handled by BitcoinWallet
- `npub` → handled by BitcoinWallet
### Exchange Rate Service
**Purpose**: Provides BTC/USD conversion for balance display.
**Usage**:
```typescript
import { exchangeRateService } from '@/lib/exchangeRateService';
const rate = await exchangeRateService.getBtcUsdRate();
const usdAmount = await exchangeRateService.satsToUsd(sats);
```
**Features**:
- 1-minute cache to avoid excessive API calls
- Fallback to stale cache on error
- Coinbase API integration
## Extension Guidelines
### Error Handling Patterns
**Toast Notifications**:
```typescript
try {
await operation();
toast({
title: 'Success',
description: 'Operation completed successfully',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Error',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
```
**Unknown Mint Handling**:
```typescript
try {
await coco.wallet.receive(token);
} catch (err) {
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await coco.mint.addMint(mintUrl, { trusted: true });
await coco.wallet.receive(token); // Retry
}
}
}
```
## Best Practices
### State Management
1. **Use refs for initialization tracking**: Prevents duplicate requests
```typescript
const hasFetchedRef = useRef(false);
if (hasFetchedRef.current) return;
hasFetchedRef.current = true;
```
2. **Persist important state**: Use `useLocalStorage` for user preferences
```typescript
const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);
```
3. **Clean up state on unmount**: Reset state when drawers/modals close
```typescript
const handleClose = (open: boolean) => {
setModalOpen(open);
if (!open) {
// Reset all related state
setInput('');
setPending(null);
}
};
```
### Event Listeners
1. **Always unsubscribe**: Clean up event listeners in useEffect return
```typescript
useEffect(() => {
const unsubscribe = coco.on('event', handler);
return () => unsubscribe();
}, [coco]);
```
2. **Store unsubscribe functions**: Use refs for complex cleanup
```typescript
const unsubscribeRef = useRef<(() => void) | null>(null);
useEffect(() => {
unsubscribeRef.current = coco.on('event', handler);
return () => {
if (unsubscribeRef.current) {
unsubscribeRef.current();
}
};
}, [coco]);
```
### Type Safety
1. **Use types from coco-cashu-core**: Import types from the library
```typescript
import type { Manager, HistoryEntry, Mint } from 'coco-cashu-core';
```
2. **Validate inputs**: Check types and values before operations
```typescript
const amount = parseInt(input);
if (isNaN(amount) || amount <= 0) {
toast({ variant: 'destructive', title: 'Invalid amount' });
return;
}
```
## Common Patterns Reference
### Mint Check Pattern
```typescript
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (isKnown) {
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
} else {
await coco.mint.addMint(mintUrl, { trusted: true });
}
```
### Quote Sync Pattern
```typescript
// Group quotes by mint
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
// Process each mint
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
// Ensure mint exists and is trusted
// Add quotes
coco.quotes.addMintQuote(mintUrl, mintQuotes.map(q => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})));
}
```
## File Organization
```
src/
├── components/
│ └── wallet/
│ ├── CashuWallet.tsx # Main orchestrator
│ ├── WalletHeader.tsx # Balance and controls
│ ├── PaymentCard.tsx # Send/receive UI
│ ├── MintSelector.tsx # Mint dropdown
│ ├── TransactionHistory.tsx # History display
│ ├── ProofBreakdownModal.tsx # Token breakdown
│ ├── RemoveMintModal.tsx # Mint removal confirmation
│ ├── SeedPhraseModal.tsx # Seed phrase restore
│ └── QRScanner.tsx # QR code scanner
├── hooks/
│ └── wallet/
│ ├── useCashu.ts # Core wallet manager
│ ├── useMintManager.ts # Mint operations
│ ├── useTokenOperations.ts # Token send/receive
│ ├── useLightningOperations.ts # Lightning operations
│ ├── useLightningAddress.ts # LNURL resolution
│ ├── useNpubCash.ts # npub.cash API
│ ├── useQRCode.ts # QR code operations
│ ├── useHistoryManager.ts # Transaction history
│ └── useSeedPhraseRestore.ts # Seed phrase restore
└── lib/
├── bolt11Decoder.ts # Lightning invoice decoding
└── exchangeRateService.ts # BTC/USD exchange rates
```
## Additional Resources
- **coco-cashu-core**: Main Cashu library documentation
- **npubcash-sdk**: npub.cash API SDK documentation
- **LNURL-pay**: Lightning address protocol specification
- **BOLT11**: Lightning invoice format specification
-1
View File
@@ -17,7 +17,6 @@ export default tseslint.config(
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
+1 -6
View File
@@ -2,13 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>NutStack</title>
<meta name="description" content="A Bitcoin wallet powered by Nostr">
<meta property="og:type" content="website">
<meta property="og:title" content="NutStack">
<meta property="og:description" content="A Bitcoin wallet powered by Nostr">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+1277 -2777
View File
File diff suppressed because it is too large. Load diff
+8 -20
View File
@@ -6,16 +6,14 @@
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm i --silent && npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'"
},
"dependencies": {
"@bitcoinerlab/secp256k1": "^1.2.0",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@getalby/sdk": "^7.0.0",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,33 +41,24 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@scure/bip39": "^2.0.0",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@vulpemventures/secp256k1-zkp": "^3.2.1",
"bitcoinjs-lib": "^7.0.0",
"boltz-core": "^3.0.0",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"coco-cashu-core": "1.0.0-rc.17",
"coco-cashu-indexeddb": "1.0.0-rc.17",
"date-fns": "^3.6.0",
"ecpair": "^3.0.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"html5-qrcode": "^2.3.8",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"npubcash-sdk": "^0.2.0",
"nostr-tools": "^2.21.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -77,14 +66,13 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^3.25.71"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
"@tailwindcss/typography": "^0.5.15",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200
/assets/* /assets/:splat 200
/* /index.html 200
+18 -31
View File
@@ -6,14 +6,13 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
import { AppConfig } from '@/contexts/AppContext';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
import AppRouter from './AppRouter';
const head = createHead({
@@ -33,44 +32,32 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "system",
relayUrl: "wss://relay.ditto.pub",
};
const presetRelays = [
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to false to completely disable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP04_OR_NIP17,
theme: "light",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
};
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
-4
View File
@@ -2,10 +2,8 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import Messages from "./pages/Messages";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { WalletContainer } from "./components/wallet/WalletContainer";
export function AppRouter() {
return (
@@ -13,8 +11,6 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/messages" element={<Messages />} />
<Route path="/wallet" element={<WalletContainer />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+14 -8
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
@@ -9,14 +9,22 @@ interface AppProviderProps {
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for RelayMetadata validation
const RelayMetadataSchema = z.object({
relays: z.array(z.object({
url: z.url(),
read: z.boolean(),
write: z.boolean(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
relayMetadata: RelayMetadataSchema,
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
@@ -24,7 +32,6 @@ export function AppProvider(props: AppProviderProps) {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
@@ -50,7 +57,6 @@ export function AppProvider(props: AppProviderProps) {
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
@@ -90,11 +96,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
@@ -1,4 +1,4 @@
import React, { createContext, useContext, useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react';
import { useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
@@ -11,6 +11,7 @@ import { NSecSigner, type NostrEvent } from '@nostrify/nostrify';
import { generateSecretKey } from 'nostr-tools';
import type { MessageProtocol } from '@/lib/dmConstants';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import { DMContext, DMContextType, FileAttachment } from '@/contexts/DMContext';
// ============================================================================
// DM Types and Constants
@@ -117,172 +118,6 @@ const createErrorLogger = (name: string) => {
const nip17ErrorLogger = createErrorLogger('NIP-17');
/**
* Direct Messaging context interface providing access to all DM functionality.
*
* @property messages - Raw message state (Map of pubkey -> participant data)
* @property isLoading - True during initial load phases
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
* @property lastSync - Unix timestamps of last successful sync for each protocol
* @property subscriptions - Connection status for real-time message subscriptions
* @property conversations - Array of conversation summaries sorted by last activity
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
* @property scanProgress - Progress info for large message history scans
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
*/
interface DMContextType {
messages: MessagesState;
isLoading: boolean;
loadingPhase: LoadingPhase;
isDoingInitialLoad: boolean;
lastSync: LastSyncData;
subscriptions: SubscriptionStatus;
conversations: ConversationSummary[];
sendMessage: (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => Promise<void>;
protocolMode: ProtocolMode;
scanProgress: ScanProgressState;
clearCacheAndRefetch: () => Promise<void>;
}
const DMContext = createContext<DMContextType | null>(null);
/**
* Hook to access the direct messaging system.
*
* Provides access to conversations, message sending, loading states, and cache management.
* Must be used within a DMProvider.
*
* @example
* ```tsx
* import { useDMContext } from '@/contexts/DMContext';
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
*
* function MyComponent() {
* const { conversations, sendMessage, isLoading } = useDMContext();
*
* // Send a message
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!',
* protocol: MESSAGE_PROTOCOL.NIP17
* });
*
* // Display conversations
* return (
* <div>
* {isLoading ? 'Loading...' : conversations.map(c => (
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @returns DMContextType - The direct messaging context
* @throws Error if used outside DMProvider
*/
// eslint-disable-next-line react-refresh/only-export-components
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
throw new Error('useDMContext must be used within DMProvider');
}
return context;
}
const MESSAGES_PER_PAGE = 25;
/**
* Hook to access paginated messages for a specific conversation.
*
* Returns the most recent messages (default 25) with the ability to load earlier messages.
* Automatically resets to default page size when switching conversations.
*
* @example
* ```tsx
* import { useConversationMessages } from '@/contexts/DMContext';
*
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
* const {
* messages,
* hasMoreMessages,
* loadEarlierMessages,
* totalCount
* } = useConversationMessages(recipientPubkey);
*
* return (
* <div>
* {hasMoreMessages && (
* <button onClick={loadEarlierMessages}>
* Load Earlier ({totalCount - messages.length} more)
* </button>
* )}
* {messages.map(msg => (
* <div key={msg.id}>{msg.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @param conversationId - The pubkey of the conversation participant
* @returns Paginated message data with loading function
*/
// eslint-disable-next-line react-refresh/only-export-components
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
const result = useMemo(() => {
const conversationData = allMessages.get(conversationId);
if (!conversationData) {
return {
messages: [],
hasMoreMessages: false,
totalCount: 0,
lastMessage: null,
lastActivity: 0,
};
}
const totalMessages = conversationData.messages.length;
const hasMore = totalMessages > visibleCount;
// Return the most recent N messages (slice from the end)
const visibleMessages = conversationData.messages.slice(-visibleCount);
return {
messages: visibleMessages,
hasMoreMessages: hasMore,
totalCount: totalMessages,
lastMessage: conversationData.lastMessage,
lastActivity: conversationData.lastActivity,
};
}, [allMessages, conversationId, visibleCount]);
const loadEarlierMessages = useCallback(() => {
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
}, []);
// Reset visible count when conversation changes
useEffect(() => {
setVisibleCount(MESSAGES_PER_PAGE);
}, [conversationId]);
return {
...result,
loadEarlierMessages,
};
}
export interface DMConfig {
enabled?: boolean;
protocolMode?: ProtocolMode;
@@ -297,55 +132,12 @@ interface DMProviderProps {
// Message Sending Types and Helpers (Internal)
// ============================================================================
/**
* File attachment for direct messages (NIP-92 compatible).
*
* All fields are required. Use with `useUploadFile` hook to upload files
* and generate the proper tags format.
*
* @example
* ```tsx
* import { useUploadFile } from '@/hooks/useUploadFile';
* import type { FileAttachment } from '@/contexts/DMContext';
*
* const { mutateAsync: uploadFile } = useUploadFile();
*
* const tags = await uploadFile(file);
* const attachment: FileAttachment = {
* url: tags[0][1],
* mimeType: file.type,
* size: file.size,
* name: file.name,
* tags: tags
* };
*
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Check out this file!',
* attachments: [attachment]
* });
* ```
*
* @property url - Blossom server URL where file is hosted
* @property mimeType - MIME type of the file (e.g., 'image/png')
* @property size - File size in bytes
* @property name - Original filename
* @property tags - NIP-94 file metadata tags (includes hashes)
*/
export interface FileAttachment {
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}
/**
* Prepare message content with file URLs appended
*/
function prepareMessageContent(content: string, attachments: FileAttachment[] = []): string {
if (attachments.length === 0) return content;
const fileUrls = attachments.map(file => file.url).join('\n');
return content ? `${content}\n\n${fileUrls}` : fileUrls;
}
@@ -384,10 +176,10 @@ export function DMProvider({ children, config }: DMProviderProps) {
const { config: appConfig } = useAppContext();
const userPubkey = useMemo(() => user?.pubkey, [user?.pubkey]);
// Track relay URL to detect changes
const previousRelayUrl = useRef<string>(appConfig.relayUrl);
// Track relay metadata to detect changes
const previousRelayMetadata = useRef(appConfig.relayMetadata);
// Determine if NIP-17 is enabled based on protocol mode
const enableNIP17 = protocolMode !== PROTOCOL_MODE.NIP04_ONLY;
@@ -418,8 +210,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
// ============================================================================
// Send NIP-04 Message (internal)
const sendNIP4Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
const sendNIP4Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
content: string;
attachments?: FileAttachment[];
}>({
@@ -462,8 +254,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
});
// Send NIP-17 Message (internal)
const sendNIP17Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
const sendNIP17Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
content: string;
attachments?: FileAttachment[];
}>({
@@ -478,7 +270,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Step 1: Create the inner Kind 14 Private Direct Message
const now = Math.floor(Date.now() / 1000);
// Generate randomized timestamps for gift wraps (NIP-59 metadata privacy)
// Randomize within ±2 days in the PAST only (relays reject future timestamps > +30min)
const randomizeTimestamp = (baseTime: number) => {
@@ -528,11 +320,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Step 3: Create TWO Kind 1059 Gift Wrap events
// Per NIP-17/NIP-59: Gift wraps MUST be signed with random, ephemeral keys
// to hide the sender's identity and provide - some - metadata privacy
// Generate random secret keys for each gift wrap
const recipientRandomKey = generateSecretKey();
const senderRandomKey = generateSecretKey();
// Create signers with the random keys
const recipientRandomSigner = new NSecSigner(recipientRandomKey);
const senderRandomSigner = new NSecSigner(senderRandomKey);
@@ -565,15 +357,15 @@ export function DMProvider({ children, config }: DMProviderProps) {
nostr.event(recipientGiftWrap),
nostr.event(senderGiftWrap),
]);
// Check for failures and log detailed errors
const recipientResult = results[0];
const senderResult = results[1];
if (recipientResult.status === 'rejected') {
console.error('[DM] Failed to publish recipient gift wrap');
console.error('[DM] Recipient gift wrap event:', recipientGiftWrap);
// Try to extract detailed errors from AggregateError
const error = recipientResult.reason;
if (error && typeof error === 'object' && 'errors' in error) {
@@ -582,11 +374,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
console.error('[DM] Recipient error:', error);
}
}
if (senderResult.status === 'rejected') {
console.error('[DM] Failed to publish sender gift wrap');
console.error('[DM] Sender gift wrap event:', senderGiftWrap);
// Try to extract detailed errors from AggregateError
const error = senderResult.reason;
if (error && typeof error === 'object' && 'errors' in error) {
@@ -595,7 +387,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
console.error('[DM] Sender error:', error);
}
}
// If both failed, throw error
if (recipientResult.status === 'rejected' && senderResult.status === 'rejected') {
throw new Error(`Both gift wraps rejected. Recipient: ${recipientResult.reason}, Sender: ${senderResult.reason}`);
@@ -686,7 +478,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
let allNIP17Events: NostrEvent[] = [];
let processedMessages = 0;
// Adjust since timestamp to account for NIP-17 timestamp fuzzing (±2 days)
// We need to query from (lastSync - 2 days) to catch messages with randomized past timestamps
// This may fetch duplicates, but they're filtered by message ID in addMessageToState
@@ -921,7 +713,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
const existingMessageIds = new Set(
existing.messages.map(msg => msg.originalGiftWrapId || msg.id)
);
const newMessages = value.messages.filter(msg =>
const newMessages = value.messages.filter(msg =>
!existingMessageIds.has(msg.originalGiftWrapId || msg.id)
);
@@ -1260,7 +1052,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
if (!sinceTimestamp && lastSync.nip17) {
subscriptionSince = lastSync.nip17 - DM_CONSTANTS.SUBSCRIPTION_OVERLAP_SECONDS;
}
// Adjust for NIP-17 timestamp fuzzing (±2 days)
// Subscribe from (lastSync - 2 days) to catch messages with randomized past timestamps
const TWO_DAYS_IN_SECONDS = 2 * 24 * 60 * 60;
@@ -1309,7 +1101,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
const { readMessagesFromDB } = await import('@/lib/dmMessageStore');
const cachedStore = await readMessagesFromDB(userPubkey);
if (!cachedStore || Object.keys(cachedStore.participants).length === 0) {
@@ -1330,13 +1122,13 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Decrypt based on message kind
let decryptedContent: string | undefined;
let error: string | undefined;
if (msg.kind === 4) {
// NIP-04 message
const otherPubkey = msg.pubkey === user?.pubkey
const otherPubkey = msg.pubkey === user?.pubkey
? msg.tags.find(([name]) => name === 'p')?.[1]
: msg.pubkey;
if (otherPubkey && user?.signer?.nip04) {
try {
decryptedContent = await user.signer.nip04.decrypt(otherPubkey, msg.content);
@@ -1350,7 +1142,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
const sealContent = await user.signer.nip44.decrypt(msg.pubkey, msg.content);
const decryptedEvent = JSON.parse(sealContent) as NostrEvent;
// Keep seal structure but add decryptedEvent for access to inner fields
return {
...msg,
@@ -1362,7 +1154,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
}
}
}
return {
...msg,
id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`,
@@ -1405,17 +1197,17 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
// ===== PHASE 1: Load cache and show immediately =====
const { nip4Since, nip17Since } = await loadAllCachedMessages();
// Mark as completed BEFORE releasing isLoading to prevent re-trigger
setHasInitialLoadCompleted(true);
// Show cached messages immediately! Don't wait for relays
setLoadingPhase(LOADING_PHASES.READY);
setIsLoading(false);
// ===== PHASE 2: Query relays in background (non-blocking, parallel) =====
setLoadingPhase(LOADING_PHASES.RELAYS);
// Run NIP-04 and NIP-17 queries IN PARALLEL
const [nip4Result, nip17Result] = await Promise.all([
queryRelaysForMessagesSince(MESSAGE_PROTOCOL.NIP04, nip4Since),
@@ -1469,7 +1261,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
setSubscriptions({ isNIP4Connected: false, isNIP17Connected: false });
setScanProgress({ nip4: null, nip17: null });
setLoadingPhase(LOADING_PHASES.IDLE);
// Trigger reload by setting hasInitialLoadCompleted to false
setHasInitialLoadCompleted(false);
} catch (error) {
@@ -1487,7 +1279,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Cleanup effect
useEffect(() => {
if (!enabled) return;
return () => {
if (nip4SubscriptionRef.current) {
nip4SubscriptionRef.current.close();
@@ -1503,7 +1295,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Cleanup subscriptions
useEffect(() => {
if (!enabled) return;
return () => {
if (nip4SubscriptionRef.current) {
nip4SubscriptionRef.current.close();
@@ -1520,14 +1312,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Detect relay changes and reload messages
useEffect(() => {
const relayChanged = previousRelayUrl.current !== appConfig.relayUrl;
previousRelayUrl.current = appConfig.relayUrl;
const relayChanged = JSON.stringify(previousRelayMetadata.current) !== JSON.stringify(appConfig.relayMetadata);
previousRelayMetadata.current = appConfig.relayMetadata;
if (relayChanged && enabled && userPubkey && hasInitialLoadCompleted) {
clearCacheAndRefetch();
}
}, [enabled, userPubkey, appConfig.relayUrl, hasInitialLoadCompleted, clearCacheAndRefetch]);
}, [enabled, userPubkey, appConfig.relayMetadata, hasInitialLoadCompleted, clearCacheAndRefetch]);
// Detect hard refresh shortcut (Ctrl+Shift+R / Cmd+Shift+R) to clear cache
useEffect(() => {
@@ -1669,14 +1461,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
}, [enabled, messages, shouldSaveImmediately, writeAllMessagesToStore, triggerDebouncedWrite]);
// Send message
const sendMessage = useCallback(async (params: {
recipientPubkey: string;
content: string;
const sendMessage = useCallback(async (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => {
if (!enabled) return;
const { recipientPubkey, content, protocol = MESSAGE_PROTOCOL.NIP04, attachments } = params;
if (!userPubkey) return;
+24 -18
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -10,7 +10,7 @@ interface NostrProviderProps {
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const { config } = useAppContext();
const queryClient = useQueryClient();
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
const relayMetadata = useRef(config.relayMetadata);
// Invalidate Nostr queries when relayUrl changes
// Invalidate Nostr queries when relay metadata changes
useEffect(() => {
relayUrl.current = config.relayUrl;
relayMetadata.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayUrl, queryClient]);
}, [config.relayMetadata, queryClient]);
// Initialize NPool only once
if (!pool.current) {
@@ -32,21 +32,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
reqRouter(filters: NostrFilter[]) {
const routes = new Map<string, NostrFilter[]>();
// Route to all read relays
const readRelays = relayMetadata.current.relays
.filter(r => r.read)
.map(r => r.url);
for (const url of readRelays) {
routes.set(url, filters);
}
return routes;
},
eventRouter(_event: NostrEvent) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
const allRelays = new Set<string>(writeRelays);
return [...allRelays];
},
+62
View File
@@ -0,0 +1,62 @@
import { useEffect } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
/**
* NostrSync - Syncs user's Nostr data
*
* This component runs globally to sync various Nostr data when the user logs in.
* Currently syncs:
* - NIP-65 relay list (kind 10002)
*/
export function NostrSync() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { config, updateConfig } = useAppContext();
useEffect(() => {
if (!user) return;
const syncRelaysFromNostr = async () => {
try {
const events = await nostr.query(
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
if (events.length > 0) {
const event = events[0];
// Only update if the event is newer than our stored data
if (event.created_at > config.relayMetadata.updatedAt) {
const fetchedRelays = event.tags
.filter(([name]) => name === 'r')
.map(([_, url, marker]) => ({
url,
read: !marker || marker === 'read',
write: !marker || marker === 'write',
}));
if (fetchedRelays.length > 0) {
console.log('Syncing relay list from Nostr:', fetchedRelays);
updateConfig((current) => ({
...current,
relayMetadata: {
relays: fetchedRelays,
updatedAt: event.created_at,
},
}));
}
}
}
} catch (error) {
console.error('Failed to sync relays from Nostr:', error);
}
};
syncRelaysFromNostr();
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
return null;
}
+7 -2
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
className="text-blue-500 hover:underline break-all"
>
{url}
</a>
@@ -61,13 +61,18 @@ export function NoteContent({
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else if (decoded.type === 'nprofile') {
const pubkey = decoded.data.pubkey;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
className="text-blue-500 hover:underline break-all"
>
{fullMatch}
</Link>
+286
View File
@@ -0,0 +1,286 @@
import { useState, useEffect } from 'react';
import { Plus, X, Wifi, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
interface Relay {
url: string;
read: boolean;
write: boolean;
}
export function RelayListManager() {
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const { toast } = useToast();
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync)
useEffect(() => {
setRelays(config.relayMetadata.relays);
}, [config.relayMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
return new URL(url).toString();
} catch {
try {
return new URL(`wss://${url}`).toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: 'Invalid relay URL',
description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)',
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (relays.some(r => r.url === normalized)) {
toast({
title: 'Relay already exists',
description: 'This relay is already in your list.',
variant: 'destructive',
});
return;
}
const newRelays = [...relays, { url: normalized, read: true, write: true }];
setRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = relays.filter(r => r.url !== url);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleRead = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, read: !r.read } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleWrite = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, write: !r.write } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: Relay[]) => {
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
relayMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP65RelayList(newRelays);
}
};
const publishNIP65RelayList = (relayList: Relay[]) => {
const tags = relayList.map(relay => {
if (relay.read && relay.write) {
return ['r', relay.url];
} else if (relay.read) {
return ['r', relay.url, 'read'];
} else if (relay.write) {
return ['r', relay.url, 'write'];
}
// If neither read nor write, don't include (shouldn't happen)
return null;
}).filter((tag): tag is string[] => tag !== null);
publishEvent(
{
kind: 10002,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: 'Relay list published',
description: 'Your relay list has been published to Nostr.',
});
},
onError: (error) => {
console.error('Failed to publish relay list:', error);
toast({
title: 'Failed to publish relay list',
description: 'There was an error publishing your relay list to Nostr.',
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.protocol === 'wss:') {
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} else {
return parsed.href;
}
} catch {
return url;
}
}
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{relays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
>
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
{/* Settings Popover */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
>
<Settings className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="end">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
Read
</Label>
<Switch
id={`read-${relay.url}`}
checked={relay.read}
onCheckedChange={() => handleToggleRead(relay.url)}
className="data-[state=checked]:bg-green-500 scale-75"
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
Write
</Label>
<Switch
id={`write-${relay.url}`}
checked={relay.write}
onCheckedChange={() => handleToggleWrite(relay.url)}
className="data-[state=checked]:bg-blue-500 scale-75"
/>
</div>
</div>
</PopoverContent>
</Popover>
{/* Remove Button */}
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={relays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-relay-url" className="sr-only">
Relay URL
</Label>
<Input
id="new-relay-url"
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
Add Relay
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
Log in to sync your relay list with Nostr
</p>
)}
</div>
);
}
-174
View File
@@ -1,174 +0,0 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
interface RelaySelectorProps {
className?: string;
}
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url: string) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("justify-between", className)}
>
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue && isValidRelayInput(inputValue) ? (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{inputValue ? "Invalid relay URL" : "No relay found."}
</div>
)}
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
.map((option) => (
<CommandItem
key={option.url}
value={option.url}
onSelect={(currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedRelay === option.url ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span className="font-medium">{option.name}</span>
<span className="text-xs text-muted-foreground">{option.url}</span>
</div>
</CommandItem>
))}
{inputValue && isValidRelayInput(inputValue) && (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer border-t"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+13 -49
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,12 @@ 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/wallet/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;
}
@@ -75,8 +74,6 @@ const WalletContent = forwardRef<HTMLDivElement, {
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
cashuBalance: number;
isCashuInitialized: boolean;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
@@ -86,43 +83,14 @@ const WalletContent = forwardRef<HTMLDivElement, {
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 Wallet</h3>
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
<div className="flex items-center gap-3">
<Coins className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Cashu Wallet</p>
<p className="text-xs text-muted-foreground">
{isCashuInitialized
? `${cashuBalance.toLocaleString()} sats available`
: "Instant Bitcoin payments"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isCashuInitialized && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={isCashuInitialized ? "default" : "secondary"} className="text-xs">
{isCashuInitialized ? "Active" : "Not Set Up"}
</Badge>
</div>
</div>
</div>
<Separator />
{/* Lightning Fallback Methods */}
<div className="space-y-3">
<h3 className="font-medium">Other Options</h3>
<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">
@@ -222,12 +190,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!isCashuInitialized && !webln && connections.length === 0 && (
{!webln && 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
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
@@ -236,7 +204,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('');
@@ -254,10 +222,8 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
} = useNWC();
const { webln } = useWallet();
const { balances, isInitialized: isCashuInitialized } = useCashu();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
const { toast } = useToast();
const handleAddConnection = async () => {
@@ -301,8 +267,6 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
connections,
connectionInfo,
activeConnection,
cashuBalance,
isCashuInitialized,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
@@ -344,7 +308,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>
@@ -358,10 +322,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 wallet methods for zaps
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
@@ -406,7 +370,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>
@@ -414,10 +378,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 wallet 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/wallet/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>
);
}
+8 -92
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,7 +30,6 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
@@ -58,9 +57,6 @@ interface ZapContentProps {
qrCodeUrl: string;
copied: boolean;
webln: WebLNProvider | null;
// Cashu-related props
canPayWithCashu: boolean;
cashuBalance: number;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
@@ -79,8 +75,6 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
@@ -145,33 +139,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 && (
<Button
variant="outline"
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
@@ -196,26 +165,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 +188,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 +207,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 +218,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" />
@@ -298,7 +242,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
const { toast } = useToast();
const { webln, activeNWC } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
@@ -306,10 +249,6 @@ 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!');
@@ -389,25 +328,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);
};
@@ -419,8 +339,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
qrCodeUrl,
copied,
webln,
canPayWithCashu,
cashuBalance,
handleZap,
handleCopy,
openInWallet,
@@ -502,9 +420,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 +448,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>
+1 -15
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,8 +10,6 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { LightningWalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -43,9 +41,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
@@ -64,15 +59,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<LightningWalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Payment Settings</span>
</DropdownMenuItem>
</LightningWalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+1 -5
View File
@@ -2,7 +2,6 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
@@ -34,15 +33,13 @@ export function LoginArea({ className }: LoginAreaProps) {
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
<span>Sign up</span>
</Button>
</div>
)}
@@ -51,7 +48,6 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
+151 -187
View File
@@ -2,20 +2,20 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
import { DialogTitle } from '@radix-ui/react-dialog';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
@@ -26,7 +26,7 @@ const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
@@ -170,203 +170,167 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const hasExtension = 'nostr' in window;
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
const defaultTab = 'nostr' in window ? 'extension' : 'key';
const renderTabs = () => (
<Tabs defaultValue="key" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="key" className="flex items-center gap-2">
<span>Secret Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<span>Remote Signer</span>
</TabsTrigger>
</TabsList>
<TabsContent value='key' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleKeyLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
type="submit"
size="lg"
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
type="button"
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleBunkerLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
type="submit"
size="lg"
className='w-full'
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Log in'}
</Button>
</form>
</TabsContent>
</Tabs>
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
Log in
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1 min-h-0'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
<div className='px-6 pb-6 space-y-4 overflow-y-auto'>
{/* Extension Login Button - shown if extension is available */}
{hasExtension && (
<div className="space-y-4">
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
<Button
className="w-full h-12 px-9"
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Log in with Extension'}
</Button>
</div>
)}
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
{hasExtension ? (
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<CollapsibleTrigger asChild>
<button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
<span>More Options</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
</button>
</CollapsibleTrigger>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent>
</Tabs>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
</div>
</DialogContent>
</Dialog>
-50
View File
@@ -1,50 +0,0 @@
import { useState } from 'react';
import { User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
export function LoginIcon() {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
if (currentUser) {
return (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
);
}
return (
<>
<Button
onClick={() => setLoginDialogOpen(true)}
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
title="Log in"
>
<User className="!h-6 !w-6" />
</Button>
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</>
);
}
+88 -435
View File
@@ -2,35 +2,26 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Download, Upload, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const sanitizeFilename = (filename: string) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [showKey, setShowKey] = useState(false);
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -43,34 +34,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('download');
};
const downloadKey = () => {
@@ -79,8 +45,14 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Create a temporary link element and trigger download
const a = document.createElement('a');
@@ -94,32 +66,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const finishKeySetup = () => {
try {
// Continue to profile step
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
@@ -158,10 +111,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
@@ -173,9 +122,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -188,30 +134,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} catch {
toast({
@@ -219,372 +141,111 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
// Still proceed to completion even if profile failed
} finally {
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
if (step === 'generate') return 'Sign up';
if (step === 'download') return 'Secret Key';
if (step === 'profile') return 'Create Your Profile';
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('welcome');
setIsLoading(false);
setStep('generate');
setNsec('');
setShowSparkles(false);
setKeySecured('none');
setShowKey(false);
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
{/* Benefits */}
<div className='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
{/* Generate Step */}
{step === 'generate' && (
<div className='text-center space-y-4'>
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
{/* Animated background elements */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
<div className='text-center space-y-6'>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
{!isLoading && (
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={generateKey}
disabled={isLoading}
>
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
<Button className="w-full h-12 px-9" onClick={generateKey}>
Generate key
</Button>
</div>
)}
{/* Download Step - Whimsical and magical */}
{/* Download Step */}
{step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
<div className='space-y-4'>
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono text-sm"
/>
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</Button>
<div className='mx-auto max-w-sm'>
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-amber-900 dark:text-amber-300'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
</p>
</div>
</div>
</div>
)}
{/* Profile Step - Optional profile setup */}
{/* Profile Step */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
</div>
{/* Publishing status indicator */}
{isPublishing && (
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<div className='p-4 rounded-lg bg-muted border'>
<div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
<div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium'>
Publishing your profile...
</span>
</div>
@@ -602,7 +263,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
@@ -616,7 +276,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='rounded-lg resize-none'
className='resize-none'
rows={3}
disabled={isPublishing}
/>
@@ -632,7 +292,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='rounded-lg flex-1'
className='flex-1'
disabled={isPublishing}
/>
<input
@@ -648,7 +308,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
@@ -664,7 +323,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
className='w-full'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
@@ -674,24 +333,18 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
Creating Profile...
</>
) : (
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
'Create profile'
)}
</Button>
<Button
variant='outline'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
className='w-full'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
'Setting up account...'
) : (
'Skip for now'
)}
+2 -1
View File
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useCallback, memo } from 'react';
import { useConversationMessages, useDMContext } from '@/contexts/DMContext';
import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useDMContext } from '@/hooks/useDMContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
+1 -1
View File
@@ -1,6 +1,6 @@
import { useMemo, useState, memo } from 'react';
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState, useCallback } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea';
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
import {
+1 -1
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { LOADING_PHASES } from '@/lib/dmConstants';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<X className="size-5" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
-145
View File
@@ -1,145 +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 > 33
? `${content.substring(0, 15)}...${content.substring(content.length - 15)}`
: content}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+2 -2
View File
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
)}
{...props}
>
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-10 w-10 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
-1
View File
@@ -47,7 +47,6 @@ const Toast = React.forwardRef<
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
duration={5000}
{...props}
/>
)
-422
View File
@@ -1,422 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/wallet/useBitcoin';
import { useNsecAccess } from '@/hooks/useNsecAccess';
import { nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import { QRModal } from '@/components/ui/qr-modal';
import { TransactionCard } from './PaymentCard';
import { ConsolidationModal } from './ConsolidationModal';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
interface BitcoinWalletHeaderProps {
utxos: UTXO[];
utxoDropdownOpen: boolean;
setUtxoDropdownOpen: (open: boolean) => void;
onShowConsolidationModal: () => void;
isConsolidating: boolean;
onShowBitcoinAddressQR: (qr: string) => void;
}
interface BitcoinWalletProps {
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
user?: { pubkey: string };
onRequestQRScanner: () => void;
onQRResult?: (result: QRScanResult) => void;
onWalletHeaderPropsChange?: (props: BitcoinWalletHeaderProps) => void;
}
// Extend Window interface for QR handler
declare global {
interface Window {
__bitcoinWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function BitcoinWallet({
toast,
user,
onRequestQRScanner,
onQRResult,
onWalletHeaderPropsChange,
}: BitcoinWalletProps) {
const { hasNsecAccess } = useNsecAccess();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
const {
utxos,
isConsolidating,
bitcoinMaxAmount,
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
} = useBitcoinOperations(bitcoinAddress);
const {
data: bitcoinTransactions = [],
isLoading: isBitcoinTransactionsLoading
} = useBitcoinTransactionHistory(bitcoinAddress);
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
// UTXO state
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
// Fetch UTXOs when component mounts
useEffect(() => {
if (bitcoinAddress) {
fetchBitcoinUtxos();
}
}, [bitcoinAddress, fetchBitcoinUtxos]);
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
if (!open) {
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
}
};
const handleReceiveDrawerClose = (open: boolean) => {
setShowReceiveModal(open);
};
// Handle focus management when drawers open
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// Handle QR scan results (called from parent WalletContainer)
useEffect(() => {
if (!onQRResult) return;
const handleQRResult = (result: QRScanResult) => {
if (result.type === 'bitcoin_address') {
setBitcoinRecipient(result.value);
setPendingBitcoinRecipient(result.value);
setShowSendModal(true);
toast({
title: "Bitcoin Address Scanned",
description: "Enter amount to send",
});
} else if (result.type === 'npub') {
try {
const decoded = nip19.decode(result.value);
if (decoded.type === 'npub') {
const address = nostrPubkeyToBitcoinAddress(decoded.data);
setBitcoinRecipient(address);
setPendingBitcoinRecipient(address);
setShowSendModal(true);
toast({
title: "Nostr npub Scanned",
description: "Enter amount to send",
});
}
} catch {
toast({
variant: "destructive",
title: "Invalid npub",
description: "Could not decode npub",
});
}
}
};
// Store handler for parent to call
window.__bitcoinWalletQRHandler = handleQRResult;
return () => {
delete window.__bitcoinWalletQRHandler;
};
}, [onQRResult, toast]);
// Expose WalletHeader props to parent WalletContainer
// Use ref to track previous values and prevent infinite loops
const prevPropsRef = useRef<{
utxosLength?: number;
utxoDropdownOpen?: boolean;
isConsolidating?: boolean;
}>({});
useEffect(() => {
if (!onWalletHeaderPropsChange) return;
// Check if values actually changed
const currentProps = {
utxosLength: utxos?.length,
utxoDropdownOpen,
isConsolidating,
};
const prevProps = prevPropsRef.current;
const hasChanged =
prevProps.utxosLength !== currentProps.utxosLength ||
prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen ||
prevProps.isConsolidating !== currentProps.isConsolidating;
if (!hasChanged && Object.keys(prevProps).length > 0) {
// Values haven't changed, skip update
return;
}
// Update ref
prevPropsRef.current = currentProps;
// Send updated props
onWalletHeaderPropsChange({
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
onShowConsolidationModal: () => setShowConsolidationModal(true),
isConsolidating,
onShowBitcoinAddressQR: async (qr: string) => {
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
},
});
}, [
onWalletHeaderPropsChange,
utxos,
utxoDropdownOpen,
isConsolidating,
// Note: Functions (setUtxoDropdownOpen, etc.) are not in deps
// because they're stable setters or we accept they may change
// The ref-based change detection ensures we only update when primitives change
]);
return (
<>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={onRequestQRScanner}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<ScanLine className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isBitcoinBalanceLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground font-medium">History</span>
</button>
</div>
</div>
{/* Modals */}
<>
{/* Consolidation Modal */}
<ConsolidationModal
isOpen={showConsolidationModal}
onClose={() => setShowConsolidationModal(false)}
utxos={utxos}
onConfirm={handleConsolidateUtxos}
isConsolidating={isConsolidating}
/>
{/* Bitcoin Address QR Modal */}
<QRModal
isOpen={showBitcoinAddressQR}
onClose={() => setShowBitcoinAddressQR(false)}
title="Bitcoin Address"
description="Scan this QR code to send Bitcoin to your address"
qrCodeUrl={bitcoinAddressQRCode}
content={bitcoinAddress || ''}
icon="qr"
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="send"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {
handleBitcoinSend(
bitcoinAmount,
pendingBitcoinRecipient,
setBitcoinAmount,
setBitcoinRecipient,
setPendingBitcoinRecipient,
setShowSendModal
);
}}
onReceive={() => {}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount={bitcoinAmount}
setBitcoinAmount={setBitcoinAmount}
bitcoinRecipient={bitcoinRecipient}
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={() => handleSendMax(setBitcoinAmount)}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive Bitcoin on-chain
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode="bitcoin"
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={null}
onSend={() => {}}
onReceive={() => {
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isBitcoinBalanceLoading}
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount=""
setBitcoinAmount={() => {}}
bitcoinRecipient=""
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your Bitcoin transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={[]}
isLoading={isBitcoinTransactionsLoading}
bitcoinTransactions={bitcoinTransactions}
isBitcoinLoading={isBitcoinTransactionsLoading}
showSats={true}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</>
);
}
-948
View File
@@ -1,948 +0,0 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useLightningAddress } from '@/hooks/wallet/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/wallet/useNpubCash';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
import { useMintManager } from '@/hooks/wallet/useMintManager';
import { useTokenOperations } from '@/hooks/wallet/useTokenOperations';
import { useLightningOperations } from '@/hooks/wallet/useLightningOperations';
import { useReverseSwapOperations } from '@/hooks/wallet/useReverseSwapOperations';
import { useSeedPhraseRestore } from '@/hooks/wallet/useSeedPhraseRestore';
import { useHistoryManager } from '@/hooks/wallet/useHistoryManager';
import { decodeBolt11Amount } from '@/lib/bolt11Decoder';
import { QRModal } from '@/components/ui/qr-modal';
import { TransactionCard } from './PaymentCard';
import { ProofBreakdownModal } from './ProofBreakdownModal';
import { RemoveMintModal } from './RemoveMintModal';
import { SeedPhraseModal } from './SeedPhraseModal';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface CashuMint {
url: string;
name?: string;
}
interface CashuWalletHeaderProps {
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;
mintDropdownOpen: boolean;
setMintDropdownOpen: (open: boolean) => void;
npubCashUsername?: string;
onShowLightningAddressQR: (qr: string) => void;
onShowSeedPhraseInfo: () => void;
}
interface CashuWalletProps {
mode: 'tokens' | 'lightning';
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
generateQRCode: (text: string) => Promise<string>;
user?: { pubkey: string };
onRequestQRScanner: () => void;
onWalletHeaderPropsChange?: (props: CashuWalletHeaderProps) => void;
}
// Extend Window interface for QR handler
declare global {
interface Window {
__cashuWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function CashuWallet({
mode,
toast,
generateQRCode,
user,
onRequestQRScanner,
onWalletHeaderPropsChange,
}: CashuWalletProps) {
// ============================================================================
// CORE HOOKS
// ============================================================================
const {
coco,
repositories,
isInitialized,
isLoading,
error,
mints,
getEncodedToken,
refreshMints,
} = useCashu();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
syncQuotesWithWallet,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
// Wrapper to handle return type mismatch
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
return setNpubCashMint(mintUrl);
};
// State to track npub.cash user info
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
// Ref to track if we've fetched user info (only fetch once)
const hasFetchedUserInfoRef = useRef(false);
// Ref to track if we've set a mint from user info (to prevent overwriting with stored mint)
const hasSetMintFromUserInfoRef = useRef(false);
// Persist active mint URL to localStorage
const [storedActiveMintUrl, setStoredActiveMintUrl] = useLocalStorage<string | null>('cashu-active-mint-url', null);
// ============================================================================
// DOMAIN HOOKS
// ============================================================================
const {
activeMintUrl,
setActiveMintUrl,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
} = useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint: handleSetNpubCashMint,
refreshMints,
});
// Wrapper for setActiveMintUrl to handle the async nature
const handleSetActiveMintSync = useCallback((url: string | null) => {
setActiveMintUrl(url);
}, [setActiveMintUrl]);
// Transaction operation hooks
const tokenOps = useTokenOperations({
coco,
activeMintUrl,
generateQRCode,
getEncodedToken,
});
const lightningOps = useLightningOperations({
coco,
activeMintUrl,
generateQRCode,
getLightningInvoice,
});
const reverseSwapOps = useReverseSwapOperations({
coco,
activeMintUrl,
});
const restore = useSeedPhraseRestore({ coco });
// Extract all needed values
const {
tokenInput,
setTokenInput,
sendAmount,
setSendAmount,
sentToken,
setSentToken,
sentTokenQRCode,
} = tokenOps;
const {
quoteAmount,
setQuoteAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
handleConfirmInvoicePayment,
mintQuoteUnsubscribeRef,
} = lightningOps;
const {
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
} = reverseSwapOps;
const {
handleRestoreFromSeedPhrase,
isRestoring,
} = restore;
// Combined receive handler that routes to appropriate operation
const handleReceive = async () => {
if (tokenInput) {
return tokenOps.handleTokenReceive();
} else if (quoteAmount) {
return lightningOps.handleLightningReceive();
}
};
// Combined send handler that routes to appropriate operation
const handleSend = async () => {
// Check for token send first
if (sendAmount && activeMintUrl) {
return tokenOps.handleTokenSend();
}
// Check for reverse swap
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
return reverseSwapOps.handleReverseSwap();
}
// Check for Lightning address payment
if (pendingLightningAddress) {
return lightningOps.handleLightningAddressPayment();
}
// Handle Lightning invoice/address input detection
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// First check if it's a Bitcoin address for reverse swap
if (reverseSwapOps.detectBitcoinAddress(input)) {
setLightningInvoice('');
setLightningAddressInput('');
return;
}
// Then check for Lightning address or invoice
lightningOps.detectAndHandleLightningInput(input);
};
const {
historyEntries,
isLoadingHistory,
} = useHistoryManager({
coco,
isInitialized,
});
// ============================================================================
// UI STATE
// ============================================================================
const showSats = true; // Always show in sats for Cashu wallet
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = useState(false);
const [showHistoryModal, setShowHistoryModal] = useState(false);
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
// Handle drawer close with state reset
const handleSendDrawerClose = (open: boolean) => {
setShowSendModal(open);
if (!open) {
// Reset all send-related state when drawer closes
setSendAmount('');
setLightningInvoice('');
setLightningAddressInput('');
setLightningAddressAmount('');
setPendingLightningAddress(null);
setDecodedInvoiceAmount(null);
setPendingInvoice(null);
// Reset reverse swap state
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
}
};
const handleReceiveDrawerClose = (open: boolean) => {
setShowReceiveModal(open);
if (!open) {
// Reset all receive-related state when drawer closes
setTokenInput('');
setQuoteAmount('');
}
};
// ============================================================================
// EFFECTS - Error Handling
// ============================================================================
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "Npub.cash Error",
description: npubCashError,
});
clearNpubCashError();
}
}, [npubCashError, clearNpubCashError, toast]);
// ============================================================================
// EFFECTS - NPub.cash Integration
// ============================================================================
// Track previous login state to detect logout
const prevLoggedInRef = useRef(isNpubCashLoggedIn);
// Fetch npub.cash user info once and set mint if available
useEffect(() => {
// Detect logout: was logged in, now not logged in
if (prevLoggedInRef.current && !isNpubCashLoggedIn) {
setNpubCashUserInfo(null);
hasFetchedUserInfoRef.current = false; // Reset so we can fetch again if they log back in
hasSetMintFromUserInfoRef.current = false;
hasAttemptedRestoreRef.current = false; // Reset restore so it can run again
}
prevLoggedInRef.current = isNpubCashLoggedIn;
// Only fetch if logged in, initialized, not loading, and we haven't fetched yet
if (!isNpubCashLoggedIn || !isInitialized || isNpubCashLoading || hasFetchedUserInfoRef.current) {
// If not logged in, mark as "fetched" (skipped) so restore logic can run
if (!isNpubCashLoggedIn && isInitialized && !hasFetchedUserInfoRef.current) {
hasFetchedUserInfoRef.current = true;
}
return;
}
// Mark as fetched to prevent duplicate requests
hasFetchedUserInfoRef.current = true;
const fetchUserInfo = async () => {
console.log('[CashuWallet] Fetching npub.cash user info...');
try {
const userInfo = await getNpubCashUserInfo();
console.log('[CashuWallet] npub.cash user info received:', userInfo);
if (userInfo && userInfo.mintUrl) {
setNpubCashUserInfo(userInfo);
console.log('[CashuWallet] Setting mint from npub.cash:', userInfo.mintUrl);
if (!coco) {
console.warn('[CashuWallet] coco not available, cannot add/set mint');
return;
}
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mintUrl.toLowerCase());
if (isKnown) {
// Mint exists but may not be trusted, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(userInfo.mintUrl);
if (!isTrusted) {
console.log('[CashuWallet] Trusting existing mint:', userInfo.mintUrl);
await coco.mint.trustMint(userInfo.mintUrl);
}
} else {
// Add mint from npub.cash and automatically trust it
console.log('[CashuWallet] Adding new mint from npub.cash:', userInfo.mintUrl);
await coco.mint.addMint(userInfo.mintUrl, { trusted: true });
}
// Set as active mint immediately
console.log('[CashuWallet] Setting active mint:', userInfo.mintUrl);
setActiveMintUrl(userInfo.mintUrl, false);
hasSetMintFromUserInfoRef.current = true;
} else {
console.log('[CashuWallet] No mintUrl in user info:', userInfo);
setNpubCashUserInfo(null);
}
} catch (err) {
console.error('[CashuWallet] Failed to get npub.cash user info:', err);
setNpubCashUserInfo(null);
hasFetchedUserInfoRef.current = false; // Allow retry on error
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, coco, setActiveMintUrl]);
// Ref to track if we've attempted restore/default mint logic
const hasAttemptedRestoreRef = useRef(false);
// Restore previous mint or add default mint if no user info mint was set
useEffect(() => {
// Only run after wallet is initialized
if (!isInitialized || !coco || hasAttemptedRestoreRef.current) return;
// If logged in, wait for user info check to complete
if (isNpubCashLoggedIn && !hasFetchedUserInfoRef.current) return;
// If we already set a mint from user info, don't override it
if (hasSetMintFromUserInfoRef.current) {
hasAttemptedRestoreRef.current = true;
return;
}
// If there's already an active mint, don't do anything
if (activeMintUrl) {
hasAttemptedRestoreRef.current = true;
return;
}
// Mark as attempted to prevent multiple runs
hasAttemptedRestoreRef.current = true;
const restoreOrAddDefaultMint = async () => {
// First, try to restore from stored mint if it exists and is valid
if (storedActiveMintUrl) {
const allMints = await coco.mint.getAllMints();
const storedMintExists = allMints.some(m => m.mintUrl.toLowerCase() === storedActiveMintUrl.toLowerCase());
if (storedMintExists) {
const isTrusted = await coco.mint.isTrustedMint(storedActiveMintUrl);
if (isTrusted) {
console.log('[CashuWallet] Restoring previous mint:', storedActiveMintUrl);
setActiveMintUrl(storedActiveMintUrl, false);
return;
}
}
}
// If no stored mint to restore, check if we need to add default mint
const trustedMints = await coco.mint.getAllTrustedMints();
// Only add default mint if no mints exist at all
if (trustedMints.length === 0) {
const defaultMintUrl = 'https://mint.minibits.cash/Bitcoin';
console.log('[CashuWallet] No mints found, adding default mint:', defaultMintUrl);
try {
await coco.mint.addMint(defaultMintUrl, { trusted: true });
// Wait a bit for mint to be added, then set as active
setTimeout(() => {
setActiveMintUrl(defaultMintUrl, false);
}, 500);
} catch (err) {
console.error('[CashuWallet] Failed to add default mint:', err);
}
}
};
restoreOrAddDefaultMint();
}, [isInitialized, coco, activeMintUrl, storedActiveMintUrl, setActiveMintUrl, isNpubCashLoggedIn]);
// Save active mint URL to localStorage when it changes
useEffect(() => {
// Save active mint URL to localStorage whenever it changes
// This includes user info mint, restored mint, default mint, and manual selections
if (activeMintUrl && storedActiveMintUrl !== activeMintUrl) {
console.log('[CashuWallet] Saving active mint to localStorage:', activeMintUrl);
setStoredActiveMintUrl(activeMintUrl);
}
}, [activeMintUrl, storedActiveMintUrl, setStoredActiveMintUrl]);
// Set up automatic quote sync subscription when logged into npub.cash
useEffect(() => {
if (!isNpubCashLoggedIn || !coco || !isInitialized) return;
let unsubscribe: (() => void) | null = null;
const setupSync = async () => {
unsubscribe = await syncQuotesWithWallet(coco);
};
setupSync();
return () => {
if (unsubscribe) {
unsubscribe();
}
};
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
// Handle focus management when drawers open to prevent aria-hidden warnings
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
// Blur any currently focused element to allow drawer's focus trap to work
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, [mintQuoteUnsubscribeRef]);
// Handle QR scan results (called from parent WalletContainer)
const handleQRResult = useCallback((result: QRScanResult) => {
switch (result.type) {
case 'lightning_invoice': {
setLightningInvoice(result.value);
setPendingInvoice(result.value);
// Decode invoice amount
const amount = decodeBolt11Amount(result.value);
setDecodedInvoiceAmount(amount);
setShowSendModal(true);
toast({
title: "Lightning Invoice Scanned",
description: amount ? `${amount} sats` : "Invoice ready to pay",
});
break;
}
case 'lightning_address': {
setLightningAddressInput(result.value);
setPendingLightningAddress(result.value);
setShowSendModal(true);
toast({
title: "Lightning Address Scanned",
description: "Enter amount to send",
});
break;
}
case 'cashu_token': {
setTokenInput(result.value);
setShowReceiveModal(true);
toast({
title: "Cashu Token Scanned",
description: "Token ready to redeem",
});
break;
}
default: {
// Bitcoin addresses and npubs are handled by BitcoinWallet
break;
}
}
}, [setLightningInvoice, setPendingInvoice, setDecodedInvoiceAmount, setShowSendModal, setLightningAddressInput, setPendingLightningAddress, setTokenInput, setShowReceiveModal, toast]);
// Expose handler to parent via window (temporary, will be improved)
useEffect(() => {
window.__cashuWalletQRHandler = handleQRResult;
return () => {
delete window.__cashuWalletQRHandler;
};
}, [handleQRResult]);
// ============================================================================
// RENDER
// ============================================================================
// Expose WalletHeader props to parent WalletContainer
// Use ref to track previous values and prevent infinite loops
const prevPropsRef = useRef<{
activeMintUrl?: string | null;
mintsLength?: number;
firstMintUrl?: string;
mintUrl?: string;
mintDropdownOpen?: boolean;
npubCashUsername?: string;
}>({});
// Extract first mint URL to avoid complex expression in dependency array
const firstMintUrl = mints?.[0]?.url;
useEffect(() => {
if (!onWalletHeaderPropsChange) return;
const npubCashUsername = user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined;
// Check if values actually changed
const currentProps = {
activeMintUrl,
mintsLength: mints?.length,
firstMintUrl,
mintUrl,
mintDropdownOpen,
npubCashUsername,
};
const prevProps = prevPropsRef.current;
const hasChanged =
prevProps.activeMintUrl !== currentProps.activeMintUrl ||
prevProps.mintsLength !== currentProps.mintsLength ||
prevProps.firstMintUrl !== currentProps.firstMintUrl ||
prevProps.mintUrl !== currentProps.mintUrl ||
prevProps.mintDropdownOpen !== currentProps.mintDropdownOpen ||
prevProps.npubCashUsername !== currentProps.npubCashUsername;
if (!hasChanged && Object.keys(prevProps).length > 0) {
// Values haven't changed, skip update
return;
}
// Update ref
prevPropsRef.current = currentProps;
// Send updated props
onWalletHeaderPropsChange({
activeMintUrl,
setActiveMintUrl: handleSetActiveMintSync,
mints: mints || [],
mintUrl,
setMintUrl,
onAddMint: handleAddMint,
onRemoveMint: handleRemoveMintClick,
onShowDenominations: (mintUrl: string) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown),
getCleanMintLabel,
mintDropdownOpen,
setMintDropdownOpen,
npubCashUsername,
onShowLightningAddressQR: async (qr: string) => {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
},
onShowSeedPhraseInfo: () => setShowSeedPhraseInfo(true),
});
}, [
onWalletHeaderPropsChange,
activeMintUrl,
mints,
firstMintUrl,
mintUrl,
mintDropdownOpen,
npubCashUserInfo?.name,
user?.pubkey,
handleSetActiveMintSync,
handleAddMint,
handleRemoveMintClick,
handleShowDenominations,
getCleanMintLabel,
setMintDropdownOpen,
setMintUrl,
setShowProofBreakdown,
setProofBreakdown,
setLightningAddressQRCode,
setShowLightningAddressQR,
setShowSeedPhraseInfo,
// Note: These functions are stable setters or wrapped in useCallback
// because they're stable from hooks or we accept they may change
// The ref-based change detection ensures we only update when primitives change
]);
return (
<>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-8 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={onRequestQRScanner}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<ScanLine className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground font-medium">History</span>
</button>
</div>
</div>
{/* Modals */}
<>
{/* Proof Breakdown Modal */}
<ProofBreakdownModal
isOpen={showProofBreakdown}
onClose={() => setShowProofBreakdown(false)}
proofBreakdown={proofBreakdown}
/>
{/* Remove Mint Modal */}
<RemoveMintModal
isOpen={showRemoveMintModal}
onClose={() => setShowRemoveMintModal(false)}
mintToRemove={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading || isNpubCashLoading}
/>
{/* QR Modals */}
<QRModal
isOpen={showLightningAddressQR}
onClose={() => setShowLightningAddressQR(false)}
title="Lightning Address"
description="Scan this QR code to send payments to your Lightning address"
qrCodeUrl={lightningAddressQRCode}
content={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) + '@npubx.cash' : ''}
icon="zap"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
{/* Sent Token Modal */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
{/* Seed Phrase Restore Modal */}
<SeedPhraseModal
isOpen={showSeedPhraseInfo}
onClose={() => setShowSeedPhraseInfo(false)}
onRestoreFromSeedPhrase={handleRestoreFromSeedPhrase}
isRestoring={isRestoring}
mints={mints}
activeMintUrl={activeMintUrl}
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send tokens or Lightning payments
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode={mode}
operation="send"
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
decodedInvoiceAmount={decodedInvoiceAmount}
setDecodedInvoiceAmount={setDecodedInvoiceAmount}
pendingInvoice={pendingInvoice}
setPendingInvoice={setPendingInvoice}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={activeMintUrl}
onSend={() => {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
}
}}
onReceive={() => {}}
onConfirmInvoice={() => {
handleConfirmInvoicePayment();
setShowSendModal(false);
}}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading || isNpubCashLoading}
// Reverse swap props
pendingBitcoinSwapAddress={pendingBitcoinSwapAddress}
setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress}
bitcoinSwapAmount={bitcoinSwapAmount}
setBitcoinSwapAmount={setBitcoinSwapAmount}
swapStatus={swapStatus}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive tokens or Lightning invoices
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
mode={mode}
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onSend={() => {}}
onReceive={() => {
handleReceive();
setShowReceiveModal(false);
}}
isResolvingAddress={false}
isLoading={isLoading || isNpubCashLoading}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
bitcoinTransactions={[]}
isBitcoinLoading={false}
showSats={showSats}
/>
</ScrollArea>
</DrawerContent>
</Drawer>
</>
</>
);
}
@@ -1,92 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, ArrowRightLeft, RefreshCw } from 'lucide-react';
import { UTXO } from '@/lib/bitcoin';
interface ConsolidationModalProps {
isOpen: boolean;
onClose: () => void;
utxos: UTXO[];
onConfirm: () => void;
isConsolidating: boolean;
}
export function ConsolidationModal({
isOpen,
onClose,
utxos,
onConfirm,
isConsolidating,
}: ConsolidationModalProps) {
if (!isOpen) return null;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] 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">
<ArrowRightLeft className="h-5 w-5 mr-2 text-primary" />
Consolidate UTXOs
</CardTitle>
<CardDescription>
Combine multiple UTXOs into a single transaction
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="text-center">
<div className="text-2xl font-bold text-primary mb-2">
{utxos.length} UTXO{utxos.length !== 1 ? 's' : ''}
</div>
<div className="text-sm text-muted-foreground">
Total Value: {utxos.reduce((sum, utxo) => sum + utxo.value, 0).toLocaleString()} sats
</div>
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>🔄 <strong>What this does:</strong> Combines all your UTXOs into a single transaction, sending the total amount (minus fees) back to your own address.</div>
<div>💰 <strong>Benefits:</strong> Reduces transaction fees for future payments and simplifies your UTXO management.</div>
<div>⚠️ <strong>Note:</strong> This will create a new transaction on the Bitcoin network and may take some time to confirm.</div>
</div>
<div className="flex justify-center">
<Button
onClick={() => {
onConfirm();
onClose();
}}
disabled={isConsolidating || utxos.length <= 1}
>
{isConsolidating ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Consolidating...
</>
) : (
<>
<ArrowRightLeft className="h-4 w-4 mr-2" />
Consolidate UTXOs
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
-192
View File
@@ -1,192 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, X, Check, ChevronDown, Landmark } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
interface CashuMint {
url: string;
name?: string;
}
interface MintSelectorProps {
balances: { [key: string]: number };
showSats: boolean;
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function MintSelector({
balances,
showSats,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: MintSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const activeMint = mints.find(mint => mint.url === activeMintUrl);
const activeBalance = activeMint ? balances[activeMint.url] || 0 : 0;
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0">
<div className="flex items-center justify-between w-full min-w-0">
{activeMint ? (
<>
<div className="flex items-center gap-2 min-w-0 flex-1">
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">{getCleanMintLabel(activeMint)}</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(activeBalance)}
</span>
</>
) : (
<span className="text-muted-foreground truncate min-w-0 flex-1">Select a mint</span>
)}
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
</div>
{mints.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem asChild>
<div className="flex gap-2 p-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="flex-1"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Escape') {
setDropdownOpen(false);
} else if (e.key === 'Enter') {
e.preventDefault();
if (mintUrl.trim()) {
onAddMint();
}
}
}}
onKeyUp={(e) => e.stopPropagation()}
/>
<Button
onClick={(e) => {
e.stopPropagation();
onAddMint();
}}
disabled={!mintUrl.trim()}
size="sm"
>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{activeMint && (
<div className="flex flex-col gap-1">
<button
onClick={() => onShowDenominations(activeMint.url)}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="View token breakdown"
>
<Landmark className="h-4 w-4" />
</button>
</div>
)}
</div>
);
}
-568
View File
@@ -1,568 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Send, Download, ArrowRight, Zap, X } from 'lucide-react';
import { useState, useEffect } from 'react';
// Helper function to prevent complex inline ternary operators
const getOperationMessage = (operation: string, mode: string): string => {
if (operation === 'send') {
return mode === 'tokens'
? 'Select a mint to send tokens'
: 'Select a mint to pay Lightning invoices';
} else {
return mode === 'tokens'
? 'Select a mint to receive tokens'
: 'Select a mint to create Lightning invoice';
}
};
// Helper function to truncate long addresses (show first 12, last 12 with ellipsis in middle)
const truncateAddress = (address: string): string => {
if (address.length <= 26) return address; // "first 12" + "..." + "last 12" = 26
return address.slice(0, 12) + '...' + address.slice(-12);
};
interface TransactionCardProps {
mode: 'tokens' | 'lightning' | 'bitcoin';
operation: 'send' | 'receive';
// Send props
sendAmount: string;
setSendAmount: (value: string) => void;
lightningInvoice: string;
setLightningInvoice: (value: string) => void;
lightningAddressInput: string;
setLightningAddressInput: (value: string) => void;
lightningAddressAmount: string;
setLightningAddressAmount: (value: string) => void;
pendingLightningAddress: string | null;
setPendingLightningAddress: (value: string | null) => void;
decodedInvoiceAmount: number | null;
setDecodedInvoiceAmount: (value: number | null) => void;
pendingInvoice: string | null;
setPendingInvoice: (value: string | null) => void;
// Receive props
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
// Common props
activeMintUrl: string | null;
onSend: () => void;
onReceive: () => void;
onConfirmInvoice?: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
// Bitcoin props
bitcoinAddress?: string;
bitcoinAmount?: string;
setBitcoinAmount?: (value: string) => void;
bitcoinRecipient?: string;
setBitcoinRecipient?: (value: string) => void;
pendingBitcoinRecipient?: string | null;
setPendingBitcoinRecipient?: (value: string | null) => void;
hasNsecAccess?: boolean;
bitcoinMaxAmount?: number;
onSendMax?: () => void;
// Reverse swap props (Lightning mode)
pendingBitcoinSwapAddress?: string | null;
setPendingBitcoinSwapAddress?: (value: string | null) => void;
bitcoinSwapAmount?: string;
setBitcoinSwapAmount?: (value: string) => void;
swapStatus?: string | null;
}
export function TransactionCard({
mode,
operation,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onSend,
onReceive,
onConfirmInvoice,
isResolvingAddress,
isLoading,
bitcoinAddress,
bitcoinAmount,
setBitcoinAmount,
bitcoinRecipient,
setBitcoinRecipient,
pendingBitcoinRecipient,
setPendingBitcoinRecipient,
hasNsecAccess,
bitcoinMaxAmount,
onSendMax,
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
}: TransactionCardProps) {
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
const [swapAmountError, setSwapAmountError] = useState<string | null>(null);
const handleSendMaxToggle = () => {
const newState = !sendMaxEnabled;
setSendMaxEnabled(newState);
if (newState && onSendMax) {
onSendMax();
}
};
// Reset send max toggle when bitcoin recipient changes
useEffect(() => {
if (!pendingBitcoinRecipient) {
setSendMaxEnabled(false);
}
}, [pendingBitcoinRecipient]);
// Reset swap amount error when swap address changes
useEffect(() => {
if (!pendingBitcoinSwapAddress) {
setSwapAmountError(null);
}
}, [pendingBitcoinSwapAddress]);
// Validate swap amount when it changes
useEffect(() => {
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
const amount = parseInt(bitcoinSwapAmount);
if (isNaN(amount) || amount <= 0) {
setSwapAmountError('Please enter a valid amount');
} else if (amount < 25_000) {
setSwapAmountError('Minimum amount is 25,000 sats');
} else if (amount > 25_000_000) {
setSwapAmountError('Maximum amount is 25,000,000 sats');
} else {
setSwapAmountError(null);
}
} else {
setSwapAmountError(null);
}
}, [bitcoinSwapAmount, pendingBitcoinSwapAddress]);
return (
<div className="space-y-8">
{/* Title */}
<div className="text-center">
<div className="text-base text-muted-foreground mt-2">
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: mode === 'bitcoin' && !pendingBitcoinRecipient
? 'Send Bitcoin on-chain'
: mode === 'bitcoin' && pendingBitcoinRecipient
? (
<div className="flex items-center justify-center gap-2">
<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">{truncateAddress(pendingBitcoinRecipient)}</span>
</span>
<button
onClick={() => {
setPendingBitcoinRecipient?.(null);
setBitcoinAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
)
: pendingInvoice && decodedInvoiceAmount ? (
<div className="flex items-center justify-center gap-2">
<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:</span>{' '}
<span className="font-semibold text-foreground">{decodedInvoiceAmount} sats</span>
</span>
<button
onClick={() => {
setPendingInvoice(null);
setDecodedInvoiceAmount(null);
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : pendingLightningAddress ? (
<div className="flex items-center justify-center gap-2">
<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:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingLightningAddress)}</span>
</span>
<button
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : pendingBitcoinSwapAddress ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-orange-500/10 border border-orange-500/20 rounded-md">
<span className="font-bold text-orange-600 dark:text-orange-400">Reverse Swap to:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingBitcoinSwapAddress)}</span>
</span>
<button
onClick={() => {
setPendingBitcoinSwapAddress?.(null);
setBitcoinSwapAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : 'Pay invoices, addresses, or Bitcoin addresses'
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
: mode === 'bitcoin'
? 'Receive Bitcoin on-chain'
: 'Deposit funds with Lightning'
)}
</div>
</div>
{/* Content */}
<div className="space-y-8">
{!activeMintUrl && mode !== 'bitcoin' && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{getOperationMessage(operation, mode)}
</div>
)}
{operation === 'send' ? (
// Send Mode
mode === 'bitcoin' ? (
// Bitcoin Send
<div className="space-y-8">
{!hasNsecAccess ? (
<div className="flex justify-center items-center h-32">
<div className="text-sm text-destructive bg-destructive/10 border border-destructive/20 p-3 rounded text-center">
⚠️ Login with nsec required to send Bitcoin
</div>
</div>
) : pendingBitcoinRecipient ? (
// Step 2: Amount Input
<div className="space-y-8">
<div className="flex items-center gap-3">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinAmount || ''}
onChange={(e) => setBitcoinAmount?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (bitcoinAmount || sendMaxEnabled) && pendingBitcoinRecipient && !isLoading) {
onSend();
}
}}
disabled={sendMaxEnabled}
className="flex-1 h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<button
onClick={handleSendMaxToggle}
disabled={!bitcoinMaxAmount}
className={`px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
sendMaxEnabled
? 'bg-orange-500 text-white border-orange-500 hover:bg-orange-600'
: 'bg-gray-100 text-gray-600 border-gray-300 hover:bg-gray-200'
} ${!bitcoinMaxAmount ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
>
Send Max
</button>
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Step 1: Recipient Input
<div className="space-y-8">
<Input
placeholder="Bitcoin address or npub..."
value={bitcoinRecipient || ''}
onChange={(e) => setBitcoinRecipient?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinRecipient && !isLoading) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={() => {
if (bitcoinRecipient) {
setPendingBitcoinRecipient?.(bitcoinRecipient);
}
}}
disabled={!bitcoinRecipient || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)}
</div>
) : mode === 'tokens' ? (
// Cashu Token Send
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!sendAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingInvoice && decodedInvoiceAmount ? (
// Lightning Invoice Confirmation
<div className="space-y-8">
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onConfirmInvoice}
disabled={!activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingBitcoinSwapAddress ? (
// Reverse Swap Amount Input
<div className="space-y-8">
<div className="space-y-2">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinSwapAmount || ''}
onChange={(e) => {
setBitcoinSwapAmount?.(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinSwapAmount && !swapAmountError && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl || isLoading}
className={`w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield] ${
swapAmountError ? 'border-destructive' : ''
}`}
/>
{swapAmountError && (
<p className="text-sm text-destructive text-center">{swapAmountError}</p>
)}
{!swapAmountError && bitcoinSwapAmount && (
<p className="text-xs text-muted-foreground text-center">
Amount must be between 25,000 and 25,000,000 sats
</p>
)}
{swapStatus && (
<p className="text-sm text-muted-foreground text-center">{swapStatus}</p>
)}
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!bitcoinSwapAmount || !!swapAmountError || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</div>
</div>
) : pendingLightningAddress ? (
// Lightning Address Amount Input
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice/Address/Bitcoin Address Input
<div className="space-y-8">
<Input
placeholder="lnbc..., [email protected], or Bitcoin address"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)
) : (
// Receive Mode
mode === 'bitcoin' ? (
// Bitcoin Receive
<div className="space-y-8">
<div className="text-center">
<div className="font-mono text-sm bg-muted p-3 rounded border break-all">
{bitcoinAddress}
</div>
</div>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : mode === 'tokens' ? (
// Cashu Token Receive
<div className="space-y-8">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice Receive
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
<Button
onClick={onReceive}
disabled={!quoteAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
)
)}
</div>
</div>
);
}
@@ -1,83 +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';
export interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface ProofBreakdownModalProps {
isOpen: boolean;
onClose: () => void;
proofBreakdown: ProofBreakdown | null;
}
export function ProofBreakdownModal({
isOpen,
onClose,
proofBreakdown,
}: ProofBreakdownModalProps) {
if (!isOpen || !proofBreakdown) 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(proofBreakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{proofBreakdown.totalBalance.toLocaleString()} sats
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(proofBreakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
);
}
-111
View File
@@ -1,111 +0,0 @@
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { useToast } from '@/hooks/useToast';
import type { QRScanResult } from '@/hooks/wallet/useQRCode';
interface QRScannerProps {
isOpen: boolean;
onClose: () => Promise<void>;
onResult: (result: QRScanResult) => void;
classifyQRCode: (text: string) => QRScanResult;
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
stopScanning: () => Promise<void>;
setModalOpen?: (isOpen: boolean) => void;
qrError: string | null;
}
export function QRScanner({
isOpen,
onClose,
onResult,
classifyQRCode,
startScanning,
stopScanning,
setModalOpen,
qrError,
}: QRScannerProps) {
const { toast } = useToast();
// Handle paste from clipboard
const handlePasteQRCode = async () => {
try {
const text = await navigator.clipboard.readText();
if (!text || !text.trim()) {
toast({
variant: "destructive",
title: "Clipboard Empty",
description: "No text found in clipboard",
});
return;
}
const result = classifyQRCode(text.trim());
onResult(result);
await stopScanning();
await onClose();
} catch (err) {
toast({
variant: "destructive",
title: "Paste Failed",
description: "Could not read from clipboard",
});
console.error('Error pasting from clipboard:', err);
}
};
// Start/stop scanning based on isOpen
useEffect(() => {
if (isOpen) {
setModalOpen?.(true);
startScanning(onResult);
} else {
setModalOpen?.(false);
stopScanning();
}
}, [isOpen, startScanning, stopScanning, setModalOpen, onResult]);
return (
<Dialog open={isOpen} onOpenChange={async (open) => {
if (!open) {
await onClose();
}
}}>
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
<DialogHeader>
<DialogTitle>Scan QR Code</DialogTitle>
<VisuallyHidden.Root asChild>
<DialogDescription>
Position the QR code within the camera view to scan
</DialogDescription>
</VisuallyHidden.Root>
</DialogHeader>
<div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
<div
id="qr-reader"
className="w-full h-full rounded-xl overflow-hidden bg-muted"
/>
{qrError && (
<div className="absolute inset-x-4 top-4 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50 shadow-lg">
{qrError}
</div>
)}
</div>
<div className="mt-4 flex justify-center">
<Button
onClick={handlePasteQRCode}
className="h-12 px-12 rounded-full"
size="lg"
>
Paste
</Button>
</div>
</DialogContent>
</Dialog>
);
}
-86
View File
@@ -1,86 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, AlertTriangle, RefreshCw } from 'lucide-react';
export interface MintToRemove {
url: string;
name?: string;
}
interface RemoveMintModalProps {
isOpen: boolean;
onClose: () => void;
mintToRemove: MintToRemove | null;
onConfirm: () => void;
isLoading: boolean;
}
export function RemoveMintModal({
isOpen,
onClose,
mintToRemove,
onConfirm,
isLoading,
}: RemoveMintModalProps) {
if (!isOpen || !mintToRemove) 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">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={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>
);
}
-136
View File
@@ -1,136 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { X, Key, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
interface SeedPhraseModalProps {
isOpen: boolean;
onClose: () => void;
onRestoreFromSeedPhrase: (seedPhrase: string, mintUrl: string) => Promise<void>;
isRestoring: boolean;
mints: Array<{ url: string; name?: string }>;
activeMintUrl: string | null;
}
export function SeedPhraseModal({
isOpen,
onClose,
onRestoreFromSeedPhrase,
isRestoring,
mints,
activeMintUrl,
}: SeedPhraseModalProps) {
const { toast } = useToast();
const [seedPhraseInput, setSeedPhraseInput] = useState('');
if (!isOpen) return null;
const handleRestore = async () => {
if (!seedPhraseInput.trim()) {
toast({
variant: "destructive",
title: "Missing Information",
description: "Please enter your seed phrase.",
});
return;
}
if (!activeMintUrl) {
toast({
variant: "destructive",
title: "No Active Mint",
description: "Please select a mint first.",
});
return;
}
try {
await onRestoreFromSeedPhrase(seedPhraseInput.trim(), activeMintUrl);
setSeedPhraseInput('');
onClose();
} catch (error) {
toast({
variant: "destructive",
title: "Restore Failed",
description: error instanceof Error ? error.message : "Failed to restore from seed phrase",
});
}
};
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<div
className="w-full max-w-md border-0 shadow-lg bg-background rounded-lg"
onClick={(e) => e.stopPropagation()}
>
<div className="relative p-6">
<button
onClick={onClose}
className="absolute top-4 right-4 p-2 hover:bg-muted rounded-md transition-colors"
>
<X className="h-4 w-4" />
</button>
<div className="flex items-center mb-4 pr-8">
<Key className="h-5 w-5 mr-2" />
<h2 className="text-lg font-semibold">Restore from Seed Phrase</h2>
</div>
<p className="text-muted-foreground mb-4">
Enter your seed phrase to restore tokens from the active mint.
</p>
{activeMintUrl && (
<div className="bg-muted p-3 rounded-md mb-4">
<p className="text-sm text-muted-foreground">
<strong>Active Mint:</strong> {mints.find(m => m.url === activeMintUrl)?.name || new URL(activeMintUrl).hostname}
</p>
</div>
)}
<div className="space-y-4">
<div>
<Label htmlFor="seed-phrase">Seed Phrase</Label>
<Input
id="seed-phrase"
type="text"
placeholder="Enter your 12-word seed phrase..."
value={seedPhraseInput}
onChange={(e) => setSeedPhraseInput(e.target.value)}
className="mt-1"
/>
</div>
<div className="bg-muted p-3 rounded-md">
<p className="text-xs text-muted-foreground">
<strong>Note:</strong> This will restore tokens from the provided seed phrase and add them to your current wallet balance.
</p>
</div>
</div>
<div className="mt-6">
<Button
onClick={handleRestore}
disabled={isRestoring || !seedPhraseInput.trim() || !activeMintUrl}
className="w-full"
>
{isRestoring ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Restoring...
</>
) : (
'Restore Tokens'
)}
</Button>
</div>
</div>
</div>
</div>
);
}
@@ -1,226 +0,0 @@
import { Loader2, History, ArrowUpRight, ArrowDownLeft, ArrowLeftRight, Zap, Coins, Link } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
export interface BitcoinTransaction {
id: string;
txid: string;
type: 'sent' | 'received' | 'consolidate';
amount: number; // in satoshis
fee?: number; // in satoshis, only for sent transactions
address: string;
confirmations: number;
blockHeight?: number;
timestamp: number;
status: 'confirmed' | 'unconfirmed' | 'pending';
}
interface TransactionHistoryProps {
entries: HistoryEntry[];
isLoading: boolean;
// Bitcoin transaction props
bitcoinTransactions?: BitcoinTransaction[];
isBitcoinLoading?: boolean;
showSats?: boolean;
}
export function TransactionHistory({
entries,
isLoading,
bitcoinTransactions = [],
isBitcoinLoading = false,
showSats = true
}: TransactionHistoryProps) {
// Icon indicating transaction type (Lightning vs Cashu)
const getTransactionTypeIcon = (type: string) => {
switch (type) {
case 'mint':
case 'melt':
return <Zap className="h-4 w-4" />;
case 'send':
case 'receive':
return <Coins className="h-4 w-4" />;
default:
return <History className="h-4 w-4" />;
}
};
// Arrow indicating direction (next to amount)
const getDirectionIcon = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
case 'melt':
case 'send':
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
default:
return null;
}
};
const getHistoryLabel = (type: string) => {
switch (type) {
case 'mint':
case 'receive':
return 'Received';
case 'melt':
case 'send':
return 'Sent';
default:
return type;
}
};
// Bitcoin transaction formatting functions
const formatBitcoinAmount = (sats: number): string => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
const btc = sats / 100000000;
return `₿${btc.toFixed(8)}`;
}
};
const formatBitcoinAddress = (address: string): string => {
return `${address.slice(0, 8)}...${address.slice(-8)}`;
};
const getBitcoinStatusColor = (status: string): string => {
switch (status) {
case 'confirmed':
return 'text-green-500';
case 'unconfirmed':
return 'text-yellow-500';
case 'pending':
return 'text-blue-500';
default:
return 'text-muted-foreground';
}
};
return (
<div className="space-y-2">
{isLoading || isBitcoinLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading transactions...</span>
</div>
) : entries.length === 0 && bitcoinTransactions.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transactions yet
</div>
) : (
<>
{/* Cashu/Lightning Transactions */}
{entries.map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getTransactionTypeIcon(entry.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
{entry.type === 'melt' && (
<div className="text-xs text-muted-foreground mt-1">
+ fees
</div>
)}
</div>
<div className="mt-1">
{getDirectionIcon(entry.type)}
</div>
</div>
</div>
</div>
))}
{/* Bitcoin Transactions */}
{bitcoinTransactions.map((tx) => (
<div
key={tx.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">
<Link className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{tx.type === 'received' ? 'Received' : tx.type === 'consolidate' ? 'Consolidate' : 'Sent'}
</span>
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
{tx.status}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{formatBitcoinAddress(tx.address)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(tx.timestamp).toLocaleString()}
{tx.confirmations > 0 && (
<span className="ml-2">
• {tx.confirmations} confirmation{tx.confirmations !== 1 ? 's' : ''}
</span>
)}
</div>
{tx.blockHeight && (
<div className="text-xs text-muted-foreground">
Block #{tx.blockHeight}
</div>
)}
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{tx.type === 'sent' ? '-' : tx.type === 'consolidate' ? '' : '+'}
{formatBitcoinAmount(tx.amount)}
</div>
{tx.fee !== undefined && tx.fee > 0 && (tx.type === 'sent' || tx.type === 'consolidate') && (
<div className="text-xs text-muted-foreground mt-1">
Fee: {formatBitcoinAmount(tx.fee)}
</div>
)}
</div>
<div className="mt-1">
{tx.type === 'received' ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : tx.type === 'consolidate' ? (
<ArrowLeftRight className="h-4 w-4 text-blue-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
</div>
</div>
</div>
</div>
))}
</>
)}
</div>
);
}
-127
View File
@@ -1,127 +0,0 @@
import { Button } from '@/components/ui/button';
import { ChevronDown, Merge } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { UTXO } from '@/lib/bitcoin';
interface UTXOSelectorProps {
utxos: UTXO[];
showSats: boolean;
bitcoinAddress: string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
export function UTXOSelector({
utxos,
showSats,
dropdownOpen,
setDropdownOpen,
onShowConsolidationModal,
isConsolidating,
}: UTXOSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
const formatUTXOBlock = (utxo: UTXO): string => {
if (utxo.status.block_height) {
return `Block #${utxo.status.block_height}`;
} else {
return 'Unconfirmed';
}
};
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0"
disabled={utxos.length === 0}
>
<div className="flex items-center justify-between w-full min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(totalBalance)}
</span>
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{utxos.length === 0 ? (
<DropdownMenuItem disabled className="flex items-center justify-center p-3 text-base text-muted-foreground">
No UTXOs available
</DropdownMenuItem>
) : (
utxos.map((utxo) => (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOBlock(utxo)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
))
)}
</div>
</DropdownMenuContent>
</DropdownMenu>
{onShowConsolidationModal && (
<button
onClick={onShowConsolidationModal}
disabled={isConsolidating}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
title="Consolidate UTXOs"
>
<Merge className="h-4 w-4" />
</button>
)}
</div>
);
}
-235
View File
@@ -1,235 +0,0 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { useQRCode, type QRScanResult } from '@/hooks/wallet/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useCashu } from '@/hooks/wallet/useCashu';
import { useBitcoinBalance } from '@/hooks/wallet/useBitcoin';
import { nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import { WalletHeader } from './WalletHeader';
import { CashuWallet } from './CashuWallet';
import { BitcoinWallet } from './BitcoinWallet';
import { QRScanner } from './QRScanner';
// Extend Window interface for QR handlers
declare global {
interface Window {
__cashuWalletQRHandler?: (result: QRScanResult) => void;
__bitcoinWalletQRHandler?: (result: QRScanResult) => void;
}
}
export function WalletContainer() {
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
const [showSats, setShowSats] = useState(true);
const [showQRScanner, setShowQRScanner] = useState(false);
// Shared hooks
const { user } = useCurrentUser();
const { toast } = useToast();
const { generateQRCode, classifyQRCode, startScanning, stopScanning, setModalOpen, error: qrError } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// Get balance data for WalletHeader
const { balances, mnemonic } = useCashu();
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
// Calculate total balance based on mode
const totalBalance: number = mode === 'bitcoin'
? (bitcoinBalanceData?.balance || 0)
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// Refs to call wallet QR handlers
const cashuWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
const bitcoinWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
// Handle QR scanner results and route to appropriate wallet
const handleQRScanResult = async (result: QRScanResult) => {
try {
await stopScanning();
setShowQRScanner(false);
switch (result.type) {
case 'cashu_token': {
setMode('tokens');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'lightning_invoice': {
setMode('lightning');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'lightning_address': {
setMode('lightning');
// Call CashuWallet handler if available
if (cashuWalletQRHandlerRef.current) {
cashuWalletQRHandlerRef.current(result);
}
break;
}
case 'bitcoin_address': {
setMode('bitcoin');
// Call BitcoinWallet handler if available
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
break;
}
case 'npub': {
setMode('bitcoin');
// Call BitcoinWallet handler if available
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
break;
}
default: {
toast({
variant: "destructive",
title: "Unknown QR Code",
description: result.value,
});
}
}
} catch (err) {
console.error('Error handling QR scan:', err);
}
};
// Set up refs to wallet QR handlers
useEffect(() => {
const checkHandlers = () => {
if (window.__cashuWalletQRHandler) {
cashuWalletQRHandlerRef.current = window.__cashuWalletQRHandler;
}
if (window.__bitcoinWalletQRHandler) {
bitcoinWalletQRHandlerRef.current = window.__bitcoinWalletQRHandler;
}
};
// Check periodically for handlers (wallets set them up asynchronously)
const interval = setInterval(checkHandlers, 100);
checkHandlers(); // Initial check
return () => clearInterval(interval);
}, []);
// WalletHeader props - these will be passed from wallets via callbacks
const [walletHeaderProps, setWalletHeaderProps] = useState<{
activeMintUrl?: string | null;
mints?: Array<{ url: string; name?: string }>;
mintUrl?: string;
setMintUrl?: (url: string) => void;
onAddMint?: () => void;
onRemoveMint?: (mint: { url: string; name?: string }) => void;
onShowDenominations?: (mintUrl: string) => void;
getCleanMintLabel?: (mint: { name?: string; url: string }) => string;
mintDropdownOpen?: boolean;
setMintDropdownOpen?: (open: boolean) => void;
npubCashUsername?: string;
utxos?: UTXO[];
utxoDropdownOpen?: boolean;
setUtxoDropdownOpen?: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
onShowLightningAddressQR?: (qr: string) => void;
onShowBitcoinAddressQR?: (qr: string) => void;
onShowSeedPhraseInfo?: () => void;
setActiveMintUrl?: (url: string | null) => void;
}>({});
// Memoize the callback to prevent infinite loops
const handleWalletHeaderPropsChange = useCallback((props: typeof walletHeaderProps) => {
setWalletHeaderProps(props);
}, []);
return (
<>
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
{/* Wallet Header */}
<WalletHeader
totalBalance={totalBalance}
balances={mode === 'bitcoin' ? {} : balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
userPubkey={user?.pubkey}
npubCashUsername={walletHeaderProps.npubCashUsername}
mnemonic={mode !== 'bitcoin' ? mnemonic : undefined}
onCopyToClipboard={copyToClipboard}
onShowLightningAddressQR={walletHeaderProps.onShowLightningAddressQR || (() => {})}
onShowBitcoinAddressQR={walletHeaderProps.onShowBitcoinAddressQR || (() => {})}
onShowSeedPhraseInfo={walletHeaderProps.onShowSeedPhraseInfo || (() => {})}
generateQRCode={generateQRCode}
// MintSelector props (only for tokens/lightning)
activeMintUrl={mode !== 'bitcoin' ? (walletHeaderProps.activeMintUrl ?? null) : null}
setActiveMintUrl={walletHeaderProps.setActiveMintUrl || (() => {})}
mints={mode !== 'bitcoin' ? (walletHeaderProps.mints || []) : []}
mintUrl={walletHeaderProps.mintUrl || ''}
setMintUrl={walletHeaderProps.setMintUrl || (() => {})}
onAddMint={walletHeaderProps.onAddMint || (() => {})}
onRemoveMint={walletHeaderProps.onRemoveMint || (() => {})}
onShowDenominations={walletHeaderProps.onShowDenominations || (() => {})}
getCleanMintLabel={walletHeaderProps.getCleanMintLabel || (() => '')}
dropdownOpen={walletHeaderProps.mintDropdownOpen || false}
setDropdownOpen={walletHeaderProps.setMintDropdownOpen || (() => {})}
// UTXOSelector props (only for bitcoin)
utxos={mode === 'bitcoin' ? (walletHeaderProps.utxos || []) : []}
utxoDropdownOpen={walletHeaderProps.utxoDropdownOpen || false}
setUtxoDropdownOpen={walletHeaderProps.setUtxoDropdownOpen || (() => {})}
onShowConsolidationModal={walletHeaderProps.onShowConsolidationModal}
isConsolidating={walletHeaderProps.isConsolidating}
/>
{/* Render appropriate wallet based on mode */}
{mode === 'tokens' || mode === 'lightning' ? (
<CashuWallet
mode={mode}
toast={toast}
generateQRCode={generateQRCode}
user={user}
onRequestQRScanner={() => setShowQRScanner(true)}
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
/>
) : (
<BitcoinWallet
toast={toast}
user={user}
onRequestQRScanner={() => setShowQRScanner(true)}
onQRResult={(result) => {
if (bitcoinWalletQRHandlerRef.current) {
bitcoinWalletQRHandlerRef.current(result);
}
}}
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
/>
)}
</div>
{/* Shared QR Scanner */}
<QRScanner
isOpen={showQRScanner}
onClose={async () => {
await stopScanning();
setShowQRScanner(false);
}}
onResult={handleQRScanResult}
classifyQRCode={classifyQRCode}
startScanning={startScanning}
stopScanning={stopScanning}
setModalOpen={setModalOpen}
qrError={qrError}
/>
</>
);
}
-352
View File
@@ -1,352 +0,0 @@
import { useState, useEffect } from 'react';
import { Zap, Coins, Copy, Check, QrCode, Link, Key } from 'lucide-react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { LoginIcon } from '@/components/auth/LoginIcon';
import { MintSelector } from './MintSelector';
import { UTXOSelector } from './UTXOSelector';
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
import { UTXO } from '@/lib/bitcoin';
interface CashuMint {
url: string;
name?: string;
}
interface WalletHeaderProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning' | 'bitcoin';
setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void;
userPubkey?: string;
npubCashUsername?: string;
mnemonic?: string | null;
onCopyToClipboard: (text: string) => Promise<void>;
onShowLightningAddressQR: (qrCode: string) => void;
onShowBitcoinAddressQR: (qrCode: string) => void;
onShowSeedPhraseInfo: () => void;
generateQRCode: (text: string) => Promise<string>;
// MintSelector props
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
// UTXOSelector props
utxos: UTXO[];
utxoDropdownOpen: boolean;
setUtxoDropdownOpen: (open: boolean) => void;
onShowConsolidationModal?: () => void;
isConsolidating?: boolean;
}
// Helper functions to prevent syntax errors in complex expressions
// These functions break down complex inline logic to make the code more maintainable
// and less prone to syntax errors when AI agents edit this file
const formatBalance = (balance: number, showSats: boolean, btcUsdRate?: number | null): string => {
if (showSats) {
return balance.toLocaleString();
}
if (btcUsdRate) {
const usdAmount = (balance / 100000000 * btcUsdRate).toFixed(2);
return usdAmount;
}
return balance.toLocaleString();
};
const getBalanceSymbol = (showSats: boolean): JSX.Element => {
return showSats ? (
<span className="text-orange-500/70">₿</span>
) : (
<span className="text-green-500/70">$</span>
);
};
const getToggleTitle = (showSats: boolean): string => {
return `Click to show in ${showSats ? 'USD' : 'sats'}`;
};
const getButtonTitle = (mode: string): string => {
switch (mode) {
case 'tokens': return 'Switch to On-Chain';
case 'lightning': return 'Switch to Cashu';
case 'bitcoin': return 'Switch to Lightning';
default: return 'Switch Mode';
}
};
export function WalletHeader({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
userPubkey,
npubCashUsername,
mnemonic,
onCopyToClipboard,
onShowLightningAddressQR,
onShowBitcoinAddressQR,
onShowSeedPhraseInfo,
generateQRCode,
// MintSelector props
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
// UTXOSelector props
utxos,
utxoDropdownOpen,
setUtxoDropdownOpen,
onShowConsolidationModal,
isConsolidating,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
const [mnemonicCopied, setMnemonicCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const toggleMode = () => {
let newMode: 'tokens' | 'lightning' | 'bitcoin';
if (mode === 'lightning') {
newMode = 'tokens';
} else if (mode === 'tokens') {
newMode = 'bitcoin';
} else {
newMode = 'lightning';
}
setMode(newMode);
};
return (
<div className="flex flex-col items-center pt-10 space-y-2">
{/* Mode Toggle */}
<div className="absolute top-3 left-3 sm:left-4 z-10">
<button
onClick={toggleMode}
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={getButtonTitle(mode)}
>
{mode === 'tokens' ? (
<Coins className="h-6 w-6" />
) : mode === 'lightning' ? (
<Zap className="h-6 w-6" />
) : (
<Link className="h-6 w-6" />
)}
</button>
</div>
{/* Login Icon */}
<div className="absolute top-3 right-3 sm:right-4 z-10">
<LoginIcon />
</div>
{/* Balance Display */}
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-6xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={getToggleTitle(showSats)}
>
<span className="italic">
{getBalanceSymbol(showSats)}
</span>
{formatBalance(totalBalance, showSats, btcUsdRate)}
</button>
{/* Custody Badge */}
<span className={`px-2 py-1 text-xs font-medium rounded-full ${
mode === 'bitcoin'
? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
}`}>
{mode === 'bitcoin' ? 'Self-Custody' : 'Mint-Custody'}
</span>
</div>
{/* Lightning Address and Mint Selector Grid */}
<div className="mt-3 px-4">
<div className="w-full max-w-[400px] mx-auto">
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && mode === 'lightning' && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
await onCopyToClipboard(lightningAddress);
setLightningAddressCopied(true);
setTimeout(() => setLightningAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Lightning address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{npubCashUsername || ''}
</span>
<span className="flex-shrink-0 text-muted-foreground">
@npubx.cash
</span>
</div>
{lightningAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
const qr = await generateQRCode(lightningAddress);
onShowLightningAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
)}
{/* Mnemonic Seed Phrase Row */}
{mode === 'tokens' && mnemonic && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
await onCopyToClipboard(mnemonic);
setMnemonicCopied(true);
setTimeout(() => setMnemonicCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy seed phrase"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{mnemonic.split(' ').map(() => '****').join(' ')}
</span>
</div>
{mnemonicCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={onShowSeedPhraseInfo}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="What is a seed phrase?"
>
<Key className="h-4 w-4" />
</button>
</div>
)}
{/* Bitcoin Address Row */}
{userPubkey && mode === 'bitcoin' && (() => {
const bitcoinAddress = nostrPubkeyToBitcoinAddress(userPubkey);
return bitcoinAddress ? (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
await onCopyToClipboard(bitcoinAddress);
setBitcoinAddressCopied(true);
setTimeout(() => setBitcoinAddressCopied(false), 2000);
}}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
title="Click to copy Bitcoin address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{bitcoinAddress}
</span>
</div>
{bitcoinAddressCopied ? (
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
) : (
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
)}
</button>
<button
onClick={async () => {
const qr = await generateQRCode(bitcoinAddress);
onShowBitcoinAddressQR(qr);
}}
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
title="Show QR Code"
>
<QrCode className="h-4 w-4" />
</button>
</div>
) : null;
})()}
{/* UTXO Selector Row */}
{mode === 'bitcoin' && (
<div className="min-w-[300px]">
<UTXOSelector
utxos={utxos}
showSats={showSats}
bitcoinAddress={userPubkey ? nostrPubkeyToBitcoinAddress(userPubkey) : ''}
dropdownOpen={utxoDropdownOpen}
setDropdownOpen={setUtxoDropdownOpen}
onShowConsolidationModal={onShowConsolidationModal}
isConsolidating={isConsolidating}
/>
</div>
)}
{/* Mint Selector Row */}
{mode !== 'bitcoin' && (
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
}
+9 -4
View File
@@ -2,11 +2,18 @@ import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export interface RelayMetadata {
/** List of relays with read/write permissions */
relays: { url: string; read: boolean; write: boolean }[];
/** Unix timestamp of when the relay list was last updated */
updatedAt: number;
}
export interface AppConfig {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
}
export interface AppContextType {
@@ -14,8 +21,6 @@ export interface AppContextType {
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
-24
View File
@@ -1,24 +0,0 @@
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/wallet/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 useCashuContext(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashuContext must be used within a CashuProvider');
}
return context;
}
+138
View File
@@ -0,0 +1,138 @@
import { createContext } from 'react';
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
import { type NostrEvent } from '@nostrify/nostrify';
import type { MessageProtocol } from '@/lib/dmConstants';
// ============================================================================
// DM Types and Constants
// ============================================================================
interface ParticipantData {
messages: DecryptedMessage[];
lastActivity: number;
lastMessage: DecryptedMessage | null;
hasNIP4: boolean;
hasNIP17: boolean;
}
type MessagesState = Map<string, ParticipantData>;
interface LastSyncData {
nip4: number | null;
nip17: number | null;
}
interface SubscriptionStatus {
isNIP4Connected: boolean;
isNIP17Connected: boolean;
}
interface ScanProgress {
current: number;
status: string;
}
interface ScanProgressState {
nip4: ScanProgress | null;
nip17: ScanProgress | null;
}
interface ConversationSummary {
id: string;
pubkey: string;
lastMessage: DecryptedMessage | null;
lastActivity: number;
hasNIP4Messages: boolean;
hasNIP17Messages: boolean;
isKnown: boolean;
isRequest: boolean;
lastMessageFromUser: boolean;
}
interface DecryptedMessage extends NostrEvent {
decryptedContent?: string;
error?: string;
isSending?: boolean;
clientFirstSeen?: number;
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
}
/**
* File attachment for direct messages (NIP-92 compatible).
*
* All fields are required. Use with `useUploadFile` hook to upload files
* and generate the proper tags format.
*
* @example
* ```tsx
* import { useUploadFile } from '@/hooks/useUploadFile';
* import type { FileAttachment } from '@/contexts/DMContext';
*
* const { mutateAsync: uploadFile } = useUploadFile();
*
* const tags = await uploadFile(file);
* const attachment: FileAttachment = {
* url: tags[0][1],
* mimeType: file.type,
* size: file.size,
* name: file.name,
* tags: tags
* };
*
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Check out this file!',
* attachments: [attachment]
* });
* ```
*
* @property url - Blossom server URL where file is hosted
* @property mimeType - MIME type of the file (e.g., 'image/png')
* @property size - File size in bytes
* @property name - Original filename
* @property tags - NIP-94 file metadata tags (includes hashes)
*/
export interface FileAttachment {
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}
/**
* Direct Messaging context interface providing access to all DM functionality.
*
* @property messages - Raw message state (Map of pubkey -> participant data)
* @property isLoading - True during initial load phases
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
* @property lastSync - Unix timestamps of last successful sync for each protocol
* @property subscriptions - Connection status for real-time message subscriptions
* @property conversations - Array of conversation summaries sorted by last activity
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
* @property scanProgress - Progress info for large message history scans
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
*/
export interface DMContextType {
messages: MessagesState;
isLoading: boolean;
loadingPhase: LoadingPhase;
isDoingInitialLoad: boolean;
lastSync: LastSyncData;
subscriptions: SubscriptionStatus;
conversations: ConversationSummary[];
sendMessage: (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => Promise<void>;
protocolMode: ProtocolMode;
scanProgress: ScanProgressState;
clearCacheAndRefetch: () => Promise<void>;
}
export const DMContext = createContext<DMContextType | null>(null);
+87
View File
@@ -0,0 +1,87 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useDMContext } from "@/hooks/useDMContext";
const MESSAGES_PER_PAGE = 25;
/**
* Hook to access paginated messages for a specific conversation.
*
* Returns the most recent messages (default 25) with the ability to load earlier messages.
* Automatically resets to default page size when switching conversations.
*
* @example
* ```tsx
* import { useConversationMessages } from '@/contexts/DMContext';
*
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
* const {
* messages,
* hasMoreMessages,
* loadEarlierMessages,
* totalCount
* } = useConversationMessages(recipientPubkey);
*
* return (
* <div>
* {hasMoreMessages && (
* <button onClick={loadEarlierMessages}>
* Load Earlier ({totalCount - messages.length} more)
* </button>
* )}
* {messages.map(msg => (
* <div key={msg.id}>{msg.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @param conversationId - The pubkey of the conversation participant
* @returns Paginated message data with loading function
*/
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
const result = useMemo(() => {
const conversationData = allMessages.get(conversationId);
if (!conversationData) {
return {
messages: [],
hasMoreMessages: false,
totalCount: 0,
lastMessage: null,
lastActivity: 0,
};
}
const totalMessages = conversationData.messages.length;
const hasMore = totalMessages > visibleCount;
// Return the most recent N messages (slice from the end)
const visibleMessages = conversationData.messages.slice(-visibleCount);
return {
messages: visibleMessages,
hasMoreMessages: hasMore,
totalCount: totalMessages,
lastMessage: conversationData.lastMessage,
lastActivity: conversationData.lastActivity,
};
}, [allMessages, conversationId, visibleCount]);
const loadEarlierMessages = useCallback(() => {
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
}, []);
// Reset visible count when conversation changes
useEffect(() => {
setVisibleCount(MESSAGES_PER_PAGE);
}, [conversationId]);
return {
...result,
loadEarlierMessages,
};
}
-52
View File
@@ -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,
};
}
+45
View File
@@ -0,0 +1,45 @@
import { useContext } from "react";
import { DMContext, DMContextType } from "@/contexts/DMContext";
/**
* Hook to access the direct messaging system.
*
* Provides access to conversations, message sending, loading states, and cache management.
* Must be used within a DMProvider.
*
* @example
* ```tsx
* import { useDMContext } from '@/hooks/useDMContext';
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
*
* function MyComponent() {
* const { conversations, sendMessage, isLoading } = useDMContext();
*
* // Send a message
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!',
* protocol: MESSAGE_PROTOCOL.NIP17
* });
*
* // Display conversations
* return (
* <div>
* {isLoading ? 'Loading...' : conversations.map(c => (
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @returns DMContextType - The direct messaging context
* @throws Error if used outside DMProvider
*/
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
throw new Error('useDMContext must be used within DMProvider');
}
return context;
}
-74
View File
@@ -1,74 +0,0 @@
import { useCallback } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
export interface NIP98Options {
url: string;
method: string;
body?: unknown;
}
/**
* Hook for creating NIP-98 HTTP Authentication headers
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
*/
export function useNIP98() {
const { user } = useCurrentUser();
/**
* Create a NIP-98 authorization header for HTTP requests
* @param options - The request details (url, method, optional body)
* @returns Promise<string> - The "Nostr base64..." authorization header value
*/
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
if (!user) {
throw new Error('User must be logged in to create NIP-98 auth header');
}
const { url, method, body } = options;
// Parse URL to remove query parameters (per NIP-98 spec)
const urlObj = new URL(url);
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
const tags: string[][] = [
['u', urlWithoutQuery],
['method', method.toUpperCase()],
];
// If there's a request body (POST, PUT, PATCH), add payload hash
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create and sign the NIP-98 event (kind 27235)
const event = await user.signer.signEvent({
kind: 27235,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
}) as NostrEvent;
// Encode the event as base64
const eventJson = JSON.stringify(event);
const base64Event = btoa(eventJson);
return `Nostr ${base64Event}`;
}, [user]);
return {
createAuthHeader,
isLoggedIn: !!user,
pubkey: user?.pubkey,
signer: user?.signer,
};
}
-51
View File
@@ -1,51 +0,0 @@
import { useNostrLogin } from '@nostrify/react/login';
import { nip19 } from 'nostr-tools';
/**
* Hook to check if the current user is logged in with nsec and get the private key.
* Only works when user is logged in with nsec (not extension or bunker).
*/
export function useNsecAccess() {
const { logins } = useNostrLogin();
const currentLogin = logins[0];
// Check if user is logged in with nsec
const hasNsecAccess = currentLogin?.type === 'nsec';
// Get the private key in hex format (only if nsec login)
const getPrivateKey = (): string | null => {
if (!hasNsecAccess || !currentLogin) return null;
try {
// The nsec is stored in the login data as 'data.nsec' property
const loginData = currentLogin as { data?: { nsec: string } };
const nsec = loginData.data?.nsec;
if (!nsec) {
console.error('No nsec found in login data');
return null;
}
const decoded: { type: string; data: Uint8Array | string | object } = nip19.decode(nsec) as { type: string; data: Uint8Array | string | object };
// Type guard to ensure we have an nsec
if (decoded.type !== 'nsec') {
console.error('Invalid nsec format, got type:', decoded.type);
return null;
}
// Convert Uint8Array to hex string
return Buffer.from(decoded.data as Uint8Array).toString('hex');
} catch (error) {
console.error('Failed to decode nsec:', error);
return null;
}
};
return {
hasNsecAccess,
getPrivateKey,
loginType: currentLogin?.type,
};
}
+1 -1
View File
@@ -85,7 +85,7 @@ export function usePostComment() {
onSuccess: (_, { root }) => {
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
});
},
});
+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
+4 -24
View File
@@ -1,22 +1,16 @@
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/wallet/useCashu';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
preferredMethod: 'cashu' | 'nwc' | 'webln' | 'manual';
// Cashu integration
hasCashu: boolean;
cashuBalance: number;
isCashuInitialized: boolean;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const { connections, getActiveConnection } = useNWC();
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
@@ -24,24 +18,13 @@ export function useWallet() {
// Access WebLN directly from browser global scope
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
// Calculate Cashu status
const hasCashu = useMemo(() => {
return isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
}, [isCashuInitialized, mints, balances]);
const cashuBalance = useMemo(() => {
return Object.values(balances).reduce((sum, balance) => sum + balance, 0);
}, [balances]);
// Calculate Lightning status values reactively
// 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'
@@ -52,9 +35,6 @@ export function useWallet() {
webln,
activeNWC,
preferredMethod,
hasCashu,
cashuBalance,
isCashuInitialized,
};
return status;
+12 -78
View File
@@ -4,7 +4,6 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/wallet/useCashu';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
@@ -30,7 +29,6 @@ export function useZaps(
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
@@ -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,20 +192,20 @@ export function useZaps(
return;
}
// Create zap request - use appropriate event format based on kind
// For addressable events (30000-39999), pass the object to get 'a' tag
// For all other events, pass the ID string to get 'e' tag
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
? actualTarget
: actualTarget.id;
const zapAmount = amount * 1000; // convert to millisats
// Validate zapAmount is a valid number
if (isNaN(zapAmount) || zapAmount <= 0) {
throw new Error('Invalid zap amount');
}
// Create zap request - always pass the full event object
// The nip57.makeZapRequest function will handle proper tag generation
// ('e' tag for regular events, 'a' tag for addressable events)
const zapRequest = nip57.makeZapRequest({
event: actualTarget,
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
relays: config.relayMetadata.relays.map(r => r.url),
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 && coco) {
// Create melt quote to convert Cashu tokens to Lightning payment
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats from your Cashu wallet to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
return;
}
} catch (cashuError) {
console.error('Cashu payment failed, falling back:', cashuError);
// Show specific Cashu error to user for debugging
const errorMessage = cashuError instanceof Error ? cashuError.message : 'Unknown Cashu error';
toast({
title: 'Cashu payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
}
}
// Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection();
// Try NWC if Cashu failed or unavailable
// Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
-462
View File
@@ -1,462 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { useState, useCallback, useEffect } from 'react';
import { fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, npubToBitcoinAddress, nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/wallet/useQRCode';
import { useNsecAccess } from '@/hooks/useNsecAccess';
// Blockstream API response types
interface BlockstreamTransactionStatus {
confirmed: boolean;
block_height?: number;
block_hash?: string;
block_time?: number;
}
interface BlockstreamTransactionInput {
prevout?: {
scriptpubkey_address?: string;
value: number;
};
}
interface BlockstreamTransactionOutput {
scriptpubkey_address?: string;
value: number;
}
// Transaction list item (from /address/:address/txs) - minimal data
interface BlockstreamTransactionListItem {
txid: string;
fee?: number;
status: BlockstreamTransactionStatus;
vin: BlockstreamTransactionInput[];
vout: BlockstreamTransactionOutput[];
}
// Full transaction details (from /tx/:txid) - includes complete prevout data
interface BlockstreamFullTransaction {
txid: string;
fee?: number;
status: BlockstreamTransactionStatus;
vin: Array<{
txid: string;
vout: number;
prevout: {
scriptpubkey_address?: string;
value: number;
};
[key: string]: unknown; // Other fields we don't need
}>;
vout: Array<{
scriptpubkey_address?: string;
value: number;
[key: string]: unknown; // Other fields we don't need
}>;
}
/**
* Fetch Bitcoin transaction history for an address from Blockstream API
* Fetches full transaction details to get complete prevout data for accurate sent/received detection
*/
async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransaction[]> {
// First, fetch the transaction list
const listResponse = await fetch(`https://blockstream.info/api/address/${address}/txs`);
if (!listResponse.ok) {
throw new Error('Failed to fetch Bitcoin transactions');
}
const txList: BlockstreamTransactionListItem[] = await listResponse.json();
// Fetch full transaction details for each transaction in parallel
// This gives us complete prevout data needed to detect sent transactions
const fullTxPromises = txList.map(async (txItem) => {
const txResponse = await fetch(`https://blockstream.info/api/tx/${txItem.txid}`);
if (!txResponse.ok) {
console.warn(`Failed to fetch full details for transaction ${txItem.txid}`);
// Fallback to list item data if full fetch fails
return null;
}
return await txResponse.json() as BlockstreamFullTransaction;
});
const fullTxs = await Promise.all(fullTxPromises);
// Transform to our BitcoinTransaction format
return fullTxs.map((tx, index) => {
// If we couldn't fetch full details, use list item data
const txItem = txList[index];
const txData = tx || {
txid: txItem.txid,
fee: txItem.fee,
status: txItem.status,
vin: txItem.vin.map(vin => ({
prevout: vin.prevout || undefined
})),
vout: txItem.vout
} as BlockstreamFullTransaction;
// Determine if this is a sent or received transaction
// Check if address appears in outputs (received)
const isReceived = txData.vout.some((output) =>
output.scriptpubkey_address === address
);
// Check if address appears in input prevouts (sent)
const isSent = txData.vin.some((input) =>
input.prevout?.scriptpubkey_address === address
);
// Calculate amount for this address
let amount = 0;
let fee: number | undefined = undefined;
// Calculate inputs and outputs for this address
const inputsFromAddress = txData.vin
.filter((input) => input.prevout?.scriptpubkey_address === address)
.reduce((sum, input) => sum + (input.prevout?.value || 0), 0);
const outputsToAddress = txData.vout
.filter((output) => output.scriptpubkey_address === address)
.reduce((sum, output) => sum + output.value, 0);
// Get the transaction fee
fee = txData.fee || 0;
// Determine transaction type and amount
let type: 'sent' | 'received' | 'consolidate';
if (isReceived && !isSent) {
// Pure received transaction - sum all outputs to this address
type = 'received';
amount = outputsToAddress;
} else if (isSent) {
// Sent transaction (may also have change output)
// Amount sent to others = inputs - change - fee
const amountSentToOthers = inputsFromAddress - outputsToAddress - fee;
// Check if this is a consolidation (self-send where all outputs go back to same address)
// A consolidation happens when amount sent to others is 0 or very small (dust threshold)
const dustThreshold = 546; // Standard Bitcoin dust limit
const isConsolidation = amountSentToOthers <= dustThreshold && outputsToAddress > 0;
if (isConsolidation) {
// For consolidation, show the output amount (the consolidated amount)
type = 'consolidate';
amount = outputsToAddress;
} else {
// Regular send transaction - show amount sent to others
type = 'sent';
amount = amountSentToOthers;
}
} else {
// Fallback (shouldn't happen, but TypeScript requires it)
type = 'received';
amount = outputsToAddress;
}
return {
id: `${txData.txid}-${index}`,
txid: txData.txid,
type,
amount: Math.abs(amount),
fee: fee,
address: address,
confirmations: txData.status.confirmed ? (txData.status.block_height ? 1 : 0) : 0, // Simplified
blockHeight: txData.status.block_height,
timestamp: (txData.status.block_time ?? 0) * 1000, // Convert to milliseconds
status: txData.status.confirmed ? 'confirmed' : 'unconfirmed'
} as BitcoinTransaction;
});
}
/**
* Hook to fetch and manage Bitcoin balance from UTXOs
*/
export function useBitcoinBalance(address: string | null) {
return useQuery({
queryKey: ['bitcoin-balance', address],
queryFn: async (): Promise<{ balance: number; utxos: UTXO[] }> => {
if (!address) {
return { balance: 0, utxos: [] };
}
const utxos = await fetchUTXOs(address);
const balance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
return { balance, utxos };
},
enabled: !!address,
refetchInterval: 30000, // Refetch every 30 seconds
staleTime: 10000, // Consider data stale after 10 seconds
});
}
/**
* Hook to fetch and manage Bitcoin transaction history
*/
export function useBitcoinTransactionHistory(address: string | null) {
return useQuery({
queryKey: ['bitcoin-transactions', address],
queryFn: async (): Promise<BitcoinTransaction[]> => {
if (!address) {
return [];
}
return fetchBitcoinTransactions(address);
},
enabled: !!address,
refetchInterval: 30000, // Refetch every 30 seconds
staleTime: 10000, // Consider data stale after 10 seconds
});
}
/**
* Hook for Bitcoin operations (send, receive, consolidate, etc.)
*/
export function useBitcoinOperations(bitcoinAddress: string | null) {
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
// Use UTXOs from useBitcoinBalance which auto-updates every 30 seconds
const utxos = bitcoinBalanceData?.utxos || [];
const isLoadingUtxos = isBitcoinBalanceLoading;
// State for Bitcoin operations
const [feeRate, setFeeRate] = useState<number>(1);
const [isConsolidating, setIsConsolidating] = useState(false);
// Fetch fee rates on mount and when UTXOs change
useEffect(() => {
getFeeRates()
.then(feeRates => setFeeRate(feeRates.fastestFee))
.catch(() => {
// Fee rate fetch failure is not critical, keep existing rate
});
}, [utxos.length]); // Re-fetch when UTXO count changes
// Calculate max send amount
const bitcoinMaxAmount = utxos.length > 0 ? calculateMaxSendAmount(utxos, feeRate) : 0;
// Fetch UTXOs manually (for immediate refresh after transactions)
// This will trigger React Query to refetch, which will update the utxos automatically
const fetchBitcoinUtxos = useCallback(async () => {
if (!bitcoinAddress) return;
try {
// Refetch balance which includes UTXOs
await refetchBitcoinBalance();
// Also update fee rates
const feeRates = await getFeeRates();
setFeeRate(feeRates.fastestFee);
} catch (error) {
console.error('Error fetching UTXOs:', error);
toast({
variant: "destructive",
title: "UTXO Error",
description: "Failed to fetch Bitcoin UTXOs",
});
}
}, [bitcoinAddress, refetchBitcoinBalance, toast]);
// Handle Send Max
const handleSendMax = (setBitcoinAmount: (amount: string) => void) => {
if (bitcoinMaxAmount > 0) {
setBitcoinAmount(bitcoinMaxAmount.toString());
}
};
// Handle Bitcoin Send
const handleBitcoinSend = async (
bitcoinAmount: string,
pendingBitcoinRecipient: string | null,
setBitcoinAmount: (amount: string) => void,
setBitcoinRecipient: (recipient: string) => void,
setPendingBitcoinRecipient: (recipient: string | null) => void,
setShowSendModal: (show: boolean) => void
) => {
if (!hasNsecAccess || !bitcoinAmount || !pendingBitcoinRecipient || !bitcoinAddress) {
toast({
variant: "destructive",
title: "Bitcoin Send Error",
description: "Missing required information for Bitcoin transaction",
});
return;
}
try {
const privateKey = getPrivateKey();
if (!privateKey) {
throw new Error('Unable to access private key');
}
const amountSats = parseInt(bitcoinAmount);
if (isNaN(amountSats) || amountSats <= 0) {
throw new Error('Invalid amount');
}
// Determine if the recipient is a Bitcoin address or npub
let recipientAddress: string;
if (pendingBitcoinRecipient.startsWith('bc1') || pendingBitcoinRecipient.startsWith('1') || pendingBitcoinRecipient.startsWith('3')) {
// It's already a Bitcoin address
recipientAddress = pendingBitcoinRecipient;
} else if (pendingBitcoinRecipient.startsWith('npub')) {
// It's an npub, convert to Bitcoin address
recipientAddress = npubToBitcoinAddress(pendingBitcoinRecipient);
} else {
// Assume it's a hex pubkey
recipientAddress = nostrPubkeyToBitcoinAddress(pendingBitcoinRecipient);
}
// Fetch UTXOs and fee rates
const [utxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
// Check if this is a Send Max transaction
const isSendMax = amountSats === bitcoinMaxAmount && bitcoinMaxAmount > 0;
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
recipientAddress,
amountSats,
utxos,
feeRates.fastestFee,
isSendMax
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
toast({
title: "Bitcoin Sent!",
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
});
// Reset form and refresh balance
setBitcoinAmount('');
setBitcoinRecipient('');
setPendingBitcoinRecipient(null);
refetchBitcoinBalance();
setShowSendModal(false);
} catch (error) {
console.error('Bitcoin send error:', error);
toast({
variant: "destructive",
title: "Bitcoin Send Failed",
description: error instanceof Error ? error.message : 'Unknown error occurred',
});
}
};
// Handle Bitcoin Receive
const handleBitcoinReceive = async (
setBitcoinAddressQRCode: (qr: string) => void,
setShowBitcoinAddressQR: (show: boolean) => void
) => {
if (!bitcoinAddress) return;
try {
const qr = await generateQRCode(bitcoinAddress);
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
} catch (error) {
console.error('QR generation error:', error);
toast({
variant: "destructive",
title: "QR Code Error",
description: "Failed to generate QR code",
});
}
};
// Handle UTXO Consolidation
const handleConsolidateUtxos = async () => {
if (!hasNsecAccess || !bitcoinAddress || utxos.length <= 1) {
toast({
variant: "destructive",
title: "Consolidation Error",
description: "Cannot consolidate UTXOs",
});
return;
}
setIsConsolidating(true);
try {
const privateKey = getPrivateKey();
if (!privateKey) {
throw new Error('Unable to access private key');
}
// For consolidation, we send all UTXOs to our own address (self-send)
const consolidationAmount = calculateMaxSendAmount(utxos, feeRate);
if (consolidationAmount <= 0) {
throw new Error('Insufficient funds for consolidation');
}
// Fetch current UTXOs and fee rates
const [fetchedUtxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
// Create consolidation transaction (self-send with all UTXOs)
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
bitcoinAddress, // Send to our own address
consolidationAmount,
fetchedUtxos,
feeRates.fastestFee,
true // sendMax = true
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
toast({
title: "UTXOs Consolidated!",
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
});
// Refresh UTXOs and balance (refetchBitcoinBalance updates UTXOs automatically)
refetchBitcoinBalance();
} catch (error) {
console.error('UTXO consolidation error:', error);
toast({
variant: "destructive",
title: "Consolidation Failed",
description: error instanceof Error ? error.message : 'Unknown error occurred',
});
} finally {
setIsConsolidating(false);
}
};
return {
// State
utxos,
isLoadingUtxos,
feeRate,
isConsolidating,
bitcoinMaxAmount,
// Functions
fetchBitcoinUtxos,
handleSendMax,
handleBitcoinSend,
handleBitcoinReceive,
handleConsolidateUtxos,
};
}
-252
View File
@@ -1,252 +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.js';
import { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
import type { Mint } from 'coco-cashu-core';
// Types from coco-cashu-core
type CocoManager = Awaited<ReturnType<typeof initializeCoco>>;
// Singleton pattern to prevent multiple initializations
let globalCocoInstance: CocoManager | null = null;
let globalRepositories: Repositories | null = null;
let globalInitializationPromise: Promise<{ coco: CocoManager; repositories: Repositories }> | null = null;
export interface UseCashuReturn {
// The typed coco manager (direct library access)
coco: CocoManager | null;
// Repositories for direct access to proof data
repositories: Repositories | null;
// React state (for reactivity)
balances: { [mintUrl: string]: number };
mints: Array<{ url: string; name?: string; info?: unknown }>;
totalBalance: number;
// Status
isInitialized: boolean;
isLoading: boolean;
error: Error | null;
// Mnemonic management
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
// Utility functions
clearError: () => void;
getEncodedToken: typeof getEncodedToken;
refreshMints: () => Promise<void>;
}
export function useCashu(): UseCashuReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance ref
const cocoRef = useRef<CocoManager | null>(null);
const repositoriesRef = useRef<Repositories | null>(null);
// React state for UI reactivity
const [balances, setBalances] = useState<{ [mintUrl: string]: number }>({});
const [mints, setMints] = useState<Array<{ url: string; name?: string; info?: unknown }>>([]);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const refreshMints = useCallback(async () => {
const coco = cocoRef.current;
if (!coco) return;
try {
// Only show trusted mints in the UI
const mintList = await coco.mint.getAllTrustedMints();
setMints(mintList.map((m: Mint) => ({
url: m.mintUrl,
name: m.name,
info: m.mintInfo
})));
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new Error('Invalid mnemonic');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the coco manager
const initializeCocoManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
// Use singleton pattern to prevent multiple initializations
if (globalCocoInstance && globalRepositories) {
cocoRef.current = globalCocoInstance;
repositoriesRef.current = globalRepositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// If there's already an initialization in progress, wait for it
if (globalInitializationPromise) {
console.log('Waiting for existing initialization...');
const { coco, repositories } = await globalInitializationPromise;
cocoRef.current = coco;
repositoriesRef.current = repositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// Generate or retrieve mnemonic
let currentMnemonic = mnemonic;
if (!currentMnemonic) {
currentMnemonic = bip39.generateMnemonic(wordlist);
setMnemonicState(currentMnemonic);
}
// Create seed from mnemonic
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories with proper initialization
const repo = new IndexedDbRepositories({ name: "cashu-wallet" });
await repo.init(); // Ensure repository is properly initialized
// Create initialization promise
globalInitializationPromise = (async () => {
const coco = await initializeCoco({
repo,
seedGetter: async () => seed,
logger: new ConsoleLogger("coco", { level: "debug" }) // Use debug level for better logging
});
return { coco, repositories: repo };
})();
// Initialize coco manager using the new API
const { coco, repositories } = await globalInitializationPromise;
// Store as singleton
console.log('Storing new coco instance as singleton');
globalCocoInstance = coco;
globalRepositories = repositories;
globalInitializationPromise = null;
cocoRef.current = coco;
repositoriesRef.current = repositories;
// Enable built-in services for automatic quote processing and state watching
try {
console.log('Enabling coco services...');
await coco.enableMintQuoteWatcher({ watchExistingPendingOnStart: false });
console.log('Mint quote watcher enabled');
await coco.enableMintQuoteProcessor();
console.log('Mint quote processor enabled');
await coco.enableProofStateWatcher();
console.log('Proof state watcher enabled');
console.log('All coco services enabled successfully');
} catch (err) {
// Don't fail initialization if watchers can't be enabled
console.warn('Failed to enable some coco services:', err);
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
setError(new Error(errorMessage));
globalInitializationPromise = null; // Reset on error
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeCocoManager();
}, [initializeCocoManager]);
// Auto-refresh balances and mints on manager events
useEffect(() => {
const coco = cocoRef.current;
if (!coco) return;
const refreshBalances = async () => {
try {
const newBalances = await coco.wallet.getBalances();
setBalances(newBalances);
} catch (err) {
console.log('Failed to refresh balances:', err);
}
};
// Initial load
refreshBalances();
refreshMints();
// Listen to events
const unsubs = [
coco.on('proofs:saved', refreshBalances),
coco.on('proofs:state-changed', refreshBalances),
coco.on('send:created', refreshBalances),
coco.on('receive:created', refreshBalances),
coco.on('mint:added', refreshMints),
coco.on('mint:updated', refreshMints),
];
return () => unsubs.forEach(unsub => unsub());
}, [isInitialized, refreshMints]);
// Calculate total balance
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
return {
// The typed coco manager (direct library access)
coco: cocoRef.current,
// Repositories for direct access to proof data
repositories: repositoriesRef.current,
// React state (for reactivity)
balances,
mints,
totalBalance,
// Status
isInitialized,
isLoading,
error,
// Mnemonic management
mnemonic,
setMnemonic,
generateMnemonic,
// Utility functions
clearError,
getEncodedToken,
refreshMints,
};
}
-95
View File
@@ -1,95 +0,0 @@
import { useState, useCallback, useEffect } from 'react';
import type { HistoryEntry, Manager } from 'coco-cashu-core';
interface UseHistoryManagerProps {
coco: Manager | null;
isInitialized: boolean;
}
export function useHistoryManager({
coco,
isInitialized,
}: UseHistoryManagerProps) {
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
// Load history from wallet
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
const entries = await coco.history.getPaginatedHistory(0, 50); // TODO: show entire history
// Filter out unpaid quotes: only show completed transactions
// - Mint quotes: only show 'ISSUED' (completed)
// - Melt quotes: only show 'PAID' (completed)
// - Send/Receive: show all (no state field)
const filteredEntries = entries.filter((entry) => {
if (entry.type === 'mint') {
return entry.state === 'ISSUED';
}
if (entry.type === 'melt') {
return entry.state === 'PAID';
}
// Send and receive entries don't have a state field, show all
return true;
});
setHistoryEntries(filteredEntries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [coco]);
// Load history on wallet initialization
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh on wallet events
useEffect(() => {
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, coco, loadHistory]);
return {
historyEntries,
setHistoryEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
loadHistory,
};
}
-250
View File
@@ -1,250 +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}`;
console.log('Resolving Lightning address:', {
lightningAddress,
lnurlEndpoint,
amountSats
});
const lnurlResponse = await fetch(lnurlEndpoint, {
headers: { 'Accept': 'application/json' },
});
if (!lnurlResponse.ok) {
console.error('LNURL Endpoint Error:', {
lightningAddress,
lnurlEndpoint,
status: lnurlResponse.status,
statusText: lnurlResponse.statusText
});
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status} ${lnurlResponse.statusText}`);
}
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
console.log('LNURL Response:', {
lightningAddress,
lnurlData
});
if (lnurlData.status && lnurlData.status !== 'OK') {
console.error('LNURL Status Error:', {
lightningAddress,
status: lnurlData.status,
response: lnurlData
});
throw new Error('LNURL endpoint returned error status');
}
if (lnurlData.tag !== 'payRequest') {
console.error('LNURL Tag Error:', {
lightningAddress,
expectedTag: 'payRequest',
actualTag: lnurlData.tag,
response: lnurlData
});
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
}
// Validate amount against min/max bounds
const minSats = lnurlData.minSendable / 1000;
const maxSats = lnurlData.maxSendable / 1000;
console.log('Amount validation:', {
lightningAddress,
amountSats,
minSats,
maxSats,
minSendable: lnurlData.minSendable,
maxSendable: lnurlData.maxSendable
});
if (amountSats < minSats) {
console.error('Amount below minimum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
}
if (amountSats > maxSats) {
console.error('Amount exceeds maximum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`);
}
// Step 2: Request invoice from callback URL
const amountMsats = amountSats * 1000;
const callbackUrl = new URL(lnurlData.callback);
callbackUrl.searchParams.set('amount', amountMsats.toString());
// Add comment if provided and allowed
if (comment && lnurlData.commentAllowed && comment.length <= lnurlData.commentAllowed) {
callbackUrl.searchParams.set('comment', comment);
}
console.log('Requesting invoice:', {
lightningAddress,
amountSats,
amountMsats,
callbackUrl: callbackUrl.toString(),
comment
});
const invoiceResponse = await fetch(callbackUrl.toString(), {
headers: { 'Accept': 'application/json' },
});
if (!invoiceResponse.ok) {
console.error('Invoice Request Error:', {
lightningAddress,
amountSats,
callbackUrl: callbackUrl.toString(),
status: invoiceResponse.status,
statusText: invoiceResponse.statusText
});
throw new Error(`Failed to get invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
}
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
console.log('Invoice Response:', {
lightningAddress,
amountSats,
invoiceData
});
// Check if we have a valid invoice (some providers return invoice directly without status field)
if (invoiceData.pr) {
console.log('Invoice generated successfully:', {
lightningAddress,
amountSats,
invoiceLength: invoiceData.pr.length
});
setIsLoading(false);
return invoiceData.pr;
}
// If no invoice but has status field, check for errors
if (invoiceData.status && invoiceData.status !== 'OK') {
const errorReason = invoiceData.reason || 'Invoice generation failed';
console.error('LNURL Invoice Error:', {
lightningAddress,
amountSats,
status: invoiceData.status,
reason: errorReason,
response: invoiceData
});
throw new Error(`Invoice generation failed: ${errorReason}`);
}
// If we get here, no invoice was provided
console.error('LNURL Invoice Missing PR:', {
lightningAddress,
amountSats,
response: invoiceData
});
throw new Error('No invoice returned from provider');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, []);
return {
getInvoice,
isLoading,
error,
};
}
export type { GetInvoiceParams };
-305
View File
@@ -1,305 +0,0 @@
import { useState, useCallback, useEffect, useRef } from 'react';
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
import type { Manager } from 'coco-cashu-core';
import { useToast } from '@/hooks/useToast';
interface UseLightningOperationsProps {
coco: Manager | null;
activeMintUrl: string | null;
generateQRCode: (text: string) => Promise<string>;
getLightningInvoice: (params: {
lightningAddress: string;
amountSats: number;
}) => Promise<string>;
}
export function useLightningOperations({
coco,
activeMintUrl,
generateQRCode,
getLightningInvoice,
}: UseLightningOperationsProps) {
const { toast } = useToast();
// Receive state
const [quoteAmount, setQuoteAmount] = useState('');
// Send state
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
// Processing state to prevent concurrent executions
const [isProcessingPayment, setIsProcessingPayment] = useState(false);
// Invoice modal state
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// Handle receive (Lightning quote/invoice creation)
const handleLightningReceive = useCallback(async () => {
if (!coco || !quoteAmount || !activeMintUrl) {
return;
}
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry,
});
setShowInvoiceModal(true);
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
toast({
title: 'Payment Received',
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
toast({
variant: 'destructive',
title: 'Quote Creation Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [coco, quoteAmount, activeMintUrl, toast, generateQRCode]);
// Detect input type and handle Lightning address/invoice parsing
const detectAndHandleLightningInput = useCallback((input: string): 'lightning_address' | 'invoice' | null => {
const trimmed = input.trim();
if (!trimmed) return null;
// Check if it's a Lightning address (contains @)
if (trimmed.includes('@')) {
setPendingLightningAddress(trimmed);
setLightningAddressInput('');
return 'lightning_address';
}
// Check if it's a Lightning invoice
if (isValidBolt11Invoice(trimmed)) {
const amount = decodeBolt11Amount(trimmed);
if (amount) {
// Show amount confirmation screen
setPendingInvoice(trimmed);
setDecodedInvoiceAmount(amount);
setLightningInvoice('');
return 'invoice';
} else {
// Failed to decode amount - show error
toast({
variant: 'destructive',
title: 'Invalid Invoice',
description: 'Unable to decode the lightning invoice amount. Please check the invoice format.',
});
setLightningInvoice('');
return null;
}
} else {
// Not a valid BOLT11 invoice - show error
toast({
variant: 'destructive',
title: 'Invalid Invoice',
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
});
setLightningInvoice('');
return null;
}
}, [toast]);
// Handle Lightning address payment
const handleLightningAddressPayment = useCallback(async () => {
// Prevent concurrent executions
if (isProcessingPayment) {
return;
}
if (!coco || !pendingLightningAddress || !lightningAddressAmount || !activeMintUrl) {
return;
}
setIsProcessingPayment(true);
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
setIsProcessingPayment(false);
return;
}
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
invoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Payment Sent',
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
} catch (err) {
console.error('Payment error:', err);
toast({
variant: 'destructive',
title: 'Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
} finally {
setIsProcessingPayment(false);
}
}, [coco, pendingLightningAddress, lightningAddressAmount, activeMintUrl, getLightningInvoice, toast, isProcessingPayment]);
// Handle confirmed invoice payment
const handleConfirmInvoicePayment = useCallback(async () => {
// Prevent concurrent executions
if (isProcessingPayment) {
return;
}
if (!coco || !pendingInvoice || !activeMintUrl) return;
setIsProcessingPayment(true);
try {
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
pendingInvoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Invoice Paid',
description: `Lightning invoice paid successfully for ${decodedInvoiceAmount} sats!`,
});
// Reset state
setPendingInvoice(null);
setDecodedInvoiceAmount(null);
} catch (err) {
toast({
variant: 'destructive',
title: 'Invoice Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
} finally {
setIsProcessingPayment(false);
}
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast, isProcessingPayment]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
return {
// Receive state
quoteAmount,
setQuoteAmount,
// Send state
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
// Invoice modal state
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
// Processing state
isProcessingPayment,
// Handlers
handleLightningReceive,
detectAndHandleLightningInput,
handleLightningAddressPayment,
handleConfirmInvoicePayment,
// Refs
mintQuoteUnsubscribeRef,
};
}
-249
View File
@@ -1,249 +0,0 @@
import { useState, useCallback } from 'react';
import type { Manager, Repositories } from 'coco-cashu-core';
import { toast } from '@/hooks/useToast';
export interface CashuMint {
url: string;
name?: string;
}
// Mint utility functions
export const getCleanMintLabel = (mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host;
} catch {
return mint.url.replace(/^https?:\/\//, '');
}
};
export const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = err instanceof Error ? err.message : String(err);
const errorName = err instanceof Error ? err.constructor.name : '';
return errorName === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
export const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = err instanceof Error ? err.message : String(err);
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
interface UseMintManagerProps {
coco: Manager | null;
mints: CashuMint[];
repositories: Repositories | null;
isNpubCashLoggedIn: boolean;
setNpubCashMint: (mintUrl: string) => Promise<boolean>;
refreshMints: () => Promise<void>;
}
export function useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint,
refreshMints,
}: UseMintManagerProps) {
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
const [mintUrl, setMintUrl] = useState('');
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
// Set active mint and optionally sync to npub.cash
const handleSetActiveMint = useCallback(
async (url: string | null, syncToNpubCash = true) => {
setActiveMintUrl(url);
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && url && syncToNpubCash) {
try {
await setNpubCashMint(url);
} catch (err) {
console.error('Failed to sync mint to npub.cash:', err);
}
}
},
[isNpubCashLoggedIn, setNpubCashMint]
);
// Add a new mint
const handleAddMint = useCallback(async () => {
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (
!normalizedUrl.startsWith('http://') &&
!normalizedUrl.startsWith('https://')
) {
normalizedUrl = `https://${normalizedUrl}`;
}
// Check if mint with same name already exists (case insensitive)
const existingMint = mints.find(mint =>
mint.url.toLowerCase() === normalizedUrl.toLowerCase()
);
if (existingMint) {
toast({
variant: 'destructive',
title: 'Mint Already Exists',
description: 'A mint with this URL already exists',
});
return;
}
// Add mint and automatically trust it
await coco.mint.addMint(normalizedUrl, { trusted: true });
setMintUrl('');
toast({
title: 'Mint Added',
description: 'Mint added and trusted successfully!',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Add Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintUrl, coco, mints]);
// Show remove confirmation modal
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
// Confirm and remove mint
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove || !repositories) return;
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(
(mint) => mint.url !== mintToRemove.url
);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: 'Mint Removed',
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: 'destructive',
title: 'Remove Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [
mintToRemove,
mints,
activeMintUrl,
handleSetActiveMint,
repositories,
refreshMints,
]);
// Show denomination breakdown for a mint
const handleShowDenominations = useCallback(
async (
mintUrl: string,
setShowProofBreakdown: (show: boolean) => void,
setProofBreakdown: (breakdown: {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}) => void
) => {
if (!repositories) return;
try {
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(
mintUrl
);
if (!proofs || proofs.length === 0) {
toast({
variant: 'destructive',
title: 'No Tokens',
description: 'No tokens found for this mint',
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations).reduce(
(sum, [amount, count]) => sum + parseInt(amount) * count,
0
);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance,
});
setShowProofBreakdown(true);
} catch (err) {
toast({
variant: 'destructive',
title: 'Failed to Get Denominations',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
},
[repositories]
);
return {
activeMintUrl,
setActiveMintUrl: handleSetActiveMint,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
};
}
-340
View File
@@ -1,340 +0,0 @@
import { useCallback, useState, useMemo, useRef } from 'react';
import { useNIP98 } from '../useNIP98';
import { NPCClient, JWTAuthProvider } from 'npubcash-sdk';
import type { Quote } from 'npubcash-types';
import type { Manager } from 'coco-cashu-core';
import type { EventTemplate, Event } from 'nostr-tools';
import { useToast } from '../useToast';
const NPUBCASH_BASE_URL = 'https://npubx.cash';
export interface NpubCashUserInfo {
pubkey: string;
name?: string;
mintUrl: string; // API returns camelCase
lockQuote: boolean; // API returns camelCase
}
/**
* Hook for interacting with npub.cash API using the official SDK
*/
export function useNpubCash() {
const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Ref to track last sync timestamp for incremental updates
const lastSyncRef = useRef<number>(0);
// Create NPCClient instance using the SDK with JWTAuthProvider for proper WebSocket auth
const npcClient = useMemo(() => {
if (!isLoggedIn || !signer) return null;
// Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature
const signingFunc = async (eventTemplate: EventTemplate): Promise<Event> => {
return await signer.signEvent(eventTemplate);
};
const auth = new JWTAuthProvider(NPUBCASH_BASE_URL, signingFunc);
return new NPCClient(NPUBCASH_BASE_URL, auth);
}, [isLoggedIn, signer]);
// Generic wrapper for SDK calls with loading state
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
try {
setIsLoading(true);
setError(null);
return await operation();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
return null;
} finally {
setIsLoading(false);
}
}, []);
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setMintUrl(mintUrl));
return result !== null;
}, [npcClient, withLoading]);
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
if (!npcClient) return null;
// Since SDK doesn't have getUserInfo, we'll use manual implementation
// This could be enhanced if SDK adds this method
return withLoading(async () => {
const url = `${NPUBCASH_BASE_URL}/api/v2/user/info`;
const authHeader = await createAuthHeader({ url, method: 'GET' });
const response = await fetch(url, {
method: 'GET',
headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' },
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
}
const data = await response.json();
return data.data.user;
});
}, [npcClient, createAuthHeader, withLoading]);
const getAllQuotes = useCallback(async (): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getAllQuotes());
return result || [];
}, [npcClient, withLoading]);
const getQuotesSince = useCallback(async (since: number): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getQuotesSince(since));
return result || [];
}, [npcClient, withLoading]);
const setLockQuotes = useCallback(async (lockQuotes: boolean): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setLock(lockQuotes));
return result !== null;
}, [npcClient, withLoading]);
const subscribeToQuotes = useCallback((
onUpdate: (quoteId: string) => void,
onError?: (msg: string) => void
) => {
if (!npcClient) return () => {};
return npcClient.subscribe(onUpdate, onError);
}, [npcClient]);
const refreshQuotes = useCallback(async (coco: Manager): Promise<void> => {
if (!npcClient || !coco) return;
try {
// Fetch all quotes from npub.cash
const quotes = await getAllQuotes();
if (quotes.length === 0) {
toast({
title: "No Quotes Found",
description: "No pending quotes found on npub.cash",
});
return;
}
// Group quotes by mint URL
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (!isKnown) {
await coco.mint.addMint(mintUrl, { trusted: true });
} else {
// Mint exists, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
}
// Add quotes to the wallet (matching main.ts format)
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Refreshed",
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
});
} else {
toast({
title: "No New Quotes",
description: "All quotes from npub.cash are already processed",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Refresh Failed",
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
});
}
}, [npcClient, getAllQuotes, toast]);
const clearError = useCallback(() => setError(null), []);
// Subscribe to quote updates and sync to wallet automatically
const syncQuotesWithWallet = useCallback(async (coco: Manager): Promise<() => void> => {
if (!npcClient || !coco) return () => {};
try {
// Fetch and sync all quotes initially
const quotes = await getAllQuotes();
if (quotes.length > 0) {
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (!isKnown) {
await coco.mint.addMint(mintUrl, { trusted: true });
} else {
// Mint exists, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
} catch (err) {
console.warn(`Failed to sync quotes for mint ${mintUrl}:`, err);
}
}
}
// Subscribe to real-time updates
const unsubscribe = subscribeToQuotes(
async (quoteId: string) => {
try {
// When a quote is updated, fetch newer quotes and sync
const recentQuotes = await getQuotesSince(lastSyncRef.current);
if (recentQuotes.length > 0) {
const quotesByMint = recentQuotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof recentQuotes>);
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (!isKnown) {
await coco.mint.addMint(mintUrl, { trusted: true });
} else {
// Mint exists, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
} catch (err) {
console.warn(`Failed to sync quote ${quoteId} for mint ${mintUrl}:`, err);
}
}
lastSyncRef.current = Math.floor(Date.now() / 1000);
}
} catch (err) {
console.error('Failed to sync quote update:', err);
}
},
(err: string) => {
console.error('Quote subscription error:', err);
toast({
variant: "destructive",
title: "Sync Error",
description: "Failed to sync quotes from npub.cash",
});
}
);
return unsubscribe;
} catch (err) {
console.error('Failed to set up quote sync:', err);
toast({
variant: "destructive",
title: "Sync Failed",
description: err instanceof Error ? err.message : 'Failed to set up quote sync',
});
return () => {};
}
}, [npcClient, getAllQuotes, getQuotesSince, subscribeToQuotes, toast]);
return {
// Core methods
setMint,
getUserInfo,
// Quote management methods
getAllQuotes,
getQuotesSince,
setLockQuotes,
subscribeToQuotes,
refreshQuotes,
syncQuotesWithWallet,
// Status
isLoading,
error,
isLoggedIn,
pubkey,
clearError,
// SDK instance for advanced usage
npcClient,
};
}
-265
View File
@@ -1,265 +0,0 @@
import { useState, useCallback, useRef } from 'react';
import QRCode from 'qrcode';
import { Html5Qrcode } from 'html5-qrcode';
import { useToast } from '@/hooks/useToast';
export type QRScanResult =
| { type: 'lightning_invoice'; value: string }
| { type: 'lightning_address'; value: string }
| { type: 'cashu_token'; value: string }
| { type: 'bitcoin_address'; value: string }
| { type: 'npub'; value: string }
| { type: 'unknown'; value: string };
interface UseQRCodeReturn {
generateQRCode: (text: string) => Promise<string>;
isGenerating: boolean;
error: string | null;
// Scanner functions
isScanning: boolean;
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
stopScanning: () => Promise<void>;
classifyQRCode: (text: string) => QRScanResult;
setModalOpen?: (isOpen: boolean) => void;
}
/**
* 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 [isScanning, setIsScanning] = useState(false);
const [scanError, setScanError] = useState<string | null>(null);
const scannerRef = useRef<Html5Qrcode | null>(null);
const isStartingRef = useRef(false);
const shouldCancelRef = useRef(false);
const modalOpenRef = useRef(true);
const { toast } = useToast();
const setModalOpen = useCallback((isOpen: boolean) => {
modalOpenRef.current = isOpen;
}, []);
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]);
const classifyQRCode = useCallback((decodedText: string): QRScanResult => {
// Lightning invoice: lnbc... or lightning:lnbc... (case insensitive)
const lightningInvoiceMatch = decodedText.match(/^(?:lightning:)?(lnbc[a-z0-9]+)$/i);
if (lightningInvoiceMatch) {
return { type: 'lightning_invoice', value: lightningInvoiceMatch[1] };
}
// Lightning address: [email protected] or lightning:[email protected]
const lightningAddressMatch = decodedText.match(/^(?:lightning:)?([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/);
if (lightningAddressMatch) {
return { type: 'lightning_address', value: lightningAddressMatch[1] };
}
// Cashu token: cashu...
if (/^cashu[A-Za-z0-9+/=_-]+$/.test(decodedText)) {
return { type: 'cashu_token', value: decodedText };
}
// Bitcoin address: bc1... or legacy (1..., 3...)
if (/^(bc1|3|1)[a-zA-Z0-9]{25,62}$/.test(decodedText)) {
return { type: 'bitcoin_address', value: decodedText };
}
// Nostr npub: npub1... or nostr:npub1...
const npubMatch = decodedText.match(/^(?:nostr:)?(npub1[a-z0-9]{58})$/);
if (npubMatch) {
return { type: 'npub', value: npubMatch[1] };
}
return { type: 'unknown', value: decodedText };
}, []);
const startScanning = useCallback(async (onResult: (result: QRScanResult) => void): Promise<void> => {
try {
isStartingRef.current = true;
shouldCancelRef.current = false;
setScanError(null);
// Find available cameras
const devices = await Html5Qrcode.getCameras();
if (devices.length === 0) {
throw new Error('No cameras found');
}
// Check if we should cancel before proceeding
if (shouldCancelRef.current) {
isStartingRef.current = false;
return;
}
// Use the rear camera by default, or first available
const cameraId = devices.length > 1
? devices.find(d => d.label.toLowerCase().includes('back') || d.label.toLowerCase().includes('rear'))?.id || devices[0].id
: devices[0].id;
// Initialize scanner
const scanner = new Html5Qrcode('qr-reader');
scannerRef.current = scanner;
// Start scanning
await scanner.start(
cameraId,
{
fps: 10,
aspectRatio: 1,
qrbox: 250
},
(decodedText) => {
const result = classifyQRCode(decodedText);
onResult(result);
},
(errorMessage) => {
// Ignore decoding errors, camera is still running
// Only log if it's not a "QR code not found" type error
if (!errorMessage.includes('qr')) {
console.debug('QR scan error:', errorMessage);
}
}
);
isStartingRef.current = false;
// Check if we should immediately stop after starting (cancel was requested during init)
if (shouldCancelRef.current || !modalOpenRef.current) {
try {
await scanner.stop();
await scanner.clear();
scannerRef.current = null;
} catch (err) {
console.error('Error stopping scanner after cancelled init:', err);
}
return;
}
setIsScanning(true);
} catch (err) {
isStartingRef.current = false;
shouldCancelRef.current = false;
let errorMessage = 'Failed to start camera';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Provide more helpful error messages
if (errorMessage.includes('NotAllowedError') || errorMessage.includes('Permission denied')) {
errorMessage = 'Camera permission denied. Please allow camera access.';
} else if (errorMessage.includes('NotFoundError') || errorMessage.includes('No device')) {
errorMessage = 'No camera found. Please connect a camera.';
}
setScanError(errorMessage);
setIsScanning(false);
console.error('Camera error:', err);
}
}, [classifyQRCode]);
const stopScanning = useCallback(async (): Promise<void> => {
try {
// If scanner is starting up, set cancel flag
if (isStartingRef.current) {
shouldCancelRef.current = true;
// Wait for startup to complete and auto-stop
let attempts = 0;
while (isStartingRef.current && attempts < 50) { // Wait up to 5 seconds
await new Promise(resolve => setTimeout(resolve, 100));
attempts++;
}
}
if (scannerRef.current) {
// Check if scanner is actually running before trying to stop
const scanner = scannerRef.current;
try {
// Html5Qrcode has a getState() method to check if it's scanning
const state = scanner.getState();
if (state === 2) { // State 2 = SCANNING
await scanner.stop();
} else if (state === 1) { // State 1 = STARTING
// Wait a bit more and try again
await new Promise(resolve => setTimeout(resolve, 200));
const newState = scanner.getState();
if (newState === 2) {
await scanner.stop();
}
}
} catch (stopErr) {
// If stop fails, try to clear anyway
console.warn('Error stopping scanner, attempting to clear:', stopErr);
}
try {
await scanner.clear();
} catch (clearErr) {
console.warn('Error clearing scanner:', clearErr);
}
scannerRef.current = null;
}
shouldCancelRef.current = false;
isStartingRef.current = false;
setIsScanning(false);
setScanError(null);
} catch (err) {
console.error('Error stopping scanner:', err);
shouldCancelRef.current = false;
isStartingRef.current = false;
setIsScanning(false);
scannerRef.current = null;
}
}, []);
return {
generateQRCode,
isGenerating,
error: error || scanError,
isScanning,
startScanning,
stopScanning,
classifyQRCode,
setModalOpen,
};
}
-444
View File
@@ -1,444 +0,0 @@
import zkpInit from '@vulpemventures/secp256k1-zkp';
import {
Transaction,
address,
initEccLib,
networks,
} from 'bitcoinjs-lib';
import {
Musig,
OutputType,
SwapTreeSerializer,
TaprootUtils,
constructClaimTransaction,
detectSwap,
targetFee,
} from 'boltz-core';
import { ECPairFactory, type ECPairAPI, type ECPairInterface } from 'ecpair';
import * as ecc from '@bitcoinerlab/secp256k1';
import { Buffer } from 'buffer';
// Initialize ECC library
initEccLib(ecc);
// Boltz API endpoints
const API_ENDPOINT = 'https://api.boltz.exchange';
const WS_ENDPOINT = 'wss://api.boltz.exchange/v2/ws';
// Use mainnet by default
const network = networks.bitcoin;
// Lazy initialization of ECPair factory
let ECPair: ECPairAPI | null = null;
function getECPair(): ECPairAPI {
if (!ECPair) {
ECPair = ECPairFactory(ecc);
}
return ECPair;
}
/**
* Generate random bytes using browser crypto API
*/
function randomBytes(length: number): Buffer {
const array = new Uint8Array(length);
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
window.crypto.getRandomValues(array);
} else {
// Fallback for Node.js environments (shouldn't happen in browser, but just in case)
for (let i = 0; i < length; i++) {
array[i] = Math.floor(Math.random() * 256);
}
}
return Buffer.from(array);
}
/**
* SHA256 hash using browser SubtleCrypto API
*
* Note: window.crypto.subtle requires a secure context (HTTPS or localhost).
* It will be undefined if the page is served over HTTP.
*/
async function sha256(data: Buffer): Promise<Buffer> {
if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
// Convert Buffer to Uint8Array for SubtleCrypto
const uint8Array = new Uint8Array(data);
const hashBuffer = await window.crypto.subtle.digest('SHA-256', uint8Array);
return Buffer.from(hashBuffer);
}
// window.crypto.subtle unavailable - likely due to:
// 1. Page served over HTTP (not HTTPS/localhost)
// 2. Very old browser without support
// 3. Test environment without crypto API
throw new Error(
'SHA256 not available: window.crypto.subtle requires HTTPS or localhost. ' +
'Please serve the application over HTTPS or use localhost for development.'
);
}
/**
* Swap status update from WebSocket
*/
export interface SwapStatusUpdate {
status: 'swap.created' | 'transaction.mempool' | 'invoice.settled' | 'transaction.confirmed';
transaction?: {
hex: string;
};
}
/**
* Reverse swap result
*/
export interface ReverseSwapResult {
/** Lightning invoice to pay */
invoice: string;
/** Swap ID for tracking */
swapId: string;
/** Function to close WebSocket connection */
close: () => void;
}
/**
* Options for creating a reverse swap
*/
export interface ReverseSwapOptions {
/** Amount in satoshis for the Lightning invoice */
invoiceAmount: number;
/** Bitcoin address to receive the on-chain funds */
destinationAddress: string;
/** Callback for swap status updates */
onStatusUpdate?: (update: SwapStatusUpdate) => void;
/** Callback when swap is successfully completed */
onSuccess?: () => void;
/** Callback for errors */
onError?: (error: Error) => void;
/** Network to use (defaults to mainnet) */
network?: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet;
}
/**
* Create a reverse swap (Lightning to on-chain Bitcoin)
*
* This function creates a reverse swap where the user pays a Lightning invoice,
* and receives Bitcoin on-chain at the specified address.
*
* @param options - Reverse swap configuration options
* @returns Promise resolving to swap result with invoice and tracking functions
*
* @example
* ```typescript
* const { invoice, swapId, close } = await createReverseSwap({
* invoiceAmount: 100_000,
* destinationAddress: 'bc1q...',
* onStatusUpdate: (update) => {
* console.log('Swap status:', update.status);
* },
* onSuccess: () => {
* console.log('Swap completed!');
* }
* });
*
* // Display invoice to user for payment
* console.log('Pay this invoice:', invoice);
*
* // Later, close the connection when done
* close();
* ```
*/
export async function createReverseSwap(
options: ReverseSwapOptions
): Promise<ReverseSwapResult> {
const {
invoiceAmount,
destinationAddress,
onStatusUpdate,
onSuccess,
onError,
network: swapNetwork = network,
} = options;
// Create a random preimage for the swap (must be 32 bytes)
const preimage = randomBytes(32);
const keys = getECPair().makeRandom();
// Hash the preimage
const preimageHash = await sha256(preimage);
// Get public key as hex - match original code exactly
// keys.publicKey is a Buffer (or Uint8Array in browser), convert to hex string
// This should be a compressed public key (33 bytes = 66 hex chars)
const claimPublicKeyHex = Buffer.from(keys.publicKey).toString('hex');
// Validate length (compressed public key should be 33 bytes = 66 hex chars)
if (claimPublicKeyHex.length !== 66) {
throw new Error(`Invalid public key hex length: expected 66 chars (33 bytes), got ${claimPublicKeyHex.length}`);
}
const requestBody = {
invoiceAmount,
to: 'BTC',
from: 'BTC',
claimPublicKey: claimPublicKeyHex,
preimageHash: preimageHash.toString('hex'),
};
console.log('[createReverseSwap] Request body:', {
...requestBody,
claimPublicKeyLength: claimPublicKeyHex.length / 2, // Divide by 2 because hex is 2 chars per byte
preimageHashLength: requestBody.preimageHash.length / 2,
});
// Create the reverse swap via API
const createResponse = await fetch(`${API_ENDPOINT}/v2/swap/reverse`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
if (!createResponse.ok) {
const errorText = await createResponse.text();
console.error('[createReverseSwap] API error response:', errorText);
throw new Error(`Failed to create reverse swap: ${errorText}`);
}
const createdResponse = await createResponse.json();
// Set up WebSocket connection for tracking swap progress
const webSocket = new WebSocket(WS_ENDPOINT);
const close = () => {
if (webSocket.readyState === WebSocket.OPEN) {
webSocket.close();
}
};
webSocket.onopen = () => {
webSocket.send(
JSON.stringify({
op: 'subscribe',
channel: 'swap.update',
args: [createdResponse.id],
})
);
};
webSocket.onmessage = async (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.event !== 'update') {
return;
}
const statusUpdate: SwapStatusUpdate = {
status: msg.args[0].status,
transaction: msg.args[0].transaction,
};
onStatusUpdate?.(statusUpdate);
switch (msg.args[0].status) {
case 'swap.created': {
// Boltz is waiting for the invoice to be paid
break;
}
case 'transaction.mempool': {
// Boltz sent an on-chain transaction, now we need to claim it
try {
await claimSwapTransaction(
createdResponse,
keys,
preimage,
destinationAddress,
msg.args[0].transaction.hex,
swapNetwork
);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
onError?.(err);
close();
throw err;
}
break;
}
case 'invoice.settled':
case 'transaction.confirmed': {
// Swap successful
onSuccess?.();
close();
break;
}
}
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
onError?.(err);
close();
}
};
webSocket.onerror = () => {
onError?.(new Error('WebSocket error occurred'));
};
webSocket.onclose = () => {
// Connection closed
};
return {
invoice: createdResponse.invoice,
swapId: createdResponse.id,
close,
};
}
/**
* Claim the swap transaction after Boltz sends it to the mempool
*/
async function claimSwapTransaction(
createdResponse: {
id: string;
refundPublicKey: string;
swapTree: string;
},
keys: ECPairInterface,
preimage: Buffer,
destinationAddress: string,
lockupTxHex: string,
swapNetwork: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet
): Promise<void> {
const boltzPublicKey = Buffer.from(createdResponse.refundPublicKey, 'hex');
// Create a musig signing session and tweak it with the Taptree of the swap scripts
const zkp = await zkpInit();
// Convert keys.publicKey (Uint8Array) to Buffer for Musig
const keysPublicKeyBuffer = Buffer.from(keys.publicKey);
const musig = new Musig(zkp, keys, randomBytes(32), [
boltzPublicKey,
keysPublicKeyBuffer,
]);
const tweakedKey = TaprootUtils.tweakMusig(
musig,
SwapTreeSerializer.deserializeSwapTree(createdResponse.swapTree).tree
);
// Parse the lockup transaction and find the output relevant for the swap
const lockupTx = Transaction.fromHex(lockupTxHex);
// Convert Transaction outputs to the format expected by detectSwap
// bitcoinjs-lib v7 uses bigint for values, but detectSwap expects number
const txOutputs = lockupTx.outs.map((out) => ({
script: Buffer.from(out.script),
value: Number(out.value), // Convert bigint to number
}));
const swapOutput = detectSwap(tweakedKey, { outs: txOutputs });
if (swapOutput === undefined) {
throw new Error('No swap output found in lockup transaction');
}
// Create a claim transaction to be signed cooperatively via a key path spend
// swapOutput.value is guaranteed to be a number because we converted it above
// (detectSwap preserves the input type, and we passed { value: number })
// TypeScript needs explicit assertion since detectSwap is generic
const swapValueForClaim: number = Number(swapOutput.value);
// Convert txHash to Buffer
const txHashBuffer = Buffer.from(lockupTx.getHash());
// Convert address script to Buffer
const destinationScript = Buffer.from(address.toOutputScript(destinationAddress, swapNetwork));
const claimTx = targetFee(2, (fee) =>
constructClaimTransaction(
[
{
...swapOutput,
value: swapValueForClaim,
keys,
preimage,
cooperative: true,
type: OutputType.Taproot,
txHash: txHashBuffer,
},
],
destinationScript,
fee
)
);
// Get the partial signature from Boltz
const claimResponse = await fetch(
`${API_ENDPOINT}/v2/swap/reverse/${createdResponse.id}/claim`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
index: 0,
transaction: claimTx.toHex(),
preimage: preimage.toString('hex'),
pubNonce: Buffer.from(musig.getPublicNonce()).toString('hex'),
}),
}
);
if (!claimResponse.ok) {
const errorText = await claimResponse.text();
throw new Error(`Failed to get claim signature: ${errorText}`);
}
const boltzSig = await claimResponse.json();
// Aggregate the nonces
musig.aggregateNonces([
[boltzPublicKey, Buffer.from(boltzSig.pubNonce, 'hex')],
]);
// Initialize the session to sign the claim transaction
// Use the already converted value for hashForWitnessV1
musig.initializeSession(
claimTx.hashForWitnessV1(
0,
[swapOutput.script],
[swapValueForClaim],
Transaction.SIGHASH_DEFAULT
)
);
// Add the partial signature from Boltz
musig.addPartial(
boltzPublicKey,
Buffer.from(boltzSig.partialSignature, 'hex')
);
// Create our partial signature
musig.signPartial();
// Witness of the input to the aggregated signature
claimTx.ins[0].witness = [musig.aggregatePartials()];
// Broadcast the finalized transaction
const broadcastResponse = await fetch(
`${API_ENDPOINT}/v2/chain/BTC/transaction`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
hex: claimTx.toHex(),
}),
}
);
if (!broadcastResponse.ok) {
const errorText = await broadcastResponse.text();
throw new Error(`Failed to broadcast transaction: ${errorText}`);
}
}
@@ -1,189 +0,0 @@
import { useState, useCallback, useEffect } from 'react';
import { nip19 } from 'nostr-tools';
import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/wallet/useReverseSwap';
import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
import type { Manager } from 'coco-cashu-core';
import { useToast } from '@/hooks/useToast';
interface UseReverseSwapOperationsProps {
coco: Manager | null;
activeMintUrl: string | null;
}
export function useReverseSwapOperations({ coco, activeMintUrl }: UseReverseSwapOperationsProps) {
const { toast } = useToast();
// Reverse swap state (Lightning -> Bitcoin)
const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState<string | null>(null);
const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState('');
const [swapStatus, setSwapStatus] = useState<string | null>(null);
const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null);
// Detect if input is a Bitcoin address or npub for reverse swap
const detectBitcoinAddress = useCallback((input: string): boolean => {
// Check if it's a Bitcoin address
if (isValidBitcoinAddress(input)) {
setPendingBitcoinSwapAddress(input);
return true;
}
// Check if it's an npub (can be converted to Bitcoin address)
try {
const decoded = nip19.decode(input);
if (decoded.type === 'npub') {
const bitcoinAddr = npubToBitcoinAddress(input);
if (bitcoinAddr) {
setPendingBitcoinSwapAddress(input); // Store npub, will convert later
return true;
}
}
} catch {
// Not an npub, continue
}
return false;
}, []);
// Handle reverse swap execution
const handleReverseSwap = useCallback(async () => {
if (!coco || !pendingBitcoinSwapAddress || !bitcoinSwapAmount || !activeMintUrl) {
return;
}
try {
const amount = parseInt(bitcoinSwapAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
// Validate reverse swap amount limits (25,000 - 25,000,000 sats)
if (amount < 25_000 || amount > 25_000_000) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Reverse swap amount must be between 25,000 and 25,000,000 sats',
});
return;
}
// Determine destination address (could be Bitcoin address or npub)
let destinationAddress = pendingBitcoinSwapAddress;
try {
// Try to decode as npub first
const decoded = nip19.decode(pendingBitcoinSwapAddress);
if (decoded.type === 'npub') {
destinationAddress = npubToBitcoinAddress(pendingBitcoinSwapAddress);
}
} catch {
// Not an npub, assume it's already a Bitcoin address
}
// Initiate reverse swap
setSwapStatus('Creating reverse swap...');
const swapResult = await createReverseSwap({
invoiceAmount: amount,
destinationAddress,
onStatusUpdate: (update: SwapStatusUpdate) => {
switch (update.status) {
case 'swap.created':
setSwapStatus('Waiting for invoice payment...');
break;
case 'transaction.mempool':
setSwapStatus('Swap transaction sent to blockchain...');
break;
case 'invoice.settled':
case 'transaction.confirmed':
setSwapStatus('Swap completed!');
break;
}
},
onSuccess: () => {
const displayAddress = destinationAddress.length > 26
? destinationAddress.slice(0, 12) + '...' + destinationAddress.slice(-12)
: destinationAddress;
toast({
title: 'Reverse Swap Completed',
description: `Successfully swapped ${amount} sats to Bitcoin address ${displayAddress}!`,
});
setSwapStatus(null);
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
if (reverseSwapClose) {
reverseSwapClose();
setReverseSwapClose(null);
}
},
onError: (error: Error) => {
toast({
variant: 'destructive',
title: 'Reverse Swap Failed',
description: error.message,
});
setSwapStatus(null);
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
if (reverseSwapClose) {
reverseSwapClose();
setReverseSwapClose(null);
}
},
});
// Store close function for cleanup
setReverseSwapClose(() => swapResult.close);
// Pay the Lightning invoice from the swap using the active mint
setSwapStatus('Paying Lightning invoice...');
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
swapResult.invoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Invoice Paid',
description: `Lightning invoice paid. Swap in progress...`,
});
} catch (err) {
console.error('Reverse swap error:', err);
toast({
variant: 'destructive',
title: 'Reverse Swap Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
setSwapStatus(null);
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
if (reverseSwapClose) {
reverseSwapClose();
setReverseSwapClose(null);
}
}
}, [coco, pendingBitcoinSwapAddress, bitcoinSwapAmount, activeMintUrl, toast, reverseSwapClose]);
// Cleanup reverse swap WebSocket on unmount
useEffect(() => {
return () => {
if (reverseSwapClose) {
reverseSwapClose();
}
};
}, [reverseSwapClose]);
return {
// State
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
// Functions
detectBitcoinAddress,
handleReverseSwap,
};
}
-116
View File
@@ -1,116 +0,0 @@
import { useState, useCallback } from 'react';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english.js';
import { initializeCoco, ConsoleLogger } from 'coco-cashu-core';
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
import type { Manager } from 'coco-cashu-core';
import { useToast } from '@/hooks/useToast';
interface UseSeedPhraseRestoreProps {
coco: Manager | null;
}
export function useSeedPhraseRestore({ coco }: UseSeedPhraseRestoreProps) {
const { toast } = useToast();
const [isRestoring, setIsRestoring] = useState(false);
const handleRestoreFromSeedPhrase = useCallback(async (seedPhrase: string, mintUrl: string) => {
if (!coco) {
throw new Error('Wallet not initialized');
}
setIsRestoring(true);
try {
// Clean and validate the seed phrase
const cleanedSeedPhrase = seedPhrase.trim().toLowerCase();
// Check if it's a valid mnemonic format
if (!bip39.validateMnemonic(cleanedSeedPhrase, wordlist)) {
// Try to provide more specific error information
const words = cleanedSeedPhrase.split(/\s+/);
if (words.length !== 12) {
throw new Error(`Seed phrase must have exactly 12 words, but found ${words.length} words`);
}
// Check if all words are valid
const invalidWords = words.filter(word => !wordlist.includes(word));
if (invalidWords.length > 0) {
throw new Error(`Invalid words found: ${invalidWords.join(', ')}`);
}
throw new Error('Invalid seed phrase format. Please check that all words are spelled correctly.');
}
// Verify this is a different seed from the current wallet
const currentMnemonic = localStorage.getItem('cashu-mnemonic');
if (currentMnemonic && currentMnemonic.toLowerCase() === cleanedSeedPhrase) {
throw new Error('This is the same seed phrase as your current wallet. Please enter a different seed phrase to restore from.');
}
// Convert seed phrase to seed
const restoredSeed = bip39.mnemonicToSeedSync(cleanedSeedPhrase);
// Get current balance before restore
const balancesBefore = await coco.wallet.getBalances();
const balanceBefore = balancesBefore[mintUrl] || 0;
// Create a temporary coco instance with the restored seed to fetch proofs
const tempRepo = new IndexedDbRepositories({ name: `cashu-wallet-restore-${Date.now()}` });
await tempRepo.init();
const tempCoco = await initializeCoco({
repo: tempRepo,
seedGetter: async () => restoredSeed,
logger: new ConsoleLogger(`restore-${Date.now()}`, { level: "debug" })
});
try {
// Restore the proofs in the temporary wallet
await tempCoco.wallet.restore(mintUrl);
// Get the restored balance from the temporary wallet
const tempBalances = await tempCoco.wallet.getBalances();
const restoredAmount = tempBalances[mintUrl] || 0;
if (restoredAmount <= 0) {
toast({
title: "No Tokens Found",
description: "No tokens were found for this seed phrase on the selected mint.",
});
return;
}
// Send the restored tokens from the temporary wallet
const token = await tempCoco.wallet.send(mintUrl, restoredAmount);
// Receive the token in the main wallet
await coco.wallet.receive(token);
// Verify the transfer
const balancesAfter = await coco.wallet.getBalances();
const balanceAfter = balancesAfter[mintUrl] || 0;
const actualRestored = balanceAfter - balanceBefore;
toast({
title: "Restore Successful",
description: `Restored ${actualRestored} sats from the seed phrase and added to your current wallet.`,
});
} finally {
// Clean up temporary database (optional - happens automatically on next session)
// The temporary IndexedDB will be isolated to the unique name we provided
}
} catch (error) {
console.error('Restore failed:', error);
throw error;
} finally {
setIsRestoring(false);
}
}, [coco, toast]);
return {
handleRestoreFromSeedPhrase,
isRestoring,
};
}
-168
View File
@@ -1,168 +0,0 @@
import { useState, useCallback } from 'react';
import { isUnknownMintError, extractMintUrlFromError } from './useMintManager';
import type { Manager } from 'coco-cashu-core';
import type { Token } from '@cashu/cashu-ts';
import { useToast } from '@/hooks/useToast';
interface UseTokenOperationsProps {
coco: Manager | null;
activeMintUrl: string | null;
generateQRCode: (text: string) => Promise<string>;
getEncodedToken: (token: Token | string) => string;
}
export function useTokenOperations({
coco,
activeMintUrl,
generateQRCode,
getEncodedToken,
}: UseTokenOperationsProps) {
const { toast } = useToast();
// Receive state
const [tokenInput, setTokenInput] = useState('');
// Send state
const [sendAmount, setSendAmount] = useState('');
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
// Generate QR code for sent token
const generateSentTokenQRCode = useCallback(async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
}, [generateQRCode]);
// Handle unknown mint error by adding the mint and retrying
const handleUnknownMintError = useCallback(
async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Check if mint exists (known) by checking all mints
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
if (isKnown) {
// Mint exists but may not be trusted, ensure it's trusted
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
if (!isTrusted) {
await coco.mint.trustMint(mintUrl);
}
} else {
// Add the mint and automatically trust it (user is explicitly receiving from it)
await coco.mint.addMint(mintUrl, { trusted: true });
}
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: 'destructive',
title: 'Receive Failed',
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
},
[coco, tokenInput, toast]
);
// Handle receive (token)
const handleTokenReceive = useCallback(async () => {
if (!coco || !tokenInput) {
return;
}
try {
console.log(
'Attempting to receive token:',
tokenInput.substring(0, 20) + '...'
);
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: 'Cashu token redeemed successfully!',
});
} catch (err) {
console.error('Token receive error:', err);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: 'destructive',
title: 'Receive Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [coco, tokenInput, toast, handleUnknownMintError]);
// Handle send (token)
const handleTokenSend = useCallback(async () => {
if (!coco || !sendAmount || !activeMintUrl) {
return;
}
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Send Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [coco, sendAmount, activeMintUrl, getEncodedToken, generateSentTokenQRCode, toast]);
return {
// Receive state
tokenInput,
setTokenInput,
// Send state
sendAmount,
setSendAmount,
// Transaction output state
sentToken,
setSentToken,
sentTokenQRCode,
// Handlers
handleTokenReceive,
handleTokenSend,
};
}
+1 -20
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
--radius: 0.75rem;
--sidebar-background: 0 0% 98%;
@@ -98,23 +98,4 @@
body {
@apply bg-background text-foreground;
}
}
@layer utilities {
/* Safe area inset utilities */
.pb-safe-bottom {
padding-bottom: env(safe-area-inset-bottom);
}
.mb-safe-bottom {
margin-bottom: env(safe-area-inset-bottom);
}
.pt-safe-top {
padding-top: env(safe-area-inset-top);
}
.mt-safe-top {
margin-top: env(safe-area-inset-top);
}
}
-322
View File
@@ -1,322 +0,0 @@
import * as bitcoin from 'bitcoinjs-lib';
import { nip19 } from 'nostr-tools';
import * as ecc from '@bitcoinerlab/secp256k1';
import { ECPairFactory, type ECPairAPI } from 'ecpair';
// Initialize ECC library immediately
bitcoin.initEccLib(ecc);
// Lazy initialization to avoid issues in test environment
let ECPair: ECPairAPI | null = null;
function getECPair(): ECPairAPI {
if (!ECPair) {
ECPair = ECPairFactory(ecc);
}
return ECPair;
}
/**
* Convert Nostr pubkey (hex) to Bitcoin Taproot address
*/
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
try {
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
const { address } = bitcoin.payments.p2tr({
internalPubkey: pubkeyBuffer,
network: bitcoin.networks.bitcoin,
});
return address || '';
} catch (error) {
console.error('Error generating Bitcoin address:', error);
return '';
}
}
/**
* Convert npub to Bitcoin Taproot address
*/
export function npubToBitcoinAddress(npub: string): string {
try {
const decoded = nip19.decode(npub);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
const pubkeyHex = decoded.data as string;
return nostrPubkeyToBitcoinAddress(pubkeyHex);
} catch (error) {
console.error('Error converting npub to Bitcoin address:', error);
throw error;
}
}
/**
* Check if a string looks like a Bitcoin address
* Supports P2PKH (starts with 1), P2SH (starts with 3), and P2TR/Taproot (starts with bc1)
*/
export function isValidBitcoinAddress(address: string): boolean {
if (!address || typeof address !== 'string') return false;
const trimmed = address.trim();
// P2PKH addresses (legacy, starts with 1)
if (trimmed.startsWith('1') && trimmed.length >= 26 && trimmed.length <= 35) {
return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed);
}
// P2SH addresses (starts with 3)
if (trimmed.startsWith('3') && trimmed.length >= 26 && trimmed.length <= 35) {
return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed);
}
// P2TR/Taproot addresses (bech32, starts with bc1)
if (trimmed.startsWith('bc1')) {
// Taproot addresses are bc1p... (62 chars) or bc1q... (42 chars for P2WPKH)
// For reverse swaps, we're mostly concerned with bc1p (Taproot)
return /^bc1[a-z0-9]{39,59}$/i.test(trimmed);
}
return false;
}
/**
* Interface for UTXO (Unspent Transaction Output)
*/
export interface UTXO {
txid: string;
vout: number;
value: number; // in satoshis
status: {
confirmed: boolean;
block_height?: number;
block_hash?: string;
block_time?: number;
};
}
/**
* Fetch UTXOs for a Bitcoin address from Blockstream API
*/
export async function fetchUTXOs(address: string): Promise<UTXO[]> {
const response = await fetch(`https://blockstream.info/api/address/${address}/utxo`);
if (!response.ok) {
throw new Error('Failed to fetch UTXOs');
}
return response.json();
}
/**
* Get recommended fee rates from Blockstream API
*/
export async function getFeeRates(): Promise<{
fastestFee: number;
halfHourFee: number;
hourFee: number;
economyFee: number;
minimumFee: number;
}> {
const response = await fetch('https://blockstream.info/api/fee-estimates');
if (!response.ok) {
throw new Error('Failed to fetch fee estimates');
}
const data = await response.json();
return {
fastestFee: Math.ceil(data['1'] || 1),
halfHourFee: Math.ceil(data['3'] || 1),
hourFee: Math.ceil(data['6'] || 1),
economyFee: Math.ceil(data['144'] || 1),
minimumFee: Math.ceil(data['504'] || 1),
};
}
/**
* Broadcast a transaction to the Bitcoin network
*/
export async function broadcastTransaction(txHex: string): Promise<string> {
const response = await fetch('https://blockstream.info/api/tx', {
method: 'POST',
body: txHex,
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to broadcast transaction: ${error}`);
}
return response.text(); // Returns the transaction ID
}
/**
* Create and sign a Bitcoin transaction
* @param privateKeyHex - Private key in hex format (from Nostr nsec)
* @param toAddress - Recipient Bitcoin address
* @param amountSats - Amount to send in satoshis
* @param utxos - Available UTXOs
* @param feeRate - Fee rate in sat/vB
* @param sendMax - If true, sends all UTXOs to recipient with no change output
* @returns Signed transaction hex
*/
export async function createBitcoinTransaction(
privateKeyHex: string,
toAddress: string,
amountSats: number,
utxos: UTXO[],
feeRate: number,
sendMax: boolean = false
): Promise<{ txHex: string; fee: number }> {
// Create key pair from private key
const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex');
const keyPair = getECPair().fromPrivateKey(privateKeyBuffer);
// Get x-only public key (32 bytes) for Taproot
// Remove the first byte (compression flag) from the 33-byte compressed pubkey
const internalPubkey = keyPair.publicKey.slice(1, 33);
// Get sender's address for change
const { address: changeAddress } = bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
});
if (!changeAddress) {
throw new Error('Failed to generate change address');
}
// Create transaction builder
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.bitcoin });
// Add inputs (UTXOs)
let totalInput = 0;
for (const utxo of utxos) {
psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
}).output!,
value: BigInt(utxo.value),
},
tapInternalKey: internalPubkey,
});
totalInput += utxo.value;
}
// Estimate transaction size based on sendMax mode
// P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes
const outputCount = sendMax ? 1 : 2; // Send Max = 1 output, Regular = 2 outputs (recipient + change)
const estimatedSize = utxos.length * 57.5 + outputCount * 43 + 10.5;
const estimatedFee = Math.ceil(estimatedSize * feeRate);
if (sendMax) {
// For Send Max: send all UTXOs to recipient, no change
const maxAmount = totalInput - estimatedFee;
if (maxAmount <= 0) {
throw new Error(
`Insufficient funds for Send Max. Total: ${totalInput} sats, Fee: ${estimatedFee} sats`
);
}
// Add single output for recipient with max amount
psbt.addOutput({
address: toAddress,
value: BigInt(maxAmount),
});
} else {
// Regular transaction: calculate change
const change = totalInput - amountSats - estimatedFee;
if (change < 0) {
throw new Error(
`Insufficient funds. Need ${amountSats + estimatedFee} sats, have ${totalInput} sats`
);
}
// Add output for recipient
psbt.addOutput({
address: toAddress,
value: BigInt(amountSats),
});
// Add change output if significant (> dust limit)
const dustLimit = 546; // Standard dust limit for Bitcoin
if (change > dustLimit) {
psbt.addOutput({
address: changeAddress,
value: BigInt(change),
});
}
}
// Create a Taproot signer
// For Taproot key-path spending, we need to tweak the private key
const tweakedSigner = keyPair.tweak(
bitcoin.crypto.taggedHash('TapTweak', internalPubkey)
);
// Sign all inputs
for (let i = 0; i < utxos.length; i++) {
psbt.signInput(i, tweakedSigner);
}
// Finalize and extract transaction
psbt.finalizeAllInputs();
const tx = psbt.extractTransaction();
return {
txHex: tx.toHex(),
fee: estimatedFee,
};
}
/**
* Convert satoshis to BTC
*/
export function satsToBTC(sats: number): string {
return (sats / 100000000).toFixed(8);
}
/**
* Convert BTC to satoshis
*/
export function btcToSats(btc: number): number {
return Math.round(btc * 100000000);
}
/**
* Calculate the maximum amount that can be sent from available UTXOs
* This accounts for fees and dust limits
* @param utxos - Available UTXOs
* @param feeRate - Fee rate in sat/vB
* @returns Maximum amount in satoshis that can be sent
*/
export function calculateMaxSendAmount(utxos: UTXO[], feeRate: number): number {
if (utxos.length === 0) {
return 0;
}
// Calculate total input value
const totalInput = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
// Estimate transaction size for a single output (no change)
// P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes
const estimatedSize = utxos.length * 57.5 + 43 + 10.5; // Single output + overhead
const estimatedFee = Math.ceil(estimatedSize * feeRate);
// Calculate maximum amount (total input minus fees)
const maxAmount = totalInput - estimatedFee;
return Math.max(0, maxAmount);
}
-85
View File
@@ -1,85 +0,0 @@
/**
* Decodes a BOLT11 lightning invoice and extracts the amount in satoshis.
* Based on the lightning-decoder project implementation.
*/
/**
* Decode a BOLT11 invoice and extract the amount in satoshis
* @param invoice - The BOLT11 invoice string
* @returns The amount in satoshis, or null if amount cannot be determined
*/
export function decodeBolt11Amount(invoice: string): number | null {
try {
// Validate and prepare invoice
if (!invoice || typeof invoice !== 'string') {
return null;
}
const normalizedInvoice = invoice.toLowerCase().trim();
// Check if it's a valid BOLT11 invoice
if (!isValidBolt11Invoice(normalizedInvoice)) {
return null;
}
// Parse the prefix to extract amount
// Format: lnbc[amount][suffix] where suffix can be m, u, n, p
const prefixMatch = normalizedInvoice.match(/^lnbc(\d*)([munp]?)/);
if (!prefixMatch) {
return null;
}
const [, amountStr, suffix] = prefixMatch;
// If no amount specified, return null (amountless invoice)
if (!amountStr) {
return null;
}
const amount = parseInt(amountStr, 10);
if (isNaN(amount)) {
return null;
}
// Define multipliers for different denominations
const multipliers: Record<string, number> = {
m: 0.001, // milli-bitcoin
u: 0.000001, // micro-bitcoin
n: 0.000000001, // nano-bitcoin
p: 0.000000000001 // pico-bitcoin
};
// Apply multiplier if suffix exists
const multiplier = multipliers[suffix] || 1;
const amountInBitcoin = amount * multiplier;
// Convert Bitcoin to satoshis (1 Bitcoin = 100,000,000 satoshis)
const amountInSatoshis = Math.round(amountInBitcoin * 100_000_000);
return amountInSatoshis;
} catch (error) {
console.error('Error decoding BOLT11 invoice:', error);
return null;
}
}
/**
* Validate if a string is a valid BOLT11 invoice
* @param invoice - The string to validate
* @returns true if the string appears to be a valid BOLT11 invoice
*/
export function isValidBolt11Invoice(invoice: string): boolean {
if (!invoice || typeof invoice !== 'string') {
return false;
}
const normalized = invoice.toLowerCase().trim();
// BOLT11 invoices start with 'lnbc' and contain '1' followed by characters (the bech32 separator)
// They also need to be long enough to contain the required components
return (
normalized.startsWith('lnbc') &&
/1[a-z0-9]/.test(normalized) &&
normalized.length > 20 // Minimum reasonable length for a BOLT11 invoice
);
}
-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();
+2 -15
View File
@@ -7,24 +7,11 @@ import { ErrorBoundary } from '@/components/ErrorBoundary';
import App from './App.tsx';
import './index.css';
// TODO: Add custom font from @fontsource-variable
// Example: import '@fontsource-variable/<font-name>';
// FIXME: a custom font should be used. Eg:
// import '@fontsource-variable/<font-name>';
createRoot(document.getElementById("root")!).render(
<ErrorBoundary>
<App />
</ErrorBoundary>
);
// Register service worker for PWA
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
console.log('SW registered: ', registration);
})
.catch((registrationError) => {
console.log('SW registration failed: ', registrationError);
});
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { useSeoMeta } from '@unhead/react';
// TODO: Customize this index page with specific content
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
const Index = () => {
useSeoMeta({
-2
View File
@@ -1,6 +1,5 @@
import { useSeoMeta } from '@unhead/react';
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
import { RelaySelector } from '@/components/RelaySelector';
const Messages = () => {
useSeoMeta({
@@ -14,7 +13,6 @@ const Messages = () => {
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-semibold">Messages</h1>
<RelaySelector />
</div>
<DMMessagingInterface className="flex-1" />
+6 -1
View File
@@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) {
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
};
return (
-19
View File
@@ -1,19 +0,0 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}