mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
get user info from npubxcash
This commit is contained in:
1 parent
1701cce6b0
commit
c8ad3b1a36
2 files changed
+176
-49
No files matched your search
+105
-45
@@ -3,7 +3,7 @@ import { nip19 } from 'nostr-tools';
|
||||
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
||||
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQRCode } from '@/hooks/useQRCode';
|
||||
@@ -17,7 +17,6 @@ import { TransactionHistory } from '@/components/wallet/TransactionHistory';
|
||||
import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal';
|
||||
import { RemoveMintModal } from '@/components/wallet/RemoveMintModal';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { QrCode, Copy, Check } from 'lucide-react';
|
||||
|
||||
export function CashuWallet() {
|
||||
@@ -50,7 +49,7 @@ export function CashuWallet() {
|
||||
|
||||
const { getCleanMintLabel } = useCashuMints(null);
|
||||
|
||||
const { setMint: setNpubCashMint, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
|
||||
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
@@ -107,6 +106,7 @@ export function CashuWallet() {
|
||||
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
|
||||
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
|
||||
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
|
||||
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
|
||||
|
||||
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
|
||||
const [currentInvoice, setCurrentInvoice] = useState<{
|
||||
@@ -126,6 +126,9 @@ export function CashuWallet() {
|
||||
|
||||
// Ref to store the mint quote redeemed event unsubscribe function
|
||||
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||
|
||||
// Ref to track if we've fetched npub.cash user info
|
||||
const hasCheckedNpubCashRef = useRef(false);
|
||||
|
||||
// ============================================================================
|
||||
// COMPUTED VALUES
|
||||
@@ -153,13 +156,15 @@ export function CashuWallet() {
|
||||
|
||||
/**
|
||||
* Set active mint
|
||||
* @param mintUrl - The mint URL to set as active
|
||||
* @param syncToNpubCash - Whether to sync this change to npub.cash (default: true for manual changes)
|
||||
*/
|
||||
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
|
||||
const handleSetActiveMint = useCallback(async (mintUrl: string | null, syncToNpubCash = true) => {
|
||||
// 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) {
|
||||
// If user is logged in to npub.cash, a mint is selected, and we should sync
|
||||
if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) {
|
||||
console.log('🔄 Syncing active mint with npub.cash:', mintUrl);
|
||||
const success = await setNpubCashMint(mintUrl);
|
||||
|
||||
@@ -572,12 +577,65 @@ export function CashuWallet() {
|
||||
}
|
||||
}, [error, toast]);
|
||||
|
||||
// Fetch npub.cash user info on mount/login and sync mint
|
||||
useEffect(() => {
|
||||
// Reset the check flag if user logs out
|
||||
if (!isNpubCashLoggedIn) {
|
||||
hasCheckedNpubCashRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Only fetch if user is logged in, wallet is initialized, and we haven't fetched yet
|
||||
if (!isInitialized || hasCheckedNpubCashRef.current) return;
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
// Mark that we've checked to prevent multiple fetches
|
||||
hasCheckedNpubCashRef.current = true;
|
||||
|
||||
console.log('🔄 Fetching npub.cash user info...');
|
||||
const userInfo = await getNpubCashUserInfo();
|
||||
|
||||
if (!userInfo) return;
|
||||
|
||||
setNpubCashUserInfo(userInfo);
|
||||
console.log('📋 npub.cash user info:', userInfo);
|
||||
|
||||
// Check if the mint from npub.cash is different from our active mint
|
||||
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
|
||||
console.log('🔄 npub.cash has a different preferred mint:', userInfo.mint_url);
|
||||
|
||||
// Check if we have this mint in our list
|
||||
const mintExists = mints.some(m => m.url === userInfo.mint_url);
|
||||
|
||||
if (!mintExists) {
|
||||
console.log('➕ Mint not in our list, adding it:', userInfo.mint_url);
|
||||
try {
|
||||
await addMint(userInfo.mint_url);
|
||||
// Wait a bit for the mint to be added
|
||||
setTimeout(() => {
|
||||
handleSetActiveMint(userInfo.mint_url, false);
|
||||
}, 500);
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to add mint from npub.cash:', err);
|
||||
}
|
||||
} else {
|
||||
// Mint exists, just set it as active (without syncing back to npub.cash)
|
||||
handleSetActiveMint(userInfo.mint_url, false);
|
||||
}
|
||||
} else if (userInfo.mint_url === activeMintUrl) {
|
||||
console.log('✅ Active mint already matches npub.cash preferred mint');
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserInfo();
|
||||
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, addMint, handleSetActiveMint]);
|
||||
|
||||
// Auto-select active mint when mints change (balances will update automatically via events)
|
||||
useEffect(() => {
|
||||
if (mints.length > 0 && !activeMintUrl) {
|
||||
// Select first mint initially - user can change via dropdown
|
||||
handleSetActiveMint(mints[0].url);
|
||||
// Don't sync to npub.cash on auto-select, only on manual changes
|
||||
handleSetActiveMint(mints[0].url, false);
|
||||
}
|
||||
}, [mints, activeMintUrl, handleSetActiveMint]);
|
||||
|
||||
@@ -678,43 +736,45 @@ export function CashuWallet() {
|
||||
{/* ========================================================================
|
||||
SECTION: Lightning Address
|
||||
======================================================================== */}
|
||||
{user?.pubkey && (
|
||||
<div className="mb-4 flex items-center justify-center gap-2">
|
||||
<button
|
||||
onClick={async () => {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const address = `${npub}@npub.cash`;
|
||||
await copyToClipboard(address);
|
||||
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-sm font-mono transition-colors h-[34px]"
|
||||
title="Click to copy Lightning address"
|
||||
>
|
||||
<span className="truncate max-w-[250px] sm:max-w-none">
|
||||
{nip19.npubEncode(user.pubkey)}@npub.cash
|
||||
</span>
|
||||
{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 npub = nip19.npubEncode(user.pubkey);
|
||||
const address = `${npub}@npub.cash`;
|
||||
const qr = await generateQRCode(address);
|
||||
setLightningAddressQRCode(qr);
|
||||
setShowLightningAddressQR(true);
|
||||
}}
|
||||
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[34px]"
|
||||
title="Show QR Code"
|
||||
>
|
||||
<QrCode className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{user?.pubkey && (() => {
|
||||
// Use username if available, otherwise use npub
|
||||
const identifier = npubCashUserInfo?.name || nip19.npubEncode(user.pubkey);
|
||||
const lightningAddress = `${identifier}@npubx.cash`;
|
||||
|
||||
return (
|
||||
<div className="mb-4 flex items-center justify-center gap-2">
|
||||
<button
|
||||
onClick={async () => {
|
||||
await copyToClipboard(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-sm font-mono transition-colors h-[34px]"
|
||||
title="Click to copy Lightning address"
|
||||
>
|
||||
<span className="truncate max-w-[250px] sm:max-w-none">
|
||||
{lightningAddress}
|
||||
</span>
|
||||
{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 qr = await generateQRCode(lightningAddress);
|
||||
setLightningAddressQRCode(qr);
|
||||
setShowLightningAddressQR(true);
|
||||
}}
|
||||
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[34px]"
|
||||
title="Show QR Code"
|
||||
>
|
||||
<QrCode className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Receive & Send Cards
|
||||
@@ -802,7 +862,7 @@ export function CashuWallet() {
|
||||
title="Lightning Address"
|
||||
description="Scan this QR code to send payments to your Lightning address"
|
||||
qrCodeUrl={lightningAddressQRCode}
|
||||
content={user?.pubkey ? `${nip19.npubEncode(user.pubkey)}@npub.cash` : ''}
|
||||
content={user?.pubkey ? `${npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)}@npubx.cash` : ''}
|
||||
icon="zap"
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useNIP98 } from './useNIP98';
|
||||
|
||||
const NPUBCASH_API_BASE = 'https://npub.cash/api/v2';
|
||||
const NPUBCASH_API_BASE = 'https://npubx.cash/api/v2';
|
||||
|
||||
export interface NpubCashUserInfo {
|
||||
pubkey: string;
|
||||
name?: string;
|
||||
mint_url: string;
|
||||
lock_quote: boolean;
|
||||
}
|
||||
|
||||
export interface NpubCashApiError {
|
||||
error: true;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface NpubCashUserInfoResponse {
|
||||
error: false;
|
||||
data: {
|
||||
user: NpubCashUserInfo;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for interacting with npub.cash API
|
||||
* Currently supports setting the user's preferred mint
|
||||
* Currently supports setting the user's preferred mint and getting user info
|
||||
*/
|
||||
export function useNpubCash() {
|
||||
const { createAuthHeader, isLoggedIn, pubkey } = useNIP98();
|
||||
@@ -46,8 +60,13 @@ export function useNpubCash() {
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json() as NpubCashApiError;
|
||||
throw new Error(errorData.message || 'Failed to set mint');
|
||||
// Try to parse JSON error, but handle HTML responses (404, etc.)
|
||||
try {
|
||||
const errorData = await response.json() as NpubCashApiError;
|
||||
throw new Error(errorData.message || `Failed to set mint (${response.status})`);
|
||||
} catch (parseError) {
|
||||
throw new Error(`Failed to set mint: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Successfully set preferred mint on npub.cash to: ${mintUrl}`);
|
||||
@@ -62,8 +81,56 @@ export function useNpubCash() {
|
||||
}
|
||||
}, [isLoggedIn, createAuthHeader]);
|
||||
|
||||
/**
|
||||
* Get user info from npub.cash
|
||||
*/
|
||||
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
|
||||
if (!isLoggedIn) {
|
||||
console.error('❌ User must be logged in to get npub.cash user info');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const url = `${NPUBCASH_API_BASE}/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) {
|
||||
// Try to parse JSON error, but handle HTML responses (404, etc.)
|
||||
try {
|
||||
const errorData = await response.json() as NpubCashApiError;
|
||||
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
|
||||
} catch (parseError) {
|
||||
throw new Error(`Failed to get user info: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
const data = await response.json() as NpubCashUserInfoResponse;
|
||||
console.log('✅ Successfully retrieved npub.cash user info:', data.data.user);
|
||||
return data.data.user;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
console.error('❌ Failed to get npub.cash user info:', errorMessage);
|
||||
setError(errorMessage);
|
||||
return null;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isLoggedIn, createAuthHeader]);
|
||||
|
||||
return {
|
||||
setMint,
|
||||
getUserInfo,
|
||||
isLoading,
|
||||
error,
|
||||
isLoggedIn,
|
||||
|
||||
Reference in new issue
Block a user