From 346ba707108ec14998369e077e80f1aab1bc1518 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Mon, 13 Oct 2025 12:33:02 -0700 Subject: [PATCH] set mint with npubxcash --- docs/NPUB_CASH_ADDRESS.md | 612 --------------------------------- src/components/CashuWallet.tsx | 29 +- src/hooks/useNIP98.ts | 73 ++++ src/hooks/useNpubCash.ts | 73 ++++ 4 files changed, 173 insertions(+), 614 deletions(-) delete mode 100644 docs/NPUB_CASH_ADDRESS.md create mode 100644 src/hooks/useNIP98.ts create mode 100644 src/hooks/useNpubCash.ts diff --git a/docs/NPUB_CASH_ADDRESS.md b/docs/NPUB_CASH_ADDRESS.md deleted file mode 100644 index 9e70b97..0000000 --- a/docs/NPUB_CASH_ADDRESS.md +++ /dev/null @@ -1,612 +0,0 @@ -# npub.cash Lightning Address Integration - -This document explains how to integrate npub.cash Lightning addresses into your Nostr application, allowing users to receive Lightning payments without any setup. - -## Overview - -npub.cash is a Lightning address service powered by Cashu and Nostr. It provides instant Lightning addresses for any Nostr public key, with no registration required. Payments are stored as Cashu quotes that users can later claim. - -### How It Works - -1. **Identity**: Your Nostr pubkey becomes your Lightning address (`npub1xxx...@npubx.cash`) -2. **Receiving**: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey -3. **Claiming**: Authenticate with NIP-98 to fetch and redeem your paid quotes from the configured mint - -## Key Features - -- **Zero Setup**: Any Nostr pubkey is instantly a valid Lightning address -- **Nostr Identity**: Uses NIP-98 authentication (no separate account needed) -- **Privacy**: Cashu provides better privacy than plain Lightning -- **Flexible**: Set your preferred Cashu mint -- **Optional Locking**: Enable NUT-20 quote locking for enhanced security - -## Basic Usage - -### Get Your Lightning Address - -```tsx -import { useNpubCash } from '@/hooks/useNpubCash'; - -function MyLightningAddress() { - const { lightningAddress, isLoading } = useNpubCash(); - - if (isLoading) return

Loading...

; - - return ( -
-

My Lightning Address

-

{lightningAddress}

- -
- ); -} -``` - -### Display Unclaimed Balance - -```tsx -function UnclaimedBalance() { - const { unclaimedAmount, quotes, refresh } = useNpubCash(); - - return ( -
-

Unclaimed Payments

-

{unclaimedAmount} sats from {quotes.length} payments

- -
- ); -} -``` - -### Fetch and Display Quotes - -```tsx -function PaymentHistory() { - const { quotes, fetchQuotes, isLoading } = useNpubCash(); - - useEffect(() => { - fetchQuotes(); - }, [fetchQuotes]); - - return ( -
-

Received Payments

- {quotes.map(quote => ( -
-

Amount: {quote.amount} sats

-

Mint: {quote.mint_url}

-

Status: {quote.state}

-

Paid: {new Date(quote.paid_at * 1000).toLocaleString()}

-
- ))} -
- ); -} -``` - -## Advanced Features - -### Set Username (Paid Feature) - -Users can optionally purchase a custom username for a cleaner Lightning address: - -```tsx -function UsernameSelector() { - const { userInfo, setUsername, isLoading } = useNpubCash(); - - const handleSetUsername = async () => { - try { - await setUsername('myusername'); - // Address becomes: myusername@npubx.cash - alert('Username set successfully!'); - } catch (error) { - // Payment required - X-Cashu header returned - console.error(error); - } - }; - - return ( -
-

Current: {userInfo?.name || 'Using npub'}

- -
- ); -} -``` - -### Configure Preferred Mint - -```tsx -function MintSelector() { - const { userInfo, setMint, isLoading } = useNpubCash(); - const [mintUrl, setMintUrl] = useState(''); - - const handleSetMint = async () => { - try { - await setMint(mintUrl); - alert('Mint updated successfully!'); - } catch (error) { - console.error('Failed to set mint:', error); - } - }; - - return ( -
-

Current Mint: {userInfo?.mint_url}

- setMintUrl(e.target.value)} - placeholder="https://mint.example.com" - /> - -
- ); -} -``` - -### Enable Quote Locking (NUT-20) - -Lock quotes to your pubkey for enhanced security: - -```tsx -function QuoteLocking() { - const { userInfo, setLockQuotes, isLoading } = useNpubCash(); - - const toggleLocking = async () => { - try { - await setLockQuotes(!userInfo?.lock_quote); - alert('Quote locking updated!'); - } catch (error) { - console.error('Failed to update locking:', error); - } - }; - - return ( -
- -

- Requires wallet with NUT-20 support -

-
- ); -} -``` - -## Complete Example: Receive Payment Widget - -```tsx -import { useState } from 'react'; -import { useNpubCash } from '@/hooks/useNpubCash'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { Badge } from '@/components/ui/badge'; - -function ReceivePaymentWidget() { - const { - lightningAddress, - unclaimedAmount, - quotes, - isLoading, - refresh, - } = useNpubCash(); - - const [copied, setCopied] = useState(false); - - const copyAddress = async () => { - if (!lightningAddress) return; - - await navigator.clipboard.writeText(lightningAddress); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }; - - return ( - - - Receive Lightning Payments - - - {/* Lightning Address */} -
- -
- - {lightningAddress || 'Loading...'} - - -
-
- - {/* Unclaimed Balance */} -
- Unclaimed Balance - - {unclaimedAmount} sats - -
- - {/* Payment History */} -
-
- Recent Payments - -
- -
- {quotes.length === 0 ? ( -

- No payments received yet -

- ) : ( - quotes.map(quote => ( -
-
- {quote.amount} sats - - {quote.state} - -
-

- {new Date(quote.paid_at * 1000).toLocaleString()} -

-

- {quote.mint_url} -

-
- )) - )} -
-
-
-
- ); -} - -export default ReceivePaymentWidget; -``` - -## API Reference - -### Hook: `useNpubCash()` - -Returns an object with the following properties and methods: - -#### State - -- `isInitialized: boolean` - Whether the hook has loaded initial data -- `isLoading: boolean` - Whether an API request is in progress -- `error: string | null` - Error message if any operation failed -- `lightningAddress: string | null` - User's npub.cash Lightning address -- `userInfo: NpubCashUserInfo | null` - User settings (mint, username, locking) -- `quotes: NpubCashQuote[]` - Array of received payment quotes -- `unclaimedAmount: number` - Total sats in unclaimed paid quotes - -#### Methods - -##### `fetchQuotes(since?: number, limit?: number): Promise` - -Fetch paid quotes from npub.cash. - -- `since` - Optional Unix timestamp to only fetch quotes paid after this time -- `limit` - Maximum number of quotes to return (default: 50) - -```tsx -const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours -``` - -##### `fetchUserInfo(): Promise` - -Fetch current user settings. - -```tsx -const info = await fetchUserInfo(); -console.log('Preferred mint:', info.mint_url); -``` - -##### `setUsername(username: string): Promise` - -Set a custom username (paid feature via Cashu 402). - -```tsx -await setUsername('alice'); // Address becomes alice@npubx.cash -``` - -##### `setMint(mintUrl: string): Promise` - -Set preferred Cashu mint for receiving payments. - -```tsx -await setMint('https://mint.example.com'); -``` - -##### `setLockQuotes(locked: boolean): Promise` - -Enable or disable quote locking to pubkey (NUT-20). - -```tsx -await setLockQuotes(true); // Enable locking -``` - -##### `refresh(): Promise` - -Refresh all data (quotes and user info) from npub.cash. - -```tsx -await refresh(); -``` - -##### `clearAuth(): void` - -Clear stored JWT token, forcing NIP-98 re-authentication on next request. - -```tsx -clearAuth(); // Next API call will require NIP-98 signature -``` - -## Types - -### `NpubCashQuote` - -```tsx -interface NpubCashQuote { - created_at: number; // Unix timestamp when quote was created - paid_at: number; // Unix timestamp when invoice was paid - expires_at: number; // Unix timestamp when quote expires - mint_url: string; // Cashu mint URL for this quote - quote_id: string; // Unique quote identifier - request: string; // Original BOLT11 invoice - amount: number; // Amount in sats - state: 'PENDING' | 'PAID' | 'EXPIRED'; - locked: boolean; // Whether quote is locked to pubkey -} -``` - -### `NpubCashUserInfo` - -```tsx -interface NpubCashUserInfo { - pubkey: string; // User's Nostr public key (hex) - name: string | null; // Custom username (if set) - mint_url: string; // User's preferred Cashu mint - lock_quote: boolean; // Whether quote locking is enabled -} -``` - -## Authentication - -The hook handles authentication automatically using two methods: - -### NIP-98 HTTP Auth - -For every API request, the hook can create a NIP-98 event (kind 27235) signed by the user's Nostr key. This is the primary authentication method. - -### JWT Tokens - -To avoid repeated signing requests (especially for browser extensions), the hook can obtain a JWT token using a single NIP-98 request. The token is cached in localStorage and automatically refreshed when expired. - -```tsx -// JWT is obtained automatically on first API call -// Cached in localStorage as 'npubcash-jwt' -// Valid for 30 minutes -``` - -## Integration with Cashu Wallet - -To claim the received funds, integrate with the existing `useCashu` hook: - -```tsx -import { useNpubCash } from '@/hooks/useNpubCash'; -import { useCashu } from '@/hooks/useCashu'; - -function ClaimFunds() { - const { quotes } = useNpubCash(); - const { redeemMintQuote, addMint } = useCashu(); - - const claimQuote = async (quote: NpubCashQuote) => { - try { - // Add mint if not already added - await addMint(quote.mint_url); - - // Redeem the quote to receive Cashu tokens - await redeemMintQuote(quote.mint_url, quote.quote_id); - - alert(`Claimed ${quote.amount} sats!`); - } catch (error) { - console.error('Failed to claim:', error); - } - }; - - return ( -
- {quotes.map(quote => ( -
-

{quote.amount} sats

- -
- ))} -
- ); -} -``` - -## Best Practices - -### 1. Track Claimed Quotes - -The hook stores `lastClaimedAt` timestamp in localStorage to track which quotes are new. Update this after claiming: - -```tsx -const [lastClaimed, setLastClaimed] = useLocalStorage('npubcash-last-claimed', 0); - -const claimAll = async () => { - for (const quote of quotes) { - await redeemMintQuote(quote.mint_url, quote.quote_id); - } - setLastClaimed(Date.now() / 1000); -}; -``` - -### 2. Handle Expired Quotes - -Quotes expire after a certain time. Filter expired quotes in your UI: - -```tsx -const activeQuotes = quotes.filter(q => - q.state === 'PAID' && q.expires_at > Date.now() / 1000 -); -``` - -### 3. Poll for New Payments - -Set up periodic polling to check for new payments: - -```tsx -useEffect(() => { - const interval = setInterval(() => { - refresh(); - }, 30000); // Every 30 seconds - - return () => clearInterval(interval); -}, [refresh]); -``` - -### 4. Display QR Code for Address - -Make it easy for users to receive payments by displaying a QR code: - -```tsx -import QRCode from 'qrcode.react'; - -function AddressQR() { - const { lightningAddress } = useNpubCash(); - - return ( -
- -

{lightningAddress}

-
- ); -} -``` - -## Error Handling - -The hook provides error state for failed operations: - -```tsx -function ErrorDisplay() { - const { error, clearAuth, refresh } = useNpubCash(); - - if (!error) return null; - - const handleRetry = () => { - if (error.includes('Authentication')) { - clearAuth(); // Clear stale JWT - } - refresh(); // Try again - }; - - return ( -
-

{error}

- -
- ); -} -``` - -## Configuration - -### Custom npub.cash Domain - -If using a self-hosted npub.cash instance: - -```tsx -// In useNpubCash.ts, modify: -const NPUBCASH_API_BASE = 'https://your-instance.com/api/v2'; -const NPUBCASH_DOMAIN = 'your-instance.com'; -``` - -## Troubleshooting - -### "No user logged in" Error - -Ensure the user is logged in via `useCurrentUser`: - -```tsx -const { user } = useCurrentUser(); -const npubCash = useNpubCash(); - -if (!user) { - return

Please log in first

; -} -``` - -### "NIP-98 validation failed" - -Check that: -1. System clock is accurate (NIP-98 events must be recent) -2. URL matches exactly (no query params in NIP-98 event URL) -3. User's signer is working properly - -### JWT Token Issues - -If JWT tokens aren't working, clear and re-authenticate: - -```tsx -const { clearAuth, refresh } = useNpubCash(); - -clearAuth(); -await refresh(); // Will create new NIP-98 auth -``` - -## Related Documentation - -- [Cashu Zap Integration](./CASHU_ZAP_INTEGRATION.md) -- [Nostr Comments System](./NOSTR_COMMENTS.md) -- [AI Chat Integration](./AI_CHAT.md) - -## Additional Resources - -- [npub.cash Documentation](https://npubx.cash/docs) -- [NIP-98: HTTP Auth](https://github.com/nostr-protocol/nips/blob/master/98.md) -- [Cashu Protocol](https://docs.cashu.space/) -- [NUT-20: Locked Tokens](https://github.com/cashubtc/nuts/blob/main/20.md) - ---- - -**Built with MKStack** - The complete framework for building Nostr applications with AI. - diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx index 322bc88..2a5e212 100644 --- a/src/components/CashuWallet.tsx +++ b/src/components/CashuWallet.tsx @@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; import { useCashuMints } from '@/hooks/cashu/useCashuMints'; import { useLightningAddress } from '@/hooks/useLightningAddress'; +import { useNpubCash } from '@/hooks/useNpubCash'; import { useToast } from '@/hooks/useToast'; import { useQRCode } from '@/hooks/useQRCode'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; @@ -13,6 +14,7 @@ import { SendCard } from '@/components/wallet/SendCard'; import { TransactionHistory } from '@/components/wallet/TransactionHistory'; import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal'; import { RemoveMintModal } from '@/components/wallet/RemoveMintModal'; +import { LoginArea } from '@/components/auth/LoginArea'; export function CashuWallet() { // ============================================================================ @@ -44,7 +46,7 @@ export function CashuWallet() { const { getCleanMintLabel } = useCashuMints(null); - + const { setMint: setNpubCashMint, isLoggedIn: isNpubCashLoggedIn } = useNpubCash(); const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); @@ -146,7 +148,24 @@ export function CashuWallet() { const handleSetActiveMint = useCallback(async (mintUrl: string | null) => { // Set the active mint locally setActiveMintUrl(mintUrl); - }, []); + + // If user is logged in to npub.cash and a mint is selected, sync it + if (isNpubCashLoggedIn && mintUrl) { + console.log('🔄 Syncing active mint with npub.cash:', mintUrl); + const success = await setNpubCashMint(mintUrl); + + if (success) { + toast({ + title: "Mint Synced", + description: "Your preferred mint has been updated on npub.cash", + }); + } else { + // Don't show error toast - the hook already logs errors + // Just log that sync failed but local mint is still set + console.warn('⚠️ Failed to sync mint with npub.cash, but local mint is still set'); + } + } + }, [isNpubCashLoggedIn, setNpubCashMint, toast]); // ============================================================================ // HELPER FUNCTIONS - History @@ -619,6 +638,12 @@ export function CashuWallet() {
+ {/* ======================================================================== + SECTION: Login Area + ======================================================================== */} +
+ +
{/* ======================================================================== SECTION: Balance Display diff --git a/src/hooks/useNIP98.ts b/src/hooks/useNIP98.ts new file mode 100644 index 0000000..0eb2c6a --- /dev/null +++ b/src/hooks/useNIP98.ts @@ -0,0 +1,73 @@ +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 - The "Nostr base64..." authorization header value + */ + const createAuthHeader = useCallback(async (options: NIP98Options): Promise => { + 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, + }; +} + diff --git a/src/hooks/useNpubCash.ts b/src/hooks/useNpubCash.ts new file mode 100644 index 0000000..ece6b67 --- /dev/null +++ b/src/hooks/useNpubCash.ts @@ -0,0 +1,73 @@ +import { useCallback, useState } from 'react'; +import { useNIP98 } from './useNIP98'; + +const NPUBCASH_API_BASE = 'https://npub.cash/api/v2'; + +export interface NpubCashApiError { + error: true; + message: string; +} + +/** + * Hook for interacting with npub.cash API + * Currently supports setting the user's preferred mint + */ +export function useNpubCash() { + const { createAuthHeader, isLoggedIn, pubkey } = useNIP98(); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + /** + * Set the user's preferred mint on npub.cash + */ + const setMint = useCallback(async (mintUrl: string): Promise => { + if (!isLoggedIn) { + console.error('❌ User must be logged in to set mint'); + return false; + } + + try { + setIsLoading(true); + setError(null); + + const url = `${NPUBCASH_API_BASE}/user/mint`; + const body = { mint_url: mintUrl }; + const authHeader = await createAuthHeader({ url, method: 'PATCH', body }); + + console.log(`🔄 Setting preferred mint on npub.cash to: ${mintUrl}`); + + const response = await fetch(url, { + method: 'PATCH', + headers: { + 'Authorization': authHeader, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + }); + + if (!response.ok) { + const errorData = await response.json() as NpubCashApiError; + throw new Error(errorData.message || 'Failed to set mint'); + } + + console.log(`✅ Successfully set preferred mint on npub.cash to: ${mintUrl}`); + return true; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Unknown error'; + console.error('❌ Failed to set npub.cash mint:', errorMessage); + setError(errorMessage); + return false; + } finally { + setIsLoading(false); + } + }, [isLoggedIn, createAuthHeader]); + + return { + setMint, + isLoading, + error, + isLoggedIn, + pubkey, + }; +} +