mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 16:13:34 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0dca78709 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Admin Configuration
|
||||
# Set this to the npub of the site administrator
|
||||
# Only this user will have access to the admin dashboard at /admin
|
||||
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
|
||||
|
||||
# Example:
|
||||
# VITE_ADMIN_NPUB=npub1sg6plzptd64u62a878hep2kev88swjh3tw00gjsfl8f237lmu63q0uf63m
|
||||
@@ -0,0 +1,170 @@
|
||||
# Site Administration Dashboard
|
||||
|
||||
The MKStack template includes a comprehensive site administration dashboard for content moderation and site management.
|
||||
|
||||
## Access
|
||||
|
||||
The admin dashboard is accessible at `/admin` and requires environment variable configuration.
|
||||
|
||||
**Authentication Required**: Only the site administrator (configured via `VITE_ADMIN_NPUB` environment variable) can access the admin dashboard. Other users will see an access denied message with a login prompt.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set the `VITE_ADMIN_NPUB` environment variable to the npub of the site administrator:
|
||||
|
||||
```bash
|
||||
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
|
||||
```
|
||||
|
||||
See `.env.example` for configuration details.
|
||||
|
||||
## Features
|
||||
|
||||
### Content Moderation Tab
|
||||
- **Recent Content Review**: View and moderate recent posts and articles
|
||||
- **Hide/Show Content**: Quickly hide inappropriate content or restore hidden content
|
||||
- **Content Types**: Distinguishes between notes, articles, and other event kinds
|
||||
- **Author Information**: Shows poster details with avatars and names
|
||||
- **Timestamps**: Recent activity tracking for moderation decisions
|
||||
|
||||
### User Management Tab
|
||||
- **Allow List**: Explicitly allowed users who can post content
|
||||
- **Deny List**: Blocked users who cannot post content
|
||||
- **Add Users**: Add users to allow/deny lists by npub
|
||||
- **User Profiles**: View user avatars, names, and npub identifiers
|
||||
- **Cross-List Management**: Adding to one list removes from the other
|
||||
|
||||
### Blocked Words Tab
|
||||
- **Word Filtering**: Add words and phrases to automatically filter content
|
||||
- **Case Sensitivity**: Toggle case-sensitive matching
|
||||
- **Whole Words**: Option to match whole words only vs partial matches
|
||||
- **Bulk Management**: Add/remove multiple blocked terms
|
||||
- **Real-time Filtering**: Immediate effect on content display
|
||||
|
||||
### Site Analytics Tab
|
||||
- **Content Statistics**: Total events, notes, articles on the site
|
||||
- **User Activity**: Unique authors and active users
|
||||
- **Time-based Metrics**: Activity in last 24 hours and 7 days
|
||||
- **Content Breakdown**: Distribution of different content types
|
||||
- **Growth Tracking**: Monitor site activity trends
|
||||
|
||||
### Site Settings Tab
|
||||
- **Site Information**: Configure site name and description
|
||||
- **Moderation Controls**: Enable/disable content moderation features
|
||||
- **Auto-hide Settings**: Automatically hide content matching blocked words
|
||||
- **Approval Workflow**: Require manual approval for all content
|
||||
- **Environment Status**: View current configuration settings
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Route Configuration
|
||||
The admin route is configured in `AppRouter.tsx` as `/admin` and takes precedence over the generic NIP-19 route.
|
||||
|
||||
### Authentication Flow
|
||||
1. Environment variable `VITE_ADMIN_NPUB` is decoded using `nip19.decode()`
|
||||
2. Current user's pubkey is compared with the admin pubkey
|
||||
3. Unauthorized users see an access denied screen with login options
|
||||
4. Authorized users see the full dashboard interface
|
||||
|
||||
### Data Fetching
|
||||
- Uses TanStack Query for efficient data fetching and caching
|
||||
- Implements proper loading states with skeleton components
|
||||
- Includes error handling and timeout management
|
||||
- Queries recent site content for moderation review
|
||||
- Fetches site-wide analytics and statistics
|
||||
|
||||
### Nostr-Based Storage
|
||||
- Uses custom event kind `39767` for persistent admin policies
|
||||
- Stores all settings as addressable Nostr events
|
||||
- Syncs across devices and browsers automatically
|
||||
- Provides backup and recovery of admin settings
|
||||
- Maintains audit trail of policy changes
|
||||
|
||||
### Components Used
|
||||
- **Tabs**: Organized dashboard sections using shadcn/ui tabs
|
||||
- **Cards**: Statistical displays and content sections
|
||||
- **Badges**: Event type indicators and verification status
|
||||
- **Avatars**: User profile images with fallbacks
|
||||
- **Skeletons**: Loading states that match content structure
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Adding Admin Dashboard Link
|
||||
Use the `AdminDashboardLink` component to add a dashboard link for logged-in users:
|
||||
|
||||
```tsx
|
||||
import { AdminDashboardLink } from '@/components/AdminDashboardLink';
|
||||
|
||||
function Header() {
|
||||
return (
|
||||
<header className="flex items-center justify-between p-4">
|
||||
<h1>My App</h1>
|
||||
<AdminDashboardLink />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Direct Access
|
||||
Site administrators can access the dashboard directly by visiting:
|
||||
```
|
||||
/admin
|
||||
```
|
||||
|
||||
### Setting Up Admin Access
|
||||
To configure admin dashboard access:
|
||||
1. Set `VITE_ADMIN_NPUB` environment variable to your npub
|
||||
2. Log in with the corresponding Nostr account
|
||||
3. Navigate to `/admin`
|
||||
4. The `AdminDashboardLink` component will automatically appear for admin users
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Environment-based Authentication**: Admin access controlled via environment variable
|
||||
- **Single Admin Model**: Only one designated admin per site instance
|
||||
- **Nostr Event Storage**: Admin policies stored as signed Nostr events (kind 39767)
|
||||
- **Cross-Device Sync**: Settings automatically sync across all admin devices
|
||||
- **Content Filtering**: Blocked words and user lists affect content display
|
||||
- **Timeout Protection**: All queries include timeout limits to prevent hanging requests
|
||||
- **No Private Key Access**: Uses existing authentication without requiring private keys
|
||||
- **Event Integrity**: All admin policies are cryptographically signed and verifiable
|
||||
|
||||
## Customization
|
||||
|
||||
The admin dashboard is designed to be easily extensible:
|
||||
|
||||
### Adding New Tabs
|
||||
1. Add a new `TabsTrigger` in the main dashboard component
|
||||
2. Create a corresponding `TabsContent` section
|
||||
3. Implement the tab's functionality as a separate component
|
||||
|
||||
### Extending Content Moderation
|
||||
- **Automated Rules**: Add automatic content filtering based on patterns
|
||||
- **Approval Queues**: Implement content approval workflows
|
||||
- **Bulk Actions**: Add bulk moderation operations
|
||||
- **Moderation History**: Track moderation actions and decisions
|
||||
|
||||
### Advanced User Management
|
||||
- **Role-based Access**: Implement different user permission levels
|
||||
- **Temporary Restrictions**: Time-limited bans or restrictions
|
||||
- **User Reporting**: Allow community reporting of problematic users
|
||||
- **Whitelist/Blacklist Import**: Bulk import of user lists
|
||||
|
||||
### Enhanced Analytics
|
||||
- **Engagement Metrics**: Track user interaction patterns
|
||||
- **Content Performance**: Analyze popular content types
|
||||
- **Moderation Statistics**: Track moderation actions and effectiveness
|
||||
- **Growth Trends**: Monitor site growth and user retention
|
||||
|
||||
## Technical Notes
|
||||
|
||||
- **React Hooks**: Follows React hooks rules with proper conditional rendering
|
||||
- **TypeScript**: Fully typed with proper error handling (with type assertions for nostr-tools)
|
||||
- **Responsive**: Works on mobile and desktop devices
|
||||
- **Accessible**: Uses semantic HTML and ARIA attributes via Radix UI
|
||||
- **Performance**: Implements query caching and loading optimization
|
||||
- **Custom Storage Hook**: `useAdminStorage` for Nostr-based persistence
|
||||
- **Environment Variables**: Requires Vite environment variable configuration
|
||||
- **Icon Library**: Uses Lucide React icons throughout the interface
|
||||
- **Custom NIP**: Implements event kind 39767 for admin storage (see `NIP.md`)
|
||||
- **Content Filtering**: `useContentFilter` hook for policy enforcement
|
||||
@@ -15,12 +15,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/docs/`: Specialized documentation for implementation patterns and features
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/components/wallet/`: Wallet system components including `CashuWallet` (main wallet interface), `WalletHeader` (balance display and mode toggle), `TransactionCard` (send/receive forms), `MintSelector` (mint management), `TransactionHistory` (unified history)
|
||||
- Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
@@ -34,11 +32,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
||||
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history)
|
||||
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing)
|
||||
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider)
|
||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||
- `useZaps`: Lightning zap functionality with payment processing
|
||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
||||
@@ -100,40 +97,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## Documentation
|
||||
|
||||
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
|
||||
|
||||
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
|
||||
|
||||
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
|
||||
|
||||
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
||||
|
||||
- **`docs/CASHU_ZAP_INTEGRATION.md`**: Read when implementing zap functionality, integrating Cashu wallet payments, or building Lightning payment features. Essential for understanding the unified ZapButton architecture and Cashu-powered Lightning zaps. **CRITICAL**: Follow the two-component architecture - `CashuWallet` for standalone wallet management, `ZapButton` for content integration.
|
||||
|
||||
## Cashu Integration Architecture
|
||||
|
||||
**IMPORTANT**: The Cashu wallet integration follows a **two-component architecture** that must be preserved:
|
||||
|
||||
### Component Separation
|
||||
- **`CashuWallet`**: Standalone wallet management interface (dedicated page/route)
|
||||
- **`ZapButton`**: Integrated zap functionality within content feeds
|
||||
|
||||
### Why This Architecture?
|
||||
- **Clean UX**: Users manage wallet separately from consuming content
|
||||
- **Performance**: Wallet operations don't interfere with feed rendering
|
||||
- **Security**: Sensitive wallet operations are isolated
|
||||
- **Mobile Optimization**: Wallet can use full-screen layouts
|
||||
|
||||
### Integration Rules
|
||||
- ✅ **CORRECT**: `CashuWallet` as separate route/page
|
||||
- ✅ **CORRECT**: `ZapButton` embedded in content feeds
|
||||
- ❌ **INCORRECT**: Embedding `CashuWallet` in content feeds
|
||||
- ❌ **INCORRECT**: Mixing wallet management with content consumption
|
||||
|
||||
**Always read `docs/CASHU_ZAP_INTEGRATION.md` before implementing any Cashu-related features.**
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
@@ -141,9 +104,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 NutStack"
|
||||
## "Vibed with 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
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
@@ -151,9 +114,9 @@ This project comes with custom hooks for querying and publishing events on the N
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
@@ -161,7 +124,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
@@ -179,7 +142,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
@@ -318,85 +281,6 @@ function useCustomHook() {
|
||||
}
|
||||
```
|
||||
|
||||
### Connecting to Multiple Nostr Relays
|
||||
|
||||
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
|
||||
|
||||
#### Single Relay Connection
|
||||
|
||||
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useSpecificRelay() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// Connect to a specific relay
|
||||
const relay = nostr.relay('wss://relay.damus.io');
|
||||
|
||||
// Query from this specific relay only
|
||||
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
|
||||
// Publish to this specific relay only
|
||||
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
|
||||
}
|
||||
```
|
||||
|
||||
#### Multiple Relay Group
|
||||
|
||||
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useRelayGroup() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// Create a group of specific relays
|
||||
const relayGroup = nostr.group([
|
||||
'wss://relay.damus.io',
|
||||
'wss://relay.nostr.band',
|
||||
'wss://nos.lol'
|
||||
]);
|
||||
|
||||
// Query from all relays in the group
|
||||
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
|
||||
// Publish to all relays in the group
|
||||
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
|
||||
}
|
||||
```
|
||||
|
||||
#### API Consistency
|
||||
|
||||
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
|
||||
|
||||
- `.query()` - Query events with filters
|
||||
- `.req()` - Create subscriptions
|
||||
- `.event()` - Publish events
|
||||
- All other Nostr protocol methods
|
||||
|
||||
#### Use Cases
|
||||
|
||||
**Single Relay (`nostr.relay()`):**
|
||||
- Testing specific relay behavior
|
||||
- Querying relay-specific content
|
||||
- Debugging connectivity issues
|
||||
- Working with specialized relays
|
||||
|
||||
**Relay Group (`nostr.group()`):**
|
||||
- Querying from trusted relay sets
|
||||
- Publishing to specific communities
|
||||
- Load balancing across relay subsets
|
||||
- Geographic relay optimization
|
||||
|
||||
**Default Pool (`nostr`):**
|
||||
- General application queries
|
||||
- Maximum reach for publishing
|
||||
- Default user experience
|
||||
- Simplified relay management
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
@@ -419,7 +303,71 @@ function usePosts() {
|
||||
}
|
||||
```
|
||||
|
||||
### Efficient Query Design
|
||||
### Infinite Scroll for Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, fetchNextPage]);
|
||||
|
||||
const posts = data?.pages.flat() || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
@@ -459,7 +407,7 @@ const [notes, reposts, genericReposts] = await Promise.all([
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
### Event Validation
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
@@ -530,7 +478,7 @@ function Post({ event }: { event: NostrEvent }) {
|
||||
}
|
||||
```
|
||||
|
||||
### `NostrMetadata` type
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
@@ -769,88 +717,6 @@ function EditProfilePage() {
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Cashu Token System
|
||||
|
||||
NutStack includes comprehensive Cashu token support using the coco-cashu-core library:
|
||||
|
||||
#### Core Architecture
|
||||
- **Token Management**: Uses coco-cashu-core for token operations and proof management
|
||||
- **Mint Operations**: Support for multiple mints with denomination handling
|
||||
- **Token Encoding**: Built-in token encoding/decoding for secure transfers
|
||||
- **Proof Storage**: IndexedDB-based proof storage via coco-cashu-indexeddb
|
||||
|
||||
#### Key Hooks
|
||||
- `useCashu`: Core wallet state, balances, and mint management
|
||||
- `useMintManager`: Mint addition, removal, and denomination display
|
||||
- `useWalletTransactions`: Send/receive token operations
|
||||
- `useHistoryManager`: Transaction history tracking
|
||||
|
||||
#### Npub.cash Integration
|
||||
- **Hosted Mints**: Automatic mint synchronization with npub.cash
|
||||
- **Quote Management**: Real-time quote updates and synchronization
|
||||
- **User Management**: Seamless integration with npub.cash user accounts
|
||||
|
||||
#### Usage Example
|
||||
```tsx
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
|
||||
function WalletComponent() {
|
||||
const { balances, mints, coco } = useCashu();
|
||||
|
||||
// Access token balances across all mints
|
||||
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
|
||||
return <div>Total Balance: {totalBalance} sats</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Bitcoin Integration
|
||||
|
||||
NutStack supports on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys:
|
||||
|
||||
#### Address Derivation
|
||||
- **Taproot P2TR**: Bitcoin addresses generated from Nostr public keys
|
||||
- **Key Conversion**: Automatic conversion from hex pubkey to Bitcoin Taproot address
|
||||
- **NIP-19 Support**: Conversion from npub format to Bitcoin address
|
||||
|
||||
#### Core Functions
|
||||
- `nostrPubkeyToBitcoinAddress()`: Convert Nostr pubkey to Bitcoin Taproot address
|
||||
- `npubToBitcoinAddress()`: Convert npub to Bitcoin address
|
||||
- `fetchUTXOs()`: Get unspent transaction outputs via Blockstream API
|
||||
- `createBitcoinTransaction()`: Build and sign Taproot transactions
|
||||
- `broadcastTransaction()`: Submit transactions to Bitcoin network
|
||||
|
||||
#### Key Hooks
|
||||
- `useBitcoinBalance`: Track Bitcoin balance via UTXO fetching
|
||||
- `useNsecAccess`: Access private key for transaction signing (requires nsec login)
|
||||
|
||||
#### Transaction Flow
|
||||
1. **Address Generation**: Derive Taproot address from Nostr pubkey
|
||||
2. **UTXO Fetching**: Get available outputs from Blockstream API
|
||||
3. **Transaction Building**: Create Taproot transaction with proper fee calculation
|
||||
4. **Signing**: Sign transaction using private key from nsec
|
||||
5. **Broadcasting**: Submit signed transaction to Bitcoin network
|
||||
|
||||
#### Usage Example
|
||||
```tsx
|
||||
import { useBitcoinBalance, useNsecAccess } from '@/hooks';
|
||||
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
||||
|
||||
function BitcoinWallet() {
|
||||
const { user } = useCurrentUser();
|
||||
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
||||
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||
const { data: bitcoinBalance } = useBitcoinBalance(bitcoinAddress);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Bitcoin Address: {bitcoinAddress}</p>
|
||||
<p>Balance: {bitcoinBalance?.balance || 0} sats</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
@@ -917,6 +783,61 @@ export function Post(/* ...props */) {
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
@@ -1017,14 +938,14 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using npm:
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `@fontsource-variable/inter`
|
||||
- For Roboto: `@fontsource/roboto`
|
||||
- For Outfit Variable: `@fontsource-variable/outfit`
|
||||
- For Poppins: `@fontsource/poppins`
|
||||
- For Open Sans: `@fontsource/open-sans`
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
@@ -1077,39 +998,6 @@ When users specify color schemes:
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
### Dialog Component Patterns
|
||||
|
||||
When using Dialog components, always ensure accessibility compliance by including required elements:
|
||||
|
||||
```tsx
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
|
||||
// ✅ Correct - Always include DialogHeader with DialogTitle
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Dialog Title</DialogTitle>
|
||||
<DialogDescription>
|
||||
Optional description for screen readers
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{/* Dialog content */}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
```
|
||||
|
||||
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
|
||||
|
||||
```tsx
|
||||
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
|
||||
|
||||
<DialogHeader>
|
||||
<VisuallyHidden>
|
||||
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
|
||||
</VisuallyHidden>
|
||||
</DialogHeader>
|
||||
```
|
||||
|
||||
## Writing Tests vs Running Tests
|
||||
|
||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
||||
@@ -1130,7 +1018,7 @@ There is an important distinction between **writing new tests** and **running ex
|
||||
### Running Tests (Executing the Test Suite)
|
||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
||||
|
||||
- **You must run the test script** to validate your changes
|
||||
- **You must run the test script** using `js-dev__run_script` tool with the "test" parameter
|
||||
- **Your task is not complete** until the test script passes without errors
|
||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
||||
@@ -1164,26 +1052,10 @@ describe('MyComponent', () => {
|
||||
});
|
||||
```
|
||||
|
||||
## Validating Your Changes
|
||||
## Testing Your Changes
|
||||
|
||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
||||
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
|
||||
### Validation Priority Order
|
||||
|
||||
Run available tools in this priority order:
|
||||
|
||||
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
|
||||
2. **Building/Compilation** (Required): Verify the project builds successfully
|
||||
3. **Linting** (Recommended): Check code style and catch potential issues
|
||||
4. **Tests** (If Available): Run existing test suite
|
||||
5. **Git Commit** (Required): Create a commit with your changes when finished
|
||||
|
||||
**Minimum Requirements:**
|
||||
- Code must type-check without errors
|
||||
- Code must build/compile successfully
|
||||
- Fix any critical linting errors that would break functionality
|
||||
- Create a git commit when your changes are complete
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,179 @@
|
||||
# NIP-XX: Site Administration Events
|
||||
|
||||
## Abstract
|
||||
|
||||
This NIP defines a custom event kind for storing site administration policies and configurations in Nostr applications. It allows site administrators to persist content moderation settings, user access controls, and site configuration across devices and sessions.
|
||||
|
||||
## Specification
|
||||
|
||||
### Event Kind
|
||||
|
||||
This NIP introduces event kind `39767` for site administration data.
|
||||
|
||||
### Event Structure
|
||||
|
||||
Site administration events are **addressable events** that use the `d` tag to identify different configuration categories.
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "<JSON-encoded administration data>",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
],
|
||||
"created_at": <unix timestamp>,
|
||||
"pubkey": "<site administrator's pubkey>"
|
||||
}
|
||||
```
|
||||
|
||||
### Content Schema
|
||||
|
||||
The `content` field contains a JSON object with the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"hiddenEvents": ["<event_id>", "..."],
|
||||
"allowList": ["<pubkey>", "..."],
|
||||
"denyList": ["<pubkey>", "..."],
|
||||
"blockedWords": ["word1", "phrase2", "..."],
|
||||
"caseSensitive": false,
|
||||
"wholeWordsOnly": true,
|
||||
"enableModeration": true,
|
||||
"autoHideBlocked": true,
|
||||
"requireApproval": false,
|
||||
"siteName": "My Nostr Site",
|
||||
"siteDescription": "A description of the site"
|
||||
}
|
||||
```
|
||||
|
||||
#### Field Descriptions
|
||||
|
||||
- **`hiddenEvents`**: Array of event IDs that have been manually hidden by the administrator
|
||||
- **`allowList`**: Array of pubkeys explicitly allowed to post content (if not empty, only these users can post)
|
||||
- **`denyList`**: Array of pubkeys blocked from posting content
|
||||
- **`blockedWords`**: Array of words or phrases that trigger content filtering
|
||||
- **`caseSensitive`**: Boolean indicating whether word filtering is case-sensitive
|
||||
- **`wholeWordsOnly`**: Boolean indicating whether to match whole words only (vs partial matches)
|
||||
- **`enableModeration`**: Boolean to enable/disable all moderation features
|
||||
- **`autoHideBlocked`**: Boolean to automatically hide content matching blocked words
|
||||
- **`requireApproval`**: Boolean to require manual approval for all content
|
||||
- **`siteName`**: String containing the site's display name
|
||||
- **`siteDescription`**: String containing the site's description
|
||||
|
||||
### Usage
|
||||
|
||||
#### Publishing Administration Events
|
||||
|
||||
Site administrators publish these events to store their moderation policies:
|
||||
|
||||
```javascript
|
||||
const adminEvent = {
|
||||
kind: 39767,
|
||||
content: JSON.stringify({
|
||||
hiddenEvents: [],
|
||||
allowList: [],
|
||||
denyList: ["banned_user_pubkey"],
|
||||
blockedWords: ["spam", "inappropriate"],
|
||||
caseSensitive: false,
|
||||
wholeWordsOnly: true,
|
||||
enableModeration: true,
|
||||
autoHideBlocked: true,
|
||||
requireApproval: false,
|
||||
siteName: "My Community",
|
||||
siteDescription: "A moderated Nostr community"
|
||||
}),
|
||||
tags: [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
};
|
||||
```
|
||||
|
||||
#### Querying Administration Events
|
||||
|
||||
Clients query for the latest administration configuration:
|
||||
|
||||
```javascript
|
||||
const adminConfig = await relay.query([{
|
||||
kinds: [39767],
|
||||
authors: [adminPubkey],
|
||||
"#d": ["admin-config"],
|
||||
limit: 1
|
||||
}]);
|
||||
```
|
||||
|
||||
### Implementation Guidelines
|
||||
|
||||
#### Authentication
|
||||
- Only events signed by the designated site administrator's private key are valid
|
||||
- The administrator's pubkey should be configured in the application (e.g., environment variable)
|
||||
- Clients should verify the event signature before applying policies
|
||||
|
||||
#### Content Filtering
|
||||
- **Allow List**: If not empty, only users on this list can post content
|
||||
- **Deny List**: Users on this list are blocked regardless of allow list status
|
||||
- **Blocked Words**: Content containing these words/phrases is filtered according to settings
|
||||
- **Case Sensitivity**: Controls whether word matching is case-sensitive
|
||||
- **Whole Words**: Controls whether to match complete words vs partial strings
|
||||
|
||||
#### Precedence Rules
|
||||
1. Deny list takes precedence over allow list
|
||||
2. Manual hiding (hiddenEvents) takes precedence over automatic filtering
|
||||
3. If moderation is disabled, no filtering is applied
|
||||
|
||||
#### Client Behavior
|
||||
- Clients should cache the latest administration event for performance
|
||||
- Updates to administration policies should be reflected immediately in the UI
|
||||
- Clients may choose to implement additional local filtering beyond these policies
|
||||
|
||||
### Security Considerations
|
||||
|
||||
- Administration events contain sensitive moderation data and should only be published by authorized administrators
|
||||
- The `alt` tag provides human-readable context for the event purpose
|
||||
- Clients should validate the JSON content structure before applying policies
|
||||
- Consider implementing rate limiting for administration event updates
|
||||
|
||||
### Rationale
|
||||
|
||||
This NIP addresses the need for persistent, cross-device site administration in decentralized Nostr applications. By storing policies as Nostr events, administrators can:
|
||||
|
||||
- Maintain consistent moderation across multiple devices
|
||||
- Backup and restore moderation settings
|
||||
- Share administrative responsibilities (with proper key management)
|
||||
- Maintain audit trails of policy changes
|
||||
|
||||
The addressable event structure allows for future expansion with additional configuration categories using different `d` tag values.
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Moderation Setup
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "{\"hiddenEvents\":[],\"allowList\":[],\"denyList\":[\"spam_user_pubkey\"],\"blockedWords\":[\"spam\",\"scam\"],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":true,\"requireApproval\":false,\"siteName\":\"Family-Friendly Community\",\"siteDescription\":\"A safe space for family discussions\"}",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Allowlist-Only Community
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "{\"hiddenEvents\":[],\"allowList\":[\"trusted_user1\",\"trusted_user2\"],\"denyList\":[],\"blockedWords\":[],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":false,\"requireApproval\":true,\"siteName\":\"Private Community\",\"siteDescription\":\"Invitation-only community\"}",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
|
||||
- [NIP-31: Dealing with Unknown Events](https://github.com/nostr-protocol/nips/blob/master/31.md)
|
||||
@@ -1,289 +1,12 @@
|
||||
# NutStack
|
||||
# MKStack
|
||||
|
||||
[](https://shakespeare.diy/clone?url=https://gitlab.com/lemonknowsall/nutstack.git)
|
||||
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## ⚠️ Security Warning
|
||||
## Features
|
||||
|
||||
**This is experimental software. No security audits have been performed. Loss of funds is possible with any AI-coded application using this template.**
|
||||
|
||||
- This software has not been audited for security vulnerabilities
|
||||
- Use at your own risk
|
||||
- Do not store significant amounts of funds in wallets created with this template
|
||||
- Always test with small amounts first
|
||||
- Consider this template for educational and development purposes only
|
||||
|
||||
---
|
||||
|
||||
**The Complete Framework for Building Nostr Clients with AI**
|
||||
|
||||
NutStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, NutStack provides everything you need to create decentralized apps on the Nostr protocol.
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
Build your Nostr app in 3 simple steps:
|
||||
|
||||
### 1. Install & Create
|
||||
```bash
|
||||
npm install -g @getstacks/stacks
|
||||
stacks nutstack
|
||||
```
|
||||
|
||||
### 2. Build with AI
|
||||
```bash
|
||||
stacks agent
|
||||
# Tell Dork AI what you want: "Build a group chat application"
|
||||
```
|
||||
|
||||
### 3. Deploy Instantly
|
||||
```bash
|
||||
npm run deploy
|
||||
# ✅ App deployed to NostrDeploy.com!
|
||||
```
|
||||
|
||||
## ✨ What Makes NutStack Special
|
||||
|
||||
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
|
||||
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
|
||||
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
||||
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
||||
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
|
||||
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), on-chain Bitcoin transactions, Wallet Connect (NIP-47), Npub.cash integration
|
||||
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
|
||||
|
||||
## 🛠 Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: Client-side routing with BrowserRouter
|
||||
- **TanStack Query**: Data fetching, caching, and state management
|
||||
- **TypeScript**: Type-safe JavaScript development
|
||||
|
||||
## 🎯 Real-World Examples
|
||||
|
||||
### Built with One Prompt
|
||||
|
||||
Each of these applications was created with just a single prompt to Dork AI:
|
||||
|
||||
- **Group Chat Application**: `"Build me a group chat application"`
|
||||
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
|
||||
|
||||
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
|
||||
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
|
||||
|
||||
- **Chess Game**: `"Build a chess game with NIP 64"`
|
||||
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
|
||||
|
||||
### Production Apps
|
||||
|
||||
Real Nostr applications built using MKStack:
|
||||
|
||||
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
|
||||
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
|
||||
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
|
||||
|
||||
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
|
||||
|
||||
## 🔧 Core Features
|
||||
|
||||
### Authentication & Users
|
||||
- `LoginArea` component with account switching
|
||||
- `useCurrentUser` hook for authentication state
|
||||
- `useAuthor` hook for fetching user profiles
|
||||
- NIP-07 browser signing support
|
||||
- Multi-account management
|
||||
|
||||
### Nostr Protocol Support
|
||||
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
|
||||
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
|
||||
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47), on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys
|
||||
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
|
||||
|
||||
### Data Management
|
||||
- `useNostr` hook for querying and publishing
|
||||
- `useNostrPublish` hook with automatic client tagging
|
||||
- Event validation and filtering
|
||||
- Infinite scroll with TanStack Query
|
||||
- Multi-relay support
|
||||
|
||||
### Wallet System
|
||||
- `useCashu` hook for Cashu wallet management
|
||||
- `useMintManager` hook for mint operations
|
||||
- `useWalletTransactions` hook for send/receive operations
|
||||
- `useHistoryManager` hook for transaction history
|
||||
- `useBitcoinBalance` hook for Bitcoin UTXO tracking
|
||||
- `useNsecAccess` hook for private key access (Bitcoin signing)
|
||||
- `useNpubCash` hook for Npub.cash API integration
|
||||
|
||||
### UI Components
|
||||
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
||||
- `NoteContent` component for rich text rendering
|
||||
- `EditProfileForm` for profile management
|
||||
- `RelaySelector` for relay switching
|
||||
- `CommentsSection` for threaded discussions
|
||||
- Light/dark theme system
|
||||
|
||||
### Media & Files
|
||||
- `useUploadFile` hook with Blossom server integration
|
||||
- NIP-94 compatible file metadata
|
||||
- Image and video support
|
||||
- File attachment to events
|
||||
|
||||
### Advanced Features
|
||||
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
|
||||
- Cryptographic operations (encryption/decryption)
|
||||
- Lightning payments and zaps
|
||||
- Real-time event subscriptions
|
||||
- Responsive design with mobile support
|
||||
|
||||
## 🤖 AI Development with Dork
|
||||
|
||||
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
|
||||
|
||||
### Supported AI Providers
|
||||
|
||||
Configure your AI provider with `stacks configure`:
|
||||
|
||||
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
|
||||
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
|
||||
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
|
||||
|
||||
### How Dork Works
|
||||
|
||||
- **Context-Aware**: Understands your entire codebase and project structure
|
||||
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
|
||||
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
|
||||
|
||||
Example prompts:
|
||||
```bash
|
||||
"Add user profiles with avatars and bio"
|
||||
"Implement NIP-17 private messaging"
|
||||
"Add a dark mode toggle"
|
||||
"Create a marketplace with NIP-15"
|
||||
```
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/ # UI components
|
||||
│ ├── ui/ # shadcn/ui components (48+ available)
|
||||
│ ├── auth/ # Authentication components
|
||||
│ └── comments/ # Comment system components
|
||||
├── hooks/ # Custom React hooks
|
||||
│ ├── useNostr # Core Nostr integration
|
||||
│ ├── useAuthor # User profile data
|
||||
│ ├── useCurrentUser # Authentication state
|
||||
│ ├── useNostrPublish # Event publishing
|
||||
│ ├── useUploadFile # File uploads
|
||||
│ └── useZaps # Lightning payments
|
||||
├── pages/ # Page components
|
||||
├── lib/ # Utility functions
|
||||
├── contexts/ # React context providers
|
||||
└── test/ # Testing utilities
|
||||
```
|
||||
|
||||
## 🎨 UI Components
|
||||
|
||||
MKStack includes 48+ shadcn/ui components:
|
||||
|
||||
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
|
||||
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
|
||||
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
|
||||
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
|
||||
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
|
||||
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
|
||||
**And many more...
|
||||
|
||||
## 🔐 Security & Best Practices
|
||||
|
||||
- **Never use `any` type**: Always use proper TypeScript types
|
||||
- **Event validation**: Filter events through validator functions for custom kinds
|
||||
- **Efficient queries**: Minimize separate queries to avoid rate limiting
|
||||
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
||||
- **Secure authentication**: Use signer interface, never request private keys directly
|
||||
|
||||
## 💰 Unified Wallet System
|
||||
|
||||
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
|
||||
|
||||
### Three Payment Modes
|
||||
|
||||
- **Tokens Mode**: Cashu token operations with mint management
|
||||
- **Lightning Mode**: Lightning invoice payments, Lightning address support, and zaps
|
||||
- **Bitcoin Mode**: On-chain Bitcoin transactions using Taproot addresses
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Mode Switching**: Seamless switching between payment methods via UI toggle
|
||||
- **Unified Interface**: Single `CashuWallet` component handles all payment types
|
||||
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
|
||||
- **Private Key Access**: Bitcoin transactions require nsec login for transaction signing
|
||||
- **Transaction History**: Unified history tracking across all payment methods
|
||||
- **Mobile Optimized**: Responsive design with drawer/modal patterns for mobile
|
||||
|
||||
### Architecture
|
||||
|
||||
The wallet system uses a component-based architecture:
|
||||
- `CashuWallet` - Main wallet interface with mode switching
|
||||
- `WalletHeader` - Balance display and mode toggle
|
||||
- `TransactionCard` - Send/receive forms for each mode
|
||||
- `MintSelector` - Cashu mint management
|
||||
- `TransactionHistory` - Unified transaction history
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
- Mobile-first approach with Tailwind breakpoints
|
||||
- `useIsMobile` hook for responsive behavior
|
||||
- Touch-friendly interactions
|
||||
- Optimized for all screen sizes
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
- Vitest with jsdom environment
|
||||
- React Testing Library with jest-dom matchers
|
||||
- `TestApp` component provides all necessary context providers
|
||||
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
Built-in deployment to NostrDeploy.com:
|
||||
|
||||
```bash
|
||||
npm run deploy
|
||||
```
|
||||
|
||||
Your app goes live instantly with:
|
||||
- Automatic builds
|
||||
- CDN distribution
|
||||
- HTTPS support
|
||||
- Custom domains available
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
For detailed documentation on building Nostr applications with MKStack:
|
||||
|
||||
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
|
||||
- [Nostr Protocol Documentation](https://nostr.com)
|
||||
- [shadcn/ui Components](https://ui.shadcn.com)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
MKStack is open source and welcomes contributions. The framework is designed to be:
|
||||
|
||||
- **Extensible**: Easy to add new NIPs and features
|
||||
- **Maintainable**: Clean architecture with TypeScript
|
||||
- **Testable**: Comprehensive testing setup included
|
||||
- **Documented**: Clear patterns and examples
|
||||
|
||||
## 📄 License
|
||||
|
||||
Open source - build amazing Nostr applications and help grow the decentralized web!
|
||||
|
||||
---
|
||||
|
||||
**"Vibed with NutStack"** - [Learn more about NutStack](https://soapbox.pub/nutstack)
|
||||
|
||||
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
|
||||
- **Site Administration**: Content moderation and site management dashboard at `/admin` (see [ADMIN_DASHBOARD.md](ADMIN_DASHBOARD.md))
|
||||
- **Nostr Protocol Integration**: Full NIP support with custom hooks for querying and publishing
|
||||
- **Authentication**: Secure login with NIP-07 browser extensions, bunker connections, and secret keys
|
||||
- **UI Components**: 48+ accessible components from shadcn/ui
|
||||
- **Responsive Design**: Mobile-first approach with Tailwind CSS
|
||||
- **Type Safety**: Full TypeScript support with proper error handling
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
### AI Integration with Shakespeare API
|
||||
|
||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
|
||||
|
||||
```tsx
|
||||
import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
|
||||
|
||||
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||
```
|
||||
|
||||
#### Basic Chat Example
|
||||
|
||||
```tsx
|
||||
function AIChat() {
|
||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim()) return;
|
||||
|
||||
const newMessages = [...messages, { role: 'user', content: input }];
|
||||
setMessages(newMessages);
|
||||
setInput('');
|
||||
|
||||
const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
|
||||
setMessages(prev => [...prev, {
|
||||
role: 'assistant',
|
||||
content: response.choices[0].message.content as string
|
||||
}]);
|
||||
};
|
||||
|
||||
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto p-4">
|
||||
{error && <div className="text-red-500 mb-4">{error}</div>}
|
||||
|
||||
<div className="space-y-2 mb-4">
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
||||
<strong>{msg.role}:</strong> {msg.content}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
||||
className="flex-1 p-2 border rounded"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Streaming Chat
|
||||
|
||||
```tsx
|
||||
const [currentResponse, setCurrentResponse] = useState('');
|
||||
|
||||
const handleStreaming = async (content: string) => {
|
||||
setCurrentResponse('');
|
||||
await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
|
||||
setCurrentResponse(prev => prev + chunk);
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
#### Models
|
||||
|
||||
- **`tybalt`**: Free model for development
|
||||
- **`shakespeare`**: Premium model (requires credits)
|
||||
|
||||
#### Key Points
|
||||
|
||||
- User must be logged in with Nostr account
|
||||
- Use `tybalt` for free testing
|
||||
- Handle `isLoading` and `error` states
|
||||
- Check `isAuthenticated` before API calls
|
||||
|
||||
## Implementation Patterns and Best Practices
|
||||
|
||||
### Streaming Response Handling
|
||||
|
||||
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
|
||||
|
||||
```tsx
|
||||
const handleStreamingResponse = async () => {
|
||||
let streamedContent = ''; // ✅ Use local variable to accumulate content
|
||||
|
||||
try {
|
||||
await sendStreamingMessage(messages, model, (chunk) => {
|
||||
streamedContent += chunk; // ✅ Accumulate in local variable
|
||||
setCurrentStreamingMessage(streamedContent); // Update UI
|
||||
});
|
||||
|
||||
// ✅ Save accumulated content to persistent state
|
||||
if (streamedContent.trim()) {
|
||||
const assistantMessage: MessageDisplay = {
|
||||
id: Date.now().toString(),
|
||||
role: 'assistant',
|
||||
content: streamedContent, // ✅ Use accumulated content
|
||||
timestamp: new Date()
|
||||
};
|
||||
setMessages(prev => [...prev, assistantMessage]);
|
||||
}
|
||||
} finally {
|
||||
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Error Boundary Patterns
|
||||
|
||||
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
|
||||
|
||||
```tsx
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
function AIChatWithErrorBoundary() {
|
||||
return (
|
||||
<ErrorBoundary
|
||||
fallback={
|
||||
<div className="p-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Something went wrong with the AI chat. Please refresh the page and try again.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<AIChat />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
// In your AI component, handle specific error types gracefully:
|
||||
function useAIWithErrorHandling() {
|
||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
||||
|
||||
const sendMessage = async (messages: ChatMessage[]) => {
|
||||
try {
|
||||
await sendChatMessage(messages, 'tybalt');
|
||||
} catch (err) {
|
||||
// Handle specific error types with user-friendly messages
|
||||
if (err.message.includes('401')) {
|
||||
throw new Error('Authentication failed. Please log in again.');
|
||||
} else if (err.message.includes('402')) {
|
||||
throw new Error('Insufficient credits. Please add credits to use premium features.');
|
||||
} else if (err.message.includes('network')) {
|
||||
throw new Error('Network error. Please check your internet connection.');
|
||||
}
|
||||
throw err; // Re-throw for error boundary
|
||||
}
|
||||
};
|
||||
|
||||
return { sendMessage, error, clearError };
|
||||
}
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
# Adding Nostr Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
## Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
@@ -1,72 +0,0 @@
|
||||
### Infinite Scroll for Nostr Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
// Remove duplicate events by ID
|
||||
const posts = useMemo(() => {
|
||||
const seen = new Set();
|
||||
return data?.pages.flat().filter(event => {
|
||||
if (!event.id || seen.has(event.id)) return false;
|
||||
seen.add(event.id);
|
||||
return true;
|
||||
}) || [];
|
||||
}, [data?.pages]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -1,613 +0,0 @@
|
||||
# Unified Wallet System for AI Agents (NutStack)
|
||||
|
||||
This document explains how AI agents can easily integrate intelligent Lightning zaps and comprehensive wallet functionality into Nostr clients using the unified NutStack wallet system.
|
||||
|
||||
## Overview
|
||||
|
||||
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
|
||||
|
||||
- **Tokens Mode**: Cashu token operations with mint management
|
||||
- **Lightning Mode**: Lightning invoice payments, Lightning address support, and zaps
|
||||
- **Bitcoin Mode**: On-chain Bitcoin transactions using Taproot addresses
|
||||
|
||||
The `CashuWallet` component provides a complete standalone wallet interface with seamless mode switching, while the `ZapButton` component offers intelligent Lightning zaps with Cashu integration for content feeds.
|
||||
|
||||
### Three-Mode Architecture
|
||||
|
||||
**Tokens Mode**:
|
||||
- Cashu token send/receive operations
|
||||
- Multiple mint management
|
||||
- Token encoding/decoding
|
||||
- Transaction history tracking
|
||||
|
||||
**Lightning Mode**:
|
||||
- Lightning invoice payment processing
|
||||
- Lightning address support
|
||||
- NIP-57 compliant zaps
|
||||
- WebLN/NWC integration
|
||||
|
||||
**Bitcoin Mode**:
|
||||
- On-chain Bitcoin transactions using Taproot addresses
|
||||
- UTXO management via Blockstream API
|
||||
- Fee estimation and transaction building
|
||||
- Requires nsec login for transaction signing
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Three-Mode Wallet**: Complete wallet system supporting Cashu tokens, Lightning, and Bitcoin
|
||||
- **Mode Switching**: Seamless switching between payment methods via UI toggle
|
||||
- **Unified Interface**: Single `CashuWallet` component handles all payment types
|
||||
- **Intelligent Zap Integration**: `ZapButton` automatically prioritizes Cashu balances for zaps
|
||||
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
|
||||
- **Mobile Optimized**: Responsive design with drawer/modal patterns
|
||||
- **Transaction History**: Unified history tracking across all payment methods
|
||||
- **NIP-57 Compliant**: Full compliance with Lightning zap standards
|
||||
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
|
||||
|
||||
## 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!
|
||||
|
||||
### Bitcoin Dependencies
|
||||
|
||||
Add these packages for Bitcoin functionality:
|
||||
|
||||
```bash
|
||||
npm install bitcoinjs-lib @bitcoinerlab/secp256k1 ecpair
|
||||
```
|
||||
|
||||
### Cashu Dependencies
|
||||
|
||||
Add these packages for Cashu token functionality:
|
||||
|
||||
```bash
|
||||
npm install coco-cashu-core coco-cashu-indexeddb @scure/bip39
|
||||
```
|
||||
|
||||
### Npub.cash Dependencies
|
||||
|
||||
Add these packages for npub.cash integration:
|
||||
|
||||
```bash
|
||||
npm install npubcash-sdk npubcash-types
|
||||
```
|
||||
|
||||
### 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} />
|
||||
```
|
||||
|
||||
## CashuWallet Component
|
||||
|
||||
The `CashuWallet` component provides a complete standalone wallet interface supporting all three payment modes:
|
||||
|
||||
### Basic Implementation
|
||||
|
||||
```tsx
|
||||
import { CashuWallet } from '@/components/wallet/CashuWallet';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/wallet" element={<CashuWallet />} />
|
||||
<Route path="/" element={<FeedPage />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Three-Mode System
|
||||
|
||||
The wallet automatically handles mode switching between:
|
||||
|
||||
```tsx
|
||||
// Mode state management
|
||||
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
|
||||
|
||||
// Mode-specific operations
|
||||
if (mode === 'bitcoin') {
|
||||
// Bitcoin transaction handling
|
||||
} else if (mode === 'tokens') {
|
||||
// Cashu token operations
|
||||
} else {
|
||||
// Lightning operations
|
||||
}
|
||||
```
|
||||
|
||||
### Component Architecture
|
||||
|
||||
- **WalletHeader**: Balance display, mode toggle, mint selector
|
||||
- **TransactionCard**: Send/receive forms for each mode
|
||||
- **TransactionHistory**: Unified transaction history
|
||||
- **MintSelector**: Cashu mint management
|
||||
|
||||
### Props and State
|
||||
|
||||
The component manages comprehensive state for all three modes:
|
||||
|
||||
```tsx
|
||||
// Bitcoin state
|
||||
const [bitcoinAmount, setBitcoinAmount] = useState('');
|
||||
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
|
||||
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||
|
||||
// Cashu state
|
||||
const { balances, mints, coco } = useCashu();
|
||||
const { activeMintUrl, setActiveMintUrl } = useMintManager();
|
||||
|
||||
// Lightning state
|
||||
const { getInvoice: getLightningInvoice } = useLightningAddress();
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The component handles common error scenarios:
|
||||
- Insufficient Cashu balance
|
||||
- Lightning address not found
|
||||
- Zap endpoint unavailable
|
||||
- Payment failures
|
||||
|
||||
## Bitcoin Mode
|
||||
|
||||
NutStack supports on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys:
|
||||
|
||||
### Nsec Requirement
|
||||
|
||||
Bitcoin transactions require nsec login to access the private key for transaction signing:
|
||||
|
||||
```tsx
|
||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||
|
||||
function BitcoinTransaction() {
|
||||
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
||||
|
||||
if (!hasNsecAccess) {
|
||||
return <div>Please login with nsec to use Bitcoin features</div>;
|
||||
}
|
||||
|
||||
const privateKey = getPrivateKey();
|
||||
// Use private key for transaction signing
|
||||
}
|
||||
```
|
||||
|
||||
### Address Derivation
|
||||
|
||||
Bitcoin addresses are automatically derived from Nostr public keys:
|
||||
|
||||
```tsx
|
||||
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
|
||||
|
||||
// From hex pubkey
|
||||
const bitcoinAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
|
||||
|
||||
// From npub format
|
||||
const bitcoinAddress = npubToBitcoinAddress('npub1...');
|
||||
```
|
||||
|
||||
### Send/Receive Flow
|
||||
|
||||
```tsx
|
||||
import { useBitcoinBalance } from '@/hooks/useBitcoinBalance';
|
||||
import { fetchUTXOs, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin';
|
||||
|
||||
function BitcoinSend() {
|
||||
const { data: bitcoinBalance, refetch } = useBitcoinBalance(bitcoinAddress);
|
||||
|
||||
const handleSend = async (amount: number, recipient: string) => {
|
||||
// Fetch UTXOs and fee rates
|
||||
const [utxos, feeRates] = await Promise.all([
|
||||
fetchUTXOs(bitcoinAddress),
|
||||
getFeeRates()
|
||||
]);
|
||||
|
||||
// Create and sign transaction
|
||||
const { txHex, fee } = await createBitcoinTransaction(
|
||||
privateKey,
|
||||
recipient,
|
||||
amount,
|
||||
utxos,
|
||||
feeRates.fastestFee
|
||||
);
|
||||
|
||||
// Broadcast transaction
|
||||
const txId = await broadcastTransaction(txHex);
|
||||
|
||||
// Refresh balance
|
||||
refetch();
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### UTXO Management
|
||||
|
||||
The system automatically handles UTXO selection and fee calculation:
|
||||
|
||||
- **UTXO Fetching**: Uses Blockstream API to get unspent outputs
|
||||
- **Fee Estimation**: Dynamic fee calculation based on network conditions
|
||||
- **Change Handling**: Automatic change output creation when needed
|
||||
- **Dust Limit**: Respects Bitcoin dust limit (546 sats)
|
||||
|
||||
### Blockstream API Integration
|
||||
|
||||
```tsx
|
||||
// Fetch UTXOs
|
||||
const utxos = await fetchUTXOs(address);
|
||||
|
||||
// Get fee rates
|
||||
const feeRates = await getFeeRates();
|
||||
// Returns: { fastestFee, halfHourFee, hourFee, economyFee, minimumFee }
|
||||
|
||||
// Broadcast transaction
|
||||
const txId = await broadcastTransaction(txHex);
|
||||
```
|
||||
|
||||
## 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
|
||||
- [ ] **Bitcoin Setup**:
|
||||
- [ ] Install Bitcoin dependencies: `bitcoinjs-lib`, `@bitcoinerlab/secp256k1`, `ecpair`
|
||||
- [ ] Import Bitcoin utility functions from `@/lib/bitcoin`
|
||||
- [ ] Ensure user login with nsec for Bitcoin features
|
||||
- [ ] Test Bitcoin send/receive with Taproot addresses
|
||||
- [ ] Verify UTXO fetching and balance display
|
||||
- [ ] **Cashu Setup**:
|
||||
- [ ] Install Cashu dependencies: `coco-cashu-core`, `coco-cashu-indexeddb`, `@scure/bip39`
|
||||
- [ ] Initialize coco-cashu-core with mnemonic
|
||||
- [ ] Add mint management UI
|
||||
- [ ] Test token send/receive flows
|
||||
- [ ] Verify npub.cash integration (optional)
|
||||
- [ ] 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 wallet experience that automatically selects the best available payment method while leveraging the benefits of Cashu tokens, Lightning payments, and on-chain Bitcoin transactions.
|
||||
Generated
+1322
-1663
File diff suppressed because it is too large.
Load diff
+5
-9
@@ -4,9 +4,9 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm i --legacy-peer-deps --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
||||
"dev": "npm i && vite",
|
||||
"build": "npm i && vite build && cp dist/index.html dist/404.html",
|
||||
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -42,21 +42,17 @@
|
||||
"@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",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"coco-cashu-core": "1.0.0-rc10",
|
||||
"coco-cashu-indexeddb": "0.8.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"lucide-react": "^0.542.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",
|
||||
@@ -69,6 +65,7 @@
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.71"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -83,7 +80,6 @@
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"@webbtc/webln-types": "^3.0.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 282 KiB |
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "NutStack",
|
||||
"short_name": "NutStack",
|
||||
"description": "Nostr application with Cashu wallet integration",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#000000",
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// public/sw.js
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
if (!event.data) return;
|
||||
|
||||
try {
|
||||
const data = event.data.json();
|
||||
|
||||
const title = data.title || "New Notification";
|
||||
const options = {
|
||||
body: data.body,
|
||||
icon: data.icon || "/icon-192.png"
|
||||
// badge: data.badge || "/badge-72x72.png",
|
||||
// data: data.data || {},
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(title, options)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("Push event error:", err);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
|
||||
// If you send a `url` in payload.data, open it
|
||||
const url = event.notification.data?.url;
|
||||
if (url) {
|
||||
event.waitUntil(clients.openWindow(url));
|
||||
}
|
||||
});
|
||||
+1
-1
@@ -31,7 +31,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
};
|
||||
|
||||
|
||||
+3
-2
@@ -3,8 +3,8 @@ import { ScrollToTop } from "./components/ScrollToTop";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import { AdminDashboard } from "./pages/AdminDashboard";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { CashuWallet } from "./components/wallet/CashuWallet";
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
@@ -12,7 +12,8 @@ export function AppRouter() {
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/wallet" element={<CashuWallet />} />
|
||||
{/* Admin dashboard route - must come before NIP-19 route */}
|
||||
<Route path="/admin" element={<AdminDashboard />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Shield } from 'lucide-react';
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export function AdminDashboardLink() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Only show admin link if user is the configured admin
|
||||
if (!user || !ADMIN_NPUB) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let adminPubkey: string = '';
|
||||
try {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only show if current user is the admin
|
||||
if (user.pubkey !== adminPubkey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href="/admin" className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4" />
|
||||
Site Admin
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, forwardRef } from 'react';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X, Coins } from 'lucide-react';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -26,13 +26,11 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||
|
||||
interface LightningWalletModalProps {
|
||||
interface WalletModalProps {
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
@@ -70,59 +68,30 @@ AddWalletContent.displayName = 'AddWalletContent';
|
||||
|
||||
// Extracted WalletContent to prevent re-renders
|
||||
const WalletContent = forwardRef<HTMLDivElement, {
|
||||
webln: WebLNProvider | null;
|
||||
hasWebLN: boolean;
|
||||
isDetecting: boolean;
|
||||
hasNWC: boolean;
|
||||
connections: NWCConnection[];
|
||||
connectionInfo: Record<string, NWCInfo>;
|
||||
activeConnection: string | null;
|
||||
cashuBalance: number;
|
||||
isCashuInitialized: boolean;
|
||||
handleSetActive: (cs: string) => void;
|
||||
handleRemoveConnection: (cs: string) => void;
|
||||
setAddDialogOpen: (open: boolean) => void;
|
||||
}>(({
|
||||
webln,
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
cashuBalance,
|
||||
isCashuInitialized,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen
|
||||
}, ref) => (
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Primary Payment Method - Cashu */}
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Primary Wallet</h3>
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
|
||||
<div className="flex items-center gap-3">
|
||||
<Coins className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Cashu Wallet</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isCashuInitialized
|
||||
? `${cashuBalance.toLocaleString()} sats available`
|
||||
: "Instant Bitcoin payments"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isCashuInitialized && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={isCashuInitialized ? "default" : "secondary"} className="text-xs">
|
||||
{isCashuInitialized ? "Active" : "Not Set Up"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Lightning Fallback Methods */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Other Options</h3>
|
||||
<h3 className="font-medium">Current Status</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
@@ -134,9 +103,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
|
||||
{webln ? "Ready" : "Not Found"}
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
@@ -222,12 +191,12 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!isCashuInitialized && !webln && connections.length === 0 && (
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning
|
||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
@@ -236,7 +205,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
));
|
||||
WalletContent.displayName = 'WalletContent';
|
||||
|
||||
export function LightningWalletModal({ children, className }: LightningWalletModalProps) {
|
||||
export function WalletModal({ children, className }: WalletModalProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [connectionUri, setConnectionUri] = useState('');
|
||||
@@ -253,11 +222,9 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { webln } = useWallet();
|
||||
const { balances, isInitialized: isCashuInitialized } = useCashu();
|
||||
const { hasWebLN, isDetecting } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleAddConnection = async () => {
|
||||
@@ -296,13 +263,12 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
};
|
||||
|
||||
const walletContentProps = {
|
||||
webln,
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
cashuBalance,
|
||||
isCashuInitialized,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen,
|
||||
@@ -344,7 +310,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Payment Settings
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
@@ -358,10 +324,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
</DrawerClose>
|
||||
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Payment Settings
|
||||
Lightning Wallet
|
||||
</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Manage wallet methods for zaps
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="overflow-y-auto">
|
||||
@@ -406,7 +372,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Payment Settings
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
@@ -414,10 +380,10 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Payment Settings
|
||||
Lightning Wallet
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Manage wallet methods for zaps
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<WalletContent {...walletContentProps} />
|
||||
|
||||
+21
-528
@@ -1,40 +1,10 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||
|
||||
interface ZapButtonProps {
|
||||
target: Event;
|
||||
@@ -43,276 +13,15 @@ interface ZapButtonProps {
|
||||
zapData?: { count: number; totalSats: number; isLoading?: boolean };
|
||||
}
|
||||
|
||||
const presetAmounts = [
|
||||
{ amount: 1, icon: Sparkle },
|
||||
{ amount: 50, icon: Sparkles },
|
||||
{ amount: 100, icon: Zap },
|
||||
{ amount: 250, icon: Star },
|
||||
{ amount: 1000, icon: Rocket },
|
||||
];
|
||||
|
||||
interface ZapContentProps {
|
||||
invoice: string | null;
|
||||
amount: number | string;
|
||||
comment: string;
|
||||
isZapping: boolean;
|
||||
qrCodeUrl: string;
|
||||
copied: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
canPayWithCashu: boolean;
|
||||
cashuBalance: number;
|
||||
handleZap: () => void;
|
||||
handleCopy: () => void;
|
||||
openInWallet: () => void;
|
||||
setAmount: (amount: number | string) => void;
|
||||
setComment: (comment: string) => void;
|
||||
inputRef: React.RefObject<HTMLInputElement>;
|
||||
zap: (amount: number, comment: string) => void;
|
||||
}
|
||||
|
||||
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
canPayWithCashu,
|
||||
cashuBalance,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
}, ref) => (
|
||||
<div ref={ref}>
|
||||
{invoice ? (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
{/* Payment amount display */}
|
||||
<div className="text-center pt-4">
|
||||
<div className="text-2xl font-bold">{amount} sats</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
|
||||
{/* QR Code */}
|
||||
<div className="flex justify-center">
|
||||
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
|
||||
<CardContent className="p-0 flex justify-center">
|
||||
{qrCodeUrl ? (
|
||||
<img
|
||||
src={qrCodeUrl}
|
||||
alt="Lightning Invoice QR Code"
|
||||
className="w-full h-auto aspect-square max-w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Invoice input */}
|
||||
<div className="space-y-2 mt-4">
|
||||
<Label htmlFor="invoice">Lightning Invoice</Label>
|
||||
<div className="flex gap-2 min-w-0">
|
||||
<Input
|
||||
id="invoice"
|
||||
value={invoice}
|
||||
readOnly
|
||||
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
|
||||
onClick={(e) => e.currentTarget.select()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleCopy}
|
||||
className="shrink-0"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="space-y-3 mt-4">
|
||||
{/* Primary Lightning payment button - powered by Cashu when available */}
|
||||
<Button
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
}}
|
||||
disabled={isZapping}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
{canPayWithCashu ? (
|
||||
<>
|
||||
<Coins className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : "Pay with Lightning"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* WebLN fallback button */}
|
||||
{webln && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
}}
|
||||
disabled={isZapping}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : "Pay with WebLN"}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={openInWallet}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open in Lightning Wallet
|
||||
</Button>
|
||||
|
||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||
{canPayWithCashu
|
||||
? "Pay Lightning invoice using your Cashu token balance, or scan QR code manually."
|
||||
: "Scan the QR code or copy the invoice to pay with any Lightning wallet."
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Cashu balance indicator */}
|
||||
{canPayWithCashu && (
|
||||
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
|
||||
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Coins className="h-4 w-4" />
|
||||
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={String(amount)}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
setAmount(parseInt(value, 10));
|
||||
}
|
||||
}}
|
||||
className="grid grid-cols-5 gap-1 w-full"
|
||||
>
|
||||
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
|
||||
<ToggleGroupItem
|
||||
key={presetAmount}
|
||||
value={String(presetAmount)}
|
||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||
disabled={canPayWithCashu && presetAmount > cashuBalance}
|
||||
>
|
||||
<Icon className="h-4 w-4 mb-1" />
|
||||
<span className="truncate">{presetAmount}</span>
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
<span className="text-xs text-muted-foreground">OR</span>
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
</div>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id="custom-amount"
|
||||
type="number"
|
||||
placeholder="Custom amount"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
className="w-full text-sm"
|
||||
max={canPayWithCashu ? cashuBalance : undefined}
|
||||
/>
|
||||
<Textarea
|
||||
id="custom-comment"
|
||||
placeholder="Add a comment (optional)"
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
className="w-full resize-none text-sm"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="px-4 pb-4">
|
||||
<Button
|
||||
onClick={handleZap}
|
||||
className="w-full"
|
||||
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
|
||||
size="default"
|
||||
>
|
||||
{isZapping ? (
|
||||
'Creating Lightning invoice...'
|
||||
) : canPayWithCashu ? (
|
||||
<>
|
||||
<Coins className="h-4 w-4 mr-2" />
|
||||
Zap {amount} sats (Cashu → Lightning)
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Zap {amount} sats
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
ZapContent.displayName = 'ZapContent';
|
||||
|
||||
export function ZapButton({
|
||||
target,
|
||||
className = "text-xs ml-1",
|
||||
showCount = true,
|
||||
zapData: externalZapData
|
||||
}: ZapButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target?.pubkey || '');
|
||||
const { toast } = useToast();
|
||||
const { webln, activeNWC } = useWallet();
|
||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
const [amount, setAmount] = useState<number | string>(100);
|
||||
const [comment, setComment] = useState<string>('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
// Check if Cashu wallet is available and has balance
|
||||
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
|
||||
// Only fetch data if not provided externally
|
||||
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
||||
@@ -321,245 +30,29 @@ export function ZapButton({
|
||||
activeNWC
|
||||
);
|
||||
|
||||
// Use external data if provided, otherwise use fetched data
|
||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
||||
const showLoading = externalZapData?.isLoading || isLoading;
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
// Generate QR code
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
|
||||
const generateQR = async () => {
|
||||
if (!invoice) {
|
||||
setQrCodeUrl('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
|
||||
width: 512,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF',
|
||||
},
|
||||
});
|
||||
|
||||
if (!isCancelled) {
|
||||
setQrCodeUrl(url);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isCancelled) {
|
||||
console.error('Failed to generate QR code:', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
generateQR();
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
};
|
||||
}, [invoice]);
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (invoice) {
|
||||
await navigator.clipboard.writeText(invoice);
|
||||
setCopied(true);
|
||||
toast({
|
||||
title: 'Invoice copied',
|
||||
description: 'Lightning invoice copied to clipboard',
|
||||
});
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const openInWallet = () => {
|
||||
if (invoice) {
|
||||
const lightningUrl = `lightning:${invoice}`;
|
||||
window.open(lightningUrl, '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
} else {
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
}, [open, setInvoice]);
|
||||
|
||||
const handleZap = () => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
if (canPayWithCashu && finalAmount > cashuBalance) {
|
||||
toast({
|
||||
title: 'Insufficient Cashu balance',
|
||||
description: `You only have ${cashuBalance} sats available.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
zap(finalAmount, comment);
|
||||
};
|
||||
|
||||
const contentProps = {
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
canPayWithCashu,
|
||||
cashuBalance,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
};
|
||||
|
||||
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
||||
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
dismissible={true}
|
||||
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
|
||||
activeSnapPoint={invoice ? 0.98 : 0.98}
|
||||
modal={true}
|
||||
shouldScaleBackground={false}
|
||||
fadeFromIndex={0}
|
||||
>
|
||||
<DrawerTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
<div className="flex items-center gap-1">
|
||||
<Zap className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{showLoading ? (
|
||||
'...'
|
||||
) : showCount && totalSats > 0 ? (
|
||||
`${totalSats.toLocaleString()}`
|
||||
) : (
|
||||
'Zap'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent
|
||||
key={invoice ? 'payment' : 'form'}
|
||||
className={cn(
|
||||
"transition-all duration-300",
|
||||
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
|
||||
)}
|
||||
data-testid="zap-modal"
|
||||
>
|
||||
<DrawerHeader className="text-center relative">
|
||||
{/* Back button when showing invoice */}
|
||||
{invoice && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setInvoice(null);
|
||||
setQrCodeUrl('');
|
||||
}}
|
||||
className="absolute left-4 top-4 flex items-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Close button */}
|
||||
<DrawerClose asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-4 top-4"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DrawerClose>
|
||||
|
||||
<DrawerTitle className="text-lg break-words pt-2">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DrawerTitle>
|
||||
<DrawerDescription className="text-sm break-words text-center">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
canPayWithCashu
|
||||
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
)}
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="flex-1 overflow-y-auto px-4 pb-4">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
// Use external data if provided, otherwise use fetched data
|
||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
||||
const showLoading = externalZapData?.isLoading || isLoading;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
<div className="flex items-center gap-1">
|
||||
<Zap className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{showLoading ? (
|
||||
'...'
|
||||
) : showCount && totalSats > 0 ? (
|
||||
`${totalSats.toLocaleString()}`
|
||||
) : (
|
||||
'Zap'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg break-words">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-center break-words">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
canPayWithCashu
|
||||
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<ZapDialog target={target}>
|
||||
<div className={`flex items-center gap-1 ${className}`}>
|
||||
<Zap className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{showLoading ? (
|
||||
'...'
|
||||
) : showCount && totalSats > 0 ? (
|
||||
`${totalSats.toLocaleString()}`
|
||||
) : (
|
||||
'Zap'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</ZapDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X, Coins } from 'lucide-react';
|
||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
@@ -30,11 +30,9 @@ import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||
|
||||
interface ZapDialogProps {
|
||||
target: Event;
|
||||
@@ -57,10 +55,7 @@ interface ZapContentProps {
|
||||
isZapping: boolean;
|
||||
qrCodeUrl: string;
|
||||
copied: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
// Cashu-related props
|
||||
canPayWithCashu: boolean;
|
||||
cashuBalance: number;
|
||||
hasWebLN: boolean;
|
||||
handleZap: () => void;
|
||||
handleCopy: () => void;
|
||||
openInWallet: () => void;
|
||||
@@ -78,9 +73,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
canPayWithCashu,
|
||||
cashuBalance,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
@@ -145,33 +138,8 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="space-y-3 mt-4">
|
||||
{/* Primary Lightning payment button - powered by Cashu when available */}
|
||||
<Button
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
}}
|
||||
disabled={isZapping}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
{canPayWithCashu ? (
|
||||
<>
|
||||
<Coins className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : `Pay with Cashu (${cashuBalance.toLocaleString()} sats)`}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : "Pay with Lightning"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* WebLN fallback button */}
|
||||
{webln && (
|
||||
{hasWebLN && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
@@ -196,26 +164,13 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
</Button>
|
||||
|
||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||
{canPayWithCashu
|
||||
? "Pay Lightning invoice using your Cashu token balance, or scan QR code manually."
|
||||
: "Scan the QR code or copy the invoice to pay with any Lightning wallet."
|
||||
}
|
||||
Scan the QR code or copy the invoice to pay with any Lightning wallet.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Cashu balance indicator */}
|
||||
{canPayWithCashu && (
|
||||
<div className="text-center mb-4 p-3 bg-muted/30 rounded-lg mx-4">
|
||||
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Coins className="h-4 w-4" />
|
||||
<span>Pay with Cashu Balance: {cashuBalance.toLocaleString()} sats</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
@@ -232,7 +187,6 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
key={presetAmount}
|
||||
value={String(presetAmount)}
|
||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||
disabled={canPayWithCashu && presetAmount > cashuBalance}
|
||||
>
|
||||
<Icon className="h-4 w-4 mb-1" />
|
||||
<span className="truncate">{presetAmount}</span>
|
||||
@@ -252,7 +206,6 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
className="w-full text-sm"
|
||||
max={canPayWithCashu ? cashuBalance : undefined}
|
||||
/>
|
||||
<Textarea
|
||||
id="custom-comment"
|
||||
@@ -264,19 +217,9 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
/>
|
||||
</div>
|
||||
<div className="px-4 pb-4">
|
||||
<Button
|
||||
onClick={handleZap}
|
||||
className="w-full"
|
||||
disabled={isZapping || (canPayWithCashu && (typeof amount === 'string' ? parseInt(amount, 10) : amount) > cashuBalance)}
|
||||
size="default"
|
||||
>
|
||||
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
|
||||
{isZapping ? (
|
||||
'Creating Lightning invoice...'
|
||||
) : canPayWithCashu ? (
|
||||
<>
|
||||
<Coins className="h-4 w-4 mr-2" />
|
||||
Zap {amount} sats (Cashu → Lightning)
|
||||
</>
|
||||
'Creating invoice...'
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
@@ -291,14 +234,14 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
));
|
||||
ZapContent.displayName = 'ZapContent';
|
||||
|
||||
|
||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target.pubkey);
|
||||
const { toast } = useToast();
|
||||
const { webln, activeNWC } = useWallet();
|
||||
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
|
||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
const [amount, setAmount] = useState<number | string>(100);
|
||||
const [comment, setComment] = useState<string>('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
@@ -306,16 +249,19 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
// Check if Cashu wallet is available and has balance
|
||||
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||
const cashuBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
// Detect WebLN when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && !hasWebLN) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [open, hasWebLN, detectWebLN]);
|
||||
|
||||
// Generate QR code
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
@@ -389,25 +335,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
const handleZap = () => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
|
||||
// Validate the amount
|
||||
if (isNaN(finalAmount) || finalAmount <= 0) {
|
||||
toast({
|
||||
title: 'Invalid amount',
|
||||
description: 'Please enter a valid amount greater than 0.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (canPayWithCashu && finalAmount > cashuBalance) {
|
||||
toast({
|
||||
title: 'Insufficient Cashu balance',
|
||||
description: `You only have ${cashuBalance} sats available.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
zap(finalAmount, comment);
|
||||
};
|
||||
|
||||
@@ -418,9 +345,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
canPayWithCashu,
|
||||
cashuBalance,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
@@ -502,9 +427,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
canPayWithCashu
|
||||
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
)}
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
@@ -532,9 +455,9 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
canPayWithCashu
|
||||
? 'Pay Lightning invoices using your Cashu token balance. Zaps support the creator of this item!'
|
||||
: 'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
<>
|
||||
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
|
||||
</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu.tsx';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { LightningWalletModal } from '@/components/WalletModal';
|
||||
import { WalletModal } from '@/components/WalletModal';
|
||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
@@ -64,15 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<LightningWalletModal>
|
||||
<WalletModal>
|
||||
<DropdownMenuItem
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Wallet className='w-4 h-4' />
|
||||
<span>Payment Settings</span>
|
||||
<span>Wallet Settings</span>
|
||||
</DropdownMenuItem>
|
||||
</LightningWalletModal>
|
||||
</WalletModal>
|
||||
<DropdownMenuItem
|
||||
onClick={onAddAccountClick}
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
|
||||
@@ -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 flex flex-col")}
|
||||
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
|
||||
>
|
||||
<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 min-h-0'>
|
||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
|
||||
{/* 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'>
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { User, UserPlus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import LoginDialog from './LoginDialog';
|
||||
import SignupDialog from './SignupDialog';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
import { AccountSwitcher } from './AccountSwitcher';
|
||||
|
||||
export function LoginIcon() {
|
||||
const { currentUser } = useLoggedInAccounts();
|
||||
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
|
||||
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
|
||||
|
||||
const handleLogin = () => {
|
||||
setLoginDialogOpen(false);
|
||||
setSignupDialogOpen(false);
|
||||
};
|
||||
|
||||
if (currentUser) {
|
||||
return (
|
||||
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setLoginDialogOpen(true)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
title="Log in"
|
||||
>
|
||||
<User className="!h-6 !w-6" />
|
||||
</Button>
|
||||
|
||||
<LoginDialog
|
||||
isOpen={loginDialogOpen}
|
||||
onClose={() => setLoginDialogOpen(false)}
|
||||
onLogin={handleLogin}
|
||||
onSignup={() => setSignupDialogOpen(true)}
|
||||
/>
|
||||
|
||||
<SignupDialog
|
||||
isOpen={signupDialogOpen}
|
||||
onClose={() => setSignupDialogOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
|
||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
@@ -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 flex-1'>
|
||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
|
||||
{/* Welcome Step - New engaging introduction */}
|
||||
{step === 'welcome' && (
|
||||
<div className='text-center space-y-4'>
|
||||
|
||||
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input hover:bg-accent hover:text-accent-foreground",
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
interface LoadingScreenProps {
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
|
||||
if (!isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
|
||||
<Card className="border-0 shadow-lg bg-background">
|
||||
<CardContent className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin mr-3" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { X, Copy, Check, QrCode, Zap, Clock } from 'lucide-react';
|
||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface QRModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
description: string;
|
||||
qrCodeUrl: string;
|
||||
content: string;
|
||||
icon?: 'qr' | 'zap';
|
||||
expiryTimestamp?: number;
|
||||
onExpiry?: () => void;
|
||||
}
|
||||
|
||||
export function QRModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
qrCodeUrl,
|
||||
content,
|
||||
icon = 'qr',
|
||||
expiryTimestamp,
|
||||
onExpiry,
|
||||
}: QRModalProps) {
|
||||
const { copy, copied } = useCopyToClipboard();
|
||||
const [timeRemaining, setTimeRemaining] = useState<number | null>(null);
|
||||
|
||||
const handleCopy = () => {
|
||||
copy(content);
|
||||
};
|
||||
|
||||
// Countdown timer effect
|
||||
useEffect(() => {
|
||||
if (!isOpen || !expiryTimestamp) return;
|
||||
|
||||
const updateTimer = () => {
|
||||
const now = Math.floor(Date.now() / 1000); // Current time in seconds
|
||||
const remaining = expiryTimestamp - now;
|
||||
|
||||
if (remaining <= 0) {
|
||||
setTimeRemaining(0);
|
||||
// Call expiry callback
|
||||
if (onExpiry) {
|
||||
onExpiry();
|
||||
}
|
||||
onClose();
|
||||
} else {
|
||||
setTimeRemaining(remaining);
|
||||
}
|
||||
};
|
||||
|
||||
// Update immediately
|
||||
updateTimer();
|
||||
|
||||
// Then update every second
|
||||
const interval = setInterval(updateTimer, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [isOpen, expiryTimestamp, onExpiry, onClose]);
|
||||
|
||||
// Format time remaining as MM:SS
|
||||
const formatTime = (seconds: number): string => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const IconComponent = icon === 'zap' ? Zap : QrCode;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<Card
|
||||
className="w-full max-w-md border-0 shadow-lg bg-background"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CardHeader className="relative">
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className="absolute top-2 right-2"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<CardTitle className="flex items-center pr-8">
|
||||
<IconComponent className="h-5 w-5 mr-2" />
|
||||
{title}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{expiryTimestamp && timeRemaining !== null && timeRemaining <= 3600 && (
|
||||
<div className="flex items-center justify-center gap-2 text-sm">
|
||||
<Clock className="h-4 w-4" />
|
||||
<span className={timeRemaining < 60 ? "text-destructive font-semibold" : "text-muted-foreground"}>
|
||||
Expires in {formatTime(timeRemaining)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-center">
|
||||
<div className="bg-white p-4 rounded-lg border shadow-sm">
|
||||
<img
|
||||
src={qrCodeUrl}
|
||||
alt={`${title} QR Code`}
|
||||
className="w-64 h-64 object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<div
|
||||
className="bg-muted p-3 rounded-lg border font-mono text-sm cursor-pointer hover:bg-muted/80 transition-colors relative group"
|
||||
onClick={handleCopy}
|
||||
title="Click to copy full content"
|
||||
>
|
||||
{content.length > 33
|
||||
? `${content.substring(0, 15)}...${content.substring(content.length - 15)}`
|
||||
: content}
|
||||
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||
</SliderPrimitive.Track>
|
||||
<SliderPrimitive.Thumb className="block h-10 w-10 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
||||
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
||||
</SliderPrimitive.Root>
|
||||
))
|
||||
Slider.displayName = SliderPrimitive.Root.displayName
|
||||
|
||||
@@ -47,7 +47,6 @@ const Toast = React.forwardRef<
|
||||
<ToastPrimitives.Root
|
||||
ref={ref}
|
||||
className={cn(toastVariants({ variant }), className)}
|
||||
duration={5000}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -1,669 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQRCode } from '@/hooks/useQRCode';
|
||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||
import { useBitcoinBalance } from '@/hooks/useBitcoinBalance';
|
||||
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin';
|
||||
import { QRModal } from '@/components/ui/qr-modal';
|
||||
import { WalletHeader } from './WalletHeader';
|
||||
import { TransactionCard } from './PaymentCard';
|
||||
import { WalletModals } from './MintModals';
|
||||
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
|
||||
import { TransactionHistory } from './TransactionHistory';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { ChevronUp, Send, Download } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export function CashuWallet() {
|
||||
// ============================================================================
|
||||
// CORE HOOKS
|
||||
// ============================================================================
|
||||
|
||||
const {
|
||||
coco,
|
||||
repositories,
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
balances,
|
||||
mints,
|
||||
getEncodedToken,
|
||||
clearError,
|
||||
refreshMints,
|
||||
} = useCashu();
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
||||
const { toast } = useToast();
|
||||
const { generateQRCode } = useQRCode();
|
||||
const { copy: copyToClipboard } = useCopyToClipboard();
|
||||
|
||||
// Bitcoin hooks
|
||||
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
||||
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
|
||||
|
||||
const {
|
||||
setMint: setNpubCashMint,
|
||||
getUserInfo: getNpubCashUserInfo,
|
||||
getAllQuotes,
|
||||
refreshQuotes,
|
||||
syncQuotesWithWallet,
|
||||
isLoggedIn: isNpubCashLoggedIn,
|
||||
isLoading: isNpubCashLoading,
|
||||
error: npubCashError,
|
||||
clearError: clearNpubCashError
|
||||
} = useNpubCash();
|
||||
|
||||
// Wrapper to handle return type mismatch
|
||||
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
|
||||
return setNpubCashMint(mintUrl);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// DOMAIN HOOKS
|
||||
// ============================================================================
|
||||
|
||||
const {
|
||||
activeMintUrl,
|
||||
setActiveMintUrl,
|
||||
mintUrl,
|
||||
setMintUrl,
|
||||
mintDropdownOpen,
|
||||
setMintDropdownOpen,
|
||||
handleAddMint,
|
||||
handleRemoveMintClick,
|
||||
handleConfirmRemoveMint,
|
||||
mintToRemove,
|
||||
setMintToRemove,
|
||||
showRemoveMintModal,
|
||||
setShowRemoveMintModal,
|
||||
getCleanMintLabel,
|
||||
handleShowDenominations,
|
||||
} = useMintManager({
|
||||
coco,
|
||||
mints,
|
||||
repositories,
|
||||
isNpubCashLoggedIn,
|
||||
setNpubCashMint: handleSetNpubCashMint,
|
||||
refreshMints,
|
||||
toast,
|
||||
});
|
||||
|
||||
// Wrapper for setActiveMintUrl to handle the async nature
|
||||
const handleSetActiveMintSync = (url: string | null) => {
|
||||
setActiveMintUrl(url);
|
||||
};
|
||||
|
||||
const {
|
||||
tokenInput,
|
||||
setTokenInput,
|
||||
quoteAmount,
|
||||
setQuoteAmount,
|
||||
sendAmount,
|
||||
setSendAmount,
|
||||
lightningInvoice,
|
||||
setLightningInvoice,
|
||||
lightningAddressInput,
|
||||
setLightningAddressInput,
|
||||
lightningAddressAmount,
|
||||
setLightningAddressAmount,
|
||||
pendingLightningAddress,
|
||||
setPendingLightningAddress,
|
||||
decodedInvoiceAmount,
|
||||
setDecodedInvoiceAmount,
|
||||
pendingInvoice,
|
||||
setPendingInvoice,
|
||||
sentToken,
|
||||
setSentToken,
|
||||
sentTokenQRCode,
|
||||
showInvoiceModal,
|
||||
setShowInvoiceModal,
|
||||
currentInvoice,
|
||||
setCurrentInvoice,
|
||||
handleReceive,
|
||||
handleSend,
|
||||
handleConfirmInvoicePayment,
|
||||
mintQuoteUnsubscribeRef,
|
||||
} = useWalletTransactions({
|
||||
coco,
|
||||
activeMintUrl,
|
||||
isNpubCashLoggedIn,
|
||||
repositories,
|
||||
generateQRCode,
|
||||
toast,
|
||||
getEncodedToken,
|
||||
getLightningInvoice,
|
||||
});
|
||||
|
||||
const {
|
||||
historyEntries,
|
||||
isLoadingHistory,
|
||||
isHistoryExpanded,
|
||||
setIsHistoryExpanded,
|
||||
} = useHistoryManager({
|
||||
coco,
|
||||
isInitialized,
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// UI STATE
|
||||
// ============================================================================
|
||||
|
||||
const [showSats, setShowSats] = useState(true);
|
||||
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
|
||||
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
||||
const [proofBreakdown, setProofBreakdown] = useState<{
|
||||
mintUrl: string;
|
||||
denominations: { [key: number]: number };
|
||||
totalBalance: number;
|
||||
} | null>(null);
|
||||
const [showLightningQR, setShowLightningQR] = useState(false);
|
||||
const [lightningQRCode, setLightningQRCode] = useState<string>('');
|
||||
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
|
||||
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
|
||||
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
|
||||
const [showSendModal, setShowSendModal] = useState(false);
|
||||
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
||||
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
||||
|
||||
// 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('');
|
||||
|
||||
// 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 Bitcoin state
|
||||
setBitcoinAmount('');
|
||||
setBitcoinRecipient('');
|
||||
setPendingBitcoinRecipient(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReceiveDrawerClose = (open: boolean) => {
|
||||
setShowReceiveModal(open);
|
||||
if (!open) {
|
||||
// Reset all receive-related state when drawer closes
|
||||
setTokenInput('');
|
||||
setQuoteAmount('');
|
||||
}
|
||||
};
|
||||
|
||||
// Ref to track if we've fetched npub.cash user info
|
||||
const hasCheckedNpubCashRef = useRef(false);
|
||||
|
||||
// ============================================================================
|
||||
// BITCOIN HANDLERS
|
||||
// ============================================================================
|
||||
|
||||
const handleBitcoinSend = async () => {
|
||||
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()
|
||||
]);
|
||||
|
||||
// Create and sign transaction
|
||||
const { txHex, fee } = await createBitcoinTransaction(
|
||||
privateKey,
|
||||
recipientAddress,
|
||||
amountSats,
|
||||
utxos,
|
||||
feeRates.fastestFee
|
||||
);
|
||||
|
||||
// Broadcast transaction
|
||||
const txId = await broadcastTransaction(txHex);
|
||||
|
||||
toast({
|
||||
title: "Bitcoin Sent!",
|
||||
description: `Transaction ${txId.slice(0, 8)}... confirmed`,
|
||||
});
|
||||
|
||||
// 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',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleBitcoinReceive = async () => {
|
||||
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",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// COMPUTED VALUES
|
||||
// ============================================================================
|
||||
|
||||
const totalBalance: number = mode === 'bitcoin'
|
||||
? (bitcoinBalanceData?.balance || 0)
|
||||
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
||||
|
||||
// ============================================================================
|
||||
// EFFECTS - Error Handling
|
||||
// ============================================================================
|
||||
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Wallet Error",
|
||||
description: error.message,
|
||||
});
|
||||
}
|
||||
}, [error, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
if (npubCashError) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Npub.cash Error",
|
||||
description: npubCashError,
|
||||
});
|
||||
clearNpubCashError();
|
||||
}
|
||||
}, [npubCashError, clearNpubCashError, toast]);
|
||||
|
||||
// ============================================================================
|
||||
// EFFECTS - NPub.cash Integration
|
||||
// ============================================================================
|
||||
|
||||
useEffect(() => {
|
||||
if (!isNpubCashLoggedIn) {
|
||||
hasCheckedNpubCashRef.current = false;
|
||||
setNpubCashUserInfo(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return;
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
hasCheckedNpubCashRef.current = true;
|
||||
|
||||
const userInfo = await getNpubCashUserInfo();
|
||||
if (!userInfo) return;
|
||||
|
||||
setNpubCashUserInfo(userInfo);
|
||||
|
||||
// Sync mint from npub.cash if different from active mint
|
||||
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
|
||||
const mintExists = mints.some(m => m.url === userInfo.mint_url);
|
||||
|
||||
if (!mintExists && coco) {
|
||||
try {
|
||||
await coco.mint.addMint(userInfo.mint_url);
|
||||
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
|
||||
} catch {
|
||||
// Silent failure - user can manually add mint if needed
|
||||
}
|
||||
} else if (mintExists) {
|
||||
setActiveMintUrl(userInfo.mint_url, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserInfo();
|
||||
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
|
||||
|
||||
// Set up automatic quote sync subscription when logged into npub.cash
|
||||
useEffect(() => {
|
||||
if (!isNpubCashLoggedIn || !coco || !isInitialized) return;
|
||||
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
const setupSync = async () => {
|
||||
unsubscribe = await syncQuotesWithWallet(coco, toast);
|
||||
};
|
||||
|
||||
setupSync();
|
||||
|
||||
return () => {
|
||||
if (unsubscribe) {
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
|
||||
|
||||
// ============================================================================
|
||||
// EFFECTS - Cleanup
|
||||
// ============================================================================
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ============================================================================
|
||||
// RENDER
|
||||
// ============================================================================
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
|
||||
|
||||
{/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */}
|
||||
<WalletHeader
|
||||
totalBalance={totalBalance}
|
||||
balances={balances}
|
||||
showSats={showSats}
|
||||
setShowSats={setShowSats}
|
||||
mode={mode}
|
||||
setMode={setMode}
|
||||
userPubkey={user?.pubkey}
|
||||
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
|
||||
onCopyToClipboard={copyToClipboard}
|
||||
onShowLightningAddressQR={(qr) => {
|
||||
setLightningAddressQRCode(qr);
|
||||
setShowLightningAddressQR(true);
|
||||
}}
|
||||
onShowBitcoinAddressQR={(qr) => {
|
||||
setBitcoinAddressQRCode(qr);
|
||||
setShowBitcoinAddressQR(true);
|
||||
}}
|
||||
generateQRCode={generateQRCode}
|
||||
// MintSelector props
|
||||
activeMintUrl={activeMintUrl}
|
||||
setActiveMintUrl={handleSetActiveMintSync}
|
||||
mints={mints}
|
||||
mintUrl={mintUrl}
|
||||
setMintUrl={setMintUrl}
|
||||
onAddMint={handleAddMint}
|
||||
onRemoveMint={handleRemoveMintClick}
|
||||
onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)}
|
||||
getCleanMintLabel={getCleanMintLabel}
|
||||
dropdownOpen={mintDropdownOpen}
|
||||
setDropdownOpen={setMintDropdownOpen}
|
||||
/>
|
||||
|
||||
|
||||
{/* Action Buttons and Transaction History Container */}
|
||||
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-20 justify-center py-8">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setShowReceiveModal(true)}
|
||||
disabled={isLoading || isNpubCashLoading}
|
||||
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||
>
|
||||
<Download className="h-12 w-12" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setShowSendModal(true)}
|
||||
disabled={isLoading || isNpubCashLoading}
|
||||
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||
>
|
||||
<Send className="h-12 w-12" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Transaction History Button */}
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<button
|
||||
onClick={() => setShowHistoryModal(true)}
|
||||
className="w-full py-2 px-4 flex justify-center border-t border-muted hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<ChevronUp className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Modals */}
|
||||
<>
|
||||
<WalletModals
|
||||
showProofBreakdown={showProofBreakdown}
|
||||
setShowProofBreakdown={setShowProofBreakdown}
|
||||
proofBreakdown={proofBreakdown}
|
||||
showRemoveMintModal={showRemoveMintModal}
|
||||
setShowRemoveMintModal={setShowRemoveMintModal}
|
||||
mintToRemove={mintToRemove}
|
||||
onConfirmRemoveMint={handleConfirmRemoveMint}
|
||||
isLoading={isLoading || isNpubCashLoading}
|
||||
showLightningQR={showLightningQR}
|
||||
setShowLightningQR={setShowLightningQR}
|
||||
lightningQRCode={lightningQRCode}
|
||||
showLightningAddressQR={showLightningAddressQR}
|
||||
setShowLightningAddressQR={setShowLightningAddressQR}
|
||||
lightningAddressQRCode={lightningAddressQRCode}
|
||||
userPubkey={user?.pubkey}
|
||||
npubCashUserInfo={npubCashUserInfo}
|
||||
currentInvoice={currentInvoice}
|
||||
showInvoiceModal={showInvoiceModal}
|
||||
setShowInvoiceModal={setShowInvoiceModal}
|
||||
mintQuoteUnsubscribeRef={mintQuoteUnsubscribeRef}
|
||||
sentToken={sentToken}
|
||||
setSentToken={setSentToken}
|
||||
sentTokenQRCode={sentTokenQRCode}
|
||||
/>
|
||||
|
||||
{/* Bottom Drawer Modals */}
|
||||
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
|
||||
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
||||
</DrawerHeader>
|
||||
<div className="px-4 pb-4">
|
||||
<TransactionCard
|
||||
mode={mode}
|
||||
operation="send"
|
||||
sendAmount={sendAmount}
|
||||
setSendAmount={setSendAmount}
|
||||
lightningInvoice={lightningInvoice}
|
||||
setLightningInvoice={setLightningInvoice}
|
||||
lightningAddressInput={lightningAddressInput}
|
||||
setLightningAddressInput={setLightningAddressInput}
|
||||
lightningAddressAmount={lightningAddressAmount}
|
||||
setLightningAddressAmount={setLightningAddressAmount}
|
||||
pendingLightningAddress={pendingLightningAddress}
|
||||
setPendingLightningAddress={setPendingLightningAddress}
|
||||
decodedInvoiceAmount={decodedInvoiceAmount}
|
||||
setDecodedInvoiceAmount={setDecodedInvoiceAmount}
|
||||
pendingInvoice={pendingInvoice}
|
||||
setPendingInvoice={setPendingInvoice}
|
||||
tokenInput=""
|
||||
setTokenInput={() => {}}
|
||||
quoteAmount=""
|
||||
setQuoteAmount={() => {}}
|
||||
activeMintUrl={activeMintUrl}
|
||||
onSend={() => {
|
||||
if (mode === 'bitcoin') {
|
||||
handleBitcoinSend();
|
||||
} else {
|
||||
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
|
||||
handleSend();
|
||||
if (mode === 'tokens' || wasPendingBefore) {
|
||||
setShowSendModal(false);
|
||||
}
|
||||
}
|
||||
}}
|
||||
onReceive={() => {}}
|
||||
onConfirmInvoice={() => {
|
||||
handleConfirmInvoicePayment();
|
||||
setShowSendModal(false);
|
||||
}}
|
||||
isResolvingAddress={isResolvingAddress}
|
||||
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
||||
// Bitcoin props
|
||||
bitcoinAddress={bitcoinAddress || ''}
|
||||
bitcoinAmount={bitcoinAmount}
|
||||
setBitcoinAmount={setBitcoinAmount}
|
||||
bitcoinRecipient={bitcoinRecipient}
|
||||
setBitcoinRecipient={setBitcoinRecipient}
|
||||
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
||||
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
||||
hasNsecAccess={hasNsecAccess}
|
||||
/>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
|
||||
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
||||
</DrawerHeader>
|
||||
<div className="px-4 pb-4">
|
||||
<TransactionCard
|
||||
mode={mode}
|
||||
operation="receive"
|
||||
sendAmount=""
|
||||
setSendAmount={() => {}}
|
||||
lightningInvoice=""
|
||||
setLightningInvoice={() => {}}
|
||||
lightningAddressInput=""
|
||||
setLightningAddressInput={() => {}}
|
||||
lightningAddressAmount=""
|
||||
setLightningAddressAmount={() => {}}
|
||||
pendingLightningAddress={null}
|
||||
setPendingLightningAddress={() => {}}
|
||||
decodedInvoiceAmount={null}
|
||||
setDecodedInvoiceAmount={() => {}}
|
||||
pendingInvoice={null}
|
||||
setPendingInvoice={() => {}}
|
||||
tokenInput={tokenInput}
|
||||
setTokenInput={setTokenInput}
|
||||
quoteAmount={quoteAmount}
|
||||
setQuoteAmount={setQuoteAmount}
|
||||
activeMintUrl={activeMintUrl}
|
||||
onSend={() => {}}
|
||||
onReceive={() => {
|
||||
if (mode === 'bitcoin') {
|
||||
handleBitcoinReceive();
|
||||
setShowReceiveModal(false);
|
||||
} else {
|
||||
handleReceive();
|
||||
setShowReceiveModal(false);
|
||||
}
|
||||
}}
|
||||
isResolvingAddress={false}
|
||||
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
||||
// Bitcoin props
|
||||
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>
|
||||
</DrawerHeader>
|
||||
<ScrollArea className="h-[80vh] px-4 pb-4">
|
||||
<TransactionHistory
|
||||
entries={historyEntries}
|
||||
isLoading={isLoadingHistory}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
{/* 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"
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { X, Coins, AlertTriangle, RefreshCw } from 'lucide-react';
|
||||
import { QRModal } from '@/components/ui/qr-modal';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface ProofBreakdown {
|
||||
mintUrl: string;
|
||||
denominations: { [key: number]: number };
|
||||
totalBalance: number;
|
||||
}
|
||||
|
||||
interface MintToRemove {
|
||||
url: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface WalletModalProps {
|
||||
// Proof Breakdown Modal
|
||||
showProofBreakdown: boolean;
|
||||
setShowProofBreakdown: (show: boolean) => void;
|
||||
proofBreakdown: ProofBreakdown | null;
|
||||
|
||||
// Remove Mint Modal
|
||||
showRemoveMintModal: boolean;
|
||||
setShowRemoveMintModal: (show: boolean) => void;
|
||||
mintToRemove: MintToRemove | null;
|
||||
onConfirmRemoveMint: () => void;
|
||||
isLoading: boolean;
|
||||
|
||||
// QR Modals
|
||||
showLightningQR: boolean;
|
||||
setShowLightningQR: (show: boolean) => void;
|
||||
lightningQRCode: string;
|
||||
showLightningAddressQR: boolean;
|
||||
setShowLightningAddressQR: (show: boolean) => void;
|
||||
lightningAddressQRCode: string;
|
||||
userPubkey?: string;
|
||||
npubCashUserInfo?: { name?: string } | null;
|
||||
|
||||
// Invoice Modal
|
||||
currentInvoice?: {
|
||||
amount: number;
|
||||
qrCodeUrl: string;
|
||||
invoice: string;
|
||||
expiry: number;
|
||||
} | null;
|
||||
showInvoiceModal: boolean;
|
||||
setShowInvoiceModal: (show: boolean) => void;
|
||||
mintQuoteUnsubscribeRef: React.MutableRefObject<(() => void) | null>;
|
||||
|
||||
// Sent Token Modal
|
||||
sentToken: string | null;
|
||||
setSentToken: (token: string | null) => void;
|
||||
sentTokenQRCode: string;
|
||||
}
|
||||
|
||||
export function WalletModals({
|
||||
showProofBreakdown,
|
||||
setShowProofBreakdown,
|
||||
proofBreakdown,
|
||||
showRemoveMintModal,
|
||||
setShowRemoveMintModal,
|
||||
mintToRemove,
|
||||
onConfirmRemoveMint,
|
||||
isLoading,
|
||||
showLightningQR,
|
||||
setShowLightningQR,
|
||||
lightningQRCode,
|
||||
showLightningAddressQR,
|
||||
setShowLightningAddressQR,
|
||||
lightningAddressQRCode,
|
||||
userPubkey,
|
||||
npubCashUserInfo,
|
||||
currentInvoice,
|
||||
showInvoiceModal,
|
||||
setShowInvoiceModal,
|
||||
mintQuoteUnsubscribeRef,
|
||||
sentToken,
|
||||
setSentToken,
|
||||
sentTokenQRCode,
|
||||
}: WalletModalProps) {
|
||||
const { toast } = useToast();
|
||||
return (
|
||||
<>
|
||||
{/* Proof Breakdown Modal */}
|
||||
{showProofBreakdown && proofBreakdown && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
onClick={() => setShowProofBreakdown(false)}
|
||||
>
|
||||
<Card
|
||||
className="w-full max-w-md border-0 shadow-lg bg-background"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CardHeader className="relative">
|
||||
<Button
|
||||
onClick={() => setShowProofBreakdown(false)}
|
||||
className="absolute top-2 right-2"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<CardTitle className="flex items-center pr-8">
|
||||
<Coins className="h-5 w-5 mr-2" />
|
||||
Token Breakdown
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{new URL(proofBreakdown.mintUrl).hostname}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="text-center py-2">
|
||||
<div className="text-2xl font-bold text-primary">
|
||||
{proofBreakdown.totalBalance.toLocaleString()} sats
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">Total Balance</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
|
||||
{Object.entries(proofBreakdown.denominations)
|
||||
.sort(([a], [b]) => parseInt(a) - parseInt(b))
|
||||
.map(([amount, count]) => (
|
||||
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
|
||||
<div className="flex items-center gap-2">
|
||||
<Coins className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
|
||||
</div>
|
||||
<Badge variant="secondary" className="bg-primary/10 text-primary">
|
||||
× {count}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
|
||||
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Remove Mint Modal */}
|
||||
{showRemoveMintModal && mintToRemove && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
|
||||
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
|
||||
<CardHeader className="relative">
|
||||
<Button
|
||||
onClick={() => setShowRemoveMintModal(false)}
|
||||
className="absolute top-2 right-2"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<CardTitle className="flex items-center pr-8">
|
||||
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
|
||||
Remove Mint
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Are you sure you want to remove this mint from your wallet?
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="bg-muted p-4 rounded-lg border">
|
||||
<div className="font-medium">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
|
||||
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
|
||||
<div>💡 You can always add this mint back later if needed.</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowRemoveMintModal(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirmRemoveMint}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
|
||||
Removing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Remove Mint
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* QR Modals */}
|
||||
<QRModal
|
||||
isOpen={showLightningQR}
|
||||
onClose={() => setShowLightningQR(false)}
|
||||
title="Lightning Address QR Code"
|
||||
description="Scan to send Lightning payments"
|
||||
qrCodeUrl={lightningQRCode}
|
||||
content={''}
|
||||
icon="qr"
|
||||
/>
|
||||
|
||||
<QRModal
|
||||
isOpen={showLightningAddressQR}
|
||||
onClose={() => setShowLightningAddressQR(false)}
|
||||
title="Lightning Address"
|
||||
description="Scan this QR code to send payments to your Lightning address"
|
||||
qrCodeUrl={lightningAddressQRCode}
|
||||
content={userPubkey ? `${npubCashUserInfo?.name || nip19.npubEncode(userPubkey)}@npubx.cash` : ''}
|
||||
icon="zap"
|
||||
/>
|
||||
|
||||
{currentInvoice && (
|
||||
<QRModal
|
||||
isOpen={showInvoiceModal}
|
||||
onClose={() => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
setShowInvoiceModal(false);
|
||||
}}
|
||||
onExpiry={() => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invoice Expired",
|
||||
description: "The Lightning invoice has expired. Please create a new one.",
|
||||
});
|
||||
}}
|
||||
title="Lightning Invoice"
|
||||
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
|
||||
qrCodeUrl={currentInvoice.qrCodeUrl}
|
||||
content={currentInvoice.invoice}
|
||||
icon="zap"
|
||||
expiryTimestamp={currentInvoice.expiry}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sent Token Modal */}
|
||||
{sentToken && (
|
||||
<QRModal
|
||||
isOpen={!!sentToken}
|
||||
onClose={() => setSentToken(null)}
|
||||
title="Cashu Token"
|
||||
description="Share this token with the recipient to send them your sats"
|
||||
qrCodeUrl={sentTokenQRCode}
|
||||
content={sentToken}
|
||||
icon="qr"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Plus, X, Check, ChevronDown, Wallet } from 'lucide-react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSeparator,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
interface CashuMint {
|
||||
url: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface MintSelectorProps {
|
||||
balances: { [key: string]: number };
|
||||
showSats: boolean;
|
||||
activeMintUrl: string | null;
|
||||
setActiveMintUrl: (url: string | null) => void;
|
||||
mints: CashuMint[];
|
||||
mintUrl: string;
|
||||
setMintUrl: (url: string) => void;
|
||||
onAddMint: () => void;
|
||||
onRemoveMint: (mint: CashuMint) => void;
|
||||
onShowDenominations: (mintUrl: string) => void;
|
||||
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
|
||||
dropdownOpen: boolean;
|
||||
setDropdownOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function MintSelector({
|
||||
balances,
|
||||
showSats,
|
||||
activeMintUrl,
|
||||
setActiveMintUrl,
|
||||
mints,
|
||||
mintUrl,
|
||||
setMintUrl,
|
||||
onAddMint,
|
||||
onRemoveMint,
|
||||
onShowDenominations,
|
||||
getCleanMintLabel,
|
||||
dropdownOpen,
|
||||
setDropdownOpen,
|
||||
}: MintSelectorProps) {
|
||||
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
exchangeRateService.getBtcUsdRate()
|
||||
.then(rate => setBtcUsdRate(rate))
|
||||
.catch(() => setBtcUsdRate(null));
|
||||
}, []);
|
||||
|
||||
const formatBalance = (sats: number): string => {
|
||||
if (showSats) {
|
||||
return `₿${sats.toLocaleString()}`;
|
||||
} else if (btcUsdRate) {
|
||||
const btcAmount = sats / 100000000;
|
||||
const usd = btcAmount * btcUsdRate;
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} else {
|
||||
return `₿${sats.toLocaleString()}`;
|
||||
}
|
||||
};
|
||||
|
||||
const activeMint = mints.find(mint => mint.url === activeMintUrl);
|
||||
const activeBalance = activeMint ? balances[activeMint.url] || 0 : 0;
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 items-center min-w-0">
|
||||
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0">
|
||||
<div className="flex items-center justify-between w-full min-w-0">
|
||||
{activeMint ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<Check className="h-5 w-5 text-primary flex-shrink-0" />
|
||||
<span className="truncate font-medium min-w-0 flex-1">{getCleanMintLabel(activeMint)}</span>
|
||||
</div>
|
||||
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
|
||||
{formatBalance(activeBalance)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground truncate min-w-0 flex-1">Select a mint</span>
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none 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"
|
||||
>
|
||||
<Wallet className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,533 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react';
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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,
|
||||
}: TransactionCardProps) {
|
||||
// Slider state for confirmation
|
||||
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
|
||||
const [addressSliderValue, setAddressSliderValue] = useState([0]);
|
||||
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
|
||||
|
||||
// State to track which slider is being actively held
|
||||
const [activeSlider, setActiveSlider] = useState<string | null>(null);
|
||||
|
||||
// Handle slider value changes and auto-submit at 100%
|
||||
const handleInvoiceSliderChange = (value: number[]) => {
|
||||
setInvoiceSliderValue(value);
|
||||
if (value[0] === 100 && onConfirmInvoice) {
|
||||
onConfirmInvoice();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddressSliderChange = (value: number[]) => {
|
||||
setAddressSliderValue(value);
|
||||
if (value[0] === 100) {
|
||||
onSend();
|
||||
}
|
||||
};
|
||||
|
||||
const handleBitcoinSliderChange = (value: number[]) => {
|
||||
setBitcoinSliderValue(value);
|
||||
if (value[0] === 100) {
|
||||
onSend();
|
||||
}
|
||||
};
|
||||
|
||||
// Reset sliders when states change
|
||||
const resetSliders = () => {
|
||||
setInvoiceSliderValue([0]);
|
||||
setAddressSliderValue([0]);
|
||||
};
|
||||
|
||||
// Handle slider release (reset on mouse/touch up)
|
||||
const handleSliderMouseUp = (sliderId: string) => {
|
||||
setActiveSlider(null);
|
||||
// Reset the slider if it hasn't reached 100
|
||||
if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) {
|
||||
setInvoiceSliderValue([0]);
|
||||
} else if (sliderId === 'address' && addressSliderValue[0] !== 100) {
|
||||
setAddressSliderValue([0]);
|
||||
} else if (sliderId === 'bitcoin' && bitcoinSliderValue[0] !== 100) {
|
||||
setBitcoinSliderValue([0]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSliderMouseDown = (sliderId: string) => {
|
||||
setActiveSlider(sliderId);
|
||||
};
|
||||
|
||||
// Reset sliders when pending states change
|
||||
useEffect(() => {
|
||||
if (!pendingInvoice) {
|
||||
setInvoiceSliderValue([0]);
|
||||
}
|
||||
}, [pendingInvoice]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingLightningAddress) {
|
||||
setAddressSliderValue([0]);
|
||||
}
|
||||
}, [pendingLightningAddress]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingBitcoinRecipient) {
|
||||
setBitcoinSliderValue([0]);
|
||||
}
|
||||
}, [pendingBitcoinRecipient]);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Title */}
|
||||
<div className="text-center">
|
||||
<p className="text-base text-muted-foreground mt-2">
|
||||
{operation === 'send' ? (
|
||||
mode === 'tokens'
|
||||
? 'Generate Cashu token to send'
|
||||
: mode === 'bitcoin' && !pendingBitcoinRecipient
|
||||
? 'Send Bitcoin on-chain'
|
||||
: mode === 'bitcoin' && pendingBitcoinRecipient
|
||||
? ''
|
||||
: 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">{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>
|
||||
) : 'Pay invoices or addresses'
|
||||
) : (
|
||||
mode === 'tokens'
|
||||
? 'Enter Cashu token to redeem'
|
||||
: mode === 'bitcoin'
|
||||
? 'Receive Bitcoin on-chain'
|
||||
: 'Deposit funds with Lightning'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="space-y-8">
|
||||
{!activeMintUrl && mode !== 'bitcoin' && (
|
||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||
{operation === 'send'
|
||||
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
|
||||
: (mode === 'tokens' ? 'Select a mint to receive tokens' : 'Select a mint to create Lightning invoice')
|
||||
}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{operation === 'send' ? (
|
||||
// Send Mode
|
||||
mode === '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 with Slider
|
||||
<div className="space-y-8">
|
||||
<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">{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>
|
||||
<Input
|
||||
placeholder="Amount (sats)"
|
||||
type="number"
|
||||
value={bitcoinAmount || ''}
|
||||
onChange={(e) => setBitcoinAmount?.(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && bitcoinAmount && pendingBitcoinRecipient && !isLoading) {
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
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="mt-6">
|
||||
<div className="relative w-full">
|
||||
<div
|
||||
onMouseDown={() => handleSliderMouseDown('bitcoin')}
|
||||
onMouseUp={() => handleSliderMouseUp('bitcoin')}
|
||||
onMouseLeave={() => handleSliderMouseUp('bitcoin')}
|
||||
onTouchEnd={() => handleSliderMouseUp('bitcoin')}
|
||||
>
|
||||
<Slider
|
||||
value={bitcoinSliderValue}
|
||||
onValueChange={handleBitcoinSliderChange}
|
||||
max={100}
|
||||
step={1}
|
||||
className="w-full h-12"
|
||||
disabled={!bitcoinAmount || isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{bitcoinSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</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">
|
||||
<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">
|
||||
<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 (with slider)
|
||||
<div className="space-y-8">
|
||||
<div className="mt-6">
|
||||
<div className="relative">
|
||||
<div
|
||||
onMouseDown={() => handleSliderMouseDown('invoice')}
|
||||
onMouseUp={() => handleSliderMouseUp('invoice')}
|
||||
onMouseLeave={() => handleSliderMouseUp('invoice')}
|
||||
onTouchEnd={() => handleSliderMouseUp('invoice')}
|
||||
>
|
||||
<Slider
|
||||
value={invoiceSliderValue}
|
||||
onValueChange={handleInvoiceSliderChange}
|
||||
max={100}
|
||||
step={1}
|
||||
className="w-full h-12"
|
||||
disabled={!activeMintUrl || isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{invoiceSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : pendingLightningAddress ? (
|
||||
// Lightning Address Amount Input with Slider
|
||||
<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="mt-6">
|
||||
<div className="relative w-full">
|
||||
<div
|
||||
onMouseDown={() => handleSliderMouseDown('address')}
|
||||
onMouseUp={() => handleSliderMouseUp('address')}
|
||||
onMouseLeave={() => handleSliderMouseUp('address')}
|
||||
onTouchEnd={() => handleSliderMouseUp('address')}
|
||||
>
|
||||
<Slider
|
||||
value={addressSliderValue}
|
||||
onValueChange={handleAddressSliderChange}
|
||||
max={100}
|
||||
step={1}
|
||||
className="w-full h-12"
|
||||
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// Lightning Invoice/Address Input
|
||||
<div className="space-y-8">
|
||||
<Input
|
||||
placeholder="lnbc... or [email protected]"
|
||||
value={lightningInvoice || lightningAddressInput}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value.includes('@')) {
|
||||
setLightningAddressInput(value);
|
||||
setLightningInvoice('');
|
||||
} else {
|
||||
setLightningInvoice(value);
|
||||
setLightningAddressInput('');
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
|
||||
onSend();
|
||||
}
|
||||
}}
|
||||
disabled={!activeMintUrl}
|
||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||
/>
|
||||
<div className="flex justify-center mt-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">
|
||||
<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">
|
||||
<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">
|
||||
<Button
|
||||
onClick={onReceive}
|
||||
disabled={!quoteAmount || !activeMintUrl || isLoading}
|
||||
className="h-12 px-12 rounded-full"
|
||||
size="lg"
|
||||
>
|
||||
<Zap className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins } from 'lucide-react';
|
||||
import type { HistoryEntry } from 'coco-cashu-core';
|
||||
|
||||
interface TransactionHistoryProps {
|
||||
entries: HistoryEntry[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function TransactionHistory({ entries, isLoading }: TransactionHistoryProps) {
|
||||
// Icon indicating transaction type (Lightning vs Cashu)
|
||||
const getTransactionTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'mint':
|
||||
case 'melt':
|
||||
return <Zap className="h-4 w-4" />;
|
||||
case 'send':
|
||||
case 'receive':
|
||||
return <Coins className="h-4 w-4" />;
|
||||
default:
|
||||
return <History className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
// Arrow indicating direction (next to amount)
|
||||
const getDirectionIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'mint':
|
||||
case 'receive':
|
||||
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
|
||||
case 'melt':
|
||||
case 'send':
|
||||
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const getHistoryLabel = (type: string) => {
|
||||
switch (type) {
|
||||
case 'mint':
|
||||
case 'receive':
|
||||
return 'Received';
|
||||
case 'melt':
|
||||
case 'send':
|
||||
return 'Sent';
|
||||
default:
|
||||
return type;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||||
<span>Loading history...</span>
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
No transactions yet
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{entries.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3 flex-1">
|
||||
<div className="mt-1">
|
||||
{getTransactionTypeIcon(entry.type)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium">
|
||||
{getHistoryLabel(entry.type)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
{new URL(entry.mintUrl).hostname}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{new Date(entry.createdAt).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right ml-4 flex items-start gap-2">
|
||||
<div>
|
||||
<div className="font-semibold">
|
||||
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
|
||||
{entry.amount.toLocaleString()} {entry.unit}
|
||||
</div>
|
||||
{entry.type === 'melt' && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
+ fees
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
{getDirectionIcon(entry.type)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Zap, Coins, Copy, Check, QrCode, Link } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { LoginIcon } from '@/components/auth/LoginIcon';
|
||||
import { MintSelector } from './MintSelector';
|
||||
import { nostrPubkeyToBitcoinAddress } 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;
|
||||
onCopyToClipboard: (text: string) => Promise<void>;
|
||||
onShowLightningAddressQR: (qrCode: string) => void;
|
||||
onShowBitcoinAddressQR: (qrCode: string) => void;
|
||||
generateQRCode: (text: string) => Promise<string>;
|
||||
// MintSelector props
|
||||
activeMintUrl: string | null;
|
||||
setActiveMintUrl: (url: string | null) => void;
|
||||
mints: CashuMint[];
|
||||
mintUrl: string;
|
||||
setMintUrl: (url: string) => void;
|
||||
onAddMint: () => void;
|
||||
onRemoveMint: (mint: CashuMint) => void;
|
||||
onShowDenominations: (mintUrl: string) => void;
|
||||
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
|
||||
dropdownOpen: boolean;
|
||||
setDropdownOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function WalletHeader({
|
||||
totalBalance,
|
||||
balances,
|
||||
showSats,
|
||||
setShowSats,
|
||||
mode,
|
||||
setMode,
|
||||
userPubkey,
|
||||
npubCashUsername,
|
||||
onCopyToClipboard,
|
||||
onShowLightningAddressQR,
|
||||
onShowBitcoinAddressQR,
|
||||
generateQRCode,
|
||||
// MintSelector props
|
||||
activeMintUrl,
|
||||
setActiveMintUrl,
|
||||
mints,
|
||||
mintUrl,
|
||||
setMintUrl,
|
||||
onAddMint,
|
||||
onRemoveMint,
|
||||
onShowDenominations,
|
||||
getCleanMintLabel,
|
||||
dropdownOpen,
|
||||
setDropdownOpen,
|
||||
}: WalletHeaderProps) {
|
||||
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
|
||||
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
|
||||
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
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);
|
||||
|
||||
toast({
|
||||
title: `${newMode === 'tokens' ? 'Cashu' : newMode === 'lightning' ? 'Lightning' : 'Bitcoin'} Enabled!`,
|
||||
description: newMode === 'tokens'
|
||||
? 'Send and receive with Cashu eCash'
|
||||
: newMode === 'lightning'
|
||||
? 'Send and receive with Lightning'
|
||||
: 'Send and receive with on-chain Bitcoin',
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
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={mode === 'tokens' ? 'Switch to Lightning' : mode === 'lightning' ? 'Switch to Bitcoin' : 'Switch to Cashu Tokens'}
|
||||
>
|
||||
{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={`Click to show in ${showSats ? 'USD' : 'sats'}`}
|
||||
>
|
||||
<span className="text-muted-foreground italic">
|
||||
{showSats ? '₿' : '$'}
|
||||
</span>
|
||||
{showSats ? totalBalance.toLocaleString() : (btcUsdRate ? `${(totalBalance / 100000000 * btcUsdRate).toFixed(2)}` : totalBalance.toLocaleString())}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Lightning Address and Mint Selector Grid */}
|
||||
<div className="mt-3 px-4">
|
||||
<div className="w-full max-w-[400px] mx-auto">
|
||||
<div className="grid grid-cols-1 gap-3">
|
||||
{/* Lightning Address Row */}
|
||||
{userPubkey && mode !== 'bitcoin' && (
|
||||
<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>
|
||||
)}
|
||||
|
||||
{/* 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;
|
||||
})()}
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { createContext, useContext, ReactNode } from 'react';
|
||||
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/cashu/useCashu';
|
||||
|
||||
const CashuContext = createContext<UseCashuReturn | null>(null);
|
||||
|
||||
export function CashuProvider({ children }: { children: ReactNode }) {
|
||||
const cashu = useCashuHook();
|
||||
|
||||
return (
|
||||
<CashuContext.Provider value={cashu}>
|
||||
{children}
|
||||
</CashuContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
const context = useContext(CashuContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useCashu must be used within a CashuProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -1,251 +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 { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
|
||||
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
|
||||
|
||||
// Types from coco-cashu-core
|
||||
type CocoManager = Awaited<ReturnType<typeof initializeCoco>>;
|
||||
|
||||
// Singleton pattern to prevent multiple initializations
|
||||
let globalCocoInstance: CocoManager | null = null;
|
||||
let globalRepositories: Repositories | null = null;
|
||||
let globalInitializationPromise: Promise<{ coco: CocoManager; repositories: Repositories }> | null = null;
|
||||
|
||||
export interface UseCashuReturn {
|
||||
// The typed coco manager (direct library access)
|
||||
coco: CocoManager | null;
|
||||
|
||||
// Repositories for direct access to proof data
|
||||
repositories: Repositories | null;
|
||||
|
||||
// React state (for reactivity)
|
||||
balances: { [mintUrl: string]: number };
|
||||
mints: Array<{ url: string; name?: string; info?: unknown }>;
|
||||
totalBalance: number;
|
||||
|
||||
// Status
|
||||
isInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
|
||||
// Mnemonic management
|
||||
mnemonic: string | null;
|
||||
setMnemonic: (mnemonic: string) => void;
|
||||
generateMnemonic: () => string;
|
||||
|
||||
// Utility functions
|
||||
clearError: () => void;
|
||||
getEncodedToken: typeof getEncodedToken;
|
||||
refreshMints: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
// Mnemonic management with localStorage
|
||||
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
||||
|
||||
// Manager instance ref
|
||||
const cocoRef = useRef<CocoManager | null>(null);
|
||||
const repositoriesRef = useRef<Repositories | null>(null);
|
||||
|
||||
// React state for UI reactivity
|
||||
const [balances, setBalances] = useState<{ [mintUrl: string]: number }>({});
|
||||
const [mints, setMints] = useState<Array<{ url: string; name?: string; info?: unknown }>>([]);
|
||||
|
||||
const clearError = useCallback(() => {
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const generateMnemonic = useCallback(() => {
|
||||
return bip39.generateMnemonic(wordlist);
|
||||
}, []);
|
||||
|
||||
const refreshMints = useCallback(async () => {
|
||||
const coco = cocoRef.current;
|
||||
if (!coco) return;
|
||||
|
||||
try {
|
||||
const mintList = await coco.mint.getAllMints();
|
||||
setMints(mintList.map((m: any) => ({
|
||||
url: m.mintUrl,
|
||||
name: m.name,
|
||||
info: m.mintInfo
|
||||
})));
|
||||
} catch (err) {
|
||||
console.error('Failed to refresh mints:', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setMnemonic = useCallback((newMnemonic: string) => {
|
||||
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
||||
throw new Error('Invalid mnemonic');
|
||||
}
|
||||
setMnemonicState(newMnemonic);
|
||||
// Reinitialize manager with new mnemonic
|
||||
setIsInitialized(false);
|
||||
}, [setMnemonicState]);
|
||||
|
||||
// Initialize the coco manager
|
||||
const initializeCocoManager = useCallback(async () => {
|
||||
if (isInitialized || isLoading) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Use singleton pattern to prevent multiple initializations
|
||||
if (globalCocoInstance && globalRepositories) {
|
||||
console.log('Using existing coco instance (singleton)');
|
||||
cocoRef.current = globalCocoInstance;
|
||||
repositoriesRef.current = globalRepositories;
|
||||
setIsInitialized(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// If there's already an initialization in progress, wait for it
|
||||
if (globalInitializationPromise) {
|
||||
console.log('Waiting for existing initialization...');
|
||||
const { coco, repositories } = await globalInitializationPromise;
|
||||
cocoRef.current = coco;
|
||||
repositoriesRef.current = repositories;
|
||||
setIsInitialized(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate or retrieve mnemonic
|
||||
let currentMnemonic = mnemonic;
|
||||
if (!currentMnemonic) {
|
||||
currentMnemonic = bip39.generateMnemonic(wordlist);
|
||||
setMnemonicState(currentMnemonic);
|
||||
}
|
||||
|
||||
// Create seed from mnemonic
|
||||
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
||||
|
||||
// Initialize repositories with proper initialization
|
||||
const repo = new IndexedDbRepositories({ name: "cashu-wallet" });
|
||||
await repo.init(); // Ensure repository is properly initialized
|
||||
|
||||
// Create initialization promise
|
||||
globalInitializationPromise = (async () => {
|
||||
const coco = await initializeCoco({
|
||||
repo,
|
||||
seedGetter: async () => seed,
|
||||
logger: new ConsoleLogger("coco", { level: "debug" }) // Use debug level for better logging
|
||||
});
|
||||
return { coco, repositories: repo };
|
||||
})();
|
||||
|
||||
// Initialize coco manager using the new API
|
||||
const { coco, repositories } = await globalInitializationPromise;
|
||||
|
||||
// Store as singleton
|
||||
console.log('Storing new coco instance as singleton');
|
||||
globalCocoInstance = coco;
|
||||
globalRepositories = repositories;
|
||||
globalInitializationPromise = null;
|
||||
cocoRef.current = coco;
|
||||
repositoriesRef.current = repositories;
|
||||
|
||||
// Enable built-in services for automatic quote processing and state watching
|
||||
try {
|
||||
console.log('Enabling coco services...');
|
||||
await coco.enableMintQuoteWatcher({ watchExistingPendingOnStart: false });
|
||||
console.log('Mint quote watcher enabled');
|
||||
|
||||
await coco.enableMintQuoteProcessor();
|
||||
console.log('Mint quote processor enabled');
|
||||
|
||||
await coco.enableProofStateWatcher();
|
||||
console.log('Proof state watcher enabled');
|
||||
|
||||
console.log('All coco services enabled successfully');
|
||||
} catch (err) {
|
||||
// Don't fail initialization if watchers can't be enabled
|
||||
console.warn('Failed to enable some coco services:', err);
|
||||
}
|
||||
|
||||
setIsInitialized(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
|
||||
setError(new Error(errorMessage));
|
||||
globalInitializationPromise = null; // Reset on error
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
||||
|
||||
// Initialize on mount and when mnemonic changes
|
||||
useEffect(() => {
|
||||
initializeCocoManager();
|
||||
}, [initializeCocoManager]);
|
||||
|
||||
// Auto-refresh balances and mints on manager events
|
||||
useEffect(() => {
|
||||
const coco = cocoRef.current;
|
||||
if (!coco) return;
|
||||
|
||||
const refreshBalances = async () => {
|
||||
try {
|
||||
const newBalances = await coco.wallet.getBalances();
|
||||
setBalances(newBalances);
|
||||
} catch (err) {
|
||||
// Silent failure - errors are handled by the manager
|
||||
}
|
||||
};
|
||||
|
||||
// Initial load
|
||||
refreshBalances();
|
||||
refreshMints();
|
||||
|
||||
// Listen to events
|
||||
const unsubs = [
|
||||
coco.on('proofs:saved', refreshBalances),
|
||||
coco.on('proofs:state-changed', refreshBalances),
|
||||
coco.on('send:created', refreshBalances),
|
||||
coco.on('receive:created', refreshBalances),
|
||||
coco.on('mint:added', refreshMints),
|
||||
coco.on('mint:updated', refreshMints),
|
||||
];
|
||||
|
||||
return () => unsubs.forEach(unsub => unsub());
|
||||
}, [isInitialized, refreshMints]);
|
||||
|
||||
// Calculate total balance
|
||||
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
|
||||
return {
|
||||
// The typed coco manager (direct library access)
|
||||
coco: cocoRef.current,
|
||||
|
||||
// Repositories for direct access to proof data
|
||||
repositories: repositoriesRef.current,
|
||||
|
||||
// React state (for reactivity)
|
||||
balances,
|
||||
mints,
|
||||
totalBalance,
|
||||
|
||||
// Status
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
|
||||
// Mnemonic management
|
||||
mnemonic,
|
||||
setMnemonic,
|
||||
generateMnemonic,
|
||||
|
||||
// Utility functions
|
||||
clearError,
|
||||
getEncodedToken,
|
||||
refreshMints,
|
||||
};
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import type { HistoryEntry } from 'coco-cashu-core';
|
||||
|
||||
interface UseHistoryManagerProps {
|
||||
coco: any; // Coco instance
|
||||
isInitialized: boolean;
|
||||
}
|
||||
|
||||
export function useHistoryManager({
|
||||
coco,
|
||||
isInitialized,
|
||||
}: UseHistoryManagerProps) {
|
||||
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
|
||||
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
|
||||
|
||||
// Load history from wallet
|
||||
const loadHistory = useCallback(async () => {
|
||||
if (!coco) return;
|
||||
|
||||
try {
|
||||
setIsLoadingHistory(true);
|
||||
const entries = await coco.history.getPaginatedHistory(0, 50); // TODO: show entire history
|
||||
setHistoryEntries(entries);
|
||||
} catch (err) {
|
||||
console.error('Failed to load history:', err);
|
||||
} finally {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
}, [coco]);
|
||||
|
||||
// Load history on wallet initialization
|
||||
useEffect(() => {
|
||||
if (isInitialized && historyEntries.length === 0) {
|
||||
loadHistory();
|
||||
}
|
||||
}, [isInitialized, historyEntries.length, loadHistory]);
|
||||
|
||||
// Auto-refresh on wallet events
|
||||
useEffect(() => {
|
||||
if (!isInitialized || !coco) return;
|
||||
|
||||
// Listen for history updates (fires on send, receive transactions)
|
||||
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
|
||||
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote paid (backup, in case creation event missed)
|
||||
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
|
||||
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribeHistoryUpdated();
|
||||
unsubscribeMeltCreated();
|
||||
unsubscribeMeltPaid();
|
||||
unsubscribeMintRedeemed();
|
||||
};
|
||||
}, [isInitialized, coco, loadHistory]);
|
||||
|
||||
return {
|
||||
historyEntries,
|
||||
setHistoryEntries,
|
||||
isLoadingHistory,
|
||||
isHistoryExpanded,
|
||||
setIsHistoryExpanded,
|
||||
loadHistory,
|
||||
};
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { getCleanMintLabel } from './walletUtils';
|
||||
|
||||
export interface CashuMint {
|
||||
url: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
interface UseMintManagerProps {
|
||||
coco: any; // Coco instance
|
||||
mints: CashuMint[];
|
||||
repositories: any; // Repositories instance
|
||||
isNpubCashLoggedIn: boolean;
|
||||
setNpubCashMint: (mintUrl: string) => Promise<boolean>;
|
||||
refreshMints: () => Promise<void>;
|
||||
toast: any; // Toast function
|
||||
}
|
||||
|
||||
export function useMintManager({
|
||||
coco,
|
||||
mints,
|
||||
repositories,
|
||||
isNpubCashLoggedIn,
|
||||
setNpubCashMint,
|
||||
refreshMints,
|
||||
toast,
|
||||
}: UseMintManagerProps) {
|
||||
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
|
||||
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
|
||||
const [mintUrl, setMintUrl] = useState('');
|
||||
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
|
||||
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
|
||||
|
||||
// Set active mint and optionally sync to npub.cash
|
||||
const handleSetActiveMint = useCallback(
|
||||
async (url: string | null, syncToNpubCash = true) => {
|
||||
setActiveMintUrl(url);
|
||||
|
||||
// Sync to npub.cash if user is logged in and we should sync
|
||||
if (isNpubCashLoggedIn && url && syncToNpubCash) {
|
||||
try {
|
||||
await setNpubCashMint(url);
|
||||
} catch (err) {
|
||||
console.error('Failed to sync mint to npub.cash:', err);
|
||||
}
|
||||
}
|
||||
},
|
||||
[isNpubCashLoggedIn, setNpubCashMint]
|
||||
);
|
||||
|
||||
// Add a new mint
|
||||
const handleAddMint = useCallback(async () => {
|
||||
if (!mintUrl.trim() || !coco) return;
|
||||
try {
|
||||
// Normalize URL - add https:// if not present
|
||||
let normalizedUrl = mintUrl.trim();
|
||||
if (
|
||||
!normalizedUrl.startsWith('http://') &&
|
||||
!normalizedUrl.startsWith('https://')
|
||||
) {
|
||||
normalizedUrl = `https://${normalizedUrl}`;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
await coco.mint.addMint(normalizedUrl);
|
||||
setMintUrl('');
|
||||
|
||||
toast({
|
||||
title: 'Mint Added',
|
||||
description: 'Mint added successfully!',
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Add Mint Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}, [mintUrl, coco, mints, toast]);
|
||||
|
||||
// Show remove confirmation modal
|
||||
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
|
||||
setMintDropdownOpen(false); // Close dropdown before showing modal
|
||||
setMintToRemove(mint);
|
||||
setShowRemoveMintModal(true);
|
||||
}, []);
|
||||
|
||||
// Confirm and remove mint
|
||||
const handleConfirmRemoveMint = useCallback(async () => {
|
||||
if (!mintToRemove || !repositories) return;
|
||||
|
||||
try {
|
||||
// Delete the mint from the backend using the mint repository directly
|
||||
await repositories.mintRepository.deleteMint(mintToRemove.url);
|
||||
|
||||
// If the removed mint was active, switch to the first available mint
|
||||
if (activeMintUrl === mintToRemove.url) {
|
||||
const remainingMints = mints.filter(
|
||||
(mint) => mint.url !== mintToRemove.url
|
||||
);
|
||||
if (remainingMints.length > 0) {
|
||||
handleSetActiveMint(remainingMints[0].url, false);
|
||||
} else {
|
||||
setActiveMintUrl(null);
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Mint Removed',
|
||||
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
|
||||
});
|
||||
|
||||
// Refresh the mints list to update the dropdown immediately
|
||||
await refreshMints();
|
||||
|
||||
setShowRemoveMintModal(false);
|
||||
setMintToRemove(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to remove mint:', err);
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Remove Mint Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}, [
|
||||
mintToRemove,
|
||||
mints,
|
||||
activeMintUrl,
|
||||
handleSetActiveMint,
|
||||
repositories,
|
||||
toast,
|
||||
refreshMints,
|
||||
]);
|
||||
|
||||
// Show denomination breakdown for a mint
|
||||
const handleShowDenominations = useCallback(
|
||||
async (
|
||||
mintUrl: string,
|
||||
setShowProofBreakdown: (show: boolean) => void,
|
||||
setProofBreakdown: (breakdown: {
|
||||
mintUrl: string;
|
||||
denominations: { [key: number]: number };
|
||||
totalBalance: number;
|
||||
}) => void
|
||||
) => {
|
||||
if (!repositories) return;
|
||||
|
||||
try {
|
||||
// Access proofs directly through the proof repository
|
||||
const proofs = await repositories.proofRepository.getReadyProofs(
|
||||
mintUrl
|
||||
);
|
||||
|
||||
if (!proofs || proofs.length === 0) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'No Tokens',
|
||||
description: 'No tokens found for this mint',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Group proofs by denomination
|
||||
const denominations: { [key: number]: number } = {};
|
||||
proofs.forEach((proof: { amount?: number }) => {
|
||||
const amount = proof.amount || 0;
|
||||
denominations[amount] = (denominations[amount] || 0) + 1;
|
||||
});
|
||||
|
||||
const totalBalance = Object.entries(denominations).reduce(
|
||||
(sum, [amount, count]) => sum + parseInt(amount) * count,
|
||||
0
|
||||
);
|
||||
|
||||
// Set the breakdown data and show the modal
|
||||
setProofBreakdown({
|
||||
mintUrl,
|
||||
denominations,
|
||||
totalBalance,
|
||||
});
|
||||
setShowProofBreakdown(true);
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Failed to Get Denominations',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
},
|
||||
[repositories, toast]
|
||||
);
|
||||
|
||||
// Auto-select first mint when mints change, or add default mint if none exist
|
||||
useEffect(() => {
|
||||
if (mints.length > 0 && !activeMintUrl) {
|
||||
// Select first mint initially - user can change via dropdown
|
||||
// Don't sync to npub.cash on auto-select, only on manual changes
|
||||
handleSetActiveMint(mints[0].url, false);
|
||||
} else if (mints.length === 0 && !activeMintUrl && coco) {
|
||||
// Add default mint if no mints exist
|
||||
const addDefaultMint = async () => {
|
||||
try {
|
||||
await coco.mint.addMint('https://mint.chorus.community');
|
||||
// The mint will be added and refreshMints will be called via event listeners
|
||||
} catch (err) {
|
||||
console.error('Failed to add default mint:', err);
|
||||
}
|
||||
};
|
||||
addDefaultMint();
|
||||
}
|
||||
}, [mints, activeMintUrl, handleSetActiveMint, coco]);
|
||||
|
||||
return {
|
||||
activeMintUrl,
|
||||
setActiveMintUrl: handleSetActiveMint,
|
||||
mintUrl,
|
||||
setMintUrl,
|
||||
mintDropdownOpen,
|
||||
setMintDropdownOpen,
|
||||
handleAddMint,
|
||||
handleRemoveMintClick,
|
||||
handleConfirmRemoveMint,
|
||||
mintToRemove,
|
||||
setMintToRemove,
|
||||
showRemoveMintModal,
|
||||
setShowRemoveMintModal,
|
||||
getCleanMintLabel,
|
||||
handleShowDenominations,
|
||||
};
|
||||
}
|
||||
@@ -1,432 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
|
||||
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
|
||||
|
||||
interface UseWalletTransactionsProps {
|
||||
coco: any; // Coco instance
|
||||
activeMintUrl: string | null;
|
||||
isNpubCashLoggedIn: boolean;
|
||||
repositories: any; // Repositories instance
|
||||
generateQRCode: (text: string) => Promise<string>;
|
||||
toast: any; // Toast function
|
||||
getEncodedToken: (token: any) => string;
|
||||
getLightningInvoice: (params: {
|
||||
lightningAddress: string;
|
||||
amountSats: number;
|
||||
}) => Promise<string>;
|
||||
}
|
||||
|
||||
export function useWalletTransactions({
|
||||
coco,
|
||||
activeMintUrl,
|
||||
isNpubCashLoggedIn,
|
||||
repositories,
|
||||
generateQRCode,
|
||||
toast,
|
||||
getEncodedToken,
|
||||
getLightningInvoice,
|
||||
}: UseWalletTransactionsProps) {
|
||||
// Receive state
|
||||
const [tokenInput, setTokenInput] = useState('');
|
||||
const [quoteAmount, setQuoteAmount] = useState('');
|
||||
|
||||
// Send state
|
||||
const [sendAmount, setSendAmount] = useState('');
|
||||
const [lightningInvoice, setLightningInvoice] = useState('');
|
||||
const [lightningAddressInput, setLightningAddressInput] = useState('');
|
||||
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
|
||||
const [pendingLightningAddress, setPendingLightningAddress] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
|
||||
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
|
||||
|
||||
// Transaction output state
|
||||
const [sentToken, setSentToken] = useState<string | null>(null);
|
||||
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
|
||||
|
||||
// Invoice modal state
|
||||
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
|
||||
const [currentInvoice, setCurrentInvoice] = useState<{
|
||||
quoteId: string;
|
||||
mintUrl: string;
|
||||
amount: number;
|
||||
invoice: string;
|
||||
qrCodeUrl: string;
|
||||
expiry: number;
|
||||
} | null>(null);
|
||||
|
||||
// Ref to store the mint quote redeemed event unsubscribe function
|
||||
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||
|
||||
// Generate QR code for sent token
|
||||
const generateSentTokenQRCode = useCallback(async (token: string) => {
|
||||
try {
|
||||
const qrCodeUrl = await generateQRCode(token);
|
||||
setSentTokenQRCode(qrCodeUrl);
|
||||
} catch (err) {
|
||||
console.error('Failed to generate sent token QR code:', err);
|
||||
}
|
||||
}, [generateQRCode]);
|
||||
|
||||
// Handle unknown mint error by adding the mint and retrying
|
||||
const handleUnknownMintError = useCallback(
|
||||
async (mintUrl: string) => {
|
||||
if (!coco) return;
|
||||
|
||||
try {
|
||||
console.log('Adding unknown mint:', mintUrl);
|
||||
|
||||
// Add the mint
|
||||
await coco.mint.addMint(mintUrl);
|
||||
|
||||
// Retry receiving the token
|
||||
await coco.wallet.receive(tokenInput);
|
||||
setTokenInput('');
|
||||
|
||||
toast({
|
||||
title: 'Token Received',
|
||||
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
|
||||
});
|
||||
} catch (retryErr) {
|
||||
console.error('Failed to add mint and retry receive:', retryErr);
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Receive Failed',
|
||||
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
|
||||
});
|
||||
}
|
||||
},
|
||||
[coco, tokenInput, toast]
|
||||
);
|
||||
|
||||
// Handle receive (token or Lightning)
|
||||
const handleReceive = useCallback(async () => {
|
||||
if (!coco) return;
|
||||
|
||||
// Receive Cashu token mode
|
||||
if (!tokenInput && !quoteAmount) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (tokenInput) {
|
||||
// Receive token mode
|
||||
try {
|
||||
console.log(
|
||||
'Attempting to receive token:',
|
||||
tokenInput.substring(0, 20) + '...'
|
||||
);
|
||||
await coco.wallet.receive(tokenInput);
|
||||
setTokenInput('');
|
||||
toast({
|
||||
title: 'Token Received',
|
||||
description: 'Cashu token redeemed successfully!',
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Token receive error:', err);
|
||||
|
||||
// Handle UnknownMintError by automatically adding the mint
|
||||
if (isUnknownMintError(err)) {
|
||||
const mintUrl = extractMintUrlFromError(err);
|
||||
if (mintUrl) {
|
||||
await handleUnknownMintError(mintUrl);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Receive Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else if (quoteAmount && activeMintUrl) {
|
||||
// Lightning quote mode
|
||||
try {
|
||||
const amount = parseInt(quoteAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Invalid Amount',
|
||||
description: 'Please enter a valid amount',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
|
||||
|
||||
// Generate QR code for the Lightning invoice
|
||||
const qrCodeUrl = await generateQRCode(quote.request);
|
||||
|
||||
// Set the invoice data and show modal
|
||||
setCurrentInvoice({
|
||||
quoteId: quote.quote,
|
||||
mintUrl: activeMintUrl,
|
||||
amount,
|
||||
invoice: quote.request,
|
||||
qrCodeUrl,
|
||||
expiry: quote.expiry,
|
||||
});
|
||||
|
||||
setShowInvoiceModal(true);
|
||||
setQuoteAmount('');
|
||||
|
||||
// Clean up any previous listener
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
|
||||
// Listen for payment notification via mint-quote:redeemed event
|
||||
const quoteId = quote.quote;
|
||||
const invoiceAmount = amount;
|
||||
|
||||
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
|
||||
const redeemedQuote = payload as { quoteId?: string };
|
||||
|
||||
// Check if this is the quote we're waiting for
|
||||
if (redeemedQuote.quoteId === quoteId) {
|
||||
toast({
|
||||
title: 'Payment Received',
|
||||
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
|
||||
});
|
||||
setShowInvoiceModal(false);
|
||||
setCurrentInvoice(null);
|
||||
|
||||
// Clean up the event listener
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
// Store unsubscribe function for cleanup
|
||||
mintQuoteUnsubscribeRef.current = unsubscribe;
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Quote Creation Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [
|
||||
coco,
|
||||
tokenInput,
|
||||
quoteAmount,
|
||||
activeMintUrl,
|
||||
toast,
|
||||
generateQRCode,
|
||||
handleUnknownMintError,
|
||||
]);
|
||||
|
||||
// Handle send (token or Lightning)
|
||||
const handleSend = useCallback(async () => {
|
||||
if (!coco) return;
|
||||
|
||||
if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Send Cashu token mode
|
||||
if (sendAmount && activeMintUrl) {
|
||||
try {
|
||||
const amount = parseInt(sendAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Invalid Amount',
|
||||
description: 'Please enter a valid amount',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const token = await coco.wallet.send(activeMintUrl, amount);
|
||||
const encodedToken = getEncodedToken(token);
|
||||
setSentToken(encodedToken);
|
||||
await generateSentTokenQRCode(encodedToken);
|
||||
setSendAmount('');
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Send Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else if (activeMintUrl) {
|
||||
// Lightning mode
|
||||
// Step 1: Check if we have a pending Lightning address awaiting amount
|
||||
if (pendingLightningAddress) {
|
||||
// Step 2: User entered amount, now resolve address and pay
|
||||
if (!lightningAddressAmount) return;
|
||||
|
||||
try {
|
||||
const amount = parseInt(lightningAddressAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Invalid Amount',
|
||||
description: 'Please enter a valid amount',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const invoice = await getLightningInvoice({
|
||||
lightningAddress: pendingLightningAddress,
|
||||
amountSats: amount,
|
||||
});
|
||||
|
||||
const meltQuote = await coco.quotes.createMeltQuote(
|
||||
activeMintUrl,
|
||||
invoice
|
||||
);
|
||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
|
||||
toast({
|
||||
title: 'Payment Sent',
|
||||
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
|
||||
});
|
||||
|
||||
// Reset state
|
||||
setPendingLightningAddress(null);
|
||||
setLightningAddressInput('');
|
||||
setLightningAddressAmount('');
|
||||
} catch (err) {
|
||||
console.error('Payment error:', err);
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Payment Failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Step 1: Check if input is a Lightning address or invoice
|
||||
const input = lightningInvoice.trim() || lightningAddressInput.trim();
|
||||
if (!input) return;
|
||||
|
||||
// Check if it's a Lightning address (contains @)
|
||||
if (input.includes('@')) {
|
||||
setPendingLightningAddress(input);
|
||||
setLightningAddressInput('');
|
||||
} else {
|
||||
// It's a regular Lightning invoice - decode to show amount first
|
||||
if (isValidBolt11Invoice(input)) {
|
||||
const amount = decodeBolt11Amount(input);
|
||||
if (amount) {
|
||||
// Show amount confirmation screen
|
||||
setPendingInvoice(input);
|
||||
setDecodedInvoiceAmount(amount);
|
||||
setLightningInvoice('');
|
||||
return;
|
||||
} else {
|
||||
// Failed to decode amount - show error and don't attempt payment
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Invalid Invoice',
|
||||
description: 'Unable to decode the lightning invoice amount. Please check the invoice format.',
|
||||
});
|
||||
setLightningInvoice('');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Not a valid BOLT11 invoice - show error and don't attempt payment
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Invalid Invoice',
|
||||
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
|
||||
});
|
||||
setLightningInvoice('');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [
|
||||
coco,
|
||||
sendAmount,
|
||||
lightningInvoice,
|
||||
lightningAddressInput,
|
||||
lightningAddressAmount,
|
||||
pendingLightningAddress,
|
||||
pendingInvoice,
|
||||
decodedInvoiceAmount,
|
||||
activeMintUrl,
|
||||
toast,
|
||||
getEncodedToken,
|
||||
generateSentTokenQRCode,
|
||||
getLightningInvoice,
|
||||
]);
|
||||
|
||||
// Handle confirmed invoice payment
|
||||
const handleConfirmInvoicePayment = useCallback(async () => {
|
||||
if (!coco || !pendingInvoice || !activeMintUrl) return;
|
||||
|
||||
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',
|
||||
});
|
||||
}
|
||||
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]);
|
||||
|
||||
// Cleanup mint quote listener on component unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
// Receive state
|
||||
tokenInput,
|
||||
setTokenInput,
|
||||
quoteAmount,
|
||||
setQuoteAmount,
|
||||
// Send state
|
||||
sendAmount,
|
||||
setSendAmount,
|
||||
lightningInvoice,
|
||||
setLightningInvoice,
|
||||
lightningAddressInput,
|
||||
setLightningAddressInput,
|
||||
lightningAddressAmount,
|
||||
setLightningAddressAmount,
|
||||
pendingLightningAddress,
|
||||
setPendingLightningAddress,
|
||||
decodedInvoiceAmount,
|
||||
setDecodedInvoiceAmount,
|
||||
pendingInvoice,
|
||||
setPendingInvoice,
|
||||
// Transaction output state
|
||||
sentToken,
|
||||
setSentToken,
|
||||
sentTokenQRCode,
|
||||
// Invoice modal state
|
||||
showInvoiceModal,
|
||||
setShowInvoiceModal,
|
||||
currentInvoice,
|
||||
setCurrentInvoice,
|
||||
// Handlers
|
||||
handleReceive,
|
||||
handleSend,
|
||||
handleConfirmInvoicePayment,
|
||||
// Refs
|
||||
mintQuoteUnsubscribeRef,
|
||||
};
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
export const getCleanMintLabel = (mint: { name?: string; url: string }): string => {
|
||||
if (mint.name && mint.name.trim().length > 0) {
|
||||
return mint.name.replace(/^https?:\/\//, '');
|
||||
}
|
||||
try {
|
||||
return new URL(mint.url).host;
|
||||
} catch {
|
||||
return mint.url.replace(/^https?:\/\//, '');
|
||||
}
|
||||
};
|
||||
|
||||
export const isUnknownMintError = (err: unknown): boolean => {
|
||||
const errorMessage = (err as any)?.message || err?.toString() || '';
|
||||
return (err as any)?.constructor?.name === 'UnknownMintError' ||
|
||||
errorMessage.includes('UnknownMintError') ||
|
||||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
|
||||
};
|
||||
|
||||
export const extractMintUrlFromError = (err: unknown): string | null => {
|
||||
const errorMessage = (err as any)?.message || err?.toString() || '';
|
||||
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
|
||||
return mintUrlMatch?.[1] || null;
|
||||
};
|
||||
@@ -0,0 +1,237 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useNostrPublish } from './useNostrPublish';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Custom kind for admin storage
|
||||
const ADMIN_STORAGE_KIND = 39767;
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export interface AdminStorageData {
|
||||
hiddenEvents: string[];
|
||||
allowList: string[];
|
||||
denyList: string[];
|
||||
blockedWords: string[];
|
||||
caseSensitive: boolean;
|
||||
wholeWordsOnly: boolean;
|
||||
enableModeration: boolean;
|
||||
autoHideBlocked: boolean;
|
||||
requireApproval: boolean;
|
||||
siteName: string;
|
||||
siteDescription: string;
|
||||
}
|
||||
|
||||
const defaultAdminData: AdminStorageData = {
|
||||
hiddenEvents: [],
|
||||
allowList: [],
|
||||
denyList: [],
|
||||
blockedWords: [],
|
||||
caseSensitive: false,
|
||||
wholeWordsOnly: true,
|
||||
enableModeration: true,
|
||||
autoHideBlocked: true,
|
||||
requireApproval: false,
|
||||
siteName: '',
|
||||
siteDescription: '',
|
||||
};
|
||||
|
||||
export function useAdminStorage() {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Get admin pubkey
|
||||
let adminPubkey: string = '';
|
||||
try {
|
||||
if (ADMIN_NPUB) {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid admin npub
|
||||
}
|
||||
|
||||
// Check if current user is admin
|
||||
const isAdmin = user?.pubkey === adminPubkey && !!adminPubkey;
|
||||
|
||||
// Query for admin storage events
|
||||
const adminDataQuery = useQuery({
|
||||
queryKey: ['admin-storage', adminPubkey],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!adminPubkey) return defaultAdminData;
|
||||
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
// Query for admin storage events
|
||||
const events = await nostr.query([{
|
||||
kinds: [ADMIN_STORAGE_KIND],
|
||||
authors: [adminPubkey],
|
||||
'#d': ['admin-config'],
|
||||
limit: 1
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
if (events.length === 0) {
|
||||
return defaultAdminData;
|
||||
}
|
||||
|
||||
// Get the most recent event
|
||||
const latestEvent = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
try {
|
||||
const data = JSON.parse(latestEvent.content) as AdminStorageData;
|
||||
// Merge with defaults to handle missing fields
|
||||
return { ...defaultAdminData, ...data };
|
||||
} catch {
|
||||
return defaultAdminData;
|
||||
}
|
||||
},
|
||||
enabled: !!adminPubkey,
|
||||
});
|
||||
|
||||
// Mutation to save admin data
|
||||
const saveAdminData = useMutation({
|
||||
mutationFn: async (data: Partial<AdminStorageData>) => {
|
||||
if (!isAdmin) {
|
||||
throw new Error('Only admin can save admin data');
|
||||
}
|
||||
|
||||
const currentData = adminDataQuery.data || defaultAdminData;
|
||||
const updatedData = { ...currentData, ...data };
|
||||
|
||||
await publishEvent({
|
||||
kind: ADMIN_STORAGE_KIND,
|
||||
content: JSON.stringify(updatedData),
|
||||
tags: [
|
||||
['d', 'admin-config'],
|
||||
['alt', 'Site administration configuration and policies'],
|
||||
],
|
||||
});
|
||||
|
||||
return updatedData;
|
||||
},
|
||||
onSuccess: (updatedData) => {
|
||||
// Update the cache with new data
|
||||
queryClient.setQueryData(['admin-storage', adminPubkey], updatedData);
|
||||
},
|
||||
});
|
||||
|
||||
// Helper functions for specific data updates
|
||||
const updateHiddenEvents = (hiddenEvents: string[]) =>
|
||||
saveAdminData.mutateAsync({ hiddenEvents });
|
||||
|
||||
const updateAllowList = (allowList: string[]) =>
|
||||
saveAdminData.mutateAsync({ allowList });
|
||||
|
||||
const updateDenyList = (denyList: string[]) =>
|
||||
saveAdminData.mutateAsync({ denyList });
|
||||
|
||||
const updateBlockedWords = (blockedWords: string[]) =>
|
||||
saveAdminData.mutateAsync({ blockedWords });
|
||||
|
||||
const updateModerationSettings = (settings: {
|
||||
caseSensitive?: boolean;
|
||||
wholeWordsOnly?: boolean;
|
||||
enableModeration?: boolean;
|
||||
autoHideBlocked?: boolean;
|
||||
requireApproval?: boolean;
|
||||
}) => saveAdminData.mutateAsync(settings);
|
||||
|
||||
const updateSiteSettings = (settings: {
|
||||
siteName?: string;
|
||||
siteDescription?: string;
|
||||
}) => saveAdminData.mutateAsync(settings);
|
||||
|
||||
return {
|
||||
// Data
|
||||
data: adminDataQuery.data || defaultAdminData,
|
||||
isLoading: adminDataQuery.isLoading,
|
||||
error: adminDataQuery.error,
|
||||
|
||||
// Auth
|
||||
isAdmin,
|
||||
adminPubkey,
|
||||
|
||||
// Mutations
|
||||
saveAdminData: saveAdminData.mutateAsync,
|
||||
isSaving: saveAdminData.isPending,
|
||||
|
||||
// Helper functions
|
||||
updateHiddenEvents,
|
||||
updateAllowList,
|
||||
updateDenyList,
|
||||
updateBlockedWords,
|
||||
updateModerationSettings,
|
||||
updateSiteSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// Hook for checking if content should be hidden based on admin policies
|
||||
export function useContentFilter() {
|
||||
const { data: adminData } = useAdminStorage();
|
||||
|
||||
const isContentHidden = (eventId: string): boolean => {
|
||||
return adminData.hiddenEvents.includes(eventId);
|
||||
};
|
||||
|
||||
const isUserBlocked = (pubkey: string): boolean => {
|
||||
// If allow list exists and user is not on it, they're blocked
|
||||
if (adminData.allowList.length > 0 && !adminData.allowList.includes(pubkey)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If user is on deny list, they're blocked
|
||||
return adminData.denyList.includes(pubkey);
|
||||
};
|
||||
|
||||
const isContentBlocked = (content: string): boolean => {
|
||||
if (!adminData.enableModeration || adminData.blockedWords.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = adminData.caseSensitive ? content : content.toLowerCase();
|
||||
|
||||
return adminData.blockedWords.some(word => {
|
||||
const searchWord = adminData.caseSensitive ? word : word.toLowerCase();
|
||||
|
||||
if (adminData.wholeWordsOnly) {
|
||||
// Match whole words only
|
||||
const regex = new RegExp(`\\b${searchWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
||||
return regex.test(text);
|
||||
} else {
|
||||
// Match partial words
|
||||
return text.includes(searchWord);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const shouldHideContent = (eventId: string, pubkey: string, content: string): boolean => {
|
||||
if (!adminData.enableModeration) return false;
|
||||
|
||||
// Check if manually hidden
|
||||
if (isContentHidden(eventId)) return true;
|
||||
|
||||
// Check if user is blocked
|
||||
if (isUserBlocked(pubkey)) return true;
|
||||
|
||||
// Check if content contains blocked words and auto-hide is enabled
|
||||
if (adminData.autoHideBlocked && isContentBlocked(content)) return true;
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
isContentHidden,
|
||||
isUserBlocked,
|
||||
isContentBlocked,
|
||||
shouldHideContent,
|
||||
adminData,
|
||||
};
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { fetchUTXOs, type UTXO } from '@/lib/bitcoin';
|
||||
|
||||
/**
|
||||
* 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
|
||||
});
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useToast } from './useToast';
|
||||
|
||||
interface UseCopyToClipboardReturn {
|
||||
copy: (text: string) => Promise<void>;
|
||||
copied: boolean;
|
||||
copyError: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for copying text to clipboard with feedback
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { copy, copied, copyError } = useCopyToClipboard();
|
||||
*
|
||||
* await copy('cashuBo2Ft...');
|
||||
* // copied will be true for 2 seconds
|
||||
* ```
|
||||
*/
|
||||
export function useCopyToClipboard(): UseCopyToClipboardReturn {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [copyError, setCopyError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const copy = useCallback(async (text: string): Promise<void> => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setCopyError(null);
|
||||
|
||||
// Auto-reset copied state after 2 seconds
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (err) {
|
||||
const errorMessage = 'Failed to copy to clipboard';
|
||||
console.error(errorMessage, err);
|
||||
setCopyError(errorMessage);
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Copy Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
return {
|
||||
copy,
|
||||
copied,
|
||||
copyError,
|
||||
};
|
||||
}
|
||||
+12
-12
@@ -1,19 +1,19 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile;
|
||||
return !!isMobile
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
// LNURL Protocol Types
|
||||
interface LNURLPayResponse {
|
||||
status: 'OK' | 'ERROR';
|
||||
tag: 'payRequest';
|
||||
commentAllowed?: number;
|
||||
minSendable: number; // millisats
|
||||
maxSendable: number; // millisats
|
||||
metadata: string;
|
||||
callback: string;
|
||||
}
|
||||
|
||||
interface LNURLInvoiceResponse {
|
||||
status: 'OK' | 'ERROR';
|
||||
reason?: string;
|
||||
pr?: string; // BOLT11 invoice
|
||||
}
|
||||
|
||||
interface GetInvoiceParams {
|
||||
lightningAddress: string;
|
||||
amountSats: number;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
interface UseLightningAddressReturn {
|
||||
getInvoice: (params: GetInvoiceParams) => Promise<string>;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for resolving Lightning addresses to invoices
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { getInvoice, isLoading, error } = useLightningAddress();
|
||||
*
|
||||
* const invoice = await getInvoice({
|
||||
* lightningAddress: '[email protected]',
|
||||
* amountSats: 1000,
|
||||
* comment: 'Thanks for the coffee!'
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function useLightningAddress(): UseLightningAddressReturn {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
/**
|
||||
* Fetches a Lightning invoice for the given address and amount
|
||||
*
|
||||
* @param params - Lightning address, amount in sats, and optional comment
|
||||
* @returns BOLT11 invoice string
|
||||
* @throws Error if resolution fails
|
||||
*/
|
||||
const getInvoice = useCallback(async (params: GetInvoiceParams): Promise<string> => {
|
||||
const { lightningAddress, amountSats, comment } = params;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Validate inputs
|
||||
if (!lightningAddress || !lightningAddress.includes('@')) {
|
||||
throw new Error('Invalid Lightning address format. Expected: [email protected]');
|
||||
}
|
||||
|
||||
if (amountSats <= 0) {
|
||||
throw new Error('Amount must be greater than 0');
|
||||
}
|
||||
|
||||
// Parse Lightning address
|
||||
const [username, domain] = lightningAddress.split('@');
|
||||
if (!username || !domain) {
|
||||
throw new Error('Invalid Lightning address format');
|
||||
}
|
||||
|
||||
// Step 1: Fetch LNURL-pay info
|
||||
const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`;
|
||||
|
||||
console.log('Resolving Lightning address:', {
|
||||
lightningAddress,
|
||||
lnurlEndpoint,
|
||||
amountSats
|
||||
});
|
||||
|
||||
const lnurlResponse = await fetch(lnurlEndpoint, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
});
|
||||
|
||||
if (!lnurlResponse.ok) {
|
||||
console.error('LNURL Endpoint Error:', {
|
||||
lightningAddress,
|
||||
lnurlEndpoint,
|
||||
status: lnurlResponse.status,
|
||||
statusText: lnurlResponse.statusText
|
||||
});
|
||||
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status} ${lnurlResponse.statusText}`);
|
||||
}
|
||||
|
||||
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
|
||||
|
||||
console.log('LNURL Response:', {
|
||||
lightningAddress,
|
||||
lnurlData
|
||||
});
|
||||
|
||||
if (lnurlData.status && lnurlData.status !== 'OK') {
|
||||
console.error('LNURL Status Error:', {
|
||||
lightningAddress,
|
||||
status: lnurlData.status,
|
||||
response: lnurlData
|
||||
});
|
||||
throw new Error('LNURL endpoint returned error status');
|
||||
}
|
||||
|
||||
if (lnurlData.tag !== 'payRequest') {
|
||||
console.error('LNURL Tag Error:', {
|
||||
lightningAddress,
|
||||
expectedTag: 'payRequest',
|
||||
actualTag: lnurlData.tag,
|
||||
response: lnurlData
|
||||
});
|
||||
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
|
||||
}
|
||||
|
||||
// Validate amount against min/max bounds
|
||||
const minSats = lnurlData.minSendable / 1000;
|
||||
const maxSats = lnurlData.maxSendable / 1000;
|
||||
|
||||
console.log('Amount validation:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
minSats,
|
||||
maxSats,
|
||||
minSendable: lnurlData.minSendable,
|
||||
maxSendable: lnurlData.maxSendable
|
||||
});
|
||||
|
||||
if (amountSats < minSats) {
|
||||
console.error('Amount below minimum:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
minSats,
|
||||
maxSats
|
||||
});
|
||||
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
|
||||
}
|
||||
|
||||
if (amountSats > maxSats) {
|
||||
console.error('Amount exceeds maximum:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
minSats,
|
||||
maxSats
|
||||
});
|
||||
throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`);
|
||||
}
|
||||
|
||||
// Step 2: Request invoice from callback URL
|
||||
const amountMsats = amountSats * 1000;
|
||||
const callbackUrl = new URL(lnurlData.callback);
|
||||
callbackUrl.searchParams.set('amount', amountMsats.toString());
|
||||
|
||||
// Add comment if provided and allowed
|
||||
if (comment && lnurlData.commentAllowed && comment.length <= lnurlData.commentAllowed) {
|
||||
callbackUrl.searchParams.set('comment', comment);
|
||||
}
|
||||
|
||||
console.log('Requesting invoice:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
amountMsats,
|
||||
callbackUrl: callbackUrl.toString(),
|
||||
comment
|
||||
});
|
||||
|
||||
const invoiceResponse = await fetch(callbackUrl.toString(), {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
});
|
||||
|
||||
if (!invoiceResponse.ok) {
|
||||
console.error('Invoice Request Error:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
callbackUrl: callbackUrl.toString(),
|
||||
status: invoiceResponse.status,
|
||||
statusText: invoiceResponse.statusText
|
||||
});
|
||||
throw new Error(`Failed to get invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
|
||||
}
|
||||
|
||||
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
|
||||
|
||||
console.log('Invoice Response:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
invoiceData
|
||||
});
|
||||
|
||||
// Check if we have a valid invoice (some providers return invoice directly without status field)
|
||||
if (invoiceData.pr) {
|
||||
console.log('Invoice generated successfully:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
invoiceLength: invoiceData.pr.length
|
||||
});
|
||||
setIsLoading(false);
|
||||
return invoiceData.pr;
|
||||
}
|
||||
|
||||
// If no invoice but has status field, check for errors
|
||||
if (invoiceData.status && invoiceData.status !== 'OK') {
|
||||
const errorReason = invoiceData.reason || 'Invoice generation failed';
|
||||
console.error('LNURL Invoice Error:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
status: invoiceData.status,
|
||||
reason: errorReason,
|
||||
response: invoiceData
|
||||
});
|
||||
throw new Error(`Invoice generation failed: ${errorReason}`);
|
||||
}
|
||||
|
||||
// If we get here, no invoice was provided
|
||||
console.error('LNURL Invoice Missing PR:', {
|
||||
lightningAddress,
|
||||
amountSats,
|
||||
response: invoiceData
|
||||
});
|
||||
throw new Error('No invoice returned from provider');
|
||||
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
|
||||
setError(errorMessage);
|
||||
setIsLoading(false);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
getInvoice,
|
||||
isLoading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
export type { GetInvoiceParams };
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export interface NIP98Options {
|
||||
url: string;
|
||||
method: string;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for creating NIP-98 HTTP Authentication headers
|
||||
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
|
||||
*/
|
||||
export function useNIP98() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
/**
|
||||
* Create a NIP-98 authorization header for HTTP requests
|
||||
* @param options - The request details (url, method, optional body)
|
||||
* @returns Promise<string> - The "Nostr base64..." authorization header value
|
||||
*/
|
||||
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to create NIP-98 auth header');
|
||||
}
|
||||
|
||||
const { url, method, body } = options;
|
||||
|
||||
// Parse URL to remove query parameters (per NIP-98 spec)
|
||||
const urlObj = new URL(url);
|
||||
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
|
||||
|
||||
const tags: string[][] = [
|
||||
['u', urlWithoutQuery],
|
||||
['method', method.toUpperCase()],
|
||||
];
|
||||
|
||||
// If there's a request body (POST, PUT, PATCH), add payload hash
|
||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
||||
const bodyString = JSON.stringify(body);
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(bodyString);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
tags.push(['payload', payloadHash]);
|
||||
}
|
||||
|
||||
// Create and sign the NIP-98 event (kind 27235)
|
||||
const event = await user.signer.signEvent({
|
||||
kind: 27235,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}) as NostrEvent;
|
||||
|
||||
// Encode the event as base64
|
||||
const eventJson = JSON.stringify(event);
|
||||
const base64Event = btoa(eventJson);
|
||||
|
||||
return `Nostr ${base64Event}`;
|
||||
}, [user]);
|
||||
|
||||
return {
|
||||
createAuthHeader,
|
||||
isLoggedIn: !!user,
|
||||
pubkey: user?.pubkey,
|
||||
signer: user?.signer,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
import { useCallback, useState, useMemo, useEffect, useRef } from 'react';
|
||||
import { useNIP98 } from './useNIP98';
|
||||
import { NPCClient, JWTAuthProvider } from 'npubcash-sdk';
|
||||
import type { User, Quote } from 'npubcash-types';
|
||||
|
||||
const NPUBCASH_BASE_URL = 'https://npubx.cash';
|
||||
|
||||
export interface NpubCashUserInfo {
|
||||
pubkey: string;
|
||||
name?: string;
|
||||
mint_url: string;
|
||||
lock_quote: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for interacting with npub.cash API using the official SDK
|
||||
*/
|
||||
export function useNpubCash() {
|
||||
const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Ref to track last sync timestamp for incremental updates
|
||||
const lastSyncRef = useRef<number>(0);
|
||||
|
||||
// Create NPCClient instance using the SDK with JWTAuthProvider for proper WebSocket auth
|
||||
const npcClient = useMemo(() => {
|
||||
if (!isLoggedIn || !signer) return null;
|
||||
// Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature
|
||||
const signingFunc = async (eventTemplate: any) => {
|
||||
return await signer.signEvent(eventTemplate);
|
||||
};
|
||||
const auth = new JWTAuthProvider(NPUBCASH_BASE_URL, signingFunc);
|
||||
return new NPCClient(NPUBCASH_BASE_URL, auth);
|
||||
}, [isLoggedIn, signer]);
|
||||
|
||||
// Generic wrapper for SDK calls with loading state
|
||||
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
return await operation();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
setError(errorMessage);
|
||||
return null;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
|
||||
if (!npcClient) return false;
|
||||
const result = await withLoading(() => npcClient.settings.setMintUrl(mintUrl));
|
||||
return result !== null;
|
||||
}, [npcClient, withLoading]);
|
||||
|
||||
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
|
||||
if (!npcClient) return null;
|
||||
|
||||
// Since SDK doesn't have getUserInfo, we'll use manual implementation
|
||||
// This could be enhanced if SDK adds this method
|
||||
return withLoading(async () => {
|
||||
const url = `${NPUBCASH_BASE_URL}/api/v2/user/info`;
|
||||
const authHeader = await createAuthHeader({ url, method: 'GET' });
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.data.user;
|
||||
});
|
||||
}, [npcClient, createAuthHeader, withLoading]);
|
||||
|
||||
const getAllQuotes = useCallback(async (): Promise<Quote[]> => {
|
||||
if (!npcClient) return [];
|
||||
const result = await withLoading(() => npcClient.getAllQuotes());
|
||||
return result || [];
|
||||
}, [npcClient, withLoading]);
|
||||
|
||||
const getQuotesSince = useCallback(async (since: number): Promise<Quote[]> => {
|
||||
if (!npcClient) return [];
|
||||
const result = await withLoading(() => npcClient.getQuotesSince(since));
|
||||
return result || [];
|
||||
}, [npcClient, withLoading]);
|
||||
|
||||
const setLockQuotes = useCallback(async (lockQuotes: boolean): Promise<boolean> => {
|
||||
if (!npcClient) return false;
|
||||
const result = await withLoading(() => npcClient.settings.setLock(lockQuotes));
|
||||
return result !== null;
|
||||
}, [npcClient, withLoading]);
|
||||
|
||||
const subscribeToQuotes = useCallback((
|
||||
onUpdate: (quoteId: string) => void,
|
||||
onError?: (msg: string) => void
|
||||
) => {
|
||||
if (!npcClient) return () => {};
|
||||
return npcClient.subscribe(onUpdate, onError);
|
||||
}, [npcClient]);
|
||||
|
||||
const refreshQuotes = useCallback(async (coco: any, toast: any): Promise<void> => {
|
||||
if (!npcClient || !coco) return;
|
||||
|
||||
try {
|
||||
// Fetch all quotes from npub.cash
|
||||
const quotes = await getAllQuotes();
|
||||
|
||||
if (quotes.length === 0) {
|
||||
toast({
|
||||
title: "No Quotes Found",
|
||||
description: "No pending quotes found on npub.cash",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Group quotes by mint URL
|
||||
const quotesByMint = quotes.reduce((acc, quote) => {
|
||||
if (!acc[quote.mintUrl]) {
|
||||
acc[quote.mintUrl] = [];
|
||||
}
|
||||
acc[quote.mintUrl].push(quote);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof quotes>);
|
||||
|
||||
let addedQuotes = 0;
|
||||
|
||||
// Process each mint's quotes
|
||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||
try {
|
||||
// Check if mint exists, add if not
|
||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
||||
if (!isKnown) {
|
||||
await coco.mint.addMint(mintUrl);
|
||||
}
|
||||
|
||||
// Add quotes to the wallet (matching main.ts format)
|
||||
coco.quotes.addMintQuote(
|
||||
mintUrl,
|
||||
mintQuotes.map((q) => ({
|
||||
...q,
|
||||
expiry: q.expiresAt,
|
||||
quote: q.quoteId,
|
||||
state: "PAID",
|
||||
unit: "sat",
|
||||
})),
|
||||
);
|
||||
|
||||
addedQuotes += mintQuotes.length;
|
||||
} catch (err) {
|
||||
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
if (addedQuotes > 0) {
|
||||
toast({
|
||||
title: "Quotes Refreshed",
|
||||
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "No New Quotes",
|
||||
description: "All quotes from npub.cash are already processed",
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Refresh Failed",
|
||||
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
|
||||
});
|
||||
}
|
||||
}, [npcClient, getAllQuotes]);
|
||||
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
// Subscribe to quote updates and sync to wallet automatically
|
||||
const syncQuotesWithWallet = useCallback(async (coco: any, toast: any): Promise<() => void> => {
|
||||
if (!npcClient || !coco) return () => {};
|
||||
|
||||
try {
|
||||
// Fetch and sync all quotes initially
|
||||
const quotes = await getAllQuotes();
|
||||
if (quotes.length > 0) {
|
||||
const quotesByMint = quotes.reduce((acc, quote) => {
|
||||
if (!acc[quote.mintUrl]) {
|
||||
acc[quote.mintUrl] = [];
|
||||
}
|
||||
acc[quote.mintUrl].push(quote);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof quotes>);
|
||||
|
||||
let addedQuotes = 0;
|
||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||
try {
|
||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
||||
if (!isKnown) {
|
||||
await coco.mint.addMint(mintUrl);
|
||||
}
|
||||
|
||||
coco.quotes.addMintQuote(
|
||||
mintUrl,
|
||||
mintQuotes.map((q) => ({
|
||||
...q,
|
||||
expiry: q.expiresAt,
|
||||
quote: q.quoteId,
|
||||
state: "PAID",
|
||||
unit: "sat",
|
||||
})),
|
||||
);
|
||||
addedQuotes += mintQuotes.length;
|
||||
} catch (err) {
|
||||
console.warn(`Failed to sync quotes for mint ${mintUrl}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
if (addedQuotes > 0) {
|
||||
toast({
|
||||
title: "Quotes Synced",
|
||||
description: `Synced ${addedQuotes} quotes from npub.cash`,
|
||||
});
|
||||
lastSyncRef.current = Math.floor(Date.now() / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe to real-time updates
|
||||
const unsubscribe = subscribeToQuotes(
|
||||
async (quoteId: string) => {
|
||||
try {
|
||||
// When a quote is updated, fetch newer quotes and sync
|
||||
const recentQuotes = await getQuotesSince(lastSyncRef.current);
|
||||
if (recentQuotes.length > 0) {
|
||||
const quotesByMint = recentQuotes.reduce((acc, quote) => {
|
||||
if (!acc[quote.mintUrl]) {
|
||||
acc[quote.mintUrl] = [];
|
||||
}
|
||||
acc[quote.mintUrl].push(quote);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof recentQuotes>);
|
||||
|
||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||
try {
|
||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
||||
if (!isKnown) {
|
||||
await coco.mint.addMint(mintUrl);
|
||||
}
|
||||
|
||||
coco.quotes.addMintQuote(
|
||||
mintUrl,
|
||||
mintQuotes.map((q) => ({
|
||||
...q,
|
||||
expiry: q.expiresAt,
|
||||
quote: q.quoteId,
|
||||
state: "PAID",
|
||||
unit: "sat",
|
||||
})),
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn(`Failed to sync quote ${quoteId} for mint ${mintUrl}:`, err);
|
||||
}
|
||||
}
|
||||
lastSyncRef.current = Math.floor(Date.now() / 1000);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to sync quote update:', err);
|
||||
}
|
||||
},
|
||||
(err: string) => {
|
||||
console.error('Quote subscription error:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Sync Error",
|
||||
description: "Failed to sync quotes from npub.cash",
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
return unsubscribe;
|
||||
} catch (err) {
|
||||
console.error('Failed to set up quote sync:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Sync Failed",
|
||||
description: err instanceof Error ? err.message : 'Failed to set up quote sync',
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
}, [npcClient, getAllQuotes, getQuotesSince, subscribeToQuotes]);
|
||||
|
||||
return {
|
||||
// Core methods
|
||||
setMint,
|
||||
getUserInfo,
|
||||
|
||||
// Quote management methods
|
||||
getAllQuotes,
|
||||
getQuotesSince,
|
||||
setLockQuotes,
|
||||
subscribeToQuotes,
|
||||
refreshQuotes,
|
||||
syncQuotesWithWallet,
|
||||
|
||||
// Status
|
||||
isLoading,
|
||||
error,
|
||||
isLoggedIn,
|
||||
pubkey,
|
||||
clearError,
|
||||
|
||||
// SDK instance for advanced usage
|
||||
npcClient,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { useNostrLogin } from '@nostrify/react/login';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
/**
|
||||
* Hook to check if the current user is logged in with nsec and get the private key.
|
||||
* Only works when user is logged in with nsec (not extension or bunker).
|
||||
*/
|
||||
export function useNsecAccess() {
|
||||
const { logins } = useNostrLogin();
|
||||
|
||||
const currentLogin = logins[0];
|
||||
|
||||
// Check if user is logged in with nsec
|
||||
const hasNsecAccess = currentLogin?.type === 'nsec';
|
||||
|
||||
// Get the private key in hex format (only if nsec login)
|
||||
const getPrivateKey = (): string | null => {
|
||||
if (!hasNsecAccess || !currentLogin) return null;
|
||||
|
||||
try {
|
||||
// The nsec is stored in the login data as 'data.nsec' property
|
||||
const loginData = currentLogin as { data?: { nsec: string } };
|
||||
const nsec = loginData.data?.nsec;
|
||||
|
||||
if (!nsec) {
|
||||
console.error('No nsec found in login data');
|
||||
return null;
|
||||
}
|
||||
|
||||
const decoded: { type: string; data: Uint8Array | string | object } = nip19.decode(nsec) as { type: string; data: Uint8Array | string | object };
|
||||
|
||||
// Type guard to ensure we have an nsec
|
||||
if (decoded.type !== 'nsec') {
|
||||
console.error('Invalid nsec format, got type:', decoded.type);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Convert Uint8Array to hex string
|
||||
return Buffer.from(decoded.data as Uint8Array).toString('hex');
|
||||
} catch (error) {
|
||||
console.error('Failed to decode nsec:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
hasNsecAccess,
|
||||
getPrivateKey,
|
||||
loginType: currentLogin?.type,
|
||||
};
|
||||
}
|
||||
@@ -1,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,372 +0,0 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string | Array<{
|
||||
type: 'text' | 'image_url';
|
||||
text?: string;
|
||||
image_url?: {
|
||||
url: string;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ChatCompletionRequest {
|
||||
model: string;
|
||||
messages: ChatMessage[];
|
||||
stream?: boolean;
|
||||
temperature?: number;
|
||||
max_tokens?: number;
|
||||
}
|
||||
|
||||
export interface ChatCompletionResponse {
|
||||
id: string;
|
||||
object: string;
|
||||
created: number;
|
||||
model: string;
|
||||
choices: Array<{
|
||||
index: number;
|
||||
message: ChatMessage;
|
||||
finish_reason: string;
|
||||
}>;
|
||||
usage: {
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
object: string;
|
||||
owned_by: string;
|
||||
created: number;
|
||||
context_window: number;
|
||||
pricing: {
|
||||
prompt: string;
|
||||
completion: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ModelsResponse {
|
||||
object: string;
|
||||
data: Model[];
|
||||
}
|
||||
|
||||
// Configuration
|
||||
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
|
||||
|
||||
// Helper function to create NIP-98 token
|
||||
async function createNIP98Token(
|
||||
method: string,
|
||||
url: string,
|
||||
body?: unknown,
|
||||
user?: NUser
|
||||
): Promise<string> {
|
||||
if (!user?.signer) {
|
||||
throw new Error('User signer is required for NIP-98 authentication');
|
||||
}
|
||||
|
||||
// Create the tags array
|
||||
const tags: string[][] = [
|
||||
['u', url],
|
||||
['method', method]
|
||||
];
|
||||
|
||||
// Add payload hash for requests with body (following NIP-98 spec)
|
||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
||||
const bodyString = JSON.stringify(body);
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(bodyString);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
tags.push(['payload', payloadHash]);
|
||||
}
|
||||
|
||||
// Create the HTTP request event
|
||||
const event = await user.signer.signEvent({
|
||||
kind: 27235, // NIP-98 HTTP Auth
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// Return the token (base64 encoded event)
|
||||
return btoa(JSON.stringify(event));
|
||||
}
|
||||
|
||||
// Helper function to handle API errors with user-friendly messages
|
||||
async function handleAPIError(response: Response) {
|
||||
if (response.status === 401) {
|
||||
throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
|
||||
} else if (response.status === 402) {
|
||||
throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
|
||||
} else if (response.status === 400) {
|
||||
try {
|
||||
const error = await response.json();
|
||||
if (error.error?.type === 'invalid_request_error') {
|
||||
// Handle specific validation errors
|
||||
if (error.error.code === 'minimum_amount_not_met') {
|
||||
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
|
||||
} else if (error.error.code === 'unsupported_method') {
|
||||
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
|
||||
} else if (error.error.code === 'invalid_url') {
|
||||
throw new Error('Invalid redirect URL provided for Stripe payment.');
|
||||
}
|
||||
}
|
||||
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
|
||||
} catch {
|
||||
throw new Error('Invalid request. Please check your parameters and try again.');
|
||||
}
|
||||
} else if (response.status === 404) {
|
||||
throw new Error('Resource not found. Please check the payment ID or try again.');
|
||||
} else if (response.status >= 500) {
|
||||
throw new Error('Server error. Please try again in a few moments.');
|
||||
} else if (!response.ok) {
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
||||
} catch {
|
||||
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function useShakespeare() {
|
||||
const { user } = useCurrentUser();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Clear error helper
|
||||
const clearError = useCallback(() => {
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// Chat completion function
|
||||
const sendChatMessage = useCallback(async (
|
||||
messages: ChatMessage[],
|
||||
model: string = 'shakespeare',
|
||||
options?: Partial<ChatCompletionRequest>
|
||||
): Promise<ChatCompletionResponse> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const requestBody: ChatCompletionRequest = {
|
||||
model,
|
||||
messages,
|
||||
...options
|
||||
};
|
||||
|
||||
const token = await createNIP98Token(
|
||||
'POST',
|
||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
||||
requestBody,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
return await response.json();
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Streaming chat completion function
|
||||
const sendStreamingMessage = useCallback(async (
|
||||
messages: ChatMessage[],
|
||||
model: string = 'shakespeare',
|
||||
onChunk: (chunk: string) => void,
|
||||
options?: Partial<ChatCompletionRequest>
|
||||
): Promise<void> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const requestBody: ChatCompletionRequest = {
|
||||
model,
|
||||
messages,
|
||||
stream: true,
|
||||
...options
|
||||
};
|
||||
|
||||
const token = await createNIP98Token(
|
||||
'POST',
|
||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
||||
requestBody,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error('No response body');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const data = line.slice(6);
|
||||
if (data === '[DONE]') return;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
const content = parsed.choices?.[0]?.delta?.content;
|
||||
if (content) {
|
||||
onChunk(content);
|
||||
}
|
||||
} catch {
|
||||
// Ignore parsing errors for incomplete chunks
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Get available models
|
||||
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const token = await createNIP98Token(
|
||||
'GET',
|
||||
`${SHAKESPEARE_API_URL}/models`,
|
||||
undefined,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
return await response.json();
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
return {
|
||||
// State
|
||||
isLoading,
|
||||
error,
|
||||
isAuthenticated: !!user,
|
||||
|
||||
// Actions
|
||||
sendChatMessage,
|
||||
sendStreamingMessage,
|
||||
getAvailableModels,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
} from "@/components/ui/toast"
|
||||
|
||||
const TOAST_LIMIT = 1
|
||||
const TOAST_REMOVE_DELAY = 1000
|
||||
const TOAST_REMOVE_DELAY = 1000000
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
|
||||
+60
-27
@@ -1,61 +1,94 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { requestProvider } from 'webln';
|
||||
|
||||
export interface WalletStatus {
|
||||
hasWebLN: boolean;
|
||||
hasNWC: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||
preferredMethod: 'cashu' | 'nwc' | 'webln' | 'manual';
|
||||
// Cashu integration
|
||||
hasCashu: boolean;
|
||||
cashuBalance: number;
|
||||
isCashuInitialized: boolean;
|
||||
isDetecting: boolean;
|
||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
||||
}
|
||||
|
||||
export function useWallet() {
|
||||
const [webln, setWebln] = useState<WebLNProvider | null>(null);
|
||||
const [isDetecting, setIsDetecting] = useState(false);
|
||||
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
|
||||
const { connections, getActiveConnection } = useNWC();
|
||||
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
|
||||
// Get the active connection directly - no memoization to avoid stale state
|
||||
const activeNWC = getActiveConnection();
|
||||
|
||||
// Access WebLN directly from browser global scope
|
||||
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
||||
// Detect WebLN
|
||||
const detectWebLN = useCallback(async () => {
|
||||
if (webln || isDetecting) return webln;
|
||||
|
||||
// Calculate Cashu status
|
||||
const hasCashu = useMemo(() => {
|
||||
return isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) > 0);
|
||||
}, [isCashuInitialized, mints, balances]);
|
||||
setIsDetecting(true);
|
||||
try {
|
||||
const provider = await requestProvider();
|
||||
setWebln(provider);
|
||||
setHasAttemptedDetection(true);
|
||||
return provider;
|
||||
} catch (error) {
|
||||
// Only log the error if it's not the common "no provider" error
|
||||
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
|
||||
console.warn('WebLN detection error:', error);
|
||||
}
|
||||
setWebln(null);
|
||||
setHasAttemptedDetection(true);
|
||||
return null;
|
||||
} finally {
|
||||
setIsDetecting(false);
|
||||
}
|
||||
}, [webln, isDetecting]);
|
||||
|
||||
const cashuBalance = useMemo(() => {
|
||||
return Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||
}, [balances]);
|
||||
// Only auto-detect once on mount
|
||||
useEffect(() => {
|
||||
if (!hasAttemptedDetection) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [detectWebLN, hasAttemptedDetection]);
|
||||
|
||||
// Calculate Lightning status values reactively
|
||||
// Test WebLN connection
|
||||
const testWebLN = useCallback(async (): Promise<boolean> => {
|
||||
if (!webln) return false;
|
||||
|
||||
try {
|
||||
await webln.enable();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('WebLN test failed:', error);
|
||||
return false;
|
||||
}
|
||||
}, [webln]);
|
||||
|
||||
// Calculate status values reactively
|
||||
const hasNWC = useMemo(() => {
|
||||
return connections.length > 0 && connections.some(c => c.isConnected);
|
||||
}, [connections]);
|
||||
|
||||
// Determine preferred payment method - Cashu first, then Lightning fallbacks
|
||||
const preferredMethod: WalletStatus['preferredMethod'] = hasCashu
|
||||
? 'cashu'
|
||||
: activeNWC
|
||||
// Determine preferred payment method
|
||||
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
|
||||
? 'nwc'
|
||||
: webln
|
||||
? 'webln'
|
||||
: 'manual';
|
||||
|
||||
const status: WalletStatus = {
|
||||
hasWebLN: !!webln,
|
||||
hasNWC,
|
||||
webln,
|
||||
activeNWC,
|
||||
isDetecting,
|
||||
preferredMethod,
|
||||
hasCashu,
|
||||
cashuBalance,
|
||||
isCashuInitialized,
|
||||
};
|
||||
|
||||
return status;
|
||||
return {
|
||||
...status,
|
||||
hasAttemptedDetection,
|
||||
detectWebLN,
|
||||
testWebLN,
|
||||
};
|
||||
}
|
||||
+15
-93
@@ -4,11 +4,10 @@ import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import type { NWCConnection } from '@/hooks/useNWC';
|
||||
import { nip57 } from 'nostr-tools';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
@@ -30,7 +29,6 @@ export function useZaps(
|
||||
|
||||
const author = useAuthor(actualTarget?.pubkey);
|
||||
const { sendPayment, getActiveConnection } = useNWC();
|
||||
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||
const [isZapping, setIsZapping] = useState(false);
|
||||
const [invoice, setInvoice] = useState<string | null>(null);
|
||||
|
||||
@@ -133,13 +131,7 @@ export function useZaps(
|
||||
}, [zapEvents, actualTarget]);
|
||||
|
||||
const zap = async (amount: number, comment: string) => {
|
||||
if (amount <= 0 || isNaN(amount)) {
|
||||
toast({
|
||||
title: 'Invalid amount',
|
||||
description: 'Please enter a valid amount greater than 0.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
if (amount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -166,17 +158,6 @@ export function useZaps(
|
||||
return;
|
||||
}
|
||||
|
||||
// Additional validation to ensure actualTarget has required properties
|
||||
if (!actualTarget.pubkey || !actualTarget.id) {
|
||||
toast({
|
||||
title: 'Invalid event',
|
||||
description: 'The event is missing required properties.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!author.data || !author.data?.metadata || !author.data?.event ) {
|
||||
toast({
|
||||
@@ -211,18 +192,18 @@ export function useZaps(
|
||||
return;
|
||||
}
|
||||
|
||||
// Create zap request - use appropriate event format based on kind
|
||||
// For addressable events (30000-39999), pass the object to get 'a' tag
|
||||
// For all other events, pass the ID string to get 'e' tag
|
||||
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
|
||||
? actualTarget
|
||||
: actualTarget.id;
|
||||
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
|
||||
// Validate zapAmount is a valid number
|
||||
if (isNaN(zapAmount) || zapAmount <= 0) {
|
||||
throw new Error('Invalid zap amount');
|
||||
}
|
||||
|
||||
// Create zap request - always pass the full event object
|
||||
// The nip57.makeZapRequest function will handle proper tag generation
|
||||
// ('e' tag for regular events, 'a' tag for addressable events)
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
event: actualTarget,
|
||||
profile: actualTarget.pubkey,
|
||||
event: event,
|
||||
amount: zapAmount,
|
||||
relays: [config.relayUrl],
|
||||
comment
|
||||
@@ -247,57 +228,10 @@ export function useZaps(
|
||||
throw new Error('Lightning service did not return a valid invoice');
|
||||
}
|
||||
|
||||
// Check if Cashu wallet is available and has sufficient balance
|
||||
const canPayWithCashu = isCashuInitialized && mints.some(mint => (balances[mint.url] || 0) >= amount);
|
||||
|
||||
if (canPayWithCashu) {
|
||||
try {
|
||||
// Find a mint with sufficient balance
|
||||
const mintWithBalance = mints.find(mint => {
|
||||
const balance = balances[mint.url] || 0;
|
||||
return balance >= amount;
|
||||
});
|
||||
|
||||
if (mintWithBalance && coco) {
|
||||
// Create melt quote to convert Cashu tokens to Lightning payment
|
||||
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
|
||||
|
||||
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
|
||||
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats from your Cashu wallet to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
return;
|
||||
}
|
||||
} catch (cashuError) {
|
||||
console.error('Cashu payment failed, falling back:', cashuError);
|
||||
|
||||
// Show specific Cashu error to user for debugging
|
||||
const errorMessage = cashuError instanceof Error ? cashuError.message : 'Unknown Cashu error';
|
||||
toast({
|
||||
title: 'Cashu payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current active NWC connection dynamically
|
||||
const currentNWCConnection = getActiveConnection();
|
||||
|
||||
// Try NWC if Cashu failed or unavailable
|
||||
// Try NWC first if available and properly connected
|
||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||
try {
|
||||
await sendPayment(currentNWCConnection, newInvoice);
|
||||
@@ -329,22 +263,10 @@ export function useZaps(
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (webln) { // Try WebLN next
|
||||
try {
|
||||
// For native WebLN, we may need to enable it first
|
||||
let webLnProvider = webln;
|
||||
if (webln.enable && typeof webln.enable === 'function') {
|
||||
const enabledProvider = await webln.enable();
|
||||
// Some implementations return the provider, others return void
|
||||
// Cast to WebLNProvider to handle both cases
|
||||
const provider = enabledProvider as WebLNProvider | undefined;
|
||||
if (provider) {
|
||||
webLnProvider = provider;
|
||||
}
|
||||
}
|
||||
|
||||
await webLnProvider.sendPayment(newInvoice);
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
@@ -361,7 +283,7 @@ export function useZaps(
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
} catch (weblnError) {
|
||||
console.error('WebLN payment failed, falling back:', weblnError);
|
||||
console.error('webln payment failed, falling back:', weblnError);
|
||||
|
||||
// Show specific WebLN error to user for debugging
|
||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
import * as bitcoin from 'bitcoinjs-lib';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import * as ecc from '@bitcoinerlab/secp256k1';
|
||||
import { ECPairFactory, type ECPairAPI } from 'ecpair';
|
||||
|
||||
// Initialize ECC library immediately
|
||||
bitcoin.initEccLib(ecc);
|
||||
|
||||
// Lazy initialization to avoid issues in test environment
|
||||
let ECPair: ECPairAPI | null = null;
|
||||
|
||||
function getECPair(): ECPairAPI {
|
||||
if (!ECPair) {
|
||||
ECPair = ECPairFactory(ecc);
|
||||
}
|
||||
return ECPair;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert Nostr pubkey (hex) to Bitcoin Taproot address
|
||||
*/
|
||||
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
|
||||
try {
|
||||
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
|
||||
|
||||
const { address } = bitcoin.payments.p2tr({
|
||||
internalPubkey: pubkeyBuffer,
|
||||
network: bitcoin.networks.bitcoin,
|
||||
});
|
||||
|
||||
return address || '';
|
||||
} catch (error) {
|
||||
console.error('Error generating Bitcoin address:', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert npub to Bitcoin Taproot address
|
||||
*/
|
||||
export function npubToBitcoinAddress(npub: string): string {
|
||||
try {
|
||||
const decoded = nip19.decode(npub);
|
||||
|
||||
if (decoded.type !== 'npub') {
|
||||
throw new Error('Invalid npub format');
|
||||
}
|
||||
|
||||
const pubkeyHex = decoded.data as string;
|
||||
return nostrPubkeyToBitcoinAddress(pubkeyHex);
|
||||
} catch (error) {
|
||||
console.error('Error converting npub to Bitcoin address:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @returns Signed transaction hex
|
||||
*/
|
||||
export async function createBitcoinTransaction(
|
||||
privateKeyHex: string,
|
||||
toAddress: string,
|
||||
amountSats: number,
|
||||
utxos: UTXO[],
|
||||
feeRate: number
|
||||
): 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
|
||||
// P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes
|
||||
const estimatedSize = utxos.length * 57.5 + 2 * 43 + 10.5; // 2 outputs (recipient + change) + overhead
|
||||
const estimatedFee = Math.ceil(estimatedSize * feeRate);
|
||||
|
||||
// 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);
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
/**
|
||||
* Decodes a BOLT11 lightning invoice and extracts the amount in satoshis.
|
||||
* Based on the lightning-decoder project implementation.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Decode a BOLT11 invoice and extract the amount in satoshis
|
||||
* @param invoice - The BOLT11 invoice string
|
||||
* @returns The amount in satoshis, or null if amount cannot be determined
|
||||
*/
|
||||
export function decodeBolt11Amount(invoice: string): number | null {
|
||||
try {
|
||||
// Validate and prepare invoice
|
||||
if (!invoice || typeof invoice !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedInvoice = invoice.toLowerCase().trim();
|
||||
|
||||
// Check if it's a valid BOLT11 invoice
|
||||
if (!isValidBolt11Invoice(normalizedInvoice)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parse the prefix to extract amount
|
||||
// Format: lnbc[amount][suffix] where suffix can be m, u, n, p
|
||||
const prefixMatch = normalizedInvoice.match(/^lnbc(\d*)([munp]?)/);
|
||||
if (!prefixMatch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [, amountStr, suffix] = prefixMatch;
|
||||
|
||||
// If no amount specified, return null (amountless invoice)
|
||||
if (!amountStr) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const amount = parseInt(amountStr, 10);
|
||||
if (isNaN(amount)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Define multipliers for different denominations
|
||||
const multipliers: Record<string, number> = {
|
||||
m: 0.001, // milli-bitcoin
|
||||
u: 0.000001, // micro-bitcoin
|
||||
n: 0.000000001, // nano-bitcoin
|
||||
p: 0.000000000001 // pico-bitcoin
|
||||
};
|
||||
|
||||
// Apply multiplier if suffix exists
|
||||
const multiplier = multipliers[suffix] || 1;
|
||||
const amountInBitcoin = amount * multiplier;
|
||||
|
||||
// Convert Bitcoin to satoshis (1 Bitcoin = 100,000,000 satoshis)
|
||||
const amountInSatoshis = Math.round(amountInBitcoin * 100_000_000);
|
||||
|
||||
return amountInSatoshis;
|
||||
} catch (error) {
|
||||
console.error('Error decoding BOLT11 invoice:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if a string is a valid BOLT11 invoice
|
||||
* @param invoice - The string to validate
|
||||
* @returns true if the string appears to be a valid BOLT11 invoice
|
||||
*/
|
||||
export function isValidBolt11Invoice(invoice: string): boolean {
|
||||
if (!invoice || typeof invoice !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = invoice.toLowerCase().trim();
|
||||
|
||||
// BOLT11 invoices start with 'lnbc' and contain '1' followed by characters (the bech32 separator)
|
||||
// They also need to be long enough to contain the required components
|
||||
return (
|
||||
normalized.startsWith('lnbc') &&
|
||||
/1[a-z0-9]/.test(normalized) &&
|
||||
normalized.length > 20 // Minimum reasonable length for a BOLT11 invoice
|
||||
);
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* Exchange rate service for fetching BTC/USD rates from Coinbase API
|
||||
*/
|
||||
export class ExchangeRateService {
|
||||
private static readonly COINBASE_API_URL = "https://api.coinbase.com/v2/exchange-rates";
|
||||
private static readonly CACHE_DURATION_MS = 60000; // 1 minute cache
|
||||
|
||||
private cachedRate: number | null = null;
|
||||
private cacheTimestamp: number = 0;
|
||||
|
||||
/**
|
||||
* Get the current BTC/USD exchange rate from Coinbase API
|
||||
* Uses caching to avoid excessive API calls
|
||||
*/
|
||||
async getBtcUsdRate(): Promise<number> {
|
||||
const now = Date.now();
|
||||
|
||||
// Return cached rate if still valid
|
||||
if (this.cachedRate && (now - this.cacheTimestamp) < ExchangeRateService.CACHE_DURATION_MS) {
|
||||
console.debug(`Using cached BTC/USD rate: ${this.cachedRate}`, {
|
||||
cache_age_ms: now - this.cacheTimestamp,
|
||||
});
|
||||
return this.cachedRate;
|
||||
}
|
||||
|
||||
try {
|
||||
console.debug("Fetching BTC/USD rate from Coinbase API");
|
||||
|
||||
const response = await fetch(`${ExchangeRateService.COINBASE_API_URL}?currency=BTC`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "MKStack/1.0",
|
||||
},
|
||||
// Add timeout to prevent hanging
|
||||
signal: AbortSignal.timeout(10000), // 10 second timeout
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Coinbase API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Validate response structure
|
||||
if (!data?.data?.rates?.USD) {
|
||||
throw new Error("Invalid response format from Coinbase API");
|
||||
}
|
||||
|
||||
const rate = parseFloat(data.data.rates.USD);
|
||||
|
||||
if (isNaN(rate) || rate <= 0) {
|
||||
throw new Error(`Invalid exchange rate received: ${data.data.rates.USD}`);
|
||||
}
|
||||
|
||||
// Update cache
|
||||
this.cachedRate = rate;
|
||||
this.cacheTimestamp = now;
|
||||
|
||||
console.info(`Fetched BTC/USD rate from Coinbase: ${rate}`, { rate });
|
||||
|
||||
return rate;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
||||
console.error(`Failed to fetch BTC/USD rate: ${errorMessage}`);
|
||||
|
||||
// If we have a cached rate, use it as fallback
|
||||
if (this.cachedRate) {
|
||||
const cacheAge = now - this.cacheTimestamp;
|
||||
console.warn(`Using stale cached rate as fallback: ${this.cachedRate}`, {
|
||||
cache_age_ms: cacheAge,
|
||||
});
|
||||
return this.cachedRate;
|
||||
}
|
||||
|
||||
// If no cached rate available, throw error
|
||||
throw new Error(`Unable to fetch BTC/USD exchange rate: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert BTC amount to USD using current exchange rate
|
||||
*/
|
||||
async btcToUsd(btcAmount: number): Promise<number> {
|
||||
const rate = await this.getBtcUsdRate();
|
||||
return btcAmount * rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert USD amount to BTC using current exchange rate
|
||||
*/
|
||||
async usdToBtc(usdAmount: number): Promise<number> {
|
||||
const rate = await this.getBtcUsdRate();
|
||||
return usdAmount / rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert sats to USD using current exchange rate
|
||||
*/
|
||||
async satsToUsd(sats: number): Promise<number> {
|
||||
const btcAmount = sats / 100000000; // Convert sats to BTC
|
||||
return this.btcToUsd(btcAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached exchange rate (useful for testing)
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.cachedRate = null;
|
||||
this.cacheTimestamp = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache status for debugging
|
||||
*/
|
||||
getCacheStatus(): { rate: number | null; age_ms: number; is_valid: boolean } {
|
||||
const now = Date.now();
|
||||
const age = now - this.cacheTimestamp;
|
||||
const isValid = this.cachedRate !== null && age < ExchangeRateService.CACHE_DURATION_MS;
|
||||
|
||||
return {
|
||||
rate: this.cachedRate,
|
||||
age_ms: age,
|
||||
is_valid: isValid,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Export a singleton instance
|
||||
export const exchangeRateService = new ExchangeRateService();
|
||||
@@ -1,12 +1,3 @@
|
||||
/**
|
||||
* Polyfill for Buffer in browser environment
|
||||
*
|
||||
* Many Node.js libraries like bitcoinjs-lib expect Buffer to be globally available.
|
||||
* This polyfill makes the buffer package's Buffer available globally.
|
||||
*/
|
||||
import { Buffer } from 'buffer';
|
||||
globalThis.Buffer = Buffer;
|
||||
|
||||
/**
|
||||
* Polyfill for AbortSignal.any()
|
||||
*
|
||||
|
||||
@@ -15,16 +15,3 @@ createRoot(document.getElementById("root")!).render(
|
||||
<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);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,825 @@
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
import { AlertCircle, Shield, Ban, UserCheck, MessageSquareX, Trash2, Plus, Eye, EyeOff } from 'lucide-react';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useAdminStorage } from '@/hooks/useAdminStorage';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import NotFound from './NotFound';
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export function AdminDashboard() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Decode admin npub from environment variable
|
||||
let adminPubkey: string = '';
|
||||
let isValidAdminNpub = false;
|
||||
|
||||
try {
|
||||
if (ADMIN_NPUB) {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
isValidAdminNpub = true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid admin npub format
|
||||
}
|
||||
|
||||
// Always call hooks - use empty string as fallback to avoid conditional calls
|
||||
const adminAuthor = useAuthor(adminPubkey || '');
|
||||
|
||||
// Return NotFound if no valid admin npub is configured
|
||||
if (!isValidAdminNpub) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
// Check if current user is the site admin
|
||||
const isAuthorized = user?.pubkey === adminPubkey;
|
||||
|
||||
if (!isAuthorized) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-amber-500" />
|
||||
Site Admin Access Required
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
You need to be logged in as the site administrator to access this admin panel.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{adminAuthor.data?.metadata && (
|
||||
<div className="flex items-center gap-3 p-4 bg-muted rounded-lg">
|
||||
<Avatar>
|
||||
<AvatarImage src={adminAuthor.data.metadata.picture} />
|
||||
<AvatarFallback>
|
||||
{(adminAuthor.data.metadata.name || genUserName(adminPubkey)).slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{adminAuthor.data.metadata.display_name || adminAuthor.data.metadata.name || genUserName(adminPubkey)}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Site Administrator
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Only the site administrator can access content moderation and site management features.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<LoginArea className="w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 max-w-6xl">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold mb-2 flex items-center gap-2">
|
||||
<Shield className="h-8 w-8" />
|
||||
Site Administration
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Manage content moderation, user access controls, and site settings
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="moderation" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-5">
|
||||
<TabsTrigger value="moderation">Content Moderation</TabsTrigger>
|
||||
<TabsTrigger value="users">User Management</TabsTrigger>
|
||||
<TabsTrigger value="blocked-words">Blocked Words</TabsTrigger>
|
||||
<TabsTrigger value="analytics">Site Analytics</TabsTrigger>
|
||||
<TabsTrigger value="settings">Site Settings</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="moderation">
|
||||
<ContentModeration />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="users">
|
||||
<UserManagement />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="blocked-words">
|
||||
<BlockedWordsManagement />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="analytics">
|
||||
<SiteAnalytics />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="settings">
|
||||
<SiteSettings />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ContentModeration() {
|
||||
const { nostr } = useNostr();
|
||||
const { data: adminData, updateHiddenEvents, isSaving } = useAdminStorage();
|
||||
|
||||
const recentContent = useQuery({
|
||||
queryKey: ['admin-recent-content'],
|
||||
queryFn: async ({ signal }) => {
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
const events = await nostr.query([{
|
||||
kinds: [1, 30023], // Notes and articles
|
||||
limit: 50
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
return events.sort((a, b) => b.created_at - a.created_at);
|
||||
},
|
||||
});
|
||||
|
||||
const hideEvent = async (eventId: string) => {
|
||||
const newHiddenEvents = [...adminData.hiddenEvents, eventId];
|
||||
await updateHiddenEvents(newHiddenEvents);
|
||||
};
|
||||
|
||||
const unhideEvent = async (eventId: string) => {
|
||||
const newHiddenEvents = adminData.hiddenEvents.filter(id => id !== eventId);
|
||||
await updateHiddenEvents(newHiddenEvents);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5" />
|
||||
Recent Content Review
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Review and moderate recent content posted to the site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{recentContent.isLoading ? (
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<div key={i} className="flex items-start gap-3 p-4 border rounded-lg">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-20" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : recentContent.data?.length ? (
|
||||
<div className="space-y-4">
|
||||
{recentContent.data.map((event) => {
|
||||
const isHidden = adminData.hiddenEvents.includes(event.id);
|
||||
return (
|
||||
<div key={event.id} className={`flex items-start gap-3 p-4 border rounded-lg ${isHidden ? 'opacity-50 bg-muted' : ''}`}>
|
||||
<UserAvatar pubkey={event.pubkey} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<UserName pubkey={event.pubkey} />
|
||||
<Badge variant={event.kind === 1 ? 'default' : 'secondary'}>
|
||||
{event.kind === 1 ? 'Note' : 'Article'}
|
||||
</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{new Date(event.created_at * 1000).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm line-clamp-3">
|
||||
{event.kind === 30023
|
||||
? event.tags.find(([tag]) => tag === 'title')?.[1] || 'Untitled Article'
|
||||
: event.content
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{isHidden ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => unhideEvent(event.id)}
|
||||
className="text-green-600 hover:text-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
Show
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => hideEvent(event.id)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<EyeOff className="h-4 w-4 mr-1" />
|
||||
Hide
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">No recent content found</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserManagement() {
|
||||
const { data: adminData, updateAllowList, updateDenyList, isSaving } = useAdminStorage();
|
||||
const [newNpub, setNewNpub] = useState('');
|
||||
|
||||
const addToAllowList = async () => {
|
||||
try {
|
||||
const decoded = nip19.decode(newNpub);
|
||||
if (decoded.type === 'npub') {
|
||||
const pubkey = decoded.data as unknown as string;
|
||||
if (!adminData.allowList.includes(pubkey)) {
|
||||
const newAllowList = [...adminData.allowList, pubkey];
|
||||
const newDenyList = adminData.denyList.filter(p => p !== pubkey); // Remove from deny list if present
|
||||
|
||||
await updateAllowList(newAllowList);
|
||||
if (newDenyList.length !== adminData.denyList.length) {
|
||||
await updateDenyList(newDenyList);
|
||||
}
|
||||
setNewNpub('');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub format
|
||||
}
|
||||
};
|
||||
|
||||
const addToDenyList = async () => {
|
||||
try {
|
||||
const decoded = nip19.decode(newNpub);
|
||||
if (decoded.type === 'npub') {
|
||||
const pubkey = decoded.data as unknown as string;
|
||||
if (!adminData.denyList.includes(pubkey)) {
|
||||
const newDenyList = [...adminData.denyList, pubkey];
|
||||
const newAllowList = adminData.allowList.filter(p => p !== pubkey); // Remove from allow list if present
|
||||
|
||||
await updateDenyList(newDenyList);
|
||||
if (newAllowList.length !== adminData.allowList.length) {
|
||||
await updateAllowList(newAllowList);
|
||||
}
|
||||
setNewNpub('');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub format
|
||||
}
|
||||
};
|
||||
|
||||
const removeFromAllowList = async (pubkey: string) => {
|
||||
const newAllowList = adminData.allowList.filter(p => p !== pubkey);
|
||||
await updateAllowList(newAllowList);
|
||||
};
|
||||
|
||||
const removeFromDenyList = async (pubkey: string) => {
|
||||
const newDenyList = adminData.denyList.filter(p => p !== pubkey);
|
||||
await updateDenyList(newDenyList);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Add User Form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<UserCheck className="h-5 w-5" />
|
||||
Add User to Lists
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Add users to allow list or deny list by their npub
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="npub1abc123..."
|
||||
value={newNpub}
|
||||
onChange={(e) => setNewNpub(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={addToAllowList} variant="outline" className="text-green-600" disabled={isSaving}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Allow
|
||||
</Button>
|
||||
<Button onClick={addToDenyList} variant="outline" className="text-red-600" disabled={isSaving}>
|
||||
<Ban className="h-4 w-4 mr-1" />
|
||||
Deny
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Allow List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-green-600">
|
||||
<UserCheck className="h-5 w-5" />
|
||||
Allow List ({adminData.allowList.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Users explicitly allowed to post content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.allowList.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.allowList.map((pubkey) => (
|
||||
<UserListItem
|
||||
key={pubkey}
|
||||
pubkey={pubkey}
|
||||
onRemove={() => removeFromAllowList(pubkey)}
|
||||
variant="allow"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No users in allow list</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Deny List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-red-600">
|
||||
<Ban className="h-5 w-5" />
|
||||
Deny List ({adminData.denyList.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Users blocked from posting content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.denyList.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.denyList.map((pubkey) => (
|
||||
<UserListItem
|
||||
key={pubkey}
|
||||
pubkey={pubkey}
|
||||
onRemove={() => removeFromDenyList(pubkey)}
|
||||
variant="deny"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No users in deny list</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockedWordsManagement() {
|
||||
const { data: adminData, updateBlockedWords, updateModerationSettings, isSaving } = useAdminStorage();
|
||||
const [newWord, setNewWord] = useState('');
|
||||
|
||||
const addBlockedWord = async () => {
|
||||
const word = newWord.trim();
|
||||
if (word && !adminData.blockedWords.includes(word)) {
|
||||
const newBlockedWords = [...adminData.blockedWords, word];
|
||||
await updateBlockedWords(newBlockedWords);
|
||||
setNewWord('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeBlockedWord = async (word: string) => {
|
||||
const newBlockedWords = adminData.blockedWords.filter(w => w !== word);
|
||||
await updateBlockedWords(newBlockedWords);
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
addBlockedWord();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<MessageSquareX className="h-5 w-5" />
|
||||
Content Filtering Settings
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure automatic content filtering options
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="case-sensitive"
|
||||
checked={adminData.caseSensitive}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ caseSensitive: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<Label htmlFor="case-sensitive">Case sensitive matching</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="whole-words"
|
||||
checked={adminData.wholeWordsOnly}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ wholeWordsOnly: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<Label htmlFor="whole-words">Match whole words only</Label>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Add Blocked Word</CardTitle>
|
||||
<CardDescription>
|
||||
Add words or phrases to automatically filter from content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter word or phrase to block..."
|
||||
value={newWord}
|
||||
onChange={(e) => setNewWord(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={addBlockedWord} disabled={isSaving}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Blocked Words ({adminData.blockedWords.length})</CardTitle>
|
||||
<CardDescription>
|
||||
Currently blocked words and phrases
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.blockedWords.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.blockedWords.map((word) => (
|
||||
<div key={word} className="flex items-center justify-between p-2 border rounded">
|
||||
<span className="font-mono text-sm">{word}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeBlockedWord(word)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">No blocked words configured</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteAnalytics() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const siteStats = useQuery({
|
||||
queryKey: ['site-analytics'],
|
||||
queryFn: async ({ signal }) => {
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
// Get recent site activity
|
||||
const recentEvents = await nostr.query([{
|
||||
kinds: [1, 30023], // Notes and articles
|
||||
limit: 100
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
const uniqueAuthors = new Set(recentEvents.map(e => e.pubkey)).size;
|
||||
const last24h = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 86400).length;
|
||||
const last7d = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 604800).length;
|
||||
|
||||
return {
|
||||
totalEvents: recentEvents.length,
|
||||
uniqueAuthors,
|
||||
last24h,
|
||||
last7d,
|
||||
notes: recentEvents.filter(e => e.kind === 1).length,
|
||||
articles: recentEvents.filter(e => e.kind === 30023).length,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Content</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.totalEvents || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">Recent events</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Active Users</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.uniqueAuthors || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">Unique authors</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Last 24h</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.last24h || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">New posts</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Last 7 days</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.last7d || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">New posts</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Content Breakdown</CardTitle>
|
||||
<CardDescription>
|
||||
Distribution of content types on your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{siteStats.isLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span>Notes</span>
|
||||
<Badge variant="default">{siteStats.data?.notes || 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>Articles</span>
|
||||
<Badge variant="secondary">{siteStats.data?.articles || 0}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteSettings() {
|
||||
const { data: adminData, updateSiteSettings, updateModerationSettings, isSaving } = useAdminStorage();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Site Information</CardTitle>
|
||||
<CardDescription>
|
||||
Basic information about your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="site-name">Site Name</Label>
|
||||
<Input
|
||||
id="site-name"
|
||||
value={adminData.siteName}
|
||||
onChange={(e) => updateSiteSettings({ siteName: e.target.value })}
|
||||
placeholder="My Nostr Site"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="site-description">Site Description</Label>
|
||||
<Textarea
|
||||
id="site-description"
|
||||
value={adminData.siteDescription}
|
||||
onChange={(e) => updateSiteSettings({ siteDescription: e.target.value })}
|
||||
placeholder="A description of your site..."
|
||||
rows={3}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Content Moderation</CardTitle>
|
||||
<CardDescription>
|
||||
Configure how content moderation works on your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Enable Content Moderation</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Apply blocked words and user lists to filter content
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.enableModeration}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ enableModeration: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Auto-hide Blocked Content</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Automatically hide content that matches blocked words
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.autoHideBlocked}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ autoHideBlocked: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Require Content Approval</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
All content must be manually approved before showing
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.requireApproval}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ requireApproval: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Environment Configuration</CardTitle>
|
||||
<CardDescription>
|
||||
Current environment settings
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 font-mono text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>VITE_ADMIN_NPUB:</span>
|
||||
<span className="text-muted-foreground">
|
||||
{ADMIN_NPUB ? `${ADMIN_NPUB.slice(0, 16)}...` : 'Not configured'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!ADMIN_NPUB && (
|
||||
<Alert className="mt-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Set VITE_ADMIN_NPUB environment variable to configure admin access.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper components
|
||||
function UserAvatar({ pubkey }: { pubkey: string }) {
|
||||
const author = useAuthor(pubkey);
|
||||
|
||||
return (
|
||||
<Avatar>
|
||||
<AvatarImage src={author.data?.metadata?.picture} />
|
||||
<AvatarFallback>
|
||||
{(author.data?.metadata?.name || genUserName(pubkey)).slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
function UserName({ pubkey }: { pubkey: string }) {
|
||||
const author = useAuthor(pubkey);
|
||||
|
||||
return (
|
||||
<span className="font-medium">
|
||||
{author.data?.metadata?.display_name || author.data?.metadata?.name || genUserName(pubkey)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function UserListItem({ pubkey, onRemove, variant, disabled }: {
|
||||
pubkey: string;
|
||||
onRemove: () => void;
|
||||
variant: 'allow' | 'deny';
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 p-2 rounded-lg border">
|
||||
<UserAvatar pubkey={pubkey} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm truncate">
|
||||
<UserName pubkey={pubkey} />
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{npub.slice(0, 20)}...
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRemove}
|
||||
className={variant === 'allow' ? 'text-green-600 hover:text-green-700' : 'text-red-600 hover:text-red-700'}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": false,
|
||||
"strictNullChecks": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
+13
-25
@@ -1,31 +1,19 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
],
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": false,
|
||||
"strictNullChecks": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
},
|
||||
"noImplicitAny": false,
|
||||
"noUnusedParameters": false,
|
||||
"skipLibCheck": true,
|
||||
"allowJs": true,
|
||||
"noUnusedLocals": false,
|
||||
"strictNullChecks": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user