mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
set mint with npubxcash
This commit is contained in:
1 parent
5dc19e857f
commit
346ba70710
4 files changed
+173
-614
No files matched your search
@@ -1,612 +0,0 @@
|
||||
# npub.cash Lightning Address Integration
|
||||
|
||||
This document explains how to integrate npub.cash Lightning addresses into your Nostr application, allowing users to receive Lightning payments without any setup.
|
||||
|
||||
## Overview
|
||||
|
||||
npub.cash is a Lightning address service powered by Cashu and Nostr. It provides instant Lightning addresses for any Nostr public key, with no registration required. Payments are stored as Cashu quotes that users can later claim.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Identity**: Your Nostr pubkey becomes your Lightning address (`[email protected]`)
|
||||
2. **Receiving**: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey
|
||||
3. **Claiming**: Authenticate with NIP-98 to fetch and redeem your paid quotes from the configured mint
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Zero Setup**: Any Nostr pubkey is instantly a valid Lightning address
|
||||
- **Nostr Identity**: Uses NIP-98 authentication (no separate account needed)
|
||||
- **Privacy**: Cashu provides better privacy than plain Lightning
|
||||
- **Flexible**: Set your preferred Cashu mint
|
||||
- **Optional Locking**: Enable NUT-20 quote locking for enhanced security
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Get Your Lightning Address
|
||||
|
||||
```tsx
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
|
||||
function MyLightningAddress() {
|
||||
const { lightningAddress, isLoading } = useNpubCash();
|
||||
|
||||
if (isLoading) return <p>Loading...</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>My Lightning Address</h3>
|
||||
<p className="font-mono">{lightningAddress}</p>
|
||||
<button onClick={() => navigator.clipboard.writeText(lightningAddress)}>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Display Unclaimed Balance
|
||||
|
||||
```tsx
|
||||
function UnclaimedBalance() {
|
||||
const { unclaimedAmount, quotes, refresh } = useNpubCash();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>Unclaimed Payments</h3>
|
||||
<p>{unclaimedAmount} sats from {quotes.length} payments</p>
|
||||
<button onClick={refresh}>Refresh</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Fetch and Display Quotes
|
||||
|
||||
```tsx
|
||||
function PaymentHistory() {
|
||||
const { quotes, fetchQuotes, isLoading } = useNpubCash();
|
||||
|
||||
useEffect(() => {
|
||||
fetchQuotes();
|
||||
}, [fetchQuotes]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>Received Payments</h3>
|
||||
{quotes.map(quote => (
|
||||
<div key={quote.quote_id} className="border p-4 rounded">
|
||||
<p>Amount: {quote.amount} sats</p>
|
||||
<p>Mint: {quote.mint_url}</p>
|
||||
<p>Status: {quote.state}</p>
|
||||
<p>Paid: {new Date(quote.paid_at * 1000).toLocaleString()}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Set Username (Paid Feature)
|
||||
|
||||
Users can optionally purchase a custom username for a cleaner Lightning address:
|
||||
|
||||
```tsx
|
||||
function UsernameSelector() {
|
||||
const { userInfo, setUsername, isLoading } = useNpubCash();
|
||||
|
||||
const handleSetUsername = async () => {
|
||||
try {
|
||||
await setUsername('myusername');
|
||||
// Address becomes: [email protected]
|
||||
alert('Username set successfully!');
|
||||
} catch (error) {
|
||||
// Payment required - X-Cashu header returned
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Current: {userInfo?.name || 'Using npub'}</p>
|
||||
<button onClick={handleSetUsername} disabled={isLoading}>
|
||||
Set Username
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Configure Preferred Mint
|
||||
|
||||
```tsx
|
||||
function MintSelector() {
|
||||
const { userInfo, setMint, isLoading } = useNpubCash();
|
||||
const [mintUrl, setMintUrl] = useState('');
|
||||
|
||||
const handleSetMint = async () => {
|
||||
try {
|
||||
await setMint(mintUrl);
|
||||
alert('Mint updated successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to set mint:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Current Mint: {userInfo?.mint_url}</p>
|
||||
<input
|
||||
type="text"
|
||||
value={mintUrl}
|
||||
onChange={(e) => setMintUrl(e.target.value)}
|
||||
placeholder="https://mint.example.com"
|
||||
/>
|
||||
<button onClick={handleSetMint} disabled={isLoading}>
|
||||
Update Mint
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Enable Quote Locking (NUT-20)
|
||||
|
||||
Lock quotes to your pubkey for enhanced security:
|
||||
|
||||
```tsx
|
||||
function QuoteLocking() {
|
||||
const { userInfo, setLockQuotes, isLoading } = useNpubCash();
|
||||
|
||||
const toggleLocking = async () => {
|
||||
try {
|
||||
await setLockQuotes(!userInfo?.lock_quote);
|
||||
alert('Quote locking updated!');
|
||||
} catch (error) {
|
||||
console.error('Failed to update locking:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={userInfo?.lock_quote || false}
|
||||
onChange={toggleLocking}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
Lock quotes to my pubkey (NUT-20)
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Requires wallet with NUT-20 support
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example: Receive Payment Widget
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
function ReceivePaymentWidget() {
|
||||
const {
|
||||
lightningAddress,
|
||||
unclaimedAmount,
|
||||
quotes,
|
||||
isLoading,
|
||||
refresh,
|
||||
} = useNpubCash();
|
||||
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const copyAddress = async () => {
|
||||
if (!lightningAddress) return;
|
||||
|
||||
await navigator.clipboard.writeText(lightningAddress);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Receive Lightning Payments</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Lightning Address */}
|
||||
<div>
|
||||
<label className="text-sm font-medium">Your Lightning Address</label>
|
||||
<div className="flex gap-2 items-center mt-1">
|
||||
<code className="flex-1 bg-muted px-3 py-2 rounded text-sm">
|
||||
{lightningAddress || 'Loading...'}
|
||||
</code>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={copyAddress}
|
||||
disabled={!lightningAddress}
|
||||
>
|
||||
{copied ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unclaimed Balance */}
|
||||
<div className="flex justify-between items-center p-4 bg-muted rounded">
|
||||
<span className="font-medium">Unclaimed Balance</span>
|
||||
<Badge variant="secondary" className="text-lg">
|
||||
{unclaimedAmount} sats
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Payment History */}
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-sm font-medium">Recent Payments</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={refresh}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-[300px] overflow-y-auto">
|
||||
{quotes.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No payments received yet
|
||||
</p>
|
||||
) : (
|
||||
quotes.map(quote => (
|
||||
<div
|
||||
key={quote.quote_id}
|
||||
className="border rounded p-3 space-y-1"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="font-semibold">{quote.amount} sats</span>
|
||||
<Badge
|
||||
variant={quote.state === 'PAID' ? 'default' : 'secondary'}
|
||||
>
|
||||
{quote.state}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(quote.paid_at * 1000).toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{quote.mint_url}
|
||||
</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default ReceivePaymentWidget;
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Hook: `useNpubCash()`
|
||||
|
||||
Returns an object with the following properties and methods:
|
||||
|
||||
#### State
|
||||
|
||||
- `isInitialized: boolean` - Whether the hook has loaded initial data
|
||||
- `isLoading: boolean` - Whether an API request is in progress
|
||||
- `error: string | null` - Error message if any operation failed
|
||||
- `lightningAddress: string | null` - User's npub.cash Lightning address
|
||||
- `userInfo: NpubCashUserInfo | null` - User settings (mint, username, locking)
|
||||
- `quotes: NpubCashQuote[]` - Array of received payment quotes
|
||||
- `unclaimedAmount: number` - Total sats in unclaimed paid quotes
|
||||
|
||||
#### Methods
|
||||
|
||||
##### `fetchQuotes(since?: number, limit?: number): Promise<NpubCashQuote[]>`
|
||||
|
||||
Fetch paid quotes from npub.cash.
|
||||
|
||||
- `since` - Optional Unix timestamp to only fetch quotes paid after this time
|
||||
- `limit` - Maximum number of quotes to return (default: 50)
|
||||
|
||||
```tsx
|
||||
const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours
|
||||
```
|
||||
|
||||
##### `fetchUserInfo(): Promise<NpubCashUserInfo>`
|
||||
|
||||
Fetch current user settings.
|
||||
|
||||
```tsx
|
||||
const info = await fetchUserInfo();
|
||||
console.log('Preferred mint:', info.mint_url);
|
||||
```
|
||||
|
||||
##### `setUsername(username: string): Promise<void>`
|
||||
|
||||
Set a custom username (paid feature via Cashu 402).
|
||||
|
||||
```tsx
|
||||
await setUsername('alice'); // Address becomes [email protected]
|
||||
```
|
||||
|
||||
##### `setMint(mintUrl: string): Promise<void>`
|
||||
|
||||
Set preferred Cashu mint for receiving payments.
|
||||
|
||||
```tsx
|
||||
await setMint('https://mint.example.com');
|
||||
```
|
||||
|
||||
##### `setLockQuotes(locked: boolean): Promise<void>`
|
||||
|
||||
Enable or disable quote locking to pubkey (NUT-20).
|
||||
|
||||
```tsx
|
||||
await setLockQuotes(true); // Enable locking
|
||||
```
|
||||
|
||||
##### `refresh(): Promise<void>`
|
||||
|
||||
Refresh all data (quotes and user info) from npub.cash.
|
||||
|
||||
```tsx
|
||||
await refresh();
|
||||
```
|
||||
|
||||
##### `clearAuth(): void`
|
||||
|
||||
Clear stored JWT token, forcing NIP-98 re-authentication on next request.
|
||||
|
||||
```tsx
|
||||
clearAuth(); // Next API call will require NIP-98 signature
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
### `NpubCashQuote`
|
||||
|
||||
```tsx
|
||||
interface NpubCashQuote {
|
||||
created_at: number; // Unix timestamp when quote was created
|
||||
paid_at: number; // Unix timestamp when invoice was paid
|
||||
expires_at: number; // Unix timestamp when quote expires
|
||||
mint_url: string; // Cashu mint URL for this quote
|
||||
quote_id: string; // Unique quote identifier
|
||||
request: string; // Original BOLT11 invoice
|
||||
amount: number; // Amount in sats
|
||||
state: 'PENDING' | 'PAID' | 'EXPIRED';
|
||||
locked: boolean; // Whether quote is locked to pubkey
|
||||
}
|
||||
```
|
||||
|
||||
### `NpubCashUserInfo`
|
||||
|
||||
```tsx
|
||||
interface NpubCashUserInfo {
|
||||
pubkey: string; // User's Nostr public key (hex)
|
||||
name: string | null; // Custom username (if set)
|
||||
mint_url: string; // User's preferred Cashu mint
|
||||
lock_quote: boolean; // Whether quote locking is enabled
|
||||
}
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
The hook handles authentication automatically using two methods:
|
||||
|
||||
### NIP-98 HTTP Auth
|
||||
|
||||
For every API request, the hook can create a NIP-98 event (kind 27235) signed by the user's Nostr key. This is the primary authentication method.
|
||||
|
||||
### JWT Tokens
|
||||
|
||||
To avoid repeated signing requests (especially for browser extensions), the hook can obtain a JWT token using a single NIP-98 request. The token is cached in localStorage and automatically refreshed when expired.
|
||||
|
||||
```tsx
|
||||
// JWT is obtained automatically on first API call
|
||||
// Cached in localStorage as 'npubcash-jwt'
|
||||
// Valid for 30 minutes
|
||||
```
|
||||
|
||||
## Integration with Cashu Wallet
|
||||
|
||||
To claim the received funds, integrate with the existing `useCashu` hook:
|
||||
|
||||
```tsx
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { useCashu } from '@/hooks/useCashu';
|
||||
|
||||
function ClaimFunds() {
|
||||
const { quotes } = useNpubCash();
|
||||
const { redeemMintQuote, addMint } = useCashu();
|
||||
|
||||
const claimQuote = async (quote: NpubCashQuote) => {
|
||||
try {
|
||||
// Add mint if not already added
|
||||
await addMint(quote.mint_url);
|
||||
|
||||
// Redeem the quote to receive Cashu tokens
|
||||
await redeemMintQuote(quote.mint_url, quote.quote_id);
|
||||
|
||||
alert(`Claimed ${quote.amount} sats!`);
|
||||
} catch (error) {
|
||||
console.error('Failed to claim:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{quotes.map(quote => (
|
||||
<div key={quote.quote_id}>
|
||||
<p>{quote.amount} sats</p>
|
||||
<button onClick={() => claimQuote(quote)}>Claim</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Track Claimed Quotes
|
||||
|
||||
The hook stores `lastClaimedAt` timestamp in localStorage to track which quotes are new. Update this after claiming:
|
||||
|
||||
```tsx
|
||||
const [lastClaimed, setLastClaimed] = useLocalStorage('npubcash-last-claimed', 0);
|
||||
|
||||
const claimAll = async () => {
|
||||
for (const quote of quotes) {
|
||||
await redeemMintQuote(quote.mint_url, quote.quote_id);
|
||||
}
|
||||
setLastClaimed(Date.now() / 1000);
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Handle Expired Quotes
|
||||
|
||||
Quotes expire after a certain time. Filter expired quotes in your UI:
|
||||
|
||||
```tsx
|
||||
const activeQuotes = quotes.filter(q =>
|
||||
q.state === 'PAID' && q.expires_at > Date.now() / 1000
|
||||
);
|
||||
```
|
||||
|
||||
### 3. Poll for New Payments
|
||||
|
||||
Set up periodic polling to check for new payments:
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
refresh();
|
||||
}, 30000); // Every 30 seconds
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [refresh]);
|
||||
```
|
||||
|
||||
### 4. Display QR Code for Address
|
||||
|
||||
Make it easy for users to receive payments by displaying a QR code:
|
||||
|
||||
```tsx
|
||||
import QRCode from 'qrcode.react';
|
||||
|
||||
function AddressQR() {
|
||||
const { lightningAddress } = useNpubCash();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<QRCode value={`lightning:${lightningAddress}`} size={256} />
|
||||
<p className="text-xs">{lightningAddress}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The hook provides error state for failed operations:
|
||||
|
||||
```tsx
|
||||
function ErrorDisplay() {
|
||||
const { error, clearAuth, refresh } = useNpubCash();
|
||||
|
||||
if (!error) return null;
|
||||
|
||||
const handleRetry = () => {
|
||||
if (error.includes('Authentication')) {
|
||||
clearAuth(); // Clear stale JWT
|
||||
}
|
||||
refresh(); // Try again
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-destructive/10 p-4 rounded">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<button onClick={handleRetry}>Retry</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Custom npub.cash Domain
|
||||
|
||||
If using a self-hosted npub.cash instance:
|
||||
|
||||
```tsx
|
||||
// In useNpubCash.ts, modify:
|
||||
const NPUBCASH_API_BASE = 'https://your-instance.com/api/v2';
|
||||
const NPUBCASH_DOMAIN = 'your-instance.com';
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "No user logged in" Error
|
||||
|
||||
Ensure the user is logged in via `useCurrentUser`:
|
||||
|
||||
```tsx
|
||||
const { user } = useCurrentUser();
|
||||
const npubCash = useNpubCash();
|
||||
|
||||
if (!user) {
|
||||
return <p>Please log in first</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### "NIP-98 validation failed"
|
||||
|
||||
Check that:
|
||||
1. System clock is accurate (NIP-98 events must be recent)
|
||||
2. URL matches exactly (no query params in NIP-98 event URL)
|
||||
3. User's signer is working properly
|
||||
|
||||
### JWT Token Issues
|
||||
|
||||
If JWT tokens aren't working, clear and re-authenticate:
|
||||
|
||||
```tsx
|
||||
const { clearAuth, refresh } = useNpubCash();
|
||||
|
||||
clearAuth();
|
||||
await refresh(); // Will create new NIP-98 auth
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Cashu Zap Integration](./CASHU_ZAP_INTEGRATION.md)
|
||||
- [Nostr Comments System](./NOSTR_COMMENTS.md)
|
||||
- [AI Chat Integration](./AI_CHAT.md)
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [npub.cash Documentation](https://npubx.cash/docs)
|
||||
- [NIP-98: HTTP Auth](https://github.com/nostr-protocol/nips/blob/master/98.md)
|
||||
- [Cashu Protocol](https://docs.cashu.space/)
|
||||
- [NUT-20: Locked Tokens](https://github.com/cashubtc/nuts/blob/main/20.md)
|
||||
|
||||
---
|
||||
|
||||
**Built with MKStack** - The complete framework for building Nostr applications with AI.
|
||||
|
||||
@@ -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() {
|
||||
<LoadingModal isLoading={isLoading || !isInitialized} />
|
||||
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Login Area
|
||||
======================================================================== */}
|
||||
<div className="absolute top-1 right-3 sm:right-4 z-10">
|
||||
<LoginArea />
|
||||
</div>
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Balance Display
|
||||
|
||||
@@ -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<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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
|
||||
/**
|
||||
* Set the user's preferred mint on npub.cash
|
||||
*/
|
||||
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user