mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
fix active mint determination
This commit is contained in:
1 parent
28e50a9d7a
commit
7d6ca0f71e
3 files changed
+140
-77
No files matched your search
@@ -3,6 +3,7 @@ import { nip19 } from 'nostr-tools';
|
||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import type { QRScanResult } from '@/hooks/useQRCode';
|
||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||
import { useTokenOperations } from '@/hooks/cashu/useTokenOperations';
|
||||
@@ -76,6 +77,18 @@ export function CashuWallet({
|
||||
return setNpubCashMint(mintUrl);
|
||||
};
|
||||
|
||||
// State to track npub.cash user info
|
||||
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
|
||||
|
||||
// Ref to track if we've fetched user info (only fetch once)
|
||||
const hasFetchedUserInfoRef = useRef(false);
|
||||
|
||||
// Ref to track if we've set a mint from user info (to prevent overwriting with stored mint)
|
||||
const hasSetMintFromUserInfoRef = useRef(false);
|
||||
|
||||
// Persist active mint URL to localStorage
|
||||
const [storedActiveMintUrl, setStoredActiveMintUrl] = useLocalStorage<string | null>('cashu-active-mint-url', null);
|
||||
|
||||
// ============================================================================
|
||||
// DOMAIN HOOKS
|
||||
// ============================================================================
|
||||
@@ -239,7 +252,6 @@ export function CashuWallet({
|
||||
} | null>(null);
|
||||
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);
|
||||
@@ -273,9 +285,6 @@ export function CashuWallet({
|
||||
}
|
||||
};
|
||||
|
||||
// Ref to track if we've fetched npub.cash user info
|
||||
const hasCheckedNpubCashRef = useRef(false);
|
||||
|
||||
// ============================================================================
|
||||
// COMPUTED VALUES
|
||||
// ============================================================================
|
||||
@@ -311,55 +320,156 @@ export function CashuWallet({
|
||||
// EFFECTS - NPub.cash Integration
|
||||
// ============================================================================
|
||||
|
||||
// Track previous login state to detect logout
|
||||
const prevLoggedInRef = useRef(isNpubCashLoggedIn);
|
||||
|
||||
// Fetch npub.cash user info once and set mint if available
|
||||
useEffect(() => {
|
||||
if (!isNpubCashLoggedIn) {
|
||||
hasCheckedNpubCashRef.current = false;
|
||||
// Detect logout: was logged in, now not logged in
|
||||
if (prevLoggedInRef.current && !isNpubCashLoggedIn) {
|
||||
setNpubCashUserInfo(null);
|
||||
hasFetchedUserInfoRef.current = false; // Reset so we can fetch again if they log back in
|
||||
hasSetMintFromUserInfoRef.current = false;
|
||||
hasAttemptedRestoreRef.current = false; // Reset restore so it can run again
|
||||
}
|
||||
prevLoggedInRef.current = isNpubCashLoggedIn;
|
||||
|
||||
// Only fetch if logged in, initialized, not loading, and we haven't fetched yet
|
||||
if (!isNpubCashLoggedIn || !isInitialized || isNpubCashLoading || hasFetchedUserInfoRef.current) {
|
||||
// If not logged in, mark as "fetched" (skipped) so restore logic can run
|
||||
if (!isNpubCashLoggedIn && isInitialized && !hasFetchedUserInfoRef.current) {
|
||||
hasFetchedUserInfoRef.current = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return;
|
||||
// Mark as fetched to prevent duplicate requests
|
||||
hasFetchedUserInfoRef.current = true;
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
hasCheckedNpubCashRef.current = true;
|
||||
|
||||
console.log('[CashuWallet] Fetching npub.cash user info...');
|
||||
try {
|
||||
const userInfo = await getNpubCashUserInfo();
|
||||
if (!userInfo) return;
|
||||
console.log('[CashuWallet] npub.cash user info received:', userInfo);
|
||||
|
||||
if (userInfo && userInfo.mintUrl) {
|
||||
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);
|
||||
console.log('[CashuWallet] Setting mint from npub.cash:', userInfo.mintUrl);
|
||||
|
||||
if (!mintExists && coco) {
|
||||
try {
|
||||
if (!coco) {
|
||||
console.warn('[CashuWallet] coco not available, cannot add/set mint');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if mint exists (known) by checking all mints
|
||||
const allMints = await coco.mint.getAllMints();
|
||||
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mint_url.toLowerCase());
|
||||
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mintUrl.toLowerCase());
|
||||
|
||||
if (isKnown) {
|
||||
// Mint exists but may not be trusted, ensure it's trusted
|
||||
const isTrusted = await coco.mint.isTrustedMint(userInfo.mint_url);
|
||||
const isTrusted = await coco.mint.isTrustedMint(userInfo.mintUrl);
|
||||
if (!isTrusted) {
|
||||
await coco.mint.trustMint(userInfo.mint_url);
|
||||
console.log('[CashuWallet] Trusting existing mint:', userInfo.mintUrl);
|
||||
await coco.mint.trustMint(userInfo.mintUrl);
|
||||
}
|
||||
} else {
|
||||
// Add mint from npub.cash and automatically trust it
|
||||
await coco.mint.addMint(userInfo.mint_url, { trusted: true });
|
||||
console.log('[CashuWallet] Adding new mint from npub.cash:', userInfo.mintUrl);
|
||||
await coco.mint.addMint(userInfo.mintUrl, { trusted: true });
|
||||
}
|
||||
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
|
||||
} catch {
|
||||
// Silent failure - user can manually add mint if needed
|
||||
|
||||
// Set as active mint immediately
|
||||
console.log('[CashuWallet] Setting active mint:', userInfo.mintUrl);
|
||||
setActiveMintUrl(userInfo.mintUrl, false);
|
||||
hasSetMintFromUserInfoRef.current = true;
|
||||
} else {
|
||||
console.log('[CashuWallet] No mintUrl in user info:', userInfo);
|
||||
setNpubCashUserInfo(null);
|
||||
}
|
||||
} else if (mintExists) {
|
||||
setActiveMintUrl(userInfo.mint_url, false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[CashuWallet] Failed to get npub.cash user info:', err);
|
||||
setNpubCashUserInfo(null);
|
||||
hasFetchedUserInfoRef.current = false; // Allow retry on error
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserInfo();
|
||||
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
|
||||
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, coco, setActiveMintUrl]);
|
||||
|
||||
// Ref to track if we've attempted restore/default mint logic
|
||||
const hasAttemptedRestoreRef = useRef(false);
|
||||
|
||||
// Restore previous mint or add default mint if no user info mint was set
|
||||
useEffect(() => {
|
||||
// Only run after wallet is initialized
|
||||
if (!isInitialized || !coco || hasAttemptedRestoreRef.current) return;
|
||||
|
||||
// If logged in, wait for user info check to complete
|
||||
if (isNpubCashLoggedIn && !hasFetchedUserInfoRef.current) return;
|
||||
|
||||
// If we already set a mint from user info, don't override it
|
||||
if (hasSetMintFromUserInfoRef.current) {
|
||||
hasAttemptedRestoreRef.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// If there's already an active mint, don't do anything
|
||||
if (activeMintUrl) {
|
||||
hasAttemptedRestoreRef.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as attempted to prevent multiple runs
|
||||
hasAttemptedRestoreRef.current = true;
|
||||
|
||||
const restoreOrAddDefaultMint = async () => {
|
||||
// First, try to restore from stored mint if it exists and is valid
|
||||
if (storedActiveMintUrl) {
|
||||
const allMints = await coco.mint.getAllMints();
|
||||
const storedMintExists = allMints.some(m => m.mintUrl.toLowerCase() === storedActiveMintUrl.toLowerCase());
|
||||
|
||||
if (storedMintExists) {
|
||||
const isTrusted = await coco.mint.isTrustedMint(storedActiveMintUrl);
|
||||
if (isTrusted) {
|
||||
console.log('[CashuWallet] Restoring previous mint:', storedActiveMintUrl);
|
||||
setActiveMintUrl(storedActiveMintUrl, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no stored mint to restore, check if we need to add default mint
|
||||
const trustedMints = await coco.mint.getAllTrustedMints();
|
||||
|
||||
// Only add default mint if no mints exist at all
|
||||
if (trustedMints.length === 0) {
|
||||
const defaultMintUrl = 'https://mint.minibits.cash/Bitcoin';
|
||||
console.log('[CashuWallet] No mints found, adding default mint:', defaultMintUrl);
|
||||
|
||||
try {
|
||||
await coco.mint.addMint(defaultMintUrl, { trusted: true });
|
||||
// Wait a bit for mint to be added, then set as active
|
||||
setTimeout(() => {
|
||||
setActiveMintUrl(defaultMintUrl, false);
|
||||
}, 500);
|
||||
} catch (err) {
|
||||
console.error('[CashuWallet] Failed to add default mint:', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
restoreOrAddDefaultMint();
|
||||
}, [isInitialized, coco, activeMintUrl, storedActiveMintUrl, setActiveMintUrl, isNpubCashLoggedIn]);
|
||||
|
||||
// Save active mint URL to localStorage when it changes
|
||||
useEffect(() => {
|
||||
// Save active mint URL to localStorage whenever it changes
|
||||
// This includes user info mint, restored mint, default mint, and manual selections
|
||||
if (activeMintUrl && storedActiveMintUrl !== activeMintUrl) {
|
||||
console.log('[CashuWallet] Saving active mint to localStorage:', activeMintUrl);
|
||||
setStoredActiveMintUrl(activeMintUrl);
|
||||
}
|
||||
}, [activeMintUrl, storedActiveMintUrl, setStoredActiveMintUrl]);
|
||||
|
||||
// Set up automatic quote sync subscription when logged into npub.cash
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { getCleanMintLabel } from './walletUtils';
|
||||
import type { Manager, Repositories } from 'coco-cashu-core';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
@@ -30,7 +30,6 @@ export function useMintManager({
|
||||
const [mintUrl, setMintUrl] = useState('');
|
||||
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
|
||||
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
|
||||
const isAddingDefaultMintRef = useRef(false);
|
||||
|
||||
// Set active mint and optionally sync to npub.cash
|
||||
const handleSetActiveMint = useCallback(
|
||||
@@ -205,44 +204,6 @@ export function useMintManager({
|
||||
[repositories]
|
||||
);
|
||||
|
||||
// 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 && !isAddingDefaultMintRef.current) {
|
||||
// Add default mint if no mints exist
|
||||
// Use ref guard to prevent multiple simultaneous additions
|
||||
isAddingDefaultMintRef.current = true;
|
||||
const addDefaultMint = async () => {
|
||||
try {
|
||||
const defaultMintUrl = 'https://mint.chorus.community';
|
||||
|
||||
// Check if mint already exists (check trusted mints since that's what we display)
|
||||
const trustedMints = await coco.mint.getAllTrustedMints();
|
||||
const mintExists = trustedMints.some((mint: { mintUrl: string }) =>
|
||||
mint.mintUrl.toLowerCase() === defaultMintUrl.toLowerCase()
|
||||
);
|
||||
|
||||
if (!mintExists) {
|
||||
// Add default mint and automatically trust it
|
||||
await coco.mint.addMint(defaultMintUrl, { trusted: true });
|
||||
// The mint will be added and refreshMints will be called via event listeners
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to add default mint:', err);
|
||||
} finally {
|
||||
// Reset the guard after a short delay to allow mints to update
|
||||
setTimeout(() => {
|
||||
isAddingDefaultMintRef.current = false;
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
addDefaultMint();
|
||||
}
|
||||
}, [mints, activeMintUrl, handleSetActiveMint, coco]);
|
||||
|
||||
return {
|
||||
activeMintUrl,
|
||||
setActiveMintUrl: handleSetActiveMint,
|
||||
|
||||
@@ -11,8 +11,8 @@ const NPUBCASH_BASE_URL = 'https://npubx.cash';
|
||||
export interface NpubCashUserInfo {
|
||||
pubkey: string;
|
||||
name?: string;
|
||||
mint_url: string;
|
||||
lock_quote: boolean;
|
||||
mintUrl: string; // API returns camelCase
|
||||
lockQuote: boolean; // API returns camelCase
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,14 +240,6 @@ export function useNpubCash() {
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user