mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 16:13:34 +00:00
Compare commits
145
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f168b17495 | ||
|
|
8cf5391817 | ||
|
|
47492df00e | ||
|
|
516461ae6e | ||
|
|
e0031c6b14 | ||
|
|
6fc1df5538 | ||
|
|
604d13f847 | ||
|
|
7d6ca0f71e | ||
|
|
28e50a9d7a | ||
|
|
0b8d104808 | ||
|
|
3df413fa84 | ||
|
|
3fbdf1fc60 | ||
|
|
4a278d29e6 | ||
|
|
e6cef5b87c | ||
|
|
80b48ae285 | ||
|
|
aec83f728e | ||
|
|
5d18a2acf1 | ||
|
|
5687faa746 | ||
|
|
df6989baf9 | ||
|
|
025cd9ed5e | ||
|
|
a5db59fa67 | ||
|
|
ae95955e9e | ||
|
|
25a5151e38 | ||
|
|
5429aa0435 | ||
|
|
0925bb9f1c | ||
|
|
fde64074ed | ||
|
|
1b285ff53f | ||
|
|
204fc46c48 | ||
|
|
a432716f47 | ||
|
|
97613fc5b2 | ||
|
|
9e29d18a70 | ||
|
|
aff1b0add5 | ||
|
|
cfd1e7269f | ||
|
|
6d9e1816ee | ||
|
|
44b264e4b4 | ||
|
|
fabbb0b50e | ||
|
|
cc393a266c | ||
|
|
e3cebf3a34 | ||
|
|
7eca8f850b | ||
|
|
f37b97630f | ||
|
|
14db9f59d0 | ||
|
|
701067fa8f | ||
|
|
ea791d405e | ||
|
|
35ad8cfa1b | ||
|
|
0fd52feabb | ||
|
|
440e02ff0e | ||
|
|
6380b1980c | ||
|
|
79980ded70 | ||
|
|
015e7b8b90 | ||
|
|
3b8c5da1fd | ||
|
|
0562cb8ee2 | ||
|
|
1b4c27d17d | ||
|
|
9d7f5e48df | ||
|
|
dbacdbc8ac | ||
|
|
1c23b6bafc | ||
|
|
1dc91bd978 | ||
|
|
69b314c831 | ||
|
|
50ed58730c | ||
|
|
69252a7526 | ||
|
|
d1ef321e38 | ||
|
|
8d14062d14 | ||
|
|
61763d04c8 | ||
|
|
ad6e0c9f8d | ||
|
|
f909795887 | ||
|
|
b66a31bc18 | ||
|
|
61fc4957e0 | ||
|
|
460a4777ee | ||
|
|
211d303301 | ||
|
|
5ad2d7fabc | ||
|
|
62a885267b | ||
|
|
76cb50f2da | ||
|
|
5c4c73f8ef | ||
|
|
d0c28b77b8 | ||
|
|
1c991e3185 | ||
|
|
7e24b0c347 | ||
|
|
6c48e7c684 | ||
|
|
d8b195e624 | ||
|
|
e6acf05e8d | ||
|
|
e8ef8f02ab | ||
|
|
e218305799 | ||
|
|
8bbb247ba8 | ||
|
|
ed80d74824 | ||
|
|
92eb50f8d2 | ||
|
|
f379a95548 | ||
|
|
24920117ae | ||
|
|
9bafd29ec9 | ||
|
|
722b1a743f | ||
|
|
d7d6f8d6d5 | ||
|
|
617edd1784 | ||
|
|
381fdaf977 | ||
|
|
15ec6c69e7 | ||
|
|
7a52562926 | ||
|
|
5d8a4d4ace | ||
|
|
cb50cbe137 | ||
|
|
79b03dee38 | ||
|
|
04ae3d89c0 | ||
|
|
1ffe78c80c | ||
|
|
04c5a84ca9 | ||
|
|
71b9c9d380 | ||
|
|
cb231c7770 | ||
|
|
d72b28cf77 | ||
|
|
7390dd6c19 | ||
|
|
6d35028424 | ||
|
|
19ecfee4bf | ||
|
|
67658eb446 | ||
|
|
d8e2e62736 | ||
|
|
f37d86b8d3 | ||
|
|
d3866ae0af | ||
|
|
f6e149893b | ||
|
|
dcffee03af | ||
|
|
9d3ead4428 | ||
|
|
9e222850ce | ||
|
|
114eb13ce6 | ||
|
|
d72fc80cc5 | ||
|
|
68031244a5 | ||
|
|
53ac562d10 | ||
|
|
51be437219 | ||
|
|
b132e4847d | ||
|
|
1d42551b36 | ||
|
|
bea63c75aa | ||
|
|
e4ee51335e | ||
|
|
8ef018df8a | ||
|
|
56bdebff5d | ||
|
|
6162217ce9 | ||
|
|
ea57135d1e | ||
|
|
49abb22471 | ||
|
|
a974da9f88 | ||
|
|
16837284fb | ||
|
|
b5bc571aa7 | ||
|
|
77803dda38 | ||
|
|
73c68f2655 | ||
|
|
f78013b083 | ||
|
|
bd956cef3f | ||
|
|
2ac097d8de | ||
|
|
aaf12120e6 | ||
|
|
5ce402105c | ||
|
|
dd3f4465c5 | ||
|
|
c8ad3b1a36 | ||
|
|
1701cce6b0 | ||
|
|
346ba70710 | ||
|
|
3f21df473b | ||
|
|
cec3b7f7d2 | ||
|
|
df0cc7c6aa | ||
|
|
629c350300 | ||
|
|
998bf4fc47 |
No files matched your search
@@ -1 +0,0 @@
|
||||
../.mcp.json
|
||||
@@ -7,11 +7,13 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai/
|
||||
yarn.lock
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
|
||||
@@ -19,7 +19,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management
|
||||
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
@@ -34,15 +35,15 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
||||
- `useCashu`: Cashu wallet management (balances, mints, melt quotes)
|
||||
- `useLightningAddress`: Lightning address validation and LNURL endpoint discovery
|
||||
- `useWallet`: Unified wallet detection (Cashu + WebLN + NWC) with intelligent payment method selection
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- **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
|
||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
||||
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
|
||||
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
|
||||
- `useConversationMessages`: Hook exported from DMContext for paginated messages
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
@@ -111,29 +112,11 @@ The project includes a **`docs/`** directory containing specialized documentatio
|
||||
|
||||
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
||||
|
||||
- **`docs/CASHU_ZAP_INTEGRATION.md`**: Read when implementing zap functionality, integrating Cashu wallet payments, or building Lightning payment features. Essential for understanding the unified ZapButton architecture and Cashu-powered Lightning zaps. **CRITICAL**: Follow the two-component architecture - `CashuWallet` for standalone wallet management, `ZapButton` for content integration.
|
||||
- **`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).
|
||||
|
||||
## Cashu Integration Architecture
|
||||
- **`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.
|
||||
|
||||
**IMPORTANT**: The Cashu wallet integration follows a **two-component architecture** that must be preserved:
|
||||
|
||||
### Component Separation
|
||||
- **`CashuWallet`**: Standalone wallet management interface (dedicated page/route)
|
||||
- **`ZapButton`**: Integrated zap functionality within content feeds
|
||||
|
||||
### Why This Architecture?
|
||||
- **Clean UX**: Users manage wallet separately from consuming content
|
||||
- **Performance**: Wallet operations don't interfere with feed rendering
|
||||
- **Security**: Sensitive wallet operations are isolated
|
||||
- **Mobile Optimization**: Wallet can use full-screen layouts
|
||||
|
||||
### Integration Rules
|
||||
- ✅ **CORRECT**: `CashuWallet` as separate route/page
|
||||
- ✅ **CORRECT**: `ZapButton` embedded in content feeds
|
||||
- ❌ **INCORRECT**: Embedding `CashuWallet` in content feeds
|
||||
- ❌ **INCORRECT**: Mixing wallet management with content consumption
|
||||
|
||||
**Always read `docs/CASHU_ZAP_INTEGRATION.md` before implementing any Cashu-related features.**
|
||||
- **`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
|
||||
|
||||
@@ -142,9 +125,9 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
|
||||
1. Edit AGENTS.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
## "Vibed with NutStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
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
|
||||
|
||||
@@ -770,6 +753,20 @@ 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.
|
||||
@@ -922,15 +919,53 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
## CRITICAL Design Standards
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
|
||||
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
|
||||
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
|
||||
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
|
||||
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
### Design Principles
|
||||
|
||||
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
||||
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
||||
- 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
|
||||
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
|
||||
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
|
||||
|
||||
### Avoid Generic Design
|
||||
|
||||
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
|
||||
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
|
||||
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
|
||||
|
||||
### Interaction Patterns
|
||||
|
||||
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
|
||||
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
|
||||
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
|
||||
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
|
||||
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
|
||||
|
||||
### Technical Requirements
|
||||
|
||||
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
|
||||
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
|
||||
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
|
||||
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
|
||||
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
|
||||
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
|
||||
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
|
||||
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
|
||||
|
||||
### Components
|
||||
|
||||
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
|
||||
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
|
||||
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
|
||||
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
|
||||
+157
-28
@@ -1,11 +1,82 @@
|
||||
### AI Integration with Shakespeare API
|
||||
|
||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
|
||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
|
||||
|
||||
```tsx
|
||||
import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
|
||||
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
|
||||
|
||||
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||
const {
|
||||
sendChatMessage,
|
||||
sendStreamingMessage,
|
||||
getAvailableModels,
|
||||
isLoading,
|
||||
error,
|
||||
isAuthenticated
|
||||
} = useShakespeare();
|
||||
```
|
||||
|
||||
#### Model Selector Component
|
||||
|
||||
```tsx
|
||||
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
|
||||
const { getAvailableModels, isLoading } = useShakespeare();
|
||||
const [models, setModels] = useState<Model[]>([]);
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
const fetchModels = async () => {
|
||||
try {
|
||||
const response = await getAvailableModels();
|
||||
// Sort models by total cost (cheapest first)
|
||||
const sortedModels = response.data.sort((a, b) => {
|
||||
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
|
||||
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
|
||||
return costA - costB;
|
||||
});
|
||||
setModels(sortedModels);
|
||||
|
||||
// Select the cheapest model by default
|
||||
if (sortedModels.length > 0) {
|
||||
const cheapestModel = sortedModels[0];
|
||||
setSelectedModel(cheapestModel.id);
|
||||
onModelSelect(cheapestModel.id);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch models:', err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchModels();
|
||||
}, [getAvailableModels, onModelSelect]);
|
||||
|
||||
const handleModelChange = (modelId: string) => {
|
||||
setSelectedModel(modelId);
|
||||
onModelSelect(modelId);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor="model-select">Choose Model:</label>
|
||||
<select
|
||||
id="model-select"
|
||||
value={selectedModel}
|
||||
onChange={(e) => handleModelChange(e.target.value)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<option value="">Select a model...</option>
|
||||
{models.map((model, index) => {
|
||||
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
|
||||
const isCheapest = index === 0;
|
||||
return (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Basic Chat Example
|
||||
@@ -15,19 +86,24 @@ function AIChat() {
|
||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim()) return;
|
||||
if (!input.trim() || !selectedModel) return;
|
||||
|
||||
const newMessages = [...messages, { role: 'user', content: input }];
|
||||
setMessages(newMessages);
|
||||
setInput('');
|
||||
|
||||
const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
|
||||
setMessages(prev => [...prev, {
|
||||
role: 'assistant',
|
||||
content: response.choices[0].message.content as string
|
||||
}]);
|
||||
try {
|
||||
const response = await sendChatMessage(newMessages, selectedModel);
|
||||
setMessages(prev => [...prev, {
|
||||
role: 'assistant',
|
||||
content: response.choices[0].message.content as string
|
||||
}]);
|
||||
} catch (err) {
|
||||
console.error('Chat error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
||||
@@ -36,6 +112,11 @@ function AIChat() {
|
||||
<div className="max-w-2xl mx-auto p-4">
|
||||
{error && <div className="text-red-500 mb-4">{error}</div>}
|
||||
|
||||
{/* Model Selection */}
|
||||
<div className="mb-4">
|
||||
<ModelSelector onModelSelect={setSelectedModel} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-4">
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
||||
@@ -50,9 +131,14 @@ function AIChat() {
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
||||
className="flex-1 p-2 border rounded"
|
||||
disabled={isLoading}
|
||||
disabled={isLoading || !selectedModel}
|
||||
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
|
||||
/>
|
||||
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
|
||||
<button
|
||||
onClick={handleSend}
|
||||
disabled={isLoading || !selectedModel}
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
@@ -61,30 +147,73 @@ function AIChat() {
|
||||
}
|
||||
```
|
||||
|
||||
#### Streaming Chat
|
||||
#### Streaming Chat Example
|
||||
|
||||
```tsx
|
||||
const [currentResponse, setCurrentResponse] = useState('');
|
||||
function StreamingChat() {
|
||||
const { sendStreamingMessage } = useShakespeare();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [currentResponse, setCurrentResponse] = useState('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
|
||||
const handleStreaming = async (content: string) => {
|
||||
setCurrentResponse('');
|
||||
await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
|
||||
setCurrentResponse(prev => prev + chunk);
|
||||
});
|
||||
};
|
||||
const handleStreaming = async (content: string) => {
|
||||
if (!selectedModel) return;
|
||||
|
||||
setCurrentResponse('');
|
||||
const newMessages = [...messages, { role: 'user', content }];
|
||||
setMessages(newMessages);
|
||||
|
||||
try {
|
||||
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
|
||||
setCurrentResponse(prev => prev + chunk);
|
||||
});
|
||||
|
||||
// Add the complete response to messages
|
||||
if (currentResponse.trim()) {
|
||||
setMessages(prev => [...prev, {
|
||||
role: 'assistant',
|
||||
content: currentResponse
|
||||
}]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Streaming error:', err);
|
||||
} finally {
|
||||
setCurrentResponse('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Model selection UI */}
|
||||
<div className="mb-4">
|
||||
<ModelSelector onModelSelect={setSelectedModel} />
|
||||
</div>
|
||||
|
||||
{/* Chat interface */}
|
||||
{/* ... rest of your chat UI */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Models
|
||||
#### Model Information
|
||||
|
||||
- **`tybalt`**: Free model for development
|
||||
- **`shakespeare`**: Premium model (requires credits)
|
||||
Models are dynamically fetched from the Shakespeare API and include:
|
||||
|
||||
- **Model ID**: Unique identifier for the model
|
||||
- **Name**: Human-readable model name
|
||||
- **Description**: Model capabilities and use cases
|
||||
- **Context Window**: Maximum token limit for conversations
|
||||
- **Pricing**: Cost per token for prompt and completion
|
||||
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
|
||||
|
||||
#### Key Points
|
||||
|
||||
- User must be logged in with Nostr account
|
||||
- Use `tybalt` for free testing
|
||||
- Handle `isLoading` and `error` states
|
||||
- Check `isAuthenticated` before API calls
|
||||
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
|
||||
- **Authentication Required**: User must be logged in with Nostr account
|
||||
- **Free vs Premium**: Check pricing to determine if model requires credits
|
||||
- **Error Handling**: Handle `isLoading` and `error` states appropriately
|
||||
- **Model Selection**: Provide UI for users to choose between available models
|
||||
|
||||
## Implementation Patterns and Best Practices
|
||||
|
||||
@@ -149,9 +278,9 @@ function AIChatWithErrorBoundary() {
|
||||
function useAIWithErrorHandling() {
|
||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
||||
|
||||
const sendMessage = async (messages: ChatMessage[]) => {
|
||||
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
|
||||
try {
|
||||
await sendChatMessage(messages, 'tybalt');
|
||||
await sendChatMessage(messages, modelId);
|
||||
} catch (err) {
|
||||
// Handle specific error types with user-friendly messages
|
||||
if (err.message.includes('401')) {
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
# 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"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,784 @@
|
||||
# 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,393 +0,0 @@
|
||||
# Unified ZapButton for AI Agents
|
||||
|
||||
This document explains how AI agents can easily integrate intelligent Lightning zaps into Nostr clients using the unified MKStack `ZapButton` component.
|
||||
|
||||
## Overview
|
||||
|
||||
The `ZapButton` component automatically prioritizes Cashu wallet balances for NIP-57 Lightning zaps when available, with intelligent fallback to traditional Lightning payments (WebLN → NWC → Manual QR). This provides a seamless user experience where users can zap directly from their Cashu token balance or use traditional Lightning methods.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Unified Component**: Single `ZapButton` handles all zap scenarios
|
||||
- **Intelligent Payment Selection**: Automatically chooses the best available payment method
|
||||
- **Cashu Integration**: Uses Cashu wallet balance when available and sufficient
|
||||
- **Smart Fallbacks**: Falls back to WebLN → NWC → Manual QR code
|
||||
- **NIP-57 Compliant**: Full compliance with Lightning zap standards
|
||||
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
|
||||
- **Mobile Optimized**: Responsive design with drawer/modal patterns
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Simple Integration
|
||||
|
||||
```tsx
|
||||
import { ZapButton } from '@/components/ZapButton';
|
||||
import type { Event } from 'nostr-tools';
|
||||
|
||||
function PostCard({ event }: { event: Event }) {
|
||||
return (
|
||||
<div className="post-card">
|
||||
<p>{event.content}</p>
|
||||
<ZapButton target={event} showCount={true} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### With Custom Styling
|
||||
|
||||
```tsx
|
||||
<ZapButton
|
||||
target={event}
|
||||
className="text-sm hover:text-yellow-500 transition-colors"
|
||||
showCount={true}
|
||||
/>
|
||||
```
|
||||
|
||||
## Component Props
|
||||
|
||||
```tsx
|
||||
interface ZapButtonProps {
|
||||
target: Event; // Required: The Nostr event to zap
|
||||
className?: string; // Optional: CSS classes for styling
|
||||
showCount?: boolean; // Optional: Show zap count (default: true)
|
||||
zapData?: { // Optional: External zap data to avoid refetching
|
||||
count: number;
|
||||
totalSats: number;
|
||||
isLoading?: boolean;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### Automatic Wallet Detection
|
||||
|
||||
The `ZapButton` automatically detects if the user has:
|
||||
1. A Cashu wallet with available balance
|
||||
2. Traditional Lightning wallet (WebLN/NWC)
|
||||
|
||||
### Payment Flow
|
||||
|
||||
The unified `ZapButton` uses an intelligent payment selection system:
|
||||
|
||||
1. **Cashu Available & Sufficient**: Uses Cashu tokens → Lightning invoice conversion
|
||||
2. **Cashu Insufficient/Unavailable**: Falls back to WebLN payment
|
||||
3. **WebLN Unavailable**: Falls back to NWC payment
|
||||
4. **NWC Unavailable**: Shows manual Lightning invoice with QR code
|
||||
|
||||
### Cashu Integration Details
|
||||
|
||||
When Cashu wallet is available and has sufficient balance:
|
||||
- Creates a NIP-57 compliant zap request
|
||||
- Gets Lightning invoice from recipient's zap endpoint
|
||||
- Uses `createMeltQuote()` to convert Cashu tokens to Lightning payment
|
||||
- Uses `payMeltQuote()` to execute the payment
|
||||
- Burns Cashu tokens and sends Lightning payment
|
||||
|
||||
## Required Dependencies
|
||||
|
||||
**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops!
|
||||
|
||||
### Setup CashuContext (Required!)
|
||||
|
||||
Create `src/contexts/CashuContext.tsx`:
|
||||
|
||||
```tsx
|
||||
import { createContext, useContext, ReactNode } from 'react';
|
||||
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
|
||||
|
||||
const CashuContext = createContext<UseCashuReturn | null>(null);
|
||||
|
||||
export function CashuProvider({ children }: { children: ReactNode }) {
|
||||
const cashu = useCashuHook();
|
||||
|
||||
return (
|
||||
<CashuContext.Provider value={cashu}>
|
||||
{children}
|
||||
</CashuContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
const context = useContext(CashuContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useCashu must be used within a CashuProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
```
|
||||
|
||||
### Wrap Your App
|
||||
|
||||
Add `CashuProvider` to your App.tsx:
|
||||
|
||||
```tsx
|
||||
import { CashuProvider } from '@/contexts/CashuContext';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<SomeProvider>
|
||||
<CashuProvider>
|
||||
{/* Your app */}
|
||||
</CashuProvider>
|
||||
</SomeProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Import from Context
|
||||
|
||||
**Always** import from the context, not the hook:
|
||||
|
||||
```tsx
|
||||
// ✅ CORRECT
|
||||
import { useCashu } from '@/contexts/CashuContext';
|
||||
|
||||
// ❌ WRONG - Will cause infinite loops!
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
```
|
||||
|
||||
This ensures all components share the same Cashu wallet instance, preventing:
|
||||
- Multiple wallet initializations
|
||||
- Infinite refresh loops
|
||||
- Performance issues
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
**IMPORTANT**: The Cashu integration uses a **two-component architecture**:
|
||||
|
||||
1. **`CashuWallet`** - Standalone wallet management interface (separate page/route)
|
||||
2. **`ZapButton`** - Integrated zap functionality within content feeds
|
||||
|
||||
### Component Separation
|
||||
|
||||
The `CashuWallet` component is designed as a **standalone wallet management interface** and should remain separate from content feeds. This separation provides:
|
||||
|
||||
- **Clean UX**: Users manage their wallet separately from consuming content
|
||||
- **Performance**: Wallet operations don't interfere with feed rendering
|
||||
- **Security**: Sensitive wallet operations are isolated
|
||||
- **Mobile Optimization**: Wallet can use full-screen layouts on mobile
|
||||
|
||||
### Integration Pattern
|
||||
|
||||
```tsx
|
||||
// ✅ CORRECT: Separate wallet management
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/wallet" element={<CashuWallet />} />
|
||||
<Route path="/" element={<FeedPage />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
// ✅ CORRECT: ZapButton integrated in content
|
||||
function FeedPage() {
|
||||
return (
|
||||
<div className="posts">
|
||||
{events.map(event => (
|
||||
<div key={event.id} className="post">
|
||||
<p>{event.content}</p>
|
||||
<ZapButton target={event} showCount={true} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ❌ INCORRECT: Don't embed CashuWallet in content feeds
|
||||
function FeedPage() {
|
||||
return (
|
||||
<div className="posts">
|
||||
<CashuWallet /> {/* Don't do this */}
|
||||
{events.map(event => (
|
||||
<div key={event.id} className="post">
|
||||
<p>{event.content}</p>
|
||||
<ZapButton target={event} showCount={true} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
```tsx
|
||||
import { ZapButton } from '@/components/ZapButton';
|
||||
import { CashuWallet } from '@/components/CashuWallet';
|
||||
import type { Event } from 'nostr-tools';
|
||||
|
||||
function NostrApp() {
|
||||
return (
|
||||
<div className="app">
|
||||
{/* Cashu wallet for balance management */}
|
||||
<CashuWallet />
|
||||
|
||||
{/* Posts with zap buttons */}
|
||||
<div className="posts">
|
||||
{events.map(event => (
|
||||
<div key={event.id} className="post">
|
||||
<p>{event.content}</p>
|
||||
<ZapButton target={event} showCount={true} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Custom Zap Data
|
||||
|
||||
If you're already fetching zap data elsewhere, pass it to avoid duplicate requests:
|
||||
|
||||
```tsx
|
||||
const zapData = useZaps(event);
|
||||
|
||||
<ZapButton
|
||||
target={event}
|
||||
zapData={zapData}
|
||||
showCount={true}
|
||||
/>
|
||||
```
|
||||
|
||||
### Conditional Rendering
|
||||
|
||||
The component automatically handles visibility based on:
|
||||
- User login status
|
||||
- Author Lightning address availability
|
||||
- Cashu wallet availability
|
||||
|
||||
```tsx
|
||||
// Only shows if user can zap
|
||||
<ZapButton target={event} />
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The component handles common error scenarios:
|
||||
- Insufficient Cashu balance
|
||||
- Lightning address not found
|
||||
- Zap endpoint unavailable
|
||||
- Payment failures
|
||||
|
||||
All errors are displayed via toast notifications.
|
||||
|
||||
## Mobile Optimization
|
||||
|
||||
The component automatically uses:
|
||||
- **Desktop**: Modal dialog
|
||||
- **Mobile**: Bottom drawer
|
||||
|
||||
No additional configuration needed.
|
||||
|
||||
## Testing
|
||||
|
||||
The component includes test IDs for easy testing:
|
||||
|
||||
```tsx
|
||||
// Unified zap modal
|
||||
data-testid="zap-modal"
|
||||
```
|
||||
|
||||
## Best Practices for AI Agents
|
||||
|
||||
1. **Maintain Component Separation**: Keep `CashuWallet` as a standalone page/route, not embedded in content feeds
|
||||
2. **Always include CashuWallet**: Provide a dedicated route/page for wallet management
|
||||
3. **Use consistent styling**: Apply your app's design system
|
||||
4. **Handle loading states**: The component manages its own loading states
|
||||
5. **Trust the intelligence**: The component handles payment method selection automatically
|
||||
6. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work
|
||||
7. **Follow the architecture**: Use `ZapButton` for content integration, `CashuWallet` for wallet management
|
||||
8. **Avoid Infinite Loops**: The `useCashu` hook includes throttling and deep comparison to prevent infinite refresh loops. Do NOT:
|
||||
- Call `refreshBalances()` in `useEffect` that depends on `balances`
|
||||
- Create circular dependencies between state updates and effects
|
||||
- Override the built-in throttling mechanisms
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### ZapButton Not Showing
|
||||
- Check if user is logged in
|
||||
- Verify author has Lightning address (lud06/lud16)
|
||||
- Ensure Cashu wallet is initialized
|
||||
|
||||
### Cashu Zaps Not Working
|
||||
- Verify Cashu wallet has sufficient balance
|
||||
- Check mint connectivity
|
||||
- Ensure Lightning invoice is valid
|
||||
|
||||
### Payment Method Fallbacks Not Working
|
||||
- Verify WebLN/NWC connection
|
||||
- Check Lightning wallet availability
|
||||
- Ensure zap endpoint is accessible
|
||||
- Test manual QR code fallback
|
||||
|
||||
### Infinite Loop: `refreshBalances` Repeatedly Called
|
||||
If you see continuous console logs like `🔄 refreshBalances: Getting balances from wallet...`, the issue is likely:
|
||||
|
||||
**Root Cause #1 (MOST COMMON)**: Multiple components are calling `useCashu()` directly from the hook instead of from the Context Provider. This creates multiple wallet instances that all try to initialize and refresh balances.
|
||||
|
||||
**Solution**: Ensure you:
|
||||
1. Created `CashuContext.tsx` as shown in the Required Dependencies section
|
||||
2. Wrapped your app with `<CashuProvider>`
|
||||
3. Import `useCashu` from `@/contexts/CashuContext` in ALL components (not from `@/hooks/useCashu`)
|
||||
|
||||
**Root Cause #2**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency.
|
||||
|
||||
**Built-in Protections**: The `useCashu` hook includes:
|
||||
- **Throttling**: Prevents calls more than once every 500ms
|
||||
- **Deep Comparison**: Only updates state if balance values actually changed
|
||||
- **Stable References**: Returns the same object reference when values are unchanged
|
||||
|
||||
**Common Mistakes to Avoid**:
|
||||
```tsx
|
||||
// ❌ INCORRECT: Creates infinite loop
|
||||
useEffect(() => {
|
||||
refreshBalances();
|
||||
}, [balances, refreshBalances]);
|
||||
|
||||
// ❌ INCORRECT: Calls refreshBalances on every balance change
|
||||
useEffect(() => {
|
||||
if (balances) {
|
||||
refreshBalances();
|
||||
}
|
||||
}, [balances]);
|
||||
|
||||
// ✅ CORRECT: Only call on mount or user action
|
||||
useEffect(() => {
|
||||
refreshBalances(); // Called once on mount
|
||||
}, []); // Empty dependency array
|
||||
|
||||
// ✅ CORRECT: Call on user action
|
||||
<Button onClick={() => refreshBalances()}>
|
||||
Refresh
|
||||
</Button>
|
||||
```
|
||||
|
||||
**If Issue Persists**: Check your implementation for:
|
||||
1. Effects that call `refreshBalances` and depend on `balances`
|
||||
2. Custom hooks that wrap `useCashu` and create circular dependencies
|
||||
3. Component re-renders that trigger unintended effect runs
|
||||
|
||||
## Integration Checklist
|
||||
|
||||
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
|
||||
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
|
||||
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
|
||||
- [ ] Import unified `ZapButton` component
|
||||
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
|
||||
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
|
||||
- [ ] Verify mobile responsiveness
|
||||
- [ ] Test error handling scenarios
|
||||
- [ ] Verify component separation (wallet management vs content integration)
|
||||
- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly)
|
||||
|
||||
This unified integration provides a seamless, intelligent zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments.
|
||||
@@ -0,0 +1,438 @@
|
||||
### Direct Messaging on Nostr
|
||||
|
||||
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, - more - private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent - cache first - local storage.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Enable Direct Messaging
|
||||
|
||||
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
|
||||
|
||||
```tsx
|
||||
import { DMProvider } from '@/contexts/DMContext';
|
||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<DMProvider config={{
|
||||
enabled: true, // Enable the DM system
|
||||
protocolMode: PROTOCOL_MODE.NIP17_ONLY
|
||||
}}>
|
||||
{/* Your app components */}
|
||||
</DMProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Config 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)
|
||||
|
||||
**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
|
||||
|
||||
```tsx
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||
|
||||
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
||||
const { sendMessage } = useDMContext();
|
||||
const [content, setContent] = useState('');
|
||||
|
||||
const handleSend = async () => {
|
||||
await sendMessage({
|
||||
recipientPubkey,
|
||||
content,
|
||||
protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
|
||||
});
|
||||
setContent('');
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="Type a message..."
|
||||
/>
|
||||
<button type="submit">Send</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Display Conversations
|
||||
|
||||
```tsx
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
|
||||
const { conversations, isLoading } = useDMContext();
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Loading conversations...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{conversations.map((conversation) => (
|
||||
<ConversationItem
|
||||
key={conversation.pubkey}
|
||||
conversation={conversation}
|
||||
onClick={() => onSelectConversation(conversation.pubkey)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConversationItem({ conversation, onClick }: {
|
||||
conversation: ConversationSummary;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const author = useAuthor(conversation.pubkey);
|
||||
const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
|
||||
const avatarUrl = author.data?.metadata?.picture;
|
||||
|
||||
return (
|
||||
<button onClick={onClick} className="w-full p-3 hover:bg-accent rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar>
|
||||
<AvatarImage src={avatarUrl} />
|
||||
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 text-left">
|
||||
<div className="font-medium">{displayName}</div>
|
||||
<div className="text-sm text-muted-foreground truncate">
|
||||
{conversation.lastMessage?.decryptedContent || 'No messages yet'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Display Messages in a Conversation
|
||||
|
||||
```tsx
|
||||
import { useConversationMessages } from '@/contexts/DMContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
|
||||
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
|
||||
const { user } = useCurrentUser();
|
||||
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-2">
|
||||
{hasMoreMessages && (
|
||||
<button onClick={loadEarlierMessages} className="text-sm text-muted-foreground">
|
||||
Load earlier messages
|
||||
</button>
|
||||
)}
|
||||
|
||||
{messages.map((message) => {
|
||||
const isFromMe = message.pubkey === user?.pubkey;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={message.id}
|
||||
className={cn(
|
||||
"flex",
|
||||
isFromMe ? "justify-end" : "justify-start"
|
||||
)}
|
||||
>
|
||||
<div className={cn(
|
||||
"max-w-[70%] rounded-lg px-4 py-2",
|
||||
isFromMe ? "bg-primary text-primary-foreground" : "bg-muted"
|
||||
)}>
|
||||
{message.error ? (
|
||||
<span className="text-red-500">🔒 {message.error}</span>
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words">
|
||||
{message.decryptedContent}
|
||||
</p>
|
||||
)}
|
||||
{message.isSending && (
|
||||
<span className="text-xs opacity-50">Sending...</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Using the Complete Messaging Interface
|
||||
|
||||
For a fully-featured messaging UI out of the box, use the `DMMessagingInterface` component:
|
||||
|
||||
```tsx
|
||||
import { DMMessagingInterface } from "@/components/dm/DMMessagingInterface";
|
||||
|
||||
function MessagesPage() {
|
||||
return (
|
||||
<div className="container mx-auto p-4 h-screen">
|
||||
<DMMessagingInterface />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `DMMessagingInterface` component provides a complete messaging UI with:
|
||||
- Conversation list with Active/Requests tabs
|
||||
- Message thread view with pagination
|
||||
- Compose area with file upload support
|
||||
- Real-time message updates
|
||||
- Mobile-responsive layout (shows one panel at a time on mobile)
|
||||
|
||||
It requires no props and works automatically when wrapped in `DMProvider`.
|
||||
|
||||
**For custom layouts**, see the "Building Custom Messaging UIs" section below for individual components (`DMConversationList`, `DMChatArea`, `DMStatusInfo`).
|
||||
|
||||
## Sending Files with Messages
|
||||
|
||||
```tsx
|
||||
import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
|
||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||
|
||||
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
|
||||
const { sendMessage } = useDMContext();
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
const [content, setContent] = useState('');
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
|
||||
const handleSend = async () => {
|
||||
let attachments: FileAttachment[] | undefined;
|
||||
|
||||
// Upload file if one is selected
|
||||
if (selectedFile) {
|
||||
const tags = await uploadFile(selectedFile);
|
||||
|
||||
attachments = [{
|
||||
url: tags[0][1], // URL from first tag
|
||||
mimeType: selectedFile.type,
|
||||
size: selectedFile.size,
|
||||
name: selectedFile.name,
|
||||
tags: tags
|
||||
}];
|
||||
}
|
||||
|
||||
await sendMessage({
|
||||
recipientPubkey,
|
||||
content,
|
||||
protocol: MESSAGE_PROTOCOL.NIP17,
|
||||
attachments,
|
||||
});
|
||||
|
||||
setContent('');
|
||||
setSelectedFile(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="Type a message..."
|
||||
/>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
|
||||
/>
|
||||
|
||||
{selectedFile && <div>Selected: {selectedFile.name}</div>}
|
||||
|
||||
<button type="submit" disabled={isUploading}>
|
||||
{isUploading ? 'Uploading...' : 'Send'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Protocol Comparison
|
||||
|
||||
### NIP-04 (Legacy)
|
||||
- **Encryption**: NIP-04 (simpler, older)
|
||||
- **Metadata**: Sender and recipient visible to relays
|
||||
- **Event Kind**: Kind 4
|
||||
- **Use When**: Compatibility with older clients
|
||||
|
||||
### NIP-17 (Modern & Private)
|
||||
- **Encryption**: NIP-44 (stronger)
|
||||
- **Metadata**: Hidden via gift wrapping (NIP-59)
|
||||
- **Event Kinds**: Kind 14 (text), Kind 15 (files)
|
||||
- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
|
||||
- **Use When**: Maximum privacy (recommended)
|
||||
|
||||
**Key Privacy Features of NIP-17:**
|
||||
- Sender identity hidden (uses random ephemeral keys)
|
||||
- Timestamps randomized (±2 days) to hide send time
|
||||
- Dual gift wraps (recipient + sender) for message history
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Conversation Categorization
|
||||
|
||||
The system automatically categorizes conversations:
|
||||
|
||||
```tsx
|
||||
const { conversations } = useDMContext();
|
||||
|
||||
// Filter by category
|
||||
const knownConversations = conversations.filter(c => c.isKnown);
|
||||
const requestConversations = conversations.filter(c => c.isRequest);
|
||||
|
||||
// isKnown = true if user has sent at least one message
|
||||
// isRequest = true if only received messages, never replied
|
||||
```
|
||||
|
||||
### Loading States
|
||||
|
||||
```tsx
|
||||
const { isLoading, loadingPhase, scanProgress } = useDMContext();
|
||||
|
||||
// Check overall loading state
|
||||
if (isLoading) {
|
||||
console.log('Current phase:', loadingPhase);
|
||||
// LOADING_PHASES.CACHE - Loading from local cache
|
||||
// LOADING_PHASES.RELAYS - Querying relays
|
||||
// LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
|
||||
// LOADING_PHASES.READY - Fully loaded
|
||||
}
|
||||
|
||||
// Display scan progress for large message histories
|
||||
if (scanProgress.nip17) {
|
||||
console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Clear Cache and Refresh
|
||||
|
||||
```tsx
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
|
||||
function SettingsButton() {
|
||||
const { clearCacheAndRefetch } = useDMContext();
|
||||
|
||||
const handleClearCache = async () => {
|
||||
await clearCacheAndRefetch();
|
||||
// Clears IndexedDB cache and reloads all messages from relays
|
||||
};
|
||||
|
||||
return (
|
||||
<button onClick={handleClearCache}>
|
||||
Clear Message Cache
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### Data Flow
|
||||
1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
|
||||
2. **Background Sync**: New messages fetched from relays in parallel
|
||||
3. **Real-time Updates**: WebSocket subscriptions for live messages
|
||||
4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
|
||||
|
||||
### Storage
|
||||
- **IndexedDB**: All messages stored locally with NIP-44 encryption
|
||||
- **Per-User Storage**: Separate encrypted store for each logged-in user
|
||||
- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
|
||||
|
||||
### Performance
|
||||
- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
|
||||
- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
|
||||
- **Pagination**: Conversation messages paginated (25/page)
|
||||
- **Deduplication**: Automatic filtering of duplicate messages by ID
|
||||
|
||||
### Security
|
||||
- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
|
||||
- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
|
||||
- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
|
||||
- **No Plaintext**: Decrypted content never persisted unencrypted
|
||||
- **Domain Isolation**: IndexedDB databases are namespaced by hostname to prevent data conflicts
|
||||
|
||||
## Building Custom Messaging UIs
|
||||
|
||||
For advanced use cases, you can use the individual DM components to build custom layouts:
|
||||
|
||||
### Available Components
|
||||
|
||||
**`DMConversationList`** - Conversation sidebar with tabs
|
||||
```tsx
|
||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||
|
||||
<DMConversationList
|
||||
selectedPubkey={selectedPubkey}
|
||||
onSelectConversation={(pubkey) => setSelectedPubkey(pubkey)}
|
||||
onStatusClick={() => setShowStatus(true)} // optional
|
||||
className="h-full"
|
||||
/>
|
||||
```
|
||||
|
||||
**`DMChatArea`** - Message thread and compose area
|
||||
```tsx
|
||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||
|
||||
<DMChatArea
|
||||
pubkey={selectedPubkey}
|
||||
onBack={() => setSelectedPubkey(null)} // optional, for mobile back button
|
||||
className="h-full"
|
||||
/>
|
||||
```
|
||||
|
||||
**`DMStatusInfo`** - Debug/status panel
|
||||
```tsx
|
||||
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
||||
|
||||
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
||||
```
|
||||
|
||||
### Custom Layout Example
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||
|
||||
function CustomMessagingLayout() {
|
||||
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen">
|
||||
{/* Custom sidebar */}
|
||||
<aside className="w-64 border-r">
|
||||
<DMConversationList
|
||||
selectedPubkey={selectedPubkey}
|
||||
onSelectConversation={setSelectedPubkey}
|
||||
/>
|
||||
</aside>
|
||||
|
||||
{/* Custom main area */}
|
||||
<main className="flex-1">
|
||||
{selectedPubkey ? (
|
||||
<DMChatArea pubkey={selectedPubkey} />
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<p>Select a conversation to start messaging</p>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,612 +0,0 @@
|
||||
# npub.cash Lightning Address Integration
|
||||
|
||||
This document explains how to integrate npub.cash Lightning addresses into your Nostr application, allowing users to receive Lightning payments without any setup.
|
||||
|
||||
## Overview
|
||||
|
||||
npub.cash is a Lightning address service powered by Cashu and Nostr. It provides instant Lightning addresses for any Nostr public key, with no registration required. Payments are stored as Cashu quotes that users can later claim.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Identity**: Your Nostr pubkey becomes your Lightning address (`[email protected]`)
|
||||
2. **Receiving**: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey
|
||||
3. **Claiming**: Authenticate with NIP-98 to fetch and redeem your paid quotes from the configured mint
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Zero Setup**: Any Nostr pubkey is instantly a valid Lightning address
|
||||
- **Nostr Identity**: Uses NIP-98 authentication (no separate account needed)
|
||||
- **Privacy**: Cashu provides better privacy than plain Lightning
|
||||
- **Flexible**: Set your preferred Cashu mint
|
||||
- **Optional Locking**: Enable NUT-20 quote locking for enhanced security
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Get Your Lightning Address
|
||||
|
||||
```tsx
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
|
||||
function MyLightningAddress() {
|
||||
const { lightningAddress, isLoading } = useNpubCash();
|
||||
|
||||
if (isLoading) return <p>Loading...</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>My Lightning Address</h3>
|
||||
<p className="font-mono">{lightningAddress}</p>
|
||||
<button onClick={() => navigator.clipboard.writeText(lightningAddress)}>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Display Unclaimed Balance
|
||||
|
||||
```tsx
|
||||
function UnclaimedBalance() {
|
||||
const { unclaimedAmount, quotes, refresh } = useNpubCash();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>Unclaimed Payments</h3>
|
||||
<p>{unclaimedAmount} sats from {quotes.length} payments</p>
|
||||
<button onClick={refresh}>Refresh</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Fetch and Display Quotes
|
||||
|
||||
```tsx
|
||||
function PaymentHistory() {
|
||||
const { quotes, fetchQuotes, isLoading } = useNpubCash();
|
||||
|
||||
useEffect(() => {
|
||||
fetchQuotes();
|
||||
}, [fetchQuotes]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>Received Payments</h3>
|
||||
{quotes.map(quote => (
|
||||
<div key={quote.quote_id} className="border p-4 rounded">
|
||||
<p>Amount: {quote.amount} sats</p>
|
||||
<p>Mint: {quote.mint_url}</p>
|
||||
<p>Status: {quote.state}</p>
|
||||
<p>Paid: {new Date(quote.paid_at * 1000).toLocaleString()}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Set Username (Paid Feature)
|
||||
|
||||
Users can optionally purchase a custom username for a cleaner Lightning address:
|
||||
|
||||
```tsx
|
||||
function UsernameSelector() {
|
||||
const { userInfo, setUsername, isLoading } = useNpubCash();
|
||||
|
||||
const handleSetUsername = async () => {
|
||||
try {
|
||||
await setUsername('myusername');
|
||||
// Address becomes: [email protected]
|
||||
alert('Username set successfully!');
|
||||
} catch (error) {
|
||||
// Payment required - X-Cashu header returned
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Current: {userInfo?.name || 'Using npub'}</p>
|
||||
<button onClick={handleSetUsername} disabled={isLoading}>
|
||||
Set Username
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Configure Preferred Mint
|
||||
|
||||
```tsx
|
||||
function MintSelector() {
|
||||
const { userInfo, setMint, isLoading } = useNpubCash();
|
||||
const [mintUrl, setMintUrl] = useState('');
|
||||
|
||||
const handleSetMint = async () => {
|
||||
try {
|
||||
await setMint(mintUrl);
|
||||
alert('Mint updated successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to set mint:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Current Mint: {userInfo?.mint_url}</p>
|
||||
<input
|
||||
type="text"
|
||||
value={mintUrl}
|
||||
onChange={(e) => setMintUrl(e.target.value)}
|
||||
placeholder="https://mint.example.com"
|
||||
/>
|
||||
<button onClick={handleSetMint} disabled={isLoading}>
|
||||
Update Mint
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Enable Quote Locking (NUT-20)
|
||||
|
||||
Lock quotes to your pubkey for enhanced security:
|
||||
|
||||
```tsx
|
||||
function QuoteLocking() {
|
||||
const { userInfo, setLockQuotes, isLoading } = useNpubCash();
|
||||
|
||||
const toggleLocking = async () => {
|
||||
try {
|
||||
await setLockQuotes(!userInfo?.lock_quote);
|
||||
alert('Quote locking updated!');
|
||||
} catch (error) {
|
||||
console.error('Failed to update locking:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={userInfo?.lock_quote || false}
|
||||
onChange={toggleLocking}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
Lock quotes to my pubkey (NUT-20)
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Requires wallet with NUT-20 support
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example: Receive Payment Widget
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
function ReceivePaymentWidget() {
|
||||
const {
|
||||
lightningAddress,
|
||||
unclaimedAmount,
|
||||
quotes,
|
||||
isLoading,
|
||||
refresh,
|
||||
} = useNpubCash();
|
||||
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const copyAddress = async () => {
|
||||
if (!lightningAddress) return;
|
||||
|
||||
await navigator.clipboard.writeText(lightningAddress);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Receive Lightning Payments</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Lightning Address */}
|
||||
<div>
|
||||
<label className="text-sm font-medium">Your Lightning Address</label>
|
||||
<div className="flex gap-2 items-center mt-1">
|
||||
<code className="flex-1 bg-muted px-3 py-2 rounded text-sm">
|
||||
{lightningAddress || 'Loading...'}
|
||||
</code>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={copyAddress}
|
||||
disabled={!lightningAddress}
|
||||
>
|
||||
{copied ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unclaimed Balance */}
|
||||
<div className="flex justify-between items-center p-4 bg-muted rounded">
|
||||
<span className="font-medium">Unclaimed Balance</span>
|
||||
<Badge variant="secondary" className="text-lg">
|
||||
{unclaimedAmount} sats
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Payment History */}
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-sm font-medium">Recent Payments</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={refresh}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-[300px] overflow-y-auto">
|
||||
{quotes.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No payments received yet
|
||||
</p>
|
||||
) : (
|
||||
quotes.map(quote => (
|
||||
<div
|
||||
key={quote.quote_id}
|
||||
className="border rounded p-3 space-y-1"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="font-semibold">{quote.amount} sats</span>
|
||||
<Badge
|
||||
variant={quote.state === 'PAID' ? 'default' : 'secondary'}
|
||||
>
|
||||
{quote.state}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(quote.paid_at * 1000).toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{quote.mint_url}
|
||||
</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default ReceivePaymentWidget;
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Hook: `useNpubCash()`
|
||||
|
||||
Returns an object with the following properties and methods:
|
||||
|
||||
#### State
|
||||
|
||||
- `isInitialized: boolean` - Whether the hook has loaded initial data
|
||||
- `isLoading: boolean` - Whether an API request is in progress
|
||||
- `error: string | null` - Error message if any operation failed
|
||||
- `lightningAddress: string | null` - User's npub.cash Lightning address
|
||||
- `userInfo: NpubCashUserInfo | null` - User settings (mint, username, locking)
|
||||
- `quotes: NpubCashQuote[]` - Array of received payment quotes
|
||||
- `unclaimedAmount: number` - Total sats in unclaimed paid quotes
|
||||
|
||||
#### Methods
|
||||
|
||||
##### `fetchQuotes(since?: number, limit?: number): Promise<NpubCashQuote[]>`
|
||||
|
||||
Fetch paid quotes from npub.cash.
|
||||
|
||||
- `since` - Optional Unix timestamp to only fetch quotes paid after this time
|
||||
- `limit` - Maximum number of quotes to return (default: 50)
|
||||
|
||||
```tsx
|
||||
const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours
|
||||
```
|
||||
|
||||
##### `fetchUserInfo(): Promise<NpubCashUserInfo>`
|
||||
|
||||
Fetch current user settings.
|
||||
|
||||
```tsx
|
||||
const info = await fetchUserInfo();
|
||||
console.log('Preferred mint:', info.mint_url);
|
||||
```
|
||||
|
||||
##### `setUsername(username: string): Promise<void>`
|
||||
|
||||
Set a custom username (paid feature via Cashu 402).
|
||||
|
||||
```tsx
|
||||
await setUsername('alice'); // Address becomes [email protected]
|
||||
```
|
||||
|
||||
##### `setMint(mintUrl: string): Promise<void>`
|
||||
|
||||
Set preferred Cashu mint for receiving payments.
|
||||
|
||||
```tsx
|
||||
await setMint('https://mint.example.com');
|
||||
```
|
||||
|
||||
##### `setLockQuotes(locked: boolean): Promise<void>`
|
||||
|
||||
Enable or disable quote locking to pubkey (NUT-20).
|
||||
|
||||
```tsx
|
||||
await setLockQuotes(true); // Enable locking
|
||||
```
|
||||
|
||||
##### `refresh(): Promise<void>`
|
||||
|
||||
Refresh all data (quotes and user info) from npub.cash.
|
||||
|
||||
```tsx
|
||||
await refresh();
|
||||
```
|
||||
|
||||
##### `clearAuth(): void`
|
||||
|
||||
Clear stored JWT token, forcing NIP-98 re-authentication on next request.
|
||||
|
||||
```tsx
|
||||
clearAuth(); // Next API call will require NIP-98 signature
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
### `NpubCashQuote`
|
||||
|
||||
```tsx
|
||||
interface NpubCashQuote {
|
||||
created_at: number; // Unix timestamp when quote was created
|
||||
paid_at: number; // Unix timestamp when invoice was paid
|
||||
expires_at: number; // Unix timestamp when quote expires
|
||||
mint_url: string; // Cashu mint URL for this quote
|
||||
quote_id: string; // Unique quote identifier
|
||||
request: string; // Original BOLT11 invoice
|
||||
amount: number; // Amount in sats
|
||||
state: 'PENDING' | 'PAID' | 'EXPIRED';
|
||||
locked: boolean; // Whether quote is locked to pubkey
|
||||
}
|
||||
```
|
||||
|
||||
### `NpubCashUserInfo`
|
||||
|
||||
```tsx
|
||||
interface NpubCashUserInfo {
|
||||
pubkey: string; // User's Nostr public key (hex)
|
||||
name: string | null; // Custom username (if set)
|
||||
mint_url: string; // User's preferred Cashu mint
|
||||
lock_quote: boolean; // Whether quote locking is enabled
|
||||
}
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
The hook handles authentication automatically using two methods:
|
||||
|
||||
### NIP-98 HTTP Auth
|
||||
|
||||
For every API request, the hook can create a NIP-98 event (kind 27235) signed by the user's Nostr key. This is the primary authentication method.
|
||||
|
||||
### JWT Tokens
|
||||
|
||||
To avoid repeated signing requests (especially for browser extensions), the hook can obtain a JWT token using a single NIP-98 request. The token is cached in localStorage and automatically refreshed when expired.
|
||||
|
||||
```tsx
|
||||
// JWT is obtained automatically on first API call
|
||||
// Cached in localStorage as 'npubcash-jwt'
|
||||
// Valid for 30 minutes
|
||||
```
|
||||
|
||||
## Integration with Cashu Wallet
|
||||
|
||||
To claim the received funds, integrate with the existing `useCashu` hook:
|
||||
|
||||
```tsx
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
|
||||
function ClaimFunds() {
|
||||
const { quotes } = useNpubCash();
|
||||
const { redeemMintQuote, addMint } = useCashu();
|
||||
|
||||
const claimQuote = async (quote: NpubCashQuote) => {
|
||||
try {
|
||||
// Add mint if not already added
|
||||
await addMint(quote.mint_url);
|
||||
|
||||
// Redeem the quote to receive Cashu tokens
|
||||
await redeemMintQuote(quote.mint_url, quote.quote_id);
|
||||
|
||||
alert(`Claimed ${quote.amount} sats!`);
|
||||
} catch (error) {
|
||||
console.error('Failed to claim:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{quotes.map(quote => (
|
||||
<div key={quote.quote_id}>
|
||||
<p>{quote.amount} sats</p>
|
||||
<button onClick={() => claimQuote(quote)}>Claim</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Track Claimed Quotes
|
||||
|
||||
The hook stores `lastClaimedAt` timestamp in localStorage to track which quotes are new. Update this after claiming:
|
||||
|
||||
```tsx
|
||||
const [lastClaimed, setLastClaimed] = useLocalStorage('npubcash-last-claimed', 0);
|
||||
|
||||
const claimAll = async () => {
|
||||
for (const quote of quotes) {
|
||||
await redeemMintQuote(quote.mint_url, quote.quote_id);
|
||||
}
|
||||
setLastClaimed(Date.now() / 1000);
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Handle Expired Quotes
|
||||
|
||||
Quotes expire after a certain time. Filter expired quotes in your UI:
|
||||
|
||||
```tsx
|
||||
const activeQuotes = quotes.filter(q =>
|
||||
q.state === 'PAID' && q.expires_at > Date.now() / 1000
|
||||
);
|
||||
```
|
||||
|
||||
### 3. Poll for New Payments
|
||||
|
||||
Set up periodic polling to check for new payments:
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
refresh();
|
||||
}, 30000); // Every 30 seconds
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [refresh]);
|
||||
```
|
||||
|
||||
### 4. Display QR Code for Address
|
||||
|
||||
Make it easy for users to receive payments by displaying a QR code:
|
||||
|
||||
```tsx
|
||||
import QRCode from 'qrcode.react';
|
||||
|
||||
function AddressQR() {
|
||||
const { lightningAddress } = useNpubCash();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<QRCode value={`lightning:${lightningAddress}`} size={256} />
|
||||
<p className="text-xs">{lightningAddress}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The hook provides error state for failed operations:
|
||||
|
||||
```tsx
|
||||
function ErrorDisplay() {
|
||||
const { error, clearAuth, refresh } = useNpubCash();
|
||||
|
||||
if (!error) return null;
|
||||
|
||||
const handleRetry = () => {
|
||||
if (error.includes('Authentication')) {
|
||||
clearAuth(); // Clear stale JWT
|
||||
}
|
||||
refresh(); // Try again
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-destructive/10 p-4 rounded">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<button onClick={handleRetry}>Retry</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Custom npub.cash Domain
|
||||
|
||||
If using a self-hosted npub.cash instance:
|
||||
|
||||
```tsx
|
||||
// In useNpubCash.ts, modify:
|
||||
const NPUBCASH_API_BASE = 'https://your-instance.com/api/v2';
|
||||
const NPUBCASH_DOMAIN = 'your-instance.com';
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "No user logged in" Error
|
||||
|
||||
Ensure the user is logged in via `useCurrentUser`:
|
||||
|
||||
```tsx
|
||||
const { user } = useCurrentUser();
|
||||
const npubCash = useNpubCash();
|
||||
|
||||
if (!user) {
|
||||
return <p>Please log in first</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### "NIP-98 validation failed"
|
||||
|
||||
Check that:
|
||||
1. System clock is accurate (NIP-98 events must be recent)
|
||||
2. URL matches exactly (no query params in NIP-98 event URL)
|
||||
3. User's signer is working properly
|
||||
|
||||
### JWT Token Issues
|
||||
|
||||
If JWT tokens aren't working, clear and re-authenticate:
|
||||
|
||||
```tsx
|
||||
const { clearAuth, refresh } = useNpubCash();
|
||||
|
||||
clearAuth();
|
||||
await refresh(); // Will create new NIP-98 auth
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Cashu Zap Integration](./CASHU_ZAP_INTEGRATION.md)
|
||||
- [Nostr Comments System](./NOSTR_COMMENTS.md)
|
||||
- [AI Chat Integration](./AI_CHAT.md)
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [npub.cash Documentation](https://npubx.cash/docs)
|
||||
- [NIP-98: HTTP Auth](https://github.com/nostr-protocol/nips/blob/master/98.md)
|
||||
- [Cashu Protocol](https://docs.cashu.space/)
|
||||
- [NUT-20: Locked Tokens](https://github.com/cashubtc/nuts/blob/main/20.md)
|
||||
|
||||
---
|
||||
|
||||
**Built with MKStack** - The complete framework for building Nostr applications with AI.
|
||||
|
||||
+6
-1
@@ -2,8 +2,13 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<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>
|
||||
|
||||
Generated
+1789
-508
File diff suppressed because it is too large.
Load diff
+16
-6
@@ -7,17 +7,15 @@
|
||||
"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 run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
"deploy": "npm i --silent && npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bitcoinerlab/secp256k1": "^1.2.0",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^5.1.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@scure/bip39": "^2.0.0",
|
||||
"coco-cashu-core": "1.0.0-rc5",
|
||||
"coco-cashu-indexeddb": "0.8.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -45,17 +43,28 @@
|
||||
"@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",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
@@ -75,6 +84,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
+24
-9
@@ -11,7 +11,9 @@ 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({
|
||||
@@ -31,17 +33,28 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
theme: "system",
|
||||
relayUrl: "wss://relay.ditto.pub",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
|
||||
{ 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,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
@@ -50,12 +63,14 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NWCProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
<DMProvider config={dmConfig}>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</DMProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
|
||||
+4
-2
@@ -2,9 +2,10 @@ 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 { CashuWallet } from "./components/CashuWallet";
|
||||
import { WalletContainer } from "./components/wallet/WalletContainer";
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
@@ -12,7 +13,8 @@ export function AppRouter() {
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/wallet" element={<CashuWallet />} />
|
||||
<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,10 +14,10 @@ interface AppProviderProps {
|
||||
}
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
const AppConfigSchema = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
});
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
const {
|
||||
@@ -28,23 +28,25 @@ export function AppProvider(props: AppProviderProps) {
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
{},
|
||||
{
|
||||
serialize: JSON.stringify,
|
||||
deserialize: (value: string) => {
|
||||
const parsed = JSON.parse(value);
|
||||
return AppConfigSchema.parse(parsed);
|
||||
return AppConfigSchema.partial().parse(parsed);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Generic config updater with callback pattern
|
||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
updateConfig,
|
||||
|
||||
@@ -1,771 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
||||
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQRCode } from '@/hooks/useQRCode';
|
||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||
import { QRModal } from '@/components/ui/qr-modal';
|
||||
import { LoadingModal } from '@/components/wallet/LoadingModal';
|
||||
import { BalanceDisplay } from '@/components/wallet/BalanceDisplay';
|
||||
import { ReceiveCard } from '@/components/wallet/ReceiveCard';
|
||||
import { SendCard } from '@/components/wallet/SendCard';
|
||||
import { TransactionHistory } from '@/components/wallet/TransactionHistory';
|
||||
import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal';
|
||||
import { RemoveMintModal } from '@/components/wallet/RemoveMintModal';
|
||||
|
||||
export function CashuWallet() {
|
||||
// ============================================================================
|
||||
// HOOKS
|
||||
// ============================================================================
|
||||
|
||||
const {
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
balances,
|
||||
mints,
|
||||
receive,
|
||||
send,
|
||||
getProofs,
|
||||
addMint,
|
||||
removeMint,
|
||||
createMintQuote,
|
||||
createMeltQuote,
|
||||
payMeltQuote,
|
||||
redeemMintQuote,
|
||||
addMintQuote,
|
||||
on,
|
||||
refreshBalances,
|
||||
refreshMints,
|
||||
clearError,
|
||||
getHistory,
|
||||
} = useCashu();
|
||||
|
||||
const { getCleanMintLabel } = useCashuMints(null);
|
||||
|
||||
|
||||
|
||||
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
||||
|
||||
const { toast } = useToast();
|
||||
const { generateQRCode } = useQRCode();
|
||||
const { copy: copyToClipboard } = useCopyToClipboard();
|
||||
|
||||
// ============================================================================
|
||||
// STATE - Input Values
|
||||
// ============================================================================
|
||||
|
||||
const [tokenInput, setTokenInput] = useState('');
|
||||
const [mintUrl, setMintUrl] = useState('');
|
||||
const [sendAmount, setSendAmount] = useState('');
|
||||
const [quoteAmount, setQuoteAmount] = useState('');
|
||||
const [lightningInvoice, setLightningInvoice] = useState('');
|
||||
const [lightningAddressInput, setLightningAddressInput] = useState('');
|
||||
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
|
||||
|
||||
// ============================================================================
|
||||
// STATE - UI State
|
||||
// ============================================================================
|
||||
|
||||
const [showSats, setShowSats] = useState(true);
|
||||
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
|
||||
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
|
||||
|
||||
// ============================================================================
|
||||
// STATE - Transaction State
|
||||
// ============================================================================
|
||||
|
||||
const [sentToken, setSentToken] = useState<string | null>(null);
|
||||
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
|
||||
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
|
||||
|
||||
// ============================================================================
|
||||
// STATE - History
|
||||
// ============================================================================
|
||||
|
||||
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
|
||||
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
|
||||
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
||||
const [proofBreakdown, setProofBreakdown] = useState<{
|
||||
mintUrl: string;
|
||||
denominations: { [key: number]: number };
|
||||
totalBalance: number;
|
||||
} | null>(null);
|
||||
|
||||
const [showLightningQR, setShowLightningQR] = useState(false);
|
||||
const [lightningQRCode, setLightningQRCode] = useState<string>('');
|
||||
|
||||
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
|
||||
const [currentInvoice, setCurrentInvoice] = useState<{
|
||||
quoteId: string;
|
||||
mintUrl: string;
|
||||
amount: number;
|
||||
invoice: string;
|
||||
qrCodeUrl: string;
|
||||
expiry: number;
|
||||
} | null>(null);
|
||||
|
||||
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
|
||||
const [mintToRemove, setMintToRemove] = useState<{
|
||||
url: string;
|
||||
name?: string;
|
||||
} | null>(null);
|
||||
|
||||
// Ref to store the mint quote redeemed event unsubscribe function
|
||||
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||
|
||||
// ============================================================================
|
||||
// COMPUTED VALUES
|
||||
// ============================================================================
|
||||
|
||||
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - QR Code Generation
|
||||
// ============================================================================
|
||||
|
||||
// Generate QR code for sent token
|
||||
const generateSentTokenQRCode = async (token: string) => {
|
||||
try {
|
||||
const qrCodeUrl = await generateQRCode(token);
|
||||
setSentTokenQRCode(qrCodeUrl);
|
||||
} catch (err) {
|
||||
console.error('Failed to generate sent token QR code:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - Mint Management
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Set active mint
|
||||
*/
|
||||
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
|
||||
// Set the active mint locally
|
||||
setActiveMintUrl(mintUrl);
|
||||
}, []);
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - History
|
||||
// ============================================================================
|
||||
|
||||
const loadHistory = useCallback(async () => {
|
||||
try {
|
||||
setIsLoadingHistory(true);
|
||||
const entries = await getHistory(50, 0); //TODO: show entire history
|
||||
setHistoryEntries(entries);
|
||||
} catch (err) {
|
||||
console.error('Failed to load history:', err);
|
||||
} finally {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
}, [getHistory]);
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS - Receive
|
||||
// ============================================================================
|
||||
|
||||
const handleReceive = async () => {
|
||||
if (mode === 'tokens') {
|
||||
if (!tokenInput.trim()) return;
|
||||
try {
|
||||
await receive(tokenInput);
|
||||
setTokenInput('');
|
||||
console.log('✅ Token received successfully!');
|
||||
toast({
|
||||
title: "Token Received",
|
||||
description: "Cashu token redeemed successfully!",
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Receive Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Lightning mode - create mint quote
|
||||
if (!quoteAmount || !activeMintUrl) return;
|
||||
try {
|
||||
const amount = parseInt(quoteAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
console.warn('⚠️ Invalid amount');
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid Amount",
|
||||
description: "Please enter a valid amount",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const quote = await createMintQuote(activeMintUrl, amount);
|
||||
|
||||
// Generate QR code for the Lightning invoice
|
||||
const qrCodeUrl = await generateQRCode(quote.request);
|
||||
|
||||
// Set the invoice data and show modal
|
||||
setCurrentInvoice({
|
||||
quoteId: quote.quote,
|
||||
mintUrl: activeMintUrl,
|
||||
amount,
|
||||
invoice: quote.request,
|
||||
qrCodeUrl,
|
||||
expiry: quote.expiry
|
||||
});
|
||||
setShowInvoiceModal(true);
|
||||
|
||||
console.log('✅ Mint quote created:', quote);
|
||||
console.log('🔗 Lightning Invoice:', quote.request);
|
||||
console.log('💡 Wallet will automatically redeem when payment is detected');
|
||||
toast({
|
||||
title: "Lightning Invoice Created",
|
||||
description: "Wallet will automatically claim tokens when payment is detected.",
|
||||
});
|
||||
setQuoteAmount('');
|
||||
|
||||
// Clean up any previous listener
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
|
||||
// Listen for payment notification via mint-quote:redeemed event (note: hyphenated!)
|
||||
console.log('🔔 Setting up payment listener for quote:', quote.quote);
|
||||
const quoteId = quote.quote;
|
||||
const invoiceAmount = amount;
|
||||
|
||||
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
|
||||
const redeemedQuote = payload as { quoteId?: string };
|
||||
console.log('🔔 Mint quote redeemed event received:', redeemedQuote);
|
||||
|
||||
// Check if this is the quote we're waiting for
|
||||
if (redeemedQuote.quoteId === quoteId) {
|
||||
console.log('✅ Our quote was redeemed! Payment detected:', redeemedQuote);
|
||||
toast({
|
||||
title: "Payment Received",
|
||||
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
|
||||
});
|
||||
setShowInvoiceModal(false);
|
||||
setCurrentInvoice(null);
|
||||
|
||||
// Clean up the event listener
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
// Store unsubscribe function for cleanup
|
||||
mintQuoteUnsubscribeRef.current = unsubscribe;
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Quote Creation Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS - Send
|
||||
// ============================================================================
|
||||
|
||||
const handleSend = async () => {
|
||||
if (mode === 'tokens') {
|
||||
if (!sendAmount || !activeMintUrl) return;
|
||||
try {
|
||||
const amount = parseInt(sendAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
console.warn('⚠️ Invalid amount');
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid Amount",
|
||||
description: "Please enter a valid amount",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const encodedToken = await send(activeMintUrl, amount);
|
||||
setSentToken(encodedToken);
|
||||
await generateSentTokenQRCode(encodedToken);
|
||||
console.log('✅ Token created successfully!');
|
||||
console.log('📤 Encoded token:', encodedToken);
|
||||
setSendAmount('');
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Send Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Lightning mode
|
||||
if (!activeMintUrl) return;
|
||||
|
||||
// Step 1: Check if we have a pending Lightning address awaiting amount
|
||||
if (pendingLightningAddress) {
|
||||
// Step 2: User entered amount, now resolve address and pay
|
||||
if (!lightningAddressAmount) return;
|
||||
|
||||
try {
|
||||
const amount = parseInt(lightningAddressAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid Amount",
|
||||
description: "Please enter a valid amount",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount);
|
||||
const invoice = await getLightningInvoice({
|
||||
lightningAddress: pendingLightningAddress,
|
||||
amountSats: amount,
|
||||
});
|
||||
|
||||
console.log('🔄 Creating melt quote for invoice:', invoice);
|
||||
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
|
||||
|
||||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
|
||||
console.log('✅ Lightning payment sent successfully!');
|
||||
toast({
|
||||
title: "Payment Sent",
|
||||
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
|
||||
});
|
||||
|
||||
// Reset state
|
||||
setPendingLightningAddress(null);
|
||||
setLightningAddressInput('');
|
||||
setLightningAddressAmount('');
|
||||
|
||||
// No need to manually refresh balances - events will handle it automatically
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Payment Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Step 1: Check if input is a Lightning address or invoice
|
||||
const input = lightningInvoice.trim() || lightningAddressInput.trim();
|
||||
if (!input) return;
|
||||
|
||||
// Check if it's a Lightning address (contains @)
|
||||
if (input.includes('@')) {
|
||||
console.log('📧 Detected Lightning address:', input);
|
||||
setPendingLightningAddress(input);
|
||||
setLightningAddressInput('');
|
||||
} else {
|
||||
// It's a regular Lightning invoice
|
||||
try {
|
||||
console.log('🔄 Creating melt quote for invoice:', input);
|
||||
const meltQuote = await createMeltQuote(activeMintUrl, input);
|
||||
|
||||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
|
||||
console.log('✅ Lightning invoice paid successfully!');
|
||||
toast({
|
||||
title: "Invoice Paid",
|
||||
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
|
||||
});
|
||||
setLightningInvoice('');
|
||||
|
||||
// No need to manually refresh balances - events will handle it automatically
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invoice Payment Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS - Utility
|
||||
// ============================================================================
|
||||
|
||||
|
||||
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
|
||||
setMintToRemove(mint);
|
||||
setShowRemoveMintModal(true);
|
||||
}, []);
|
||||
|
||||
const handleConfirmRemoveMint = useCallback(async () => {
|
||||
if (!mintToRemove) return;
|
||||
|
||||
try {
|
||||
await removeMint(mintToRemove.url);
|
||||
|
||||
// Manually refresh mints since there's no mint:removed event
|
||||
await refreshMints();
|
||||
|
||||
// If the removed mint was the active mint, select the first available mint
|
||||
if (activeMintUrl === mintToRemove.url) {
|
||||
const remainingMints = mints.filter(m => m.url !== mintToRemove.url);
|
||||
if (remainingMints.length > 0) {
|
||||
setActiveMintUrl(remainingMints[0].url);
|
||||
} else {
|
||||
setActiveMintUrl(null);
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Mint Removed",
|
||||
description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`,
|
||||
});
|
||||
|
||||
setShowRemoveMintModal(false);
|
||||
setMintToRemove(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to remove mint:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Remove Failed",
|
||||
description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`,
|
||||
});
|
||||
}
|
||||
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS - Mint Management
|
||||
// ============================================================================
|
||||
|
||||
const handleAddMint = async () => {
|
||||
if (!mintUrl.trim()) return;
|
||||
try {
|
||||
// Normalize URL - add https:// if not present
|
||||
let normalizedUrl = mintUrl.trim();
|
||||
if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
|
||||
normalizedUrl = `https://${normalizedUrl}`;
|
||||
}
|
||||
|
||||
await addMint(normalizedUrl);
|
||||
setMintUrl('');
|
||||
|
||||
// No need to manually refresh - events will handle it automatically
|
||||
console.log('✅ Mint added successfully:', normalizedUrl);
|
||||
toast({
|
||||
title: "Mint Added",
|
||||
description: "Mint added successfully!",
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Add Mint Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS - Quote Management
|
||||
// ============================================================================
|
||||
|
||||
|
||||
|
||||
const handleShowDenominations = async (mintUrl: string) => {
|
||||
try {
|
||||
console.log('🔍 Getting token denominations for mint:', mintUrl);
|
||||
|
||||
// Get proofs from the wallet for this specific mint
|
||||
const proofs = await getProofs(mintUrl);
|
||||
console.log('💰 Raw proofs for mint:', proofs);
|
||||
|
||||
if (!proofs || proofs.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "No Tokens",
|
||||
description: "No tokens found for this mint",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Group proofs by denomination
|
||||
const denominations: { [key: number]: number } = {};
|
||||
proofs.forEach((proof: { amount?: number }) => {
|
||||
const amount = proof.amount || 0;
|
||||
denominations[amount] = (denominations[amount] || 0) + 1;
|
||||
});
|
||||
|
||||
const totalBalance = Object.entries(denominations)
|
||||
.reduce((sum, [amount, count]) => sum + (parseInt(amount) * count), 0);
|
||||
|
||||
// Set the breakdown data and show the modal
|
||||
setProofBreakdown({
|
||||
mintUrl,
|
||||
denominations,
|
||||
totalBalance
|
||||
});
|
||||
setShowProofBreakdown(true);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Failed to get denominations:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to Get Denominations",
|
||||
description: "Failed to get token denominations. Check console for details.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// EFFECTS
|
||||
// ============================================================================
|
||||
|
||||
// Show error toasts when errors occur
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Wallet Error",
|
||||
description: error.message,
|
||||
});
|
||||
}
|
||||
}, [error, toast]);
|
||||
|
||||
|
||||
// Auto-select active mint when mints change (balances will update automatically via events)
|
||||
useEffect(() => {
|
||||
if (mints.length > 0 && !activeMintUrl) {
|
||||
// Select first mint initially - user can change via dropdown
|
||||
handleSetActiveMint(mints[0].url);
|
||||
}
|
||||
}, [mints, activeMintUrl, handleSetActiveMint]);
|
||||
|
||||
// Load transaction history when wallet is initialized
|
||||
useEffect(() => {
|
||||
if (isInitialized && historyEntries.length === 0) {
|
||||
loadHistory();
|
||||
}
|
||||
}, [isInitialized, historyEntries.length, loadHistory]);
|
||||
|
||||
// Auto-refresh transaction history on new transactions
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
console.log('📜 Setting up history auto-refresh listeners...');
|
||||
|
||||
// Listen for history updates (fires on send, receive transactions)
|
||||
const unsubscribeHistoryUpdated = on('history:updated', () => {
|
||||
console.log('📜 History updated event, refreshing...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
|
||||
const unsubscribeMeltCreated = on('melt-quote:created', () => {
|
||||
console.log('📜 Melt quote created, refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote paid (backup, in case creation event missed)
|
||||
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
|
||||
console.log('📜 Melt quote paid, refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
|
||||
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
|
||||
console.log('📜 Mint quote redeemed (invoice paid), refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeHistoryUpdated();
|
||||
unsubscribeMeltCreated();
|
||||
unsubscribeMeltPaid();
|
||||
unsubscribeMintRedeemed();
|
||||
};
|
||||
}, [isInitialized, on, loadHistory]);
|
||||
|
||||
// Cleanup mint quote listener on component unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (component unmount)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// RENDER - Main UI
|
||||
// ============================================================================
|
||||
|
||||
return (
|
||||
<>
|
||||
<LoadingModal isLoading={isLoading || !isInitialized} />
|
||||
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
|
||||
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Balance Display
|
||||
======================================================================== */}
|
||||
<BalanceDisplay
|
||||
totalBalance={totalBalance}
|
||||
balances={balances}
|
||||
showSats={showSats}
|
||||
setShowSats={setShowSats}
|
||||
mode={mode}
|
||||
setMode={setMode}
|
||||
activeMintUrl={activeMintUrl}
|
||||
setActiveMintUrl={handleSetActiveMint}
|
||||
mints={mints}
|
||||
mintUrl={mintUrl}
|
||||
setMintUrl={setMintUrl}
|
||||
onAddMint={handleAddMint}
|
||||
onRemoveMint={handleRemoveMintClick}
|
||||
onShowDenominations={handleShowDenominations}
|
||||
getCleanMintLabel={getCleanMintLabel}
|
||||
/>
|
||||
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Receive & Send Cards
|
||||
======================================================================== */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<ReceiveCard
|
||||
mode={mode}
|
||||
tokenInput={tokenInput}
|
||||
setTokenInput={setTokenInput}
|
||||
quoteAmount={quoteAmount}
|
||||
setQuoteAmount={setQuoteAmount}
|
||||
activeMintUrl={activeMintUrl}
|
||||
onReceive={handleReceive}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<SendCard
|
||||
mode={mode}
|
||||
sendAmount={sendAmount}
|
||||
setSendAmount={setSendAmount}
|
||||
lightningInvoice={lightningInvoice}
|
||||
setLightningInvoice={setLightningInvoice}
|
||||
lightningAddressInput={lightningAddressInput}
|
||||
setLightningAddressInput={setLightningAddressInput}
|
||||
lightningAddressAmount={lightningAddressAmount}
|
||||
setLightningAddressAmount={setLightningAddressAmount}
|
||||
pendingLightningAddress={pendingLightningAddress}
|
||||
setPendingLightningAddress={setPendingLightningAddress}
|
||||
activeMintUrl={activeMintUrl}
|
||||
onSend={handleSend}
|
||||
isResolvingAddress={isResolvingAddress}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Sent Token Display
|
||||
======================================================================== */}
|
||||
{sentToken && (
|
||||
<QRModal
|
||||
isOpen={!!sentToken}
|
||||
onClose={() => setSentToken(null)}
|
||||
title="Cashu Token"
|
||||
description="Share this token with the recipient to send them your sats"
|
||||
qrCodeUrl={sentTokenQRCode}
|
||||
content={sentToken}
|
||||
icon="qr"
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Transaction History
|
||||
======================================================================== */}
|
||||
<TransactionHistory
|
||||
entries={historyEntries}
|
||||
isLoading={isLoadingHistory}
|
||||
isExpanded={isHistoryExpanded}
|
||||
setIsExpanded={setIsHistoryExpanded}
|
||||
/>
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Modals
|
||||
======================================================================== */}
|
||||
<>
|
||||
<ProofBreakdownModal
|
||||
isOpen={showProofBreakdown}
|
||||
onClose={() => setShowProofBreakdown(false)}
|
||||
breakdown={proofBreakdown}
|
||||
/>
|
||||
|
||||
<QRModal
|
||||
isOpen={showLightningQR}
|
||||
onClose={() => setShowLightningQR(false)}
|
||||
title="Lightning Address QR Code"
|
||||
description="Scan to send Lightning payments"
|
||||
qrCodeUrl={lightningQRCode}
|
||||
content={''}
|
||||
icon="qr"
|
||||
/>
|
||||
|
||||
{currentInvoice && (
|
||||
<QRModal
|
||||
isOpen={showInvoiceModal}
|
||||
onClose={() => {
|
||||
// Clean up event listener when modal is closed manually
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (modal closed)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
setShowInvoiceModal(false);
|
||||
}}
|
||||
onExpiry={() => {
|
||||
// Clean up event listener when invoice expires
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (invoice expired)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
// Show destructive toast
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invoice Expired",
|
||||
description: "The Lightning invoice has expired. Please create a new one.",
|
||||
});
|
||||
}}
|
||||
title="Lightning Invoice"
|
||||
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
|
||||
qrCodeUrl={currentInvoice.qrCodeUrl}
|
||||
content={currentInvoice.invoice}
|
||||
icon="zap"
|
||||
expiryTimestamp={currentInvoice.expiry}
|
||||
/>
|
||||
)}
|
||||
|
||||
<RemoveMintModal
|
||||
isOpen={showRemoveMintModal}
|
||||
onClose={() => setShowRemoveMintModal(false)}
|
||||
mint={mintToRemove}
|
||||
onConfirm={handleConfirmRemoveMint}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -20,10 +20,10 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
// Use refs so the pool always has the latest data
|
||||
const relayUrl = useRef<string>(config.relayUrl);
|
||||
|
||||
// Update refs when config changes
|
||||
// Invalidate Nostr queries when relayUrl changes
|
||||
useEffect(() => {
|
||||
relayUrl.current = config.relayUrl;
|
||||
queryClient.resetQueries();
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||
}, [config.relayUrl, queryClient]);
|
||||
|
||||
// Initialize NPool only once
|
||||
|
||||
@@ -26,7 +26,7 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
import { useCashu } from '@/hooks/wallet/useCashu';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
@@ -95,7 +95,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Primary Payment Method - Cashu */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Primary Payment Method</h3>
|
||||
<h3 className="font-medium">Primary Wallet</h3>
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
|
||||
<div className="flex items-center gap-3">
|
||||
<Coins className="h-4 w-4 text-muted-foreground" />
|
||||
@@ -116,19 +116,13 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground text-center">
|
||||
Cashu tokens are used first for Lightning zaps. Set up your Cashu wallet for instant payments.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Lightning Fallback Methods */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Lightning Fallback Methods</h3>
|
||||
<div className="text-xs text-muted-foreground mb-3">
|
||||
Used when Cashu balance is insufficient or unavailable
|
||||
</div>
|
||||
<h3 className="font-medium">Other Options</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
@@ -233,7 +227,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning fallback.
|
||||
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
@@ -367,7 +361,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
Payment Settings
|
||||
</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Manage Cashu wallet and Lightning fallback methods for zaps.
|
||||
Manage wallet methods for zaps
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="overflow-y-auto">
|
||||
@@ -423,7 +417,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
Payment Settings
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Manage Cashu wallet and Lightning fallback methods for zaps.
|
||||
Manage wallet methods for zaps
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<WalletContent {...walletContentProps} />
|
||||
|
||||
@@ -30,7 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
import { useCashu } from '@/hooks/wallet/useCashu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
@@ -30,7 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
import { useCashu } from '@/hooks/wallet/useCashu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
@@ -182,7 +182,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
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 overflow-y-scroll")}
|
||||
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')}>
|
||||
|
||||
@@ -190,7 +190,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
Sign up or log in to continue
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
|
||||
<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'>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
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)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -301,7 +301,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
||||
{getTitle()}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
|
||||
<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'>
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
||||
import { useConversationMessages, useDMContext } from '@/contexts/DMContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants';
|
||||
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { ArrowLeft, Send, Loader2, AlertTriangle, Key, ShieldCheck } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { NoteContent } from '@/components/NoteContent';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface DMChatAreaProps {
|
||||
pubkey: string | null;
|
||||
onBack?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const MessageBubble = memo(({
|
||||
message,
|
||||
isFromCurrentUser
|
||||
}: {
|
||||
message: {
|
||||
id: string;
|
||||
pubkey: string;
|
||||
kind: number;
|
||||
tags: string[][];
|
||||
decryptedContent?: string;
|
||||
decryptedEvent?: NostrEvent;
|
||||
error?: string;
|
||||
created_at: number;
|
||||
isSending?: boolean;
|
||||
};
|
||||
isFromCurrentUser: boolean;
|
||||
}) => {
|
||||
// For NIP-17, use inner message kind (14/15); for NIP-04, use message kind (4)
|
||||
const actualKind = message.decryptedEvent?.kind || message.kind;
|
||||
const isNIP4Message = message.kind === 4;
|
||||
const isFileAttachment = actualKind === 15; // Kind 15 = files/attachments
|
||||
|
||||
// Create a NostrEvent object for NoteContent (only used for kind 15)
|
||||
// For NIP-17 file attachments, use the decryptedEvent which has the actual tags
|
||||
const messageEvent: NostrEvent = message.decryptedEvent || {
|
||||
id: message.id,
|
||||
pubkey: message.pubkey,
|
||||
created_at: message.created_at,
|
||||
kind: message.kind,
|
||||
tags: message.tags,
|
||||
content: message.decryptedContent || '',
|
||||
sig: '', // Not needed for display
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("flex mb-4", isFromCurrentUser ? "justify-end" : "justify-start")}>
|
||||
<div className={cn(
|
||||
"max-w-[70%] rounded-lg px-4 py-2",
|
||||
isFromCurrentUser
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted"
|
||||
)}>
|
||||
{message.error ? (
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<p className="text-sm italic opacity-70 cursor-help">🔒 Failed to decrypt</p>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs">{message.error}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : isFileAttachment ? (
|
||||
// Kind 15: Use NoteContent to render files/media with imeta tags
|
||||
<div className="text-sm">
|
||||
<NoteContent event={messageEvent} className="whitespace-pre-wrap break-words" />
|
||||
</div>
|
||||
) : (
|
||||
// Kind 4 (NIP-04) and Kind 14 (NIP-17 text): Display plain text
|
||||
<p className="text-sm whitespace-pre-wrap break-words">
|
||||
{message.decryptedContent}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<TooltipProvider>
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<span className={cn(
|
||||
"text-xs opacity-70 cursor-default",
|
||||
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
||||
)}>
|
||||
{formatConversationTime(message.created_at)}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs">{formatFullDateTime(message.created_at)}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<TooltipProvider>
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<span className={cn(
|
||||
"flex-shrink-0 opacity-50",
|
||||
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
||||
)}>
|
||||
{message.kind === 4 ? (
|
||||
<Key className="h-3 w-3" />
|
||||
) : (
|
||||
<ShieldCheck className="h-3 w-3" />
|
||||
)}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs">
|
||||
{message.kind === 4 && "NIP-04 Kind 4 (Legacy DM)"}
|
||||
{message.kind === 14 && "NIP-17 Kind 14 (Private Message)"}
|
||||
{message.kind === 15 && "NIP-17 Kind 15 (Media)"}
|
||||
{message.kind !== 4 && message.kind !== 14 && message.kind !== 15 && `Kind ${message.kind}`}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
{isNIP4Message && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex-shrink-0">
|
||||
<AlertTriangle className="h-3 w-3 text-yellow-600 dark:text-yellow-500" />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs">Uses outdated NIP-04 encryption</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{message.isSending && (
|
||||
<Loader2 className="h-3 w-3 animate-spin opacity-70" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
MessageBubble.displayName = 'MessageBubble';
|
||||
|
||||
const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => {
|
||||
const author = useAuthor(pubkey);
|
||||
const metadata = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name || genUserName(pubkey);
|
||||
const avatarUrl = metadata?.picture;
|
||||
const initials = displayName.slice(0, 2).toUpperCase();
|
||||
|
||||
return (
|
||||
<div className="p-4 border-b flex items-center gap-3">
|
||||
{onBack && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onBack}
|
||||
className="md:hidden"
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={avatarUrl} alt={displayName} />
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="font-semibold truncate">{displayName}</h2>
|
||||
{metadata?.nip05 && (
|
||||
<p className="text-xs text-muted-foreground truncate">{metadata.nip05}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const EmptyState = ({ isLoading }: { isLoading: boolean }) => {
|
||||
return (
|
||||
<div className="h-full flex items-center justify-center p-8">
|
||||
<div className="text-center text-muted-foreground max-w-sm">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
|
||||
<p className="text-sm">Loading conversations...</p>
|
||||
<p className="text-xs mt-2">
|
||||
Fetching encrypted messages from relays
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm">Select a conversation to start messaging</p>
|
||||
<p className="text-xs mt-2">
|
||||
Your messages are encrypted and stored locally
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => {
|
||||
const { user } = useCurrentUser();
|
||||
const { sendMessage, protocolMode, isLoading } = useDMContext();
|
||||
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey || '');
|
||||
|
||||
const [messageText, setMessageText] = useState('');
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||
|
||||
// Determine default protocol based on mode
|
||||
const getDefaultProtocol = () => {
|
||||
if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04;
|
||||
if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17;
|
||||
if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17;
|
||||
// Fallback to NIP-17 for any unexpected mode
|
||||
return MESSAGE_PROTOCOL.NIP17;
|
||||
};
|
||||
|
||||
const [selectedProtocol, setSelectedProtocol] = useState<MessageProtocol>(getDefaultProtocol());
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Determine if selection is allowed
|
||||
const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17;
|
||||
|
||||
// Auto-scroll to bottom when new messages arrive
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
||||
if (scrollContainer) {
|
||||
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [messages.length]);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
if (!messageText.trim() || !pubkey || !user) return;
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
await sendMessage({
|
||||
recipientPubkey: pubkey,
|
||||
content: messageText.trim(),
|
||||
protocol: selectedProtocol,
|
||||
});
|
||||
setMessageText('');
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [messageText, pubkey, user, sendMessage, selectedProtocol]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}, [handleSend]);
|
||||
|
||||
const handleLoadMore = useCallback(async () => {
|
||||
if (!scrollAreaRef.current || isLoadingMore) return;
|
||||
|
||||
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
||||
if (!scrollContainer) return;
|
||||
|
||||
// Store current scroll position and height
|
||||
const previousScrollHeight = scrollContainer.scrollHeight;
|
||||
const previousScrollTop = scrollContainer.scrollTop;
|
||||
|
||||
setIsLoadingMore(true);
|
||||
|
||||
// Load more messages
|
||||
loadEarlierMessages();
|
||||
|
||||
// Wait for DOM to update, then restore relative scroll position
|
||||
setTimeout(() => {
|
||||
if (scrollContainer) {
|
||||
const newScrollHeight = scrollContainer.scrollHeight;
|
||||
const heightDifference = newScrollHeight - previousScrollHeight;
|
||||
scrollContainer.scrollTop = previousScrollTop + heightDifference;
|
||||
}
|
||||
setIsLoadingMore(false);
|
||||
}, 0);
|
||||
}, [loadEarlierMessages, isLoadingMore]);
|
||||
|
||||
if (!pubkey) {
|
||||
return (
|
||||
<Card className={cn("h-full", className)}>
|
||||
<EmptyState isLoading={isLoading} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card className={cn("h-full flex items-center justify-center", className)}>
|
||||
<div className="text-center text-muted-foreground">
|
||||
<p className="text-sm">Please log in to view messages</p>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={cn("h-full flex flex-col", className)}>
|
||||
<ChatHeader pubkey={pubkey} onBack={onBack} />
|
||||
|
||||
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4">
|
||||
{messages.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<p className="text-sm">No messages yet</p>
|
||||
<p className="text-xs mt-1">Send a message to start the conversation</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{hasMoreMessages && (
|
||||
<div className="flex justify-center mb-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleLoadMore}
|
||||
disabled={isLoadingMore}
|
||||
className="text-xs"
|
||||
>
|
||||
{isLoadingMore ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin mr-2" />
|
||||
Loading...
|
||||
</>
|
||||
) : (
|
||||
'Load Earlier Messages'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{messages.map((message) => (
|
||||
<MessageBubble
|
||||
key={message.id}
|
||||
message={message}
|
||||
isFromCurrentUser={message.pubkey === user.pubkey}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
<div className="p-4 border-t">
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
value={messageText}
|
||||
onChange={(e) => setMessageText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
|
||||
className="min-h-[80px] resize-none"
|
||||
disabled={isSending}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!messageText.trim() || isSending}
|
||||
size="icon"
|
||||
className="h-[44px] w-[90px]"
|
||||
>
|
||||
{isSending ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
) : (
|
||||
<Send className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
<Select
|
||||
value={selectedProtocol}
|
||||
onValueChange={(value) => setSelectedProtocol(value as MessageProtocol)}
|
||||
disabled={!allowSelection}
|
||||
>
|
||||
<SelectTrigger className="h-[32px] w-[90px] text-xs px-2">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={MESSAGE_PROTOCOL.NIP17} className="text-xs">
|
||||
NIP-17
|
||||
</SelectItem>
|
||||
<SelectItem value={MESSAGE_PROTOCOL.NIP04} className="text-xs">
|
||||
NIP-04
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,266 @@
|
||||
import { useMemo, useState, memo } from 'react';
|
||||
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { LOADING_PHASES } from '@/lib/dmConstants';
|
||||
|
||||
interface DMConversationListProps {
|
||||
selectedPubkey: string | null;
|
||||
onSelectConversation: (pubkey: string) => void;
|
||||
className?: string;
|
||||
onStatusClick?: () => void;
|
||||
}
|
||||
|
||||
interface ConversationItemProps {
|
||||
pubkey: string;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
lastMessage: { decryptedContent?: string; error?: string } | null;
|
||||
lastActivity: number;
|
||||
hasNIP4Messages: boolean;
|
||||
}
|
||||
|
||||
const ConversationItemComponent = ({
|
||||
pubkey,
|
||||
isSelected,
|
||||
onClick,
|
||||
lastMessage,
|
||||
lastActivity,
|
||||
hasNIP4Messages
|
||||
}: ConversationItemProps) => {
|
||||
const author = useAuthor(pubkey);
|
||||
const metadata = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name || genUserName(pubkey);
|
||||
const avatarUrl = metadata?.picture;
|
||||
const initials = displayName.slice(0, 2).toUpperCase();
|
||||
|
||||
const lastMessagePreview = lastMessage?.error
|
||||
? '🔒 Encrypted message'
|
||||
: lastMessage?.decryptedContent || 'No messages yet';
|
||||
|
||||
// Show skeleton only for name/avatar while loading (we already have message data)
|
||||
const isLoadingProfile = author.isLoading && !metadata;
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent block overflow-hidden",
|
||||
isSelected && "bg-accent"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-3 max-w-full">
|
||||
{isLoadingProfile ? (
|
||||
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
||||
) : (
|
||||
<Avatar className="h-10 w-10 flex-shrink-0">
|
||||
<AvatarImage src={avatarUrl} alt={displayName} />
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0 flex-1">
|
||||
{isLoadingProfile ? (
|
||||
<Skeleton className="h-[1.25rem] w-24" />
|
||||
) : (
|
||||
<span className="font-medium text-sm truncate">{displayName}</span>
|
||||
)}
|
||||
{hasNIP4Messages && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex-shrink-0">
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-500" />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">
|
||||
<p className="text-xs max-w-[200px]">Some messages use outdated NIP-04 encryption</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0 cursor-default">
|
||||
{formatConversationTime(lastActivity)}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">
|
||||
<p className="text-xs">{formatFullDateTime(lastActivity)}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground truncate">
|
||||
{lastMessagePreview}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
const ConversationItem = memo(ConversationItemComponent);
|
||||
ConversationItem.displayName = 'ConversationItem';
|
||||
|
||||
const ConversationListSkeleton = () => {
|
||||
return (
|
||||
<div className="space-y-2 p-4">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<div key={i} className="flex items-start gap-3 p-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-12" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const DMConversationList = ({
|
||||
selectedPubkey,
|
||||
onSelectConversation,
|
||||
className,
|
||||
onStatusClick
|
||||
}: DMConversationListProps) => {
|
||||
const { conversations, isLoading, loadingPhase } = useDMContext();
|
||||
const [activeTab, setActiveTab] = useState<'known' | 'requests'>('known');
|
||||
|
||||
// Filter conversations by type
|
||||
const { knownConversations, requestConversations } = useMemo(() => {
|
||||
return {
|
||||
knownConversations: conversations.filter(c => c.isKnown),
|
||||
requestConversations: conversations.filter(c => c.isRequest),
|
||||
};
|
||||
}, [conversations]);
|
||||
|
||||
// Get the current list based on active tab
|
||||
const currentConversations = activeTab === 'known' ? knownConversations : requestConversations;
|
||||
|
||||
// Show skeleton during initial load (cache + relays) if we have no conversations yet
|
||||
const isInitialLoad = (loadingPhase === LOADING_PHASES.CACHE || loadingPhase === LOADING_PHASES.RELAYS) && conversations.length === 0;
|
||||
|
||||
return (
|
||||
<Card className={cn("h-full flex flex-col overflow-hidden", className)}>
|
||||
{/* Header - always visible */}
|
||||
<div className="p-4 border-b flex-shrink-0 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="font-semibold text-lg">Messages</h2>
|
||||
{(loadingPhase === LOADING_PHASES.CACHE ||
|
||||
loadingPhase === LOADING_PHASES.RELAYS ||
|
||||
loadingPhase === LOADING_PHASES.SUBSCRIPTIONS) && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex items-center">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p className="text-xs">
|
||||
{loadingPhase === LOADING_PHASES.CACHE && 'Loading from cache...'}
|
||||
{loadingPhase === LOADING_PHASES.RELAYS && 'Querying relays for new messages...'}
|
||||
{loadingPhase === LOADING_PHASES.SUBSCRIPTIONS && 'Setting up subscriptions...'}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
{onStatusClick && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={onStatusClick}
|
||||
aria-label="View messaging status"
|
||||
>
|
||||
<Info className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tab buttons - always visible */}
|
||||
<div className="px-2 pt-2 flex-shrink-0">
|
||||
<div className="grid grid-cols-2 gap-1 bg-muted p-1 rounded-lg">
|
||||
<button
|
||||
onClick={() => setActiveTab('known')}
|
||||
className={cn(
|
||||
"text-xs py-2 px-3 rounded-md transition-colors",
|
||||
activeTab === 'known'
|
||||
? "bg-background shadow-sm font-medium"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Active {knownConversations.length > 0 && `(${knownConversations.length})`}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('requests')}
|
||||
className={cn(
|
||||
"text-xs py-2 px-3 rounded-md transition-colors",
|
||||
activeTab === 'requests'
|
||||
? "bg-background shadow-sm font-medium"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Requests {requestConversations.length > 0 && `(${requestConversations.length})`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content area - show skeleton during initial load, otherwise show conversations */}
|
||||
<div className="flex-1 min-h-0 mt-2 overflow-hidden">
|
||||
{(isLoading || isInitialLoad) ? (
|
||||
<ConversationListSkeleton />
|
||||
) : conversations.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-center text-muted-foreground px-4">
|
||||
<div>
|
||||
<p className="text-sm">No conversations yet</p>
|
||||
<p className="text-xs mt-1">Start a new conversation to get started</p>
|
||||
</div>
|
||||
</div>
|
||||
) : currentConversations.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-32 text-center text-muted-foreground px-4">
|
||||
<p className="text-sm">No {activeTab} conversations</p>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="h-full block">
|
||||
<div className="block w-full px-2 py-2 space-y-1">
|
||||
{currentConversations.map((conversation) => (
|
||||
<ConversationItem
|
||||
key={conversation.pubkey}
|
||||
pubkey={conversation.pubkey}
|
||||
isSelected={selectedPubkey === conversation.pubkey}
|
||||
onClick={() => onSelectConversation(conversation.pubkey)}
|
||||
lastMessage={conversation.lastMessage}
|
||||
lastActivity={conversation.lastActivity}
|
||||
hasNIP4Messages={conversation.hasNIP4Messages}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
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 { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface DMMessagingInterfaceProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const DMMessagingInterface = ({ className }: DMMessagingInterfaceProps) => {
|
||||
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
||||
const [statusModalOpen, setStatusModalOpen] = useState(false);
|
||||
const isMobile = useIsMobile();
|
||||
const { clearCacheAndRefetch } = useDMContext();
|
||||
|
||||
// On mobile, show only one panel at a time
|
||||
const showConversationList = !isMobile || !selectedPubkey;
|
||||
const showChatArea = !isMobile || selectedPubkey;
|
||||
|
||||
const handleSelectConversation = useCallback((pubkey: string) => {
|
||||
setSelectedPubkey(pubkey);
|
||||
}, []);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
setSelectedPubkey(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Status Modal */}
|
||||
<Dialog open={statusModalOpen} onOpenChange={setStatusModalOpen}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Messaging Status</DialogTitle>
|
||||
<DialogDescription>
|
||||
View loading status, cache info, and connection details
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<div className={cn("flex gap-4 overflow-hidden", className)}>
|
||||
{/* Conversation List - Left Sidebar */}
|
||||
<div className={cn(
|
||||
"md:w-80 md:flex-shrink-0",
|
||||
isMobile && !showConversationList && "hidden",
|
||||
isMobile && showConversationList && "w-full"
|
||||
)}>
|
||||
<DMConversationList
|
||||
selectedPubkey={selectedPubkey}
|
||||
onSelectConversation={handleSelectConversation}
|
||||
className="h-full"
|
||||
onStatusClick={() => setStatusModalOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Chat Area - Right Panel */}
|
||||
<div className={cn(
|
||||
"flex-1 md:min-w-0",
|
||||
isMobile && !showChatArea && "hidden",
|
||||
isMobile && showChatArea && "w-full"
|
||||
)}>
|
||||
<DMChatArea
|
||||
pubkey={selectedPubkey}
|
||||
onBack={isMobile ? handleBack : undefined}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { useState } from 'react';
|
||||
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
import { LOADING_PHASES } from '@/lib/dmConstants';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface DMStatusInfoProps {
|
||||
clearCacheAndRefetch?: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const DMStatusInfo = ({ clearCacheAndRefetch }: DMStatusInfoProps) => {
|
||||
const [isClearing, setIsClearing] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const {
|
||||
loadingPhase,
|
||||
subscriptions,
|
||||
scanProgress,
|
||||
isDoingInitialLoad,
|
||||
lastSync,
|
||||
conversations,
|
||||
} = useDMContext();
|
||||
|
||||
const handleClearCache = async () => {
|
||||
if (!clearCacheAndRefetch) return;
|
||||
|
||||
setIsClearing(true);
|
||||
try {
|
||||
await clearCacheAndRefetch();
|
||||
toast({
|
||||
title: 'Cache cleared',
|
||||
description: 'Refetching messages from relays...',
|
||||
});
|
||||
setIsClearing(false);
|
||||
} catch (error) {
|
||||
console.error('Error clearing cache:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to clear cache. Please try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsClearing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getLoadingPhaseInfo = () => {
|
||||
switch (loadingPhase) {
|
||||
case LOADING_PHASES.IDLE:
|
||||
return { label: 'Idle', description: 'Not yet initialized', icon: Loader2, color: 'text-muted-foreground' };
|
||||
case LOADING_PHASES.CACHE:
|
||||
return { label: 'Loading from cache', description: 'Reading cached messages...', icon: Database, color: 'text-blue-500' };
|
||||
case LOADING_PHASES.RELAYS:
|
||||
return { label: 'Loading from relays', description: 'Fetching messages from Nostr relays...', icon: Wifi, color: 'text-yellow-500' };
|
||||
case LOADING_PHASES.SUBSCRIPTIONS:
|
||||
return { label: 'Connecting subscriptions', description: 'Setting up real-time message sync...', icon: RefreshCw, color: 'text-orange-500' };
|
||||
case LOADING_PHASES.READY:
|
||||
return { label: 'Ready', description: 'All systems operational', icon: CheckCircle2, color: 'text-green-500' };
|
||||
default:
|
||||
return { label: 'Unknown', description: 'Status unknown', icon: Loader2, color: 'text-muted-foreground' };
|
||||
}
|
||||
};
|
||||
|
||||
const phaseInfo = getLoadingPhaseInfo();
|
||||
const PhaseIcon = phaseInfo.icon;
|
||||
|
||||
const formatTimestamp = (timestamp: number | null) => {
|
||||
if (!timestamp) return 'Never';
|
||||
const date = new Date(timestamp * 1000);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
|
||||
if (diffMins < 1) return 'Just now';
|
||||
if (diffMins < 60) return `${diffMins}m ago`;
|
||||
if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
|
||||
return date.toLocaleDateString();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Loading Phase */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-start gap-3">
|
||||
<PhaseIcon className={`h-5 w-5 ${phaseInfo.color} ${loadingPhase !== LOADING_PHASES.READY ? 'animate-pulse' : ''}`} />
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="font-medium">{phaseInfo.label}</p>
|
||||
{isDoingInitialLoad && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Initial Load
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{phaseInfo.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Scan Progress */}
|
||||
{(scanProgress.nip4 !== null || scanProgress.nip17 !== null) && (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium">Scanning Messages</p>
|
||||
{scanProgress.nip4 !== null && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="text-muted-foreground">NIP-4 (Legacy)</span>
|
||||
<span className="text-muted-foreground">{scanProgress.nip4.current} events</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{scanProgress.nip4.status}</p>
|
||||
</div>
|
||||
)}
|
||||
{scanProgress.nip17 !== null && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="text-muted-foreground">NIP-17 (Private)</span>
|
||||
<span className="text-muted-foreground">{scanProgress.nip17.current} events</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{scanProgress.nip17.status}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Subscriptions */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium">Real-time Subscriptions</p>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">NIP-4 (Legacy DMs)</span>
|
||||
<Badge variant={subscriptions.isNIP4Connected ? 'default' : 'secondary'}>
|
||||
{subscriptions.isNIP4Connected ? 'Connected' : 'Disconnected'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">NIP-17 (Private DMs)</span>
|
||||
<Badge variant={subscriptions.isNIP17Connected ? 'default' : 'secondary'}>
|
||||
{subscriptions.isNIP17Connected ? 'Connected' : 'Disconnected'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cache Info */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium">Cache Information</p>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Conversations</span>
|
||||
<span className="font-medium">{conversations.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Last NIP-4 sync</span>
|
||||
<span className="font-medium">{formatTimestamp(lastSync.nip4)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Last NIP-17 sync</span>
|
||||
<span className="font-medium">{formatTimestamp(lastSync.nip17)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Actions */}
|
||||
{clearCacheAndRefetch && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">Cache Management</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Clear all cached messages and refetch from relays. This will force a fresh sync.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleClearCache}
|
||||
disabled={isClearing}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{isClearing ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Clearing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Clear Cache & Refetch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -125,7 +125,9 @@ export function QRModal({
|
||||
onClick={handleCopy}
|
||||
title="Click to copy full content"
|
||||
>
|
||||
{content.length > 20 ? `${content.substring(0, 20)}...` : 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" />
|
||||
|
||||
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
|
||||
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||
</SliderPrimitive.Track>
|
||||
<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.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.Root>
|
||||
))
|
||||
Slider.displayName = SliderPrimitive.Root.displayName
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Wallet, ChevronDown, Plus, X, Zap, Coins, HelpCircle } from 'lucide-react';
|
||||
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
|
||||
|
||||
interface CashuMint {
|
||||
url: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface BalanceDisplayProps {
|
||||
totalBalance: number;
|
||||
balances: { [key: string]: number };
|
||||
showSats: boolean;
|
||||
setShowSats: (showSats: boolean) => void;
|
||||
mode: 'tokens' | 'lightning';
|
||||
setMode: (mode: 'tokens' | 'lightning') => void;
|
||||
activeMintUrl: string | null;
|
||||
setActiveMintUrl: (url: string | null) => void;
|
||||
mints: CashuMint[];
|
||||
mintUrl: string;
|
||||
setMintUrl: (url: string) => void;
|
||||
onAddMint: () => void;
|
||||
onRemoveMint: (mint: CashuMint) => void;
|
||||
onShowDenominations: (mintUrl: string) => void;
|
||||
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
|
||||
}
|
||||
|
||||
export function BalanceDisplay({
|
||||
totalBalance,
|
||||
balances,
|
||||
showSats,
|
||||
setShowSats,
|
||||
mode,
|
||||
setMode,
|
||||
activeMintUrl,
|
||||
setActiveMintUrl,
|
||||
mints,
|
||||
mintUrl,
|
||||
setMintUrl,
|
||||
onAddMint,
|
||||
onRemoveMint,
|
||||
onShowDenominations,
|
||||
getCleanMintLabel,
|
||||
}: BalanceDisplayProps) {
|
||||
const { convertCurrency } = useCashuBalances(null);
|
||||
|
||||
return (
|
||||
<div className="text-center py-2">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => setShowSats(!showSats)}
|
||||
className="text-5xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
|
||||
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
|
||||
>
|
||||
{convertCurrency(totalBalance, showSats)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Main Mode Toggle */}
|
||||
<div className="mt-4 flex items-center justify-center">
|
||||
<div className="flex gap-1 bg-muted rounded-lg p-1">
|
||||
<button
|
||||
onClick={() => setMode('tokens')}
|
||||
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
|
||||
mode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||||
}`}
|
||||
>
|
||||
<Coins className="h-4 w-4" />
|
||||
Cashu
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMode('lightning')}
|
||||
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
|
||||
mode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||||
}`}
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active Mint Dropdown and Balance */}
|
||||
<div className="mt-3 flex items-center justify-center gap-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
|
||||
<Wallet className="h-4 w-4" />
|
||||
{activeMintUrl ? getCleanMintLabel({ url: activeMintUrl }) : 'Select Mint'}
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center" className="w-72">
|
||||
{mints.length === 0 && (
|
||||
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
|
||||
)}
|
||||
{mints
|
||||
.filter((mint) => mint.url)
|
||||
.map((mint, index) => (
|
||||
<DropdownMenuItem
|
||||
key={`dd-mint-${mint.url || `unknown-${index}`}`}
|
||||
className="flex items-center justify-between"
|
||||
onClick={() => setActiveMintUrl(mint.url)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{getCleanMintLabel(mint)}</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemoveMint(mint);
|
||||
}}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<div className="px-2 py-1.5">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="mint.example.com"
|
||||
value={mintUrl}
|
||||
onChange={(e) => setMintUrl(e.target.value)}
|
||||
className="h-8"
|
||||
/>
|
||||
<Button size="sm" onClick={onAddMint} disabled={!mintUrl.trim()}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Active Mint Balance */}
|
||||
{activeMintUrl && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => activeMintUrl && onShowDenominations(activeMintUrl)}
|
||||
className="text-sm font-semibold tabular-nums hover:opacity-80 transition-opacity cursor-pointer text-muted-foreground hover:text-foreground"
|
||||
title="Click to see proof breakdown"
|
||||
>
|
||||
{convertCurrency(balances[activeMintUrl] || 0, showSats)}
|
||||
</button>
|
||||
|
||||
{/* Help button */}
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground">
|
||||
<HelpCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
What is a Mint?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="space-y-3 text-left">
|
||||
<p>
|
||||
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Key features:</strong>
|
||||
</p>
|
||||
<ul className="list-disc list-inside space-y-1 ml-4">
|
||||
<li>Issues tokens when you deposit Lightning payments</li>
|
||||
<li>Redeems tokens when you receive them</li>
|
||||
<li>Manages your token balance</li>
|
||||
<li>Enables Lightning ↔ Cashu conversions</li>
|
||||
</ul>
|
||||
<p>
|
||||
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
|
||||
</p>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,948 @@
|
||||
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>
|
||||
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
interface LoadingModalProps {
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function LoadingModal({ isLoading }: LoadingModalProps) {
|
||||
if (!isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
|
||||
<Card className="border-0 shadow-lg bg-background">
|
||||
<CardContent className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin mr-3" />
|
||||
<span className="text-lg font-medium">Loading</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -2,9 +2,8 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { X, Coins } from 'lucide-react';
|
||||
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
|
||||
|
||||
interface ProofBreakdown {
|
||||
export interface ProofBreakdown {
|
||||
mintUrl: string;
|
||||
denominations: { [key: number]: number };
|
||||
totalBalance: number;
|
||||
@@ -13,20 +12,22 @@ interface ProofBreakdown {
|
||||
interface ProofBreakdownModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
breakdown: ProofBreakdown | null;
|
||||
proofBreakdown: ProofBreakdown | null;
|
||||
}
|
||||
|
||||
export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) {
|
||||
const { convertCurrency } = useCashuBalances(null);
|
||||
|
||||
if (!isOpen || !breakdown) return null;
|
||||
export function ProofBreakdownModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
proofBreakdown,
|
||||
}: ProofBreakdownModalProps) {
|
||||
if (!isOpen || !proofBreakdown) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<Card
|
||||
<Card
|
||||
className="w-full max-w-md border-0 shadow-lg bg-background"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
@@ -44,20 +45,20 @@ export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdo
|
||||
Token Breakdown
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{new URL(breakdown.mintUrl).hostname}
|
||||
{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">
|
||||
{convertCurrency(breakdown.totalBalance)}
|
||||
{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(breakdown.denominations)
|
||||
{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">
|
||||
@@ -71,7 +72,7 @@ export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdo
|
||||
</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>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Download, Zap } from 'lucide-react';
|
||||
|
||||
interface ReceiveCardProps {
|
||||
mode: 'tokens' | 'lightning';
|
||||
tokenInput: string;
|
||||
setTokenInput: (value: string) => void;
|
||||
quoteAmount: string;
|
||||
setQuoteAmount: (value: string) => void;
|
||||
activeMintUrl: string | null;
|
||||
onReceive: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function ReceiveCard({
|
||||
mode,
|
||||
tokenInput,
|
||||
setTokenInput,
|
||||
quoteAmount,
|
||||
setQuoteAmount,
|
||||
activeMintUrl,
|
||||
onReceive,
|
||||
isLoading,
|
||||
}: ReceiveCardProps) {
|
||||
return (
|
||||
<Card className="border-0 shadow-none bg-muted/30">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<Download className="h-5 w-5 mr-2" />
|
||||
Receive
|
||||
</CardTitle>
|
||||
<CardDescription className="min-h-[2.5rem] flex items-center">
|
||||
{mode === 'tokens'
|
||||
? 'Enter Cashu token to redeem'
|
||||
: 'Deposit funds with Lightning'
|
||||
}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{mode === 'tokens' ? (
|
||||
<>
|
||||
{!activeMintUrl && (
|
||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||
Select a mint to receive tokens
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="cashuBo2Ft..."
|
||||
value={tokenInput}
|
||||
onChange={(e) => setTokenInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
|
||||
onReceive();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!activeMintUrl}
|
||||
/>
|
||||
<Button onClick={onReceive} disabled={!tokenInput.trim() || !activeMintUrl || isLoading}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Receive
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{!activeMintUrl && (
|
||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||
Select a mint to create Lightning invoice
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Amount (sats)"
|
||||
type="number"
|
||||
value={quoteAmount}
|
||||
onChange={(e) => setQuoteAmount(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
|
||||
onReceive();
|
||||
}
|
||||
}}
|
||||
disabled={!activeMintUrl}
|
||||
/>
|
||||
<Button onClick={onReceive} disabled={!quoteAmount || !activeMintUrl || isLoading}>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Quote
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertTriangle, X, RefreshCw } from 'lucide-react';
|
||||
import { X, AlertTriangle, RefreshCw } from 'lucide-react';
|
||||
|
||||
interface MintToRemove {
|
||||
export interface MintToRemove {
|
||||
url: string;
|
||||
name?: string;
|
||||
}
|
||||
@@ -10,13 +10,19 @@ interface MintToRemove {
|
||||
interface RemoveMintModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
mint: MintToRemove | null;
|
||||
mintToRemove: MintToRemove | null;
|
||||
onConfirm: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }: RemoveMintModalProps) {
|
||||
if (!isOpen || !mint) return null;
|
||||
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">
|
||||
@@ -40,17 +46,14 @@ export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }:
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="bg-muted p-4 rounded-lg border">
|
||||
<div className="font-medium">{mint.name || new URL(mint.url).hostname}</div>
|
||||
<div className="text-sm text-muted-foreground font-mono break-all">
|
||||
{mint.url}
|
||||
</div>
|
||||
<div 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"
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
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,183 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Send, Zap, Loader2, X } from 'lucide-react';
|
||||
|
||||
interface SendCardProps {
|
||||
mode: 'tokens' | 'lightning';
|
||||
sendAmount: string;
|
||||
setSendAmount: (value: string) => void;
|
||||
lightningInvoice: string;
|
||||
setLightningInvoice: (value: string) => void;
|
||||
lightningAddressInput: string;
|
||||
setLightningAddressInput: (value: string) => void;
|
||||
lightningAddressAmount: string;
|
||||
setLightningAddressAmount: (value: string) => void;
|
||||
pendingLightningAddress: string | null;
|
||||
setPendingLightningAddress: (value: string | null) => void;
|
||||
activeMintUrl: string | null;
|
||||
onSend: () => void;
|
||||
isResolvingAddress: boolean;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function SendCard({
|
||||
mode,
|
||||
sendAmount,
|
||||
setSendAmount,
|
||||
lightningInvoice,
|
||||
setLightningInvoice,
|
||||
lightningAddressInput,
|
||||
setLightningAddressInput,
|
||||
lightningAddressAmount,
|
||||
setLightningAddressAmount,
|
||||
pendingLightningAddress,
|
||||
setPendingLightningAddress,
|
||||
activeMintUrl,
|
||||
onSend,
|
||||
isResolvingAddress,
|
||||
isLoading,
|
||||
}: SendCardProps) {
|
||||
return (
|
||||
<Card className="border-0 shadow-none bg-muted/30">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center">
|
||||
<Send className="h-5 w-5 mr-2" />
|
||||
Send
|
||||
</CardTitle>
|
||||
<CardDescription className="min-h-[2.5rem] flex items-center">
|
||||
{mode === 'tokens'
|
||||
? 'Generate Cashu token to send'
|
||||
: pendingLightningAddress
|
||||
? (
|
||||
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
||||
<span className="font-bold text-primary">Sending to:</span>{' '}
|
||||
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
|
||||
</span>
|
||||
)
|
||||
: 'Pay Lightning invoices or addresses from balance'
|
||||
}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{mode === 'tokens' ? (
|
||||
<>
|
||||
{!activeMintUrl && (
|
||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||
Select a mint to send tokens
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Amount (sats)"
|
||||
type="number"
|
||||
value={sendAmount}
|
||||
onChange={(e) => setSendAmount(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
disabled={!activeMintUrl}
|
||||
/>
|
||||
<Button onClick={onSend} disabled={!sendAmount || !activeMintUrl || isLoading}>
|
||||
<Send className="h-4 w-4 mr-2" />
|
||||
Send
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{!activeMintUrl && (
|
||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||
Select a mint to pay Lightning invoices
|
||||
</div>
|
||||
)}
|
||||
{pendingLightningAddress ? (
|
||||
// Step 2: Show amount input for Lightning address
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Amount (sats)"
|
||||
type="number"
|
||||
value={lightningAddressAmount}
|
||||
onChange={(e) => setLightningAddressAmount(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
disabled={!activeMintUrl}
|
||||
/>
|
||||
<Button
|
||||
onClick={onSend}
|
||||
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
||||
>
|
||||
{isResolvingAddress ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Pay
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setPendingLightningAddress(null);
|
||||
setLightningAddressAmount('');
|
||||
}}
|
||||
className="h-10 w-10"
|
||||
title="Cancel"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// Step 1: Show invoice/address input
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="lnbc... or [email protected]"
|
||||
value={lightningInvoice || lightningAddressInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value.includes('@')) {
|
||||
setLightningAddressInput(value);
|
||||
setLightningInvoice('');
|
||||
} else {
|
||||
setLightningInvoice(value);
|
||||
setLightningAddressInput('');
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={!activeMintUrl}
|
||||
/>
|
||||
<Button
|
||||
onClick={onSend}
|
||||
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
|
||||
>
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Pay
|
||||
</>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,35 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
|
||||
import type { HistoryEntry } from '@/hooks/useCashu';
|
||||
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;
|
||||
isExpanded: boolean;
|
||||
setIsExpanded: (expanded: boolean) => void;
|
||||
// Bitcoin transaction props
|
||||
bitcoinTransactions?: BitcoinTransaction[];
|
||||
isBitcoinLoading?: boolean;
|
||||
showSats?: boolean;
|
||||
}
|
||||
|
||||
export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpanded }: TransactionHistoryProps) {
|
||||
export function TransactionHistory({
|
||||
entries,
|
||||
isLoading,
|
||||
bitcoinTransactions = [],
|
||||
isBitcoinLoading = false,
|
||||
showSats = true
|
||||
}: TransactionHistoryProps) {
|
||||
// Icon indicating transaction type (Lightning vs Cashu)
|
||||
const getTransactionTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
@@ -43,131 +61,166 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
|
||||
const getHistoryLabel = (type: string) => {
|
||||
switch (type) {
|
||||
case 'mint':
|
||||
return 'Mint Tokens';
|
||||
case 'melt':
|
||||
return 'Melt Tokens';
|
||||
case 'send':
|
||||
return 'Send Tokens';
|
||||
case 'receive':
|
||||
return 'Receive Tokens';
|
||||
return 'Received';
|
||||
case 'melt':
|
||||
case 'send':
|
||||
return 'Sent';
|
||||
default:
|
||||
return type;
|
||||
}
|
||||
};
|
||||
|
||||
const getHistoryStateColor = (state?: string) => {
|
||||
if (!state) return 'bg-gray-500';
|
||||
switch (state) {
|
||||
case 'PAID':
|
||||
return 'bg-green-500';
|
||||
case 'UNPAID':
|
||||
return 'bg-yellow-500';
|
||||
case 'PENDING':
|
||||
return 'bg-blue-500';
|
||||
// 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 'bg-gray-500';
|
||||
return 'text-muted-foreground';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="mt-6 border-0 shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<History className="h-5 w-5 mr-2" />
|
||||
Transaction History
|
||||
</div>
|
||||
{entries.length > 3 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
className="gap-1"
|
||||
<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"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
Hide
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
Show
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
View your recent transactions
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<span>Loading history...</span>
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
No transaction history yet
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{(isExpanded ? entries : entries.slice(0, 3)).map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3 flex-1">
|
||||
<div className="mt-1">
|
||||
{getTransactionTypeIcon(entry.type)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium">
|
||||
{getHistoryLabel(entry.type)}
|
||||
</span>
|
||||
{entry.state && entry.type !== 'mint' && entry.type !== 'melt' && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
|
||||
>
|
||||
{entry.state}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
{new URL(entry.mintUrl).hostname}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{new Date(entry.createdAt).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
<div 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="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 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="mt-1">
|
||||
{getDirectionIcon(entry.type)}
|
||||
<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>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createContext, useContext, ReactNode } from 'react';
|
||||
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
|
||||
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/wallet/useCashu';
|
||||
|
||||
const CashuContext = createContext<UseCashuReturn | null>(null);
|
||||
|
||||
@@ -13,13 +13,12 @@ export function CashuProvider({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
export function useCashuContext(): UseCashuReturn {
|
||||
const context = useContext(CashuContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useCashu must be used within a CashuProvider');
|
||||
throw new Error('useCashuContext must be used within a CashuProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,102 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useCashuManager } from './useCashuManager';
|
||||
import { useCashuBalances } from './useCashuBalances';
|
||||
import { useCashuMints } from './useCashuMints';
|
||||
import { useCashuQuotes } from './useCashuQuotes';
|
||||
import { useCashuWallet } from './useCashuWallet';
|
||||
import { useCashuHistory } from './useCashuHistory';
|
||||
import { useCashuSubscriptions } from './useCashuSubscriptions';
|
||||
import { useCashuManagerOperations } from './useCashuManagerOperations';
|
||||
import { UseCashuReturn, CashuWalletError } from './types';
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
const manager = useCashuManager();
|
||||
const balances = useCashuBalances(manager.manager);
|
||||
const mints = useCashuMints(manager.manager);
|
||||
const quotes = useCashuQuotes(manager.manager, manager.repositories);
|
||||
const wallet = useCashuWallet(manager.manager, manager.repositories);
|
||||
const history = useCashuHistory(manager.manager);
|
||||
const subscriptions = useCashuSubscriptions(manager.manager);
|
||||
const managerOperations = useCashuManagerOperations(manager.manager);
|
||||
|
||||
// Combine all errors into a single error state
|
||||
const combinedError = useMemo(() => {
|
||||
const errors = [
|
||||
manager.error,
|
||||
balances.error,
|
||||
mints.error,
|
||||
quotes.error,
|
||||
wallet.error,
|
||||
history.error,
|
||||
subscriptions.error,
|
||||
managerOperations.error,
|
||||
].filter(Boolean) as CashuWalletError[];
|
||||
|
||||
return errors.length > 0 ? errors[0] : null;
|
||||
}, [manager.error, balances.error, mints.error, quotes.error, wallet.error, history.error, subscriptions.error, managerOperations.error]);
|
||||
|
||||
// Combine all loading states
|
||||
const combinedIsLoading = useMemo(() => {
|
||||
return manager.isLoading || balances.isLoading || mints.isLoading || quotes.isLoading || wallet.isLoading || history.isLoading || subscriptions.isLoading || managerOperations.isLoading;
|
||||
}, [manager.isLoading, balances.isLoading, mints.isLoading, quotes.isLoading, wallet.isLoading, history.isLoading, subscriptions.isLoading, managerOperations.isLoading]);
|
||||
|
||||
return {
|
||||
// State
|
||||
isInitialized: manager.isInitialized,
|
||||
isLoading: combinedIsLoading,
|
||||
error: combinedError,
|
||||
balances: balances.balances,
|
||||
mints: mints.mints,
|
||||
mnemonic: manager.mnemonic,
|
||||
|
||||
// Actions
|
||||
// Wallet operations
|
||||
receive: wallet.receive,
|
||||
send: wallet.send,
|
||||
getBalances: balances.getBalances,
|
||||
getProofs: wallet.getProofs,
|
||||
|
||||
// Mint operations
|
||||
addMint: mints.addMint,
|
||||
removeMint: mints.removeMint,
|
||||
getMints: mints.getMints,
|
||||
|
||||
// Quote operations
|
||||
createMintQuote: quotes.createMintQuote,
|
||||
redeemMintQuote: quotes.redeemMintQuote,
|
||||
createMeltQuote: quotes.createMeltQuote,
|
||||
payMeltQuote: quotes.payMeltQuote,
|
||||
addMintQuote: quotes.addMintQuote,
|
||||
|
||||
// Subscription operations
|
||||
awaitMintQuotePaid: subscriptions.awaitMintQuotePaid,
|
||||
awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid,
|
||||
|
||||
// Manager operations
|
||||
enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher,
|
||||
disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher,
|
||||
enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor,
|
||||
disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor,
|
||||
waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor,
|
||||
enableProofStateWatcher: managerOperations.enableProofStateWatcher,
|
||||
disableProofStateWatcher: managerOperations.disableProofStateWatcher,
|
||||
|
||||
// Event operations
|
||||
on: managerOperations.on,
|
||||
once: managerOperations.once,
|
||||
off: managerOperations.off,
|
||||
|
||||
// Mnemonic operations
|
||||
setMnemonic: manager.setMnemonic,
|
||||
generateMnemonic: manager.generateMnemonic,
|
||||
getMnemonic: manager.getMnemonic,
|
||||
|
||||
// History operations
|
||||
getHistory: history.getHistory,
|
||||
|
||||
// Utility operations
|
||||
refreshBalances: balances.refreshBalances,
|
||||
refreshMints: mints.refreshMints,
|
||||
clearError: manager.clearError,
|
||||
};
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
// Error types that align with coco-cashu patterns
|
||||
export class CashuWalletError extends Error {
|
||||
constructor(message: string, public code: string, public details?: unknown) {
|
||||
super(message);
|
||||
this.name = 'CashuWalletError';
|
||||
}
|
||||
}
|
||||
|
||||
export class CashuInitializationError extends CashuWalletError {
|
||||
constructor(message: string, details?: unknown) {
|
||||
super(message, 'INITIALIZATION_ERROR', details);
|
||||
}
|
||||
}
|
||||
|
||||
export class CashuMintError extends CashuWalletError {
|
||||
constructor(message: string, mintUrl: string, details?: unknown) {
|
||||
super(message, 'MINT_ERROR', details);
|
||||
this.mintUrl = mintUrl;
|
||||
}
|
||||
public mintUrl: string;
|
||||
}
|
||||
|
||||
export class CashuQuoteError extends CashuWalletError {
|
||||
constructor(message: string, quoteId: string, details?: unknown) {
|
||||
super(message, 'QUOTE_ERROR', details);
|
||||
this.quoteId = quoteId;
|
||||
}
|
||||
public quoteId: string;
|
||||
}
|
||||
|
||||
export class CashuTokenError extends CashuWalletError {
|
||||
constructor(message: string, token?: string, details?: unknown) {
|
||||
super(message, 'TOKEN_ERROR', details);
|
||||
this.token = token;
|
||||
}
|
||||
public token?: string;
|
||||
}
|
||||
|
||||
// Core types
|
||||
export interface CashuBalance {
|
||||
[mintUrl: string]: number;
|
||||
}
|
||||
|
||||
export interface CashuMint {
|
||||
url: string;
|
||||
name?: string;
|
||||
info?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CashuMintQuote {
|
||||
quote: string;
|
||||
request: string;
|
||||
expiry: number;
|
||||
}
|
||||
|
||||
export interface CashuMeltQuote {
|
||||
quote: string;
|
||||
request: string;
|
||||
expiry: number;
|
||||
}
|
||||
|
||||
export interface CashuToken {
|
||||
mint: string;
|
||||
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
id: string;
|
||||
type: 'mint' | 'melt' | 'send' | 'receive';
|
||||
mintUrl: string;
|
||||
amount: number;
|
||||
unit: string;
|
||||
createdAt: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
quoteId?: string;
|
||||
state?: string;
|
||||
paymentRequest?: string;
|
||||
token?: CashuToken;
|
||||
}
|
||||
|
||||
// Hook state types
|
||||
export interface CashuState {
|
||||
isInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
balances: CashuBalance;
|
||||
mints: CashuMint[];
|
||||
mnemonic: string | null;
|
||||
}
|
||||
|
||||
export interface CashuActions {
|
||||
// Wallet operations
|
||||
receive: (token: string | CashuToken) => Promise<void>;
|
||||
send: (mintUrl: string, amount: number) => Promise<string>;
|
||||
getBalances: () => Promise<CashuBalance>;
|
||||
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
|
||||
|
||||
// Mint operations
|
||||
addMint: (mintUrl: string) => Promise<void>;
|
||||
removeMint: (mintUrl: string) => Promise<void>;
|
||||
getMints: () => Promise<CashuMint[]>;
|
||||
|
||||
// Quote operations
|
||||
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
|
||||
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
|
||||
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
|
||||
// Subscription operations (NEW)
|
||||
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
||||
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
||||
|
||||
// Manager operations (NEW)
|
||||
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
|
||||
disableMintQuoteWatcher: () => Promise<void>;
|
||||
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
|
||||
disableMintQuoteProcessor: () => Promise<void>;
|
||||
waitForMintQuoteProcessor: () => Promise<void>;
|
||||
enableProofStateWatcher: () => Promise<void>;
|
||||
disableProofStateWatcher: () => Promise<void>;
|
||||
|
||||
// Event operations (NEW)
|
||||
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
||||
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
||||
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
|
||||
|
||||
// Mnemonic operations
|
||||
setMnemonic: (mnemonic: string) => void;
|
||||
generateMnemonic: () => string;
|
||||
getMnemonic: () => string | null;
|
||||
|
||||
// History operations
|
||||
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
|
||||
|
||||
// Utility operations
|
||||
refreshBalances: () => Promise<void>;
|
||||
refreshMints: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
export type UseCashuReturn = CashuState & CashuActions;
|
||||
@@ -1,204 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { CashuBalance, CashuWalletError } from './types';
|
||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||
import { toast } from '../useToast';
|
||||
|
||||
export interface UseCashuBalancesReturn {
|
||||
balances: CashuBalance;
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
refreshBalances: () => Promise<void>;
|
||||
getBalances: () => Promise<CashuBalance>;
|
||||
convertCurrency: (sats: number, showSats?: boolean) => string;
|
||||
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
|
||||
}
|
||||
|
||||
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
|
||||
const [balances, setBalances] = useState<CashuBalance>({});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
|
||||
|
||||
// Throttling refs
|
||||
const lastRefreshTimeRef = useRef<number>(0);
|
||||
const isRefreshingRef = useRef<boolean>(false);
|
||||
const REFRESH_THROTTLE_MS = 200;
|
||||
|
||||
const refreshBalances = useCallback(async () => {
|
||||
if (!manager) return;
|
||||
|
||||
// Prevent concurrent calls
|
||||
if (isRefreshingRef.current) {
|
||||
console.log('⏭️ refreshBalances: Skipping (already in progress)');
|
||||
return;
|
||||
}
|
||||
|
||||
// Throttle rapid successive calls
|
||||
const now = Date.now();
|
||||
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
|
||||
console.log('⏭️ refreshBalances: Skipping (throttled)');
|
||||
return;
|
||||
}
|
||||
|
||||
isRefreshingRef.current = true;
|
||||
lastRefreshTimeRef.current = now;
|
||||
|
||||
try {
|
||||
console.log('🔄 refreshBalances: Getting balances from wallet...');
|
||||
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
|
||||
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
|
||||
|
||||
// Only update state if balances actually changed (deep comparison)
|
||||
setBalances(prevBalances => {
|
||||
const hasChanged =
|
||||
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
|
||||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
|
||||
|
||||
if (hasChanged) {
|
||||
console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
|
||||
return newBalances;
|
||||
} else {
|
||||
console.log('⏭️ refreshBalances: Balances unchanged, skipping state update');
|
||||
return prevBalances;
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('❌ refreshBalances: Failed to refresh balances:', err);
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balances';
|
||||
setError(new CashuWalletError(errorMessage, 'BALANCE_REFRESH_ERROR', { originalError: err }));
|
||||
} finally {
|
||||
isRefreshingRef.current = false;
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const getBalances = useCallback(async (): Promise<CashuBalance> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
return await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
|
||||
const cashuError = new CashuWalletError(errorMessage, 'GET_BALANCES_ERROR', { originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
// Set up event listeners for automatic balance updates using coco events
|
||||
useEffect(() => {
|
||||
if (!manager) return;
|
||||
|
||||
const unsubscribeProofsSaved = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:saved', () => {
|
||||
console.log('📨 Proofs saved, refreshing balances...');
|
||||
refreshBalances();
|
||||
});
|
||||
|
||||
const unsubscribeProofsStateChanged = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:state-changed', () => {
|
||||
console.log('🔄 Proofs state changed, refreshing balances...');
|
||||
refreshBalances();
|
||||
});
|
||||
|
||||
const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => {
|
||||
console.log('📤 Send created, refreshing balances...');
|
||||
// Bypass throttling for send operations to ensure immediate balance update
|
||||
setTimeout(async () => {
|
||||
if (!manager) return;
|
||||
try {
|
||||
console.log('🔄 send:created: Getting balances from wallet...');
|
||||
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
|
||||
console.log('💰 send:created: Raw balances from wallet:', newBalances);
|
||||
|
||||
setBalances(prevBalances => {
|
||||
const hasChanged =
|
||||
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
|
||||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
|
||||
|
||||
if (hasChanged) {
|
||||
console.log('✅ send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
|
||||
return newBalances;
|
||||
} else {
|
||||
console.log('⏭️ send:created: Balances unchanged, skipping state update');
|
||||
return prevBalances;
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('❌ send:created: Failed to refresh balances:', err);
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('receive:created', () => {
|
||||
console.log('📥 Receive created, refreshing balances...');
|
||||
refreshBalances();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeProofsSaved();
|
||||
unsubscribeProofsStateChanged();
|
||||
unsubscribeSendCreated();
|
||||
unsubscribeReceiveCreated();
|
||||
};
|
||||
}, [manager, refreshBalances]);
|
||||
|
||||
// Initial balance load
|
||||
useEffect(() => {
|
||||
if (manager && Object.keys(balances).length === 0) {
|
||||
refreshBalances();
|
||||
}
|
||||
}, [manager, balances, refreshBalances]);
|
||||
|
||||
// Fetch exchange rate on mount for fallback
|
||||
useEffect(() => {
|
||||
exchangeRateService.getBtcUsdRate()
|
||||
.then(rate => setFallbackRate(rate))
|
||||
.catch(error => {
|
||||
console.warn('Failed to fetch initial exchange rate:', error);
|
||||
// Keep fallbackRate as null to show sats instead of USD
|
||||
});
|
||||
}, []);
|
||||
|
||||
const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => {
|
||||
if (showSats) {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
} else {
|
||||
// Only show USD if we have a valid exchange rate
|
||||
if (fallbackRate) {
|
||||
const btcAmount = sats / 100000000;
|
||||
const usd = btcAmount * fallbackRate;
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} else {
|
||||
// If no exchange rate available, show sats instead of incorrect USD
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
}
|
||||
}
|
||||
}, [fallbackRate]);
|
||||
|
||||
const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise<string> => {
|
||||
if (showSats) {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
} else {
|
||||
try {
|
||||
const usd = await exchangeRateService.satsToUsd(sats);
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch exchange rate:', error);
|
||||
// If exchange rate fails, show sats instead of incorrect USD
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
balances,
|
||||
isLoading,
|
||||
error,
|
||||
refreshBalances,
|
||||
getBalances,
|
||||
convertCurrency,
|
||||
convertCurrencyAsync,
|
||||
};
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { HistoryEntry, CashuWalletError } from './types';
|
||||
|
||||
export interface UseCashuHistoryReturn {
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
|
||||
}
|
||||
|
||||
export function useCashuHistory(manager: unknown | null): UseCashuHistoryReturn {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
|
||||
const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise<HistoryEntry[]> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
console.log('📜 Getting transaction history...');
|
||||
|
||||
const entries = await (manager as { history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> } }).history.getPaginatedHistory(offset, limit);
|
||||
console.log(`✅ Found ${entries.length} history entries`);
|
||||
|
||||
return entries as unknown as HistoryEntry[];
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
|
||||
console.error('❌ Error getting history:', err);
|
||||
const cashuError = new CashuWalletError(errorMessage, 'GET_HISTORY_ERROR', { limit, offset, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
getHistory,
|
||||
};
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useLocalStorage } from '../useLocalStorage';
|
||||
import * as bip39 from '@scure/bip39';
|
||||
import { wordlist } from '@scure/bip39/wordlists/english';
|
||||
import { CashuInitializationError, CashuWalletError } from './types';
|
||||
|
||||
// Dynamic imports for coco-cashu packages
|
||||
let Manager: unknown = null;
|
||||
let IndexedDbRepositories: unknown = null;
|
||||
let ConsoleLogger: unknown = null;
|
||||
let getEncodedToken: unknown = null;
|
||||
let _getDecodedToken: unknown = null;
|
||||
|
||||
// Lazy load coco-cashu packages
|
||||
const loadCocoCashu = async () => {
|
||||
if (Manager) return; // Already loaded
|
||||
|
||||
try {
|
||||
const coreModule = await import('coco-cashu-core');
|
||||
const indexedDbModule = await import('coco-cashu-indexeddb');
|
||||
|
||||
Manager = coreModule.Manager;
|
||||
ConsoleLogger = coreModule.ConsoleLogger;
|
||||
getEncodedToken = coreModule.getEncodedToken;
|
||||
_getDecodedToken = coreModule.getDecodedToken;
|
||||
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
|
||||
} catch (error) {
|
||||
console.error('Failed to load coco-cashu packages:', error);
|
||||
throw new CashuInitializationError(
|
||||
'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb',
|
||||
{ error }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export interface UseCashuManagerReturn {
|
||||
manager: unknown | null;
|
||||
repositories: unknown | null;
|
||||
isInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
mnemonic: string | null;
|
||||
setMnemonic: (mnemonic: string) => void;
|
||||
generateMnemonic: () => string;
|
||||
getMnemonic: () => string | null;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
export function useCashuManager(): UseCashuManagerReturn {
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
|
||||
// Mnemonic management with localStorage
|
||||
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
||||
|
||||
// Manager instance refs
|
||||
const managerRef = useRef<unknown>(null);
|
||||
const repositoriesRef = useRef<unknown>(null);
|
||||
|
||||
const clearError = useCallback(() => {
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const generateMnemonic = useCallback(() => {
|
||||
return bip39.generateMnemonic(wordlist);
|
||||
}, []);
|
||||
|
||||
const getMnemonic = useCallback(() => {
|
||||
return mnemonic;
|
||||
}, [mnemonic]);
|
||||
|
||||
const setMnemonic = useCallback((newMnemonic: string) => {
|
||||
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
||||
throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC');
|
||||
}
|
||||
setMnemonicState(newMnemonic);
|
||||
// Reinitialize manager with new mnemonic
|
||||
setIsInitialized(false);
|
||||
}, [setMnemonicState]);
|
||||
|
||||
// Initialize the manager
|
||||
const initializeManager = useCallback(async () => {
|
||||
if (isInitialized || isLoading) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await loadCocoCashu();
|
||||
|
||||
// Generate or retrieve mnemonic
|
||||
let currentMnemonic = mnemonic;
|
||||
if (!currentMnemonic) {
|
||||
currentMnemonic = bip39.generateMnemonic(wordlist);
|
||||
setMnemonicState(currentMnemonic);
|
||||
}
|
||||
|
||||
// Create seed from mnemonic
|
||||
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
||||
|
||||
// Initialize repositories
|
||||
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
|
||||
await repositories.init();
|
||||
repositoriesRef.current = repositories;
|
||||
|
||||
// Initialize manager
|
||||
const manager = new (Manager as new (
|
||||
repositories: unknown,
|
||||
seedGetter: () => Promise<Uint8Array>,
|
||||
logger?: unknown
|
||||
) => {
|
||||
wallet: { getBalances: () => Promise<Record<string, number>>; receive: (token: string | unknown) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<unknown> };
|
||||
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
|
||||
quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<unknown>; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>; createMeltQuote: (mintUrl: string, invoice: string) => Promise<unknown>; payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> };
|
||||
history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> };
|
||||
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
|
||||
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
|
||||
enableProofStateWatcher: () => Promise<void>;
|
||||
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
||||
})(
|
||||
repositories,
|
||||
async () => seed,
|
||||
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
|
||||
);
|
||||
managerRef.current = manager;
|
||||
|
||||
// Enable built-in services for automatic quote processing and state watching
|
||||
try {
|
||||
await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true });
|
||||
await manager.enableMintQuoteProcessor();
|
||||
await manager.enableProofStateWatcher();
|
||||
console.log('✅ Enabled coco-cashu watcher services');
|
||||
} catch (err) {
|
||||
console.warn('⚠️ Failed to enable some watcher services:', err);
|
||||
// Don't fail initialization if watchers can't be enabled
|
||||
}
|
||||
|
||||
setIsInitialized(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
|
||||
const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err });
|
||||
setError(cashuError);
|
||||
console.error('Cashu initialization error:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
||||
|
||||
// Initialize on mount and when mnemonic changes
|
||||
useEffect(() => {
|
||||
initializeManager();
|
||||
}, [initializeManager]);
|
||||
|
||||
return {
|
||||
manager: managerRef.current,
|
||||
repositories: repositoriesRef.current,
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
mnemonic,
|
||||
setMnemonic,
|
||||
generateMnemonic,
|
||||
getMnemonic,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
import { useCallback } from 'react';
|
||||
import { CashuWalletError } from './types';
|
||||
|
||||
export interface UseCashuManagerOperationsReturn {
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
|
||||
disableMintQuoteWatcher: () => Promise<void>;
|
||||
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
|
||||
disableMintQuoteProcessor: () => Promise<void>;
|
||||
waitForMintQuoteProcessor: () => Promise<void>;
|
||||
enableProofStateWatcher: () => Promise<void>;
|
||||
disableProofStateWatcher: () => Promise<void>;
|
||||
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
||||
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
||||
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
|
||||
}
|
||||
|
||||
export function useCashuManagerOperations(manager: unknown | null): UseCashuManagerOperationsReturn {
|
||||
const isLoading = false; // Manager operations are typically async but don't have loading states
|
||||
const error = null; // Errors are handled per-operation
|
||||
|
||||
const enableMintQuoteWatcher = useCallback(async (options?: { watchExistingPendingOnStart?: boolean }) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void> }).enableMintQuoteWatcher(options);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote watcher';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteWatcher', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const disableMintQuoteWatcher = useCallback(async () => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { disableMintQuoteWatcher: () => Promise<void> }).disableMintQuoteWatcher();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote watcher';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteWatcher', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const enableMintQuoteProcessor = useCallback(async (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void> }).enableMintQuoteProcessor(options);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote processor';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteProcessor', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const disableMintQuoteProcessor = useCallback(async () => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { disableMintQuoteProcessor: () => Promise<void> }).disableMintQuoteProcessor();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote processor';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteProcessor', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const waitForMintQuoteProcessor = useCallback(async () => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { waitForMintQuoteProcessor: () => Promise<void> }).waitForMintQuoteProcessor();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to wait for mint quote processor';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'waitForMintQuoteProcessor', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const enableProofStateWatcher = useCallback(async () => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { enableProofStateWatcher: () => Promise<void> }).enableProofStateWatcher();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to enable proof state watcher';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableProofStateWatcher', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const disableProofStateWatcher = useCallback(async () => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
await (manager as { disableProofStateWatcher: () => Promise<void> }).disableProofStateWatcher();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to disable proof state watcher';
|
||||
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableProofStateWatcher', originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const on = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
return (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on(event, handler);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add event listener';
|
||||
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'on', event, originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const once = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
return (manager as { once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).once(event, handler);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add one-time event listener';
|
||||
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'once', event, originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const off = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
(manager as { off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void }).off(event, handler);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to remove event listener';
|
||||
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'off', event, originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
enableMintQuoteWatcher,
|
||||
disableMintQuoteWatcher,
|
||||
enableMintQuoteProcessor,
|
||||
disableMintQuoteProcessor,
|
||||
waitForMintQuoteProcessor,
|
||||
enableProofStateWatcher,
|
||||
disableProofStateWatcher,
|
||||
on,
|
||||
once,
|
||||
off,
|
||||
};
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CashuMint, CashuWalletError } from './types';
|
||||
|
||||
export interface UseCashuMintsReturn {
|
||||
mints: CashuMint[];
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
refreshMints: () => Promise<void>;
|
||||
getMints: () => Promise<CashuMint[]>;
|
||||
addMint: (mintUrl: string) => Promise<void>;
|
||||
removeMint: (mintUrl: string) => Promise<void>;
|
||||
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
|
||||
}
|
||||
|
||||
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
|
||||
const [mints, setMints] = useState<CashuMint[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
|
||||
const refreshMints = useCallback(async () => {
|
||||
if (!manager) return;
|
||||
|
||||
try {
|
||||
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
|
||||
const formattedMints = mintList
|
||||
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
|
||||
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
|
||||
url: mint.mintUrl, // Map mintUrl to url for consistency
|
||||
name: mint.name,
|
||||
info: mint.mintInfo
|
||||
}));
|
||||
|
||||
// If no mints exist, add the default mint
|
||||
if (formattedMints.length === 0) {
|
||||
console.log('🔧 No mints found, adding default mint: mint.chorus.community');
|
||||
try {
|
||||
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint('https://mint.chorus.community');
|
||||
// The mint:added event will trigger refreshMints again, so we don't need to set mints here
|
||||
return;
|
||||
} catch (err) {
|
||||
console.warn('⚠️ Failed to add default mint:', err);
|
||||
// Continue with empty mints if default mint fails
|
||||
}
|
||||
}
|
||||
|
||||
setMints(formattedMints);
|
||||
} catch (err) {
|
||||
console.error('Failed to refresh mints:', err);
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh mints';
|
||||
setError(new CashuWalletError(errorMessage, 'MINT_REFRESH_ERROR', { originalError: err }));
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const getMints = useCallback(async (): Promise<CashuMint[]> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
|
||||
return mintList
|
||||
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
|
||||
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
|
||||
url: mint.mintUrl, // Map mintUrl to url for consistency
|
||||
name: mint.name,
|
||||
info: mint.mintInfo
|
||||
}));
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get mints';
|
||||
const cashuError = new CashuWalletError(errorMessage, 'GET_MINTS_ERROR', { originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const addMint = useCallback(async (mintUrl: string) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint(mintUrl);
|
||||
// No need to manually refresh - events will handle it automatically
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
|
||||
const cashuError = new CashuWalletError(errorMessage, 'ADD_MINT_ERROR', { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const removeMint = useCallback(async (mintUrl: string) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Access the mintService directly through the manager to use deleteMint
|
||||
// The manager has a private mintService property that we can access
|
||||
const mintService = (manager as any).mintService;
|
||||
if (!mintService || typeof mintService.deleteMint !== 'function') {
|
||||
throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR');
|
||||
}
|
||||
|
||||
await mintService.deleteMint(mintUrl);
|
||||
|
||||
// No need to manually refresh - events will handle it automatically
|
||||
console.log('✅ Mint removed successfully:', mintUrl);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint';
|
||||
const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
// Set up event listeners for automatic mint updates using coco events
|
||||
useEffect(() => {
|
||||
if (!manager) return;
|
||||
|
||||
const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:added', () => {
|
||||
console.log('➕ Mint added, refreshing mints...');
|
||||
refreshMints();
|
||||
});
|
||||
|
||||
const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:updated', () => {
|
||||
console.log('🔄 Mint updated, refreshing mints...');
|
||||
refreshMints();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeMintAdded();
|
||||
unsubscribeMintUpdated();
|
||||
};
|
||||
}, [manager, refreshMints]);
|
||||
|
||||
// Initial mints load
|
||||
useEffect(() => {
|
||||
if (manager && mints.length === 0) {
|
||||
refreshMints();
|
||||
}
|
||||
}, [manager, mints.length, refreshMints]);
|
||||
|
||||
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
|
||||
if (mint.name && mint.name.trim().length > 0) {
|
||||
// If name looks like a URL, strip protocol as well
|
||||
return mint.name.replace(/^https?:\/\//, '');
|
||||
}
|
||||
try {
|
||||
return new URL(mint.url).host; // host excludes protocol and preserves port if any
|
||||
} catch {
|
||||
// Fallback: manual strip
|
||||
return mint.url.replace(/^https?:\/\//, '');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mints,
|
||||
isLoading,
|
||||
error,
|
||||
refreshMints,
|
||||
getMints,
|
||||
addMint,
|
||||
removeMint,
|
||||
getCleanMintLabel,
|
||||
};
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { CashuMintQuote, CashuMeltQuote, CashuWalletError, CashuQuoteError } from './types';
|
||||
|
||||
export interface UseCashuQuotesReturn {
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
|
||||
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
|
||||
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function useCashuQuotes(manager: unknown | null, repositories: unknown | null): UseCashuQuotesReturn {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
|
||||
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const quote = await (manager as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote> } }).quotes.createMintQuote(mintUrl, amount);
|
||||
return {
|
||||
quote: quote.quote,
|
||||
request: quote.request,
|
||||
expiry: quote.expiry
|
||||
};
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote';
|
||||
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, amount, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
|
||||
console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length);
|
||||
console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl);
|
||||
|
||||
await (manager as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
|
||||
console.log('✅ redeemMintQuote: Quote redeemed successfully');
|
||||
} catch (err) {
|
||||
console.error('❌ redeemMintQuote: Error details:', {
|
||||
message: err instanceof Error ? err.message : 'Unknown error',
|
||||
mintUrl,
|
||||
quoteId,
|
||||
quoteIdType: typeof quoteId,
|
||||
quoteIdLength: quoteId.length
|
||||
});
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote';
|
||||
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
|
||||
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId });
|
||||
|
||||
// Access the mint quote repository
|
||||
const mintQuoteRepo = (repositories as {
|
||||
mintQuoteRepository?: {
|
||||
addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise<void>
|
||||
}
|
||||
})?.mintQuoteRepository;
|
||||
|
||||
if (!mintQuoteRepo) {
|
||||
throw new CashuWalletError('Mint quote repository not available', 'REPOSITORY_NOT_AVAILABLE');
|
||||
}
|
||||
|
||||
// Add the quote to the repository with UNPAID state
|
||||
// The mint processor will check and redeem it
|
||||
await mintQuoteRepo.addMintQuote({
|
||||
quote: quoteId,
|
||||
mintUrl: mintUrl,
|
||||
state: 'UNPAID', // Mark as UNPAID so coco will check it
|
||||
});
|
||||
|
||||
console.log('✅ Mint quote added to repository successfully');
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote';
|
||||
console.error('❌ Error adding mint quote:', err);
|
||||
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager, repositories]);
|
||||
|
||||
const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise<CashuMeltQuote> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const quote = await (manager as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote> } }).quotes.createMeltQuote(mintUrl, invoice);
|
||||
return {
|
||||
quote: quote.quote,
|
||||
request: quote.request,
|
||||
expiry: quote.expiry
|
||||
};
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote';
|
||||
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, invoice, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
await (manager as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.payMeltQuote(mintUrl, quoteId);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
|
||||
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
createMintQuote,
|
||||
redeemMintQuote,
|
||||
createMeltQuote,
|
||||
payMeltQuote,
|
||||
addMintQuote,
|
||||
};
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { useCallback } from 'react';
|
||||
import { CashuWalletError } from './types';
|
||||
|
||||
export interface UseCashuSubscriptionsReturn {
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
||||
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function useCashuSubscriptions(manager: unknown | null): UseCashuSubscriptionsReturn {
|
||||
const isLoading = false; // Subscription operations are typically async but don't have loading states
|
||||
const error = null; // Errors are handled per-operation
|
||||
|
||||
const awaitMintQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
return await (manager as { subscription: { awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMintQuotePaid(mintUrl, quoteId);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to await mint quote payment';
|
||||
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const awaitMeltQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
return await (manager as { subscription: { awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMeltQuotePaid(mintUrl, quoteId);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to await melt quote payment';
|
||||
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
awaitMintQuotePaid,
|
||||
awaitMeltQuotePaid,
|
||||
};
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { CashuToken, CashuWalletError, CashuTokenError } from './types';
|
||||
|
||||
// Dynamic import for getEncodedToken
|
||||
let getEncodedToken: unknown = null;
|
||||
|
||||
const loadGetEncodedToken = async () => {
|
||||
if (getEncodedToken) return;
|
||||
try {
|
||||
const coreModule = await import('coco-cashu-core');
|
||||
getEncodedToken = coreModule.getEncodedToken;
|
||||
} catch (error) {
|
||||
console.error('Failed to load getEncodedToken:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export interface UseCashuWalletReturn {
|
||||
isLoading: boolean;
|
||||
error: CashuWalletError | null;
|
||||
receive: (token: string | CashuToken) => Promise<void>;
|
||||
send: (mintUrl: string, amount: number) => Promise<string>;
|
||||
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
|
||||
}
|
||||
|
||||
export function useCashuWallet(manager: unknown | null, repositories: unknown | null): UseCashuWalletReturn {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
|
||||
const receive = useCallback(async (token: string | CashuToken) => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
await (manager as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).wallet.receive(token);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
|
||||
const cashuError = new CashuTokenError(errorMessage, typeof token === 'string' ? token : undefined, { originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const send = useCallback(async (mintUrl: string, amount: number): Promise<string> => {
|
||||
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Load getEncodedToken if not already loaded
|
||||
await loadGetEncodedToken();
|
||||
|
||||
const token = await (manager as { wallet: { send: (mintUrl: string, amount: number) => Promise<CashuToken> } }).wallet.send(mintUrl, amount);
|
||||
|
||||
// Encode the token into a Cashu token string
|
||||
const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token);
|
||||
return encodedToken;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
|
||||
const cashuError = new CashuWalletError(errorMessage, 'SEND_ERROR', { mintUrl, amount, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager]);
|
||||
|
||||
const getProofs = useCallback(async (mintUrl: string): Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
|
||||
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
|
||||
|
||||
// Access the proof repository
|
||||
const proofRepo = (repositories as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise<Array<Record<string, unknown>>> } })?.proofRepository;
|
||||
if (!proofRepo) {
|
||||
throw new CashuWalletError('Proof repository not available', 'REPOSITORY_NOT_AVAILABLE');
|
||||
}
|
||||
|
||||
// Get ready proofs for this mint (proofs available to spend)
|
||||
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
|
||||
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`);
|
||||
|
||||
return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
|
||||
console.error('❌ Error getting proofs:', err);
|
||||
const cashuError = new CashuWalletError(errorMessage, 'GET_PROOFS_ERROR', { mintUrl, originalError: err });
|
||||
setError(cashuError);
|
||||
throw cashuError;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [manager, repositories]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
receive,
|
||||
send,
|
||||
getProofs,
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export function useAuthor(pubkey: string | undefined) {
|
||||
return { event };
|
||||
}
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
|
||||
retry: 3,
|
||||
});
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// Re-export the new modular useCashu hook and types
|
||||
export { useCashu } from './cashu/index';
|
||||
export type {
|
||||
UseCashuReturn,
|
||||
CashuBalance,
|
||||
CashuMint,
|
||||
CashuMintQuote,
|
||||
CashuMeltQuote,
|
||||
CashuToken,
|
||||
HistoryEntry,
|
||||
CashuWalletError,
|
||||
CashuInitializationError,
|
||||
CashuMintError,
|
||||
CashuQuoteError,
|
||||
CashuTokenError
|
||||
} from './cashu/types';
|
||||
|
||||
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryFn: async (c) => {
|
||||
const filter: NostrFilter = { kinds: [1111] };
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
|
||||
const { logins, setLogin, removeLogin } = useNostrLogin();
|
||||
|
||||
const { data: authors = [] } = useQuery({
|
||||
queryKey: ['logins', logins.map((l) => l.id).join(';')],
|
||||
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
|
||||
queryFn: async ({ signal }) => {
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export interface NIP98Options {
|
||||
url: string;
|
||||
method: string;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for creating NIP-98 HTTP Authentication headers
|
||||
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
|
||||
*/
|
||||
export function useNIP98() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
/**
|
||||
* Create a NIP-98 authorization header for HTTP requests
|
||||
* @param options - The request details (url, method, optional body)
|
||||
* @returns Promise<string> - The "Nostr base64..." authorization header value
|
||||
*/
|
||||
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to create NIP-98 auth header');
|
||||
}
|
||||
|
||||
const { url, method, body } = options;
|
||||
|
||||
// Parse URL to remove query parameters (per NIP-98 spec)
|
||||
const urlObj = new URL(url);
|
||||
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
|
||||
|
||||
const tags: string[][] = [
|
||||
['u', urlWithoutQuery],
|
||||
['method', method.toUpperCase()],
|
||||
];
|
||||
|
||||
// If there's a request body (POST, PUT, PATCH), add payload hash
|
||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
||||
const bodyString = JSON.stringify(body);
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(bodyString);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
tags.push(['payload', payloadHash]);
|
||||
}
|
||||
|
||||
// Create and sign the NIP-98 event (kind 27235)
|
||||
const event = await user.signer.signEvent({
|
||||
kind: 27235,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}) as NostrEvent;
|
||||
|
||||
// Encode the event as base64
|
||||
const eventJson = JSON.stringify(event);
|
||||
const base64Event = btoa(eventJson);
|
||||
|
||||
return `Nostr ${base64Event}`;
|
||||
}, [user]);
|
||||
|
||||
return {
|
||||
createAuthHeader,
|
||||
isLoggedIn: !!user,
|
||||
pubkey: user?.pubkey,
|
||||
signer: user?.signer,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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,62 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import { useToast } from './useToast';
|
||||
|
||||
interface UseQRCodeReturn {
|
||||
generateQRCode: (text: string) => Promise<string>;
|
||||
isGenerating: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for generating QR codes
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { generateQRCode, isGenerating, error } = useQRCode();
|
||||
*
|
||||
* const qrCodeUrl = await generateQRCode('cashuBo2Ft...');
|
||||
* ```
|
||||
*/
|
||||
export function useQRCode(): UseQRCodeReturn {
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const generateQRCode = useCallback(async (text: string): Promise<string> => {
|
||||
setIsGenerating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const qrCodeUrl = await QRCode.toDataURL(text, {
|
||||
width: 256,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF',
|
||||
},
|
||||
});
|
||||
setIsGenerating(false);
|
||||
return qrCodeUrl;
|
||||
} catch (err) {
|
||||
const errorMessage = 'Failed to generate QR code';
|
||||
console.error(errorMessage, err);
|
||||
setError(errorMessage);
|
||||
setIsGenerating(false);
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "QR Code Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
|
||||
return '';
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
return {
|
||||
generateQRCode,
|
||||
isGenerating,
|
||||
error,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
import { useCashu } from '@/hooks/wallet/useCashu';
|
||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||
|
||||
export interface WalletStatus {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
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 +30,7 @@ export function useZaps(
|
||||
|
||||
const author = useAuthor(actualTarget?.pubkey);
|
||||
const { sendPayment, getActiveConnection } = useNWC();
|
||||
const { createMeltQuote, payMeltQuote, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
const [isZapping, setIsZapping] = useState(false);
|
||||
const [invoice, setInvoice] = useState<string | null>(null);
|
||||
|
||||
@@ -258,12 +258,12 @@ export function useZaps(
|
||||
return balance >= amount;
|
||||
});
|
||||
|
||||
if (mintWithBalance) {
|
||||
if (mintWithBalance && coco) {
|
||||
// Create melt quote to convert Cashu tokens to Lightning payment
|
||||
const meltQuote = await createMeltQuote(mintWithBalance.url, newInvoice);
|
||||
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
|
||||
|
||||
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
|
||||
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
||||
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -79,21 +79,49 @@ export function useLightningAddress(): UseLightningAddressReturn {
|
||||
// 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) {
|
||||
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status}`);
|
||||
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();
|
||||
|
||||
if (lnurlData.status !== 'OK') {
|
||||
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}`);
|
||||
}
|
||||
|
||||
@@ -101,11 +129,32 @@ export function useLightningAddress(): UseLightningAddressReturn {
|
||||
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`);
|
||||
}
|
||||
|
||||
@@ -119,26 +168,68 @@ export function useLightningAddress(): UseLightningAddressReturn {
|
||||
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) {
|
||||
throw new Error(`Failed to get invoice: ${invoiceResponse.status}`);
|
||||
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();
|
||||
|
||||
if (invoiceData.status !== 'OK') {
|
||||
throw new Error(invoiceData.reason || 'Invoice generation failed');
|
||||
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 (!invoiceData.pr) {
|
||||
throw new Error('No invoice returned from provider');
|
||||
// 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}`);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
return invoiceData.pr;
|
||||
// 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';
|
||||
@@ -0,0 +1,305 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -98,4 +98,23 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 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
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// ============================================================================
|
||||
// Message Protocol Types
|
||||
// ============================================================================
|
||||
|
||||
export const MESSAGE_PROTOCOL = {
|
||||
NIP04: 'nip04',
|
||||
NIP17: 'nip17',
|
||||
UNKNOWN: 'unknown',
|
||||
} as const;
|
||||
|
||||
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
|
||||
|
||||
// ============================================================================
|
||||
// Protocol Mode (for user selection)
|
||||
// ============================================================================
|
||||
|
||||
export const PROTOCOL_MODE = {
|
||||
NIP04_ONLY: 'nip04_only',
|
||||
NIP17_ONLY: 'nip17_only',
|
||||
NIP04_OR_NIP17: 'nip04_or_nip17',
|
||||
} as const;
|
||||
|
||||
export type ProtocolMode = typeof PROTOCOL_MODE[keyof typeof PROTOCOL_MODE];
|
||||
|
||||
// ============================================================================
|
||||
// Loading Phases
|
||||
// ============================================================================
|
||||
|
||||
export const LOADING_PHASES = {
|
||||
IDLE: 'idle',
|
||||
CACHE: 'cache',
|
||||
RELAYS: 'relays',
|
||||
SUBSCRIPTIONS: 'subscriptions',
|
||||
READY: 'ready',
|
||||
} as const;
|
||||
|
||||
export type LoadingPhase = typeof LOADING_PHASES[keyof typeof LOADING_PHASES];
|
||||
|
||||
// ============================================================================
|
||||
// Protocol Configuration
|
||||
// ============================================================================
|
||||
|
||||
export const PROTOCOL_CONFIG = {
|
||||
[MESSAGE_PROTOCOL.NIP04]: {
|
||||
label: 'NIP-04',
|
||||
description: 'Legacy DMs',
|
||||
kind: 4,
|
||||
},
|
||||
[MESSAGE_PROTOCOL.NIP17]: {
|
||||
label: 'NIP-17',
|
||||
description: 'Private DMs',
|
||||
kind: 1059,
|
||||
},
|
||||
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
||||
label: 'Unknown',
|
||||
description: 'Unknown protocol',
|
||||
kind: 0,
|
||||
},
|
||||
} as const;
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get the message protocol from an event kind
|
||||
*/
|
||||
export function getMessageProtocol(event: NostrEvent): MessageProtocol {
|
||||
switch (event.kind) {
|
||||
case 4:
|
||||
return MESSAGE_PROTOCOL.NIP04;
|
||||
case 1059:
|
||||
return MESSAGE_PROTOCOL.NIP17;
|
||||
default:
|
||||
return MESSAGE_PROTOCOL.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a protocol is valid for sending messages
|
||||
*/
|
||||
export function isValidSendProtocol(protocol: MessageProtocol): boolean {
|
||||
return protocol === MESSAGE_PROTOCOL.NIP04 || protocol === MESSAGE_PROTOCOL.NIP17;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { openDB, type IDBPDatabase } from 'idb';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// ============================================================================
|
||||
// IndexedDB Schema
|
||||
// ============================================================================
|
||||
|
||||
// Use domain-based naming to avoid conflicts between apps on same domain
|
||||
const getDBName = () => {
|
||||
// Use hostname for unique DB per app (e.g., 'nostr-dm-store-localhost', 'nostr-dm-store-myapp.com')
|
||||
const hostname = typeof window !== 'undefined' ? window.location.hostname : 'default';
|
||||
return `nostr-dm-store-${hostname}`;
|
||||
};
|
||||
const DB_NAME = getDBName();
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = 'messages';
|
||||
|
||||
interface StoredParticipant {
|
||||
messages: NostrEvent[];
|
||||
lastActivity: number;
|
||||
hasNIP4: boolean;
|
||||
hasNIP17: boolean;
|
||||
}
|
||||
|
||||
export interface MessageStore {
|
||||
participants: Record<string, StoredParticipant>;
|
||||
lastSync: {
|
||||
nip4: number | null;
|
||||
nip17: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Database Operations
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Open the IndexedDB database
|
||||
*/
|
||||
async function openDatabase(): Promise<IDBPDatabase> {
|
||||
return openDB(DB_NAME, DB_VERSION, {
|
||||
upgrade(db) {
|
||||
// Create the messages store if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
db.createObjectStore(STORE_NAME);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write messages to IndexedDB for a specific user
|
||||
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
||||
*/
|
||||
export async function writeMessagesToDB(
|
||||
userPubkey: string,
|
||||
messageStore: MessageStore
|
||||
): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
|
||||
// Store messages in their original encrypted form (no NIP-44 wrapper needed)
|
||||
// Each message content is already encrypted by the sender
|
||||
await db.put(STORE_NAME, messageStore, userPubkey);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] ❌ Error writing to IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read messages from IndexedDB for a specific user
|
||||
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
||||
*/
|
||||
export async function readMessagesFromDB(
|
||||
userPubkey: string
|
||||
): Promise<MessageStore | undefined> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
const data = await db.get(STORE_NAME, userPubkey);
|
||||
|
||||
if (!data) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return data as MessageStore;
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error reading from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete messages from IndexedDB for a specific user
|
||||
*/
|
||||
export async function deleteMessagesFromDB(userPubkey: string): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
await db.delete(STORE_NAME, userPubkey);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error deleting from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all messages from IndexedDB
|
||||
*/
|
||||
export async function clearAllMessages(): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
await db.clear(STORE_NAME);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error clearing IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Validate that an event is a proper DM event
|
||||
*/
|
||||
export function validateDMEvent(event: NostrEvent): boolean {
|
||||
// Must be kind 4 (NIP-04 DM)
|
||||
if (event.kind !== 4) return false;
|
||||
|
||||
// Must have a 'p' tag
|
||||
const hasRecipient = event.tags?.some(([name]) => name === 'p');
|
||||
if (!hasRecipient) return false;
|
||||
|
||||
// Must have content (even if encrypted)
|
||||
if (!event.content) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the recipient pubkey from a DM event
|
||||
*/
|
||||
export function getRecipientPubkey(event: NostrEvent): string | undefined {
|
||||
return event.tags?.find(([name]) => name === 'p')?.[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the conversation partner pubkey from a DM event
|
||||
* (the other person in the conversation, not the current user)
|
||||
*/
|
||||
export function getConversationPartner(event: NostrEvent, userPubkey: string): string | undefined {
|
||||
const isFromUser = event.pubkey === userPubkey;
|
||||
|
||||
if (isFromUser) {
|
||||
// If we sent it, the partner is the recipient
|
||||
return getRecipientPubkey(event);
|
||||
} else {
|
||||
// If they sent it, the partner is the author
|
||||
return event.pubkey;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format timestamp for display (matches Signal/WhatsApp/Telegram pattern)
|
||||
* Today: Show time (e.g., "2:45 PM")
|
||||
* Yesterday: "Yesterday"
|
||||
* This week: Day name (e.g., "Mon")
|
||||
* This year: Month and day (e.g., "Jan 15")
|
||||
* Older: Full date (e.g., "Jan 15, 2024")
|
||||
*/
|
||||
export function formatConversationTime(timestamp: number): string {
|
||||
const date = new Date(timestamp * 1000);
|
||||
const now = new Date();
|
||||
|
||||
// Start of today (midnight)
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
|
||||
// Start of yesterday
|
||||
const yesterdayStart = new Date(todayStart);
|
||||
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
|
||||
|
||||
// Start of this week (assuming week starts on Sunday, adjust if needed)
|
||||
const weekStart = new Date(todayStart);
|
||||
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
|
||||
|
||||
if (date >= todayStart) {
|
||||
// Today: Show time (e.g., "2:45 PM")
|
||||
return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
|
||||
} else if (date >= yesterdayStart) {
|
||||
// Yesterday
|
||||
return 'Yesterday';
|
||||
} else if (date >= weekStart) {
|
||||
// This week: Show day name (e.g., "Monday")
|
||||
return date.toLocaleDateString(undefined, { weekday: 'short' });
|
||||
} else if (date.getFullYear() === now.getFullYear()) {
|
||||
// This year: Show month and day (e.g., "Jan 15")
|
||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||
} else {
|
||||
// Older: Show full date (e.g., "Jan 15, 2024")
|
||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format timestamp as full date and time for tooltips
|
||||
* e.g., "Mon, Jan 15, 2024, 2:45 PM"
|
||||
*/
|
||||
export function formatFullDateTime(timestamp: number): string {
|
||||
const date = new Date(timestamp * 1000);
|
||||
return date.toLocaleString(undefined, {
|
||||
weekday: 'short',
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,15 @@
|
||||
import Buffer from 'buffer';
|
||||
|
||||
/**
|
||||
* Polyfill for Buffer in browser environment
|
||||
*
|
||||
* Many Node.js libraries like isomorphic-git and bitcoinjs-lib expect Buffer to be globally available.
|
||||
* This polyfill makes the buffer package's Buffer available globally.
|
||||
*/
|
||||
if (!globalThis.Buffer) {
|
||||
globalThis.Buffer = Buffer.Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polyfill for AbortSignal.any()
|
||||
*
|
||||
|
||||
+15
-2
@@ -7,11 +7,24 @@ import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
|
||||
// FIXME: a custom font should be used. Eg:
|
||||
// import '@fontsource-variable/<font-name>';
|
||||
// TODO: Add custom font from @fontsource-variable
|
||||
// Example: 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
@@ -1,6 +1,6 @@
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
|
||||
// TODO: Customize this index page with specific content
|
||||
|
||||
const Index = () => {
|
||||
useSeoMeta({
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
|
||||
const Messages = () => {
|
||||
useSeoMeta({
|
||||
title: 'Messages',
|
||||
description: 'Private encrypted messaging on Nostr',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="container mx-auto p-4 h-screen flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-semibold">Messages</h1>
|
||||
<RelaySelector />
|
||||
</div>
|
||||
|
||||
<DMMessagingInterface className="flex-1" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Messages;
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
|
||||
Reference in new issue
Block a user