#2 Reduce console noise: strip debug logs from relay queries, publish, trust score, weather, coaches, NostrSync

Co-authored-by: shakespeare.diy <assistant@shakespeare.diy>
This commit is contained in:
shakespeare.diy 2026-08-27 10:17:01 +07:00
parent 2fa85c2bce
commit 3fd82f2425
8 changed files with 6 additions and 75 deletions

View file

@ -79,8 +79,6 @@ export function NostrSync() {
}, [user?.pubkey]); }, [user?.pubkey]);
async function doSync(pubkey: string, attempt = 1) { async function doSync(pubkey: string, attempt = 1) {
console.log(`[NostrSync] Starting sync for ${pubkey.slice(0, 8)}... attempt ${attempt}`);
// Always invalidate stale cache first so useAuthor refetches // Always invalidate stale cache first so useAuthor refetches
queryClient.invalidateQueries({ queryKey: ['author', pubkey] }); queryClient.invalidateQueries({ queryKey: ['author', pubkey] });
queryClient.removeQueries({ queryKey: ['author', pubkey] }); queryClient.removeQueries({ queryKey: ['author', pubkey] });
@ -99,7 +97,6 @@ export function NostrSync() {
const event = events[0]; const event = events[0];
try { try {
const metadata = n.json().pipe(n.metadata()).parse(event.content); const metadata = n.json().pipe(n.metadata()).parse(event.content);
console.log(`[NostrSync] Got profile: ${metadata.name ?? 'unnamed'}`);
// Populate useAuthor cache // Populate useAuthor cache
queryClient.setQueryData(['author', pubkey], { metadata, event }); queryClient.setQueryData(['author', pubkey], { metadata, event });
// Populate useLoggedInAccounts cache // Populate useLoggedInAccounts cache
@ -141,7 +138,6 @@ export function NostrSync() {
write: !marker || marker === 'write', write: !marker || marker === 'write',
})); }));
if (fetchedRelays.length > 0) { if (fetchedRelays.length > 0) {
console.log(`[NostrSync] Got ${fetchedRelays.length} relays from NIP-65`);
updateConfig(c => ({ updateConfig(c => ({
...c, ...c,
relayMetadata: { relays: fetchedRelays, updatedAt: event.created_at }, relayMetadata: { relays: fetchedRelays, updatedAt: event.created_at },
@ -170,7 +166,6 @@ export function NostrSync() {
// ── 1. Citrine (local relay — fastest, no internet needed) ─────────────── // ── 1. Citrine (local relay — fastest, no internet needed) ───────────────
const citrineAvailable = await isCitrineAvailable(); const citrineAvailable = await isCitrineAvailable();
if (citrineAvailable) { if (citrineAvailable) {
console.log('[NostrSync] Citrine available — querying local relay');
const g = nostr.group([CITRINE_URL]); const g = nostr.group([CITRINE_URL]);
const [r, p] = await Promise.all([fetchRelays(g), fetchProfile(g)]); const [r, p] = await Promise.all([fetchRelays(g), fetchProfile(g)]);
relaysSynced = r; relaysSynced = r;
@ -179,7 +174,6 @@ export function NostrSync() {
// ── 2. Bootstrap relays (always-on aggregators) ────────────────────────── // ── 2. Bootstrap relays (always-on aggregators) ──────────────────────────
if (!profileSynced || !relaysSynced) { if (!profileSynced || !relaysSynced) {
console.log('[NostrSync] Trying bootstrap relays...');
const g = nostr.group(BOOTSTRAP_RELAYS); const g = nostr.group(BOOTSTRAP_RELAYS);
const [r, p] = await Promise.all([ const [r, p] = await Promise.all([
relaysSynced ? Promise.resolve(true) : fetchRelays(g), relaysSynced ? Promise.resolve(true) : fetchRelays(g),
@ -191,7 +185,6 @@ export function NostrSync() {
// ── 3. Main relay pool ─────────────────────────────────────────────────── // ── 3. Main relay pool ───────────────────────────────────────────────────
if (!profileSynced || !relaysSynced) { if (!profileSynced || !relaysSynced) {
console.log('[NostrSync] Trying main relay pool...');
const [r, p] = await Promise.all([ const [r, p] = await Promise.all([
relaysSynced ? Promise.resolve(true) : fetchRelays(nostr), relaysSynced ? Promise.resolve(true) : fetchRelays(nostr),
profileSynced ? Promise.resolve(true) : fetchProfile(nostr), profileSynced ? Promise.resolve(true) : fetchProfile(nostr),
@ -201,7 +194,6 @@ export function NostrSync() {
} }
const success = profileSynced && relaysSynced; const success = profileSynced && relaysSynced;
console.log(`[NostrSync] Done — profile:${profileSynced} relays:${relaysSynced}`);
if (success) { if (success) {
syncState.current.set(pubkey, true); syncState.current.set(pubkey, true);
@ -214,11 +206,10 @@ export function NostrSync() {
retryTimers.current.set(pubkey, t); retryTimers.current.set(pubkey, t);
} else { } else {
syncState.current.set(pubkey, false); syncState.current.set(pubkey, false);
console.error('[NostrSync] All attempts failed for', pubkey.slice(0, 8));
// Don't show error toast if profile simply doesn't exist yet — // Don't show error toast if profile simply doesn't exist yet —
// it's a new account, not a connection error // it's a new account, not a connection error
if (!profileSynced) { if (!profileSynced) {
console.log('[NostrSync] No profile found — may be a new account'); // New account — no profile published yet, nothing to sync.
} else { } else {
toast({ toast({
title: 'Could not load profile', title: 'Could not load profile',

View file

@ -873,7 +873,6 @@ export function SpotMap({
// Add moveend handler for BTC Map updates // Add moveend handler for BTC Map updates
map.on('moveend', () => { map.on('moveend', () => {
const center = map.getCenter(); const center = map.getCenter();
console.log('[SpotMap] Map moved to:', center.lat, center.lng);
onMapMoveRef.current?.({ lat: center.lat, lon: center.lng }); onMapMoveRef.current?.({ lat: center.lat, lon: center.lng });
}); });
@ -923,10 +922,8 @@ export function SpotMap({
map.invalidateSize(); map.invalidateSize();
// Force a redraw to ensure everything is ready // Force a redraw to ensure everything is ready
map.whenReady(() => { map.whenReady(() => {
console.log('[SpotMap] Map is ready');
// Trigger initial map move event // Trigger initial map move event
const center = map.getCenter(); const center = map.getCenter();
console.log('[SpotMap] Initial center:', center.lat, center.lng);
onMapMoveRef.current?.({ lat: center.lat, lon: center.lng }); onMapMoveRef.current?.({ lat: center.lat, lon: center.lng });
}); });
}, 100); }, 100);
@ -1019,8 +1016,6 @@ export function SpotMap({
// Ensure we have location data before adding markers // Ensure we have location data before adding markers
if (locationGroups.length === 0) return; if (locationGroups.length === 0) return;
console.log('[SpotMap] Adding', locationGroups.length, 'markers to map');
// Add new markers for each location group // Add new markers for each location group
locationGroups.forEach((group) => { locationGroups.forEach((group) => {
const hasSpots = group.spots.length > 0; const hasSpots = group.spots.length > 0;
@ -1146,8 +1141,6 @@ export function SpotMap({
// Add tour markers (separate from spot/shop markers) // Add tour markers (separate from spot/shop markers)
if (showTours && tours.length > 0) { if (showTours && tours.length > 0) {
console.log('[SpotMap] Adding', tours.length, 'tour markers');
tours.forEach((tour) => { tours.forEach((tour) => {
// Use meeting point coords if available, otherwise decode geohash // Use meeting point coords if available, otherwise decode geohash
let lat: number, lng: number; let lat: number, lng: number;
@ -1439,8 +1432,6 @@ export function SpotMap({
// Don't add markers if BTC Map is disabled // Don't add markers if BTC Map is disabled
if (!showBtcMap || btcMapPlaces.length === 0) return; if (!showBtcMap || btcMapPlaces.length === 0) return;
console.log('[SpotMap] Adding', btcMapPlaces.length, 'BTC Map markers');
btcMapPlaces.forEach((place) => { btcMapPlaces.forEach((place) => {
const boosted = isBoosted(place.boosted_until); const boosted = isBoosted(place.boosted_until);
const recentlyVerified = isRecentlyVerified(place.verified_at); const recentlyVerified = isRecentlyVerified(place.verified_at);

View file

@ -13,8 +13,6 @@ export function useCoaches(limit = 100) {
queryFn: async () => { queryFn: async () => {
const signal = AbortSignal.timeout(10000); const signal = AbortSignal.timeout(10000);
console.log('[useCoaches] Querying for coaches...');
const events = await querySkateContent( const events = await querySkateContent(
[ [
{ {
@ -26,16 +24,12 @@ export function useCoaches(limit = 100) {
{ signal } { signal }
); );
console.log(`[useCoaches] Received ${events.length} events`);
const coaches: SkateCoach[] = []; const coaches: SkateCoach[] = [];
for (const event of events) { for (const event of events) {
const coach = parseSkateCoach(event); const coach = parseSkateCoach(event);
if (coach) coaches.push(coach); if (coach) coaches.push(coach);
} }
console.log(`[useCoaches] Parsed coaches: ${coaches.length}`);
return coaches.sort((a, b) => b.createdAt - a.createdAt); return coaches.sort((a, b) => b.createdAt - a.createdAt);
}, },
staleTime: 30000, staleTime: 30000,
@ -69,14 +63,9 @@ export function useCoach(identifier: string, pubkey?: string) {
if (pubkey) filter.authors = [pubkey]; if (pubkey) filter.authors = [pubkey];
console.log(`[useCoach] Querying for coach: ${identifier}`);
const events = await querySkateContent([filter], { signal }); const events = await querySkateContent([filter], { signal });
console.log(`[useCoach] Received ${events.length} events`);
if (events.length === 0) { if (events.length === 0) {
console.warn(`[useCoach] No events found for identifier: ${identifier}`);
return null; return null;
} }
@ -96,8 +85,6 @@ export function useUserCoachProfile(pubkey: string) {
queryFn: async () => { queryFn: async () => {
const signal = AbortSignal.timeout(10000); const signal = AbortSignal.timeout(10000);
console.log(`[useUserCoachProfile] Querying for coach profile: ${pubkey}`);
const events = await querySkateContent( const events = await querySkateContent(
[ [
{ {
@ -110,10 +97,7 @@ export function useUserCoachProfile(pubkey: string) {
{ signal } { signal }
); );
console.log(`[useUserCoachProfile] Received ${events.length} events`);
if (events.length === 0) { if (events.length === 0) {
console.warn(`[useUserCoachProfile] No coach profile found for pubkey: ${pubkey}`);
return null; return null;
} }

View file

@ -18,8 +18,6 @@ export function useNostrPublish(): UseMutationResult<NostrEvent> {
throw new Error("You must be logged in to publish events"); throw new Error("You must be logged in to publish events");
} }
console.log('[useNostrPublish] Starting publish for kind:', t.kind);
const tags = t.tags ?? []; const tags = t.tags ?? [];
// Add the client tag if it doesn't exist // Add the client tag if it doesn't exist
@ -27,31 +25,22 @@ export function useNostrPublish(): UseMutationResult<NostrEvent> {
tags.push(["client", location.hostname]); tags.push(["client", location.hostname]);
} }
console.log('[useNostrPublish] Tags prepared:', tags.length, 'tags');
// Sign the event // Sign the event
console.log('[useNostrPublish] Signing event...');
const event = await user.signer.signEvent({ const event = await user.signer.signEvent({
kind: t.kind, kind: t.kind,
content: t.content ?? "", content: t.content ?? "",
tags, tags,
created_at: t.created_at ?? Math.floor(Date.now() / 1000), created_at: t.created_at ?? Math.floor(Date.now() / 1000),
}); });
console.log('[useNostrPublish] Event signed successfully:', event.id);
// Publish with retry logic // Publish with retry logic
console.log('[useNostrPublish] Publishing to relays...');
await publishEventWithRetry(nostr, event); await publishEventWithRetry(nostr, event);
console.log('[useNostrPublish] Publish complete!');
return event; return event;
}, },
onError: (error) => { onError: (error) => {
console.error("Failed to publish event:", error); console.error("Failed to publish event:", error);
}, },
onSuccess: (data) => {
console.log("Event published successfully:", data);
},
}); });
} }
@ -75,8 +64,6 @@ async function publishEventWithRetry(
try { try {
// Attempt to publish // Attempt to publish
await nostr.event(event, { signal: controller.signal }); await nostr.event(event, { signal: controller.signal });
console.log(`Event published successfully (attempt ${attempt + 1}/${maxRetries + 1})`);
return; // Success! return; // Success!
} finally { } finally {
@ -85,12 +72,10 @@ async function publishEventWithRetry(
} catch (error) { } catch (error) {
lastError = error instanceof Error ? error : new Error(String(error)); lastError = error instanceof Error ? error : new Error(String(error));
console.warn(`Publish attempt ${attempt + 1} failed:`, lastError.message);
// If this isn't the last attempt, wait before retrying // If this isn't the last attempt, wait before retrying
if (attempt < maxRetries) { if (attempt < maxRetries) {
const backoffMs = 1000 * Math.pow(2, attempt); const backoffMs = 1000 * Math.pow(2, attempt);
console.log(`Retrying in ${backoffMs}ms...`);
await new Promise(resolve => setTimeout(resolve, backoffMs)); await new Promise(resolve => setTimeout(resolve, backoffMs));
} }
} }

View file

@ -79,17 +79,15 @@ export function useSkateRelays() {
): Promise<NostrEvent[]> => { ): Promise<NostrEvent[]> => {
const relays = getReadRelays(); const relays = getReadRelays();
console.log(`[useSkateRelays] Querying ${relays.length} relay(s):`, relays); // Query all relays in parallel. Individual relay failures/timeouts are
// expected (some relays are slow or offline) and handled silently — the
// Query all relays in parallel // other relays still return results.
const queryPromises = relays.map(async (relayUrl) => { const queryPromises = relays.map(async (relayUrl) => {
try { try {
const relay = nostr.relay(relayUrl); const relay = nostr.relay(relayUrl);
const events = await relay.query(filters, options); const events = await relay.query(filters, options);
console.log(`[useSkateRelays] ${relayUrl} returned ${events.length} events`);
return events; return events;
} catch (error) { } catch {
console.warn(`[useSkateRelays] Failed to query ${relayUrl}:`, error);
return []; return [];
} }
}); });
@ -115,7 +113,6 @@ export function useSkateRelays() {
} }
const uniqueEvents = Array.from(eventMap.values()); const uniqueEvents = Array.from(eventMap.values());
console.log(`[useSkateRelays] Total unique events: ${uniqueEvents.length}`);
return uniqueEvents; return uniqueEvents;
}; };

View file

@ -59,8 +59,6 @@ export function useMultipleSpotWeather(geohashes: string[], enabled: boolean = t
return useQuery({ return useQuery({
queryKey: ['multiple-spot-weather', geohashes.sort().join(',')], queryKey: ['multiple-spot-weather', geohashes.sort().join(',')],
queryFn: async () => { queryFn: async () => {
console.log('[useMultipleSpotWeather] Fetching weather for geohashes:', geohashes);
// Deduplicate geohashes to avoid fetching the same location multiple times // Deduplicate geohashes to avoid fetching the same location multiple times
const uniqueGeohashes = [...new Set(geohashes)]; const uniqueGeohashes = [...new Set(geohashes)];
@ -100,7 +98,6 @@ export function useMultipleSpotWeather(geohashes: string[], enabled: boolean = t
} }
}); });
console.log('[useMultipleSpotWeather] Weather data fetched for', weatherMap.size, 'locations');
return weatherMap; return weatherMap;
}, },
enabled: enabled && geohashes.length > 0, enabled: enabled && geohashes.length > 0,

View file

@ -42,7 +42,6 @@ export function useTrustScore(targetPubkey: string | undefined) {
const followList = followListEvents[0]; const followList = followListEvents[0];
if (!followList) { if (!followList) {
console.warn('[useTrustScore] No follow list found for source pubkey');
return 0; return 0;
} }
@ -55,7 +54,6 @@ export function useTrustScore(targetPubkey: string | undefined) {
// Direct follow = 90 // Direct follow = 90
if (following.has(targetPubkey)) { if (following.has(targetPubkey)) {
console.log(`[useTrustScore] ${targetPubkey.slice(0, 8)} is directly followed: 90`);
return 90; return 90;
} }
@ -71,7 +69,6 @@ export function useTrustScore(targetPubkey: string | undefined) {
.map(([, pubkey]) => pubkey); .map(([, pubkey]) => pubkey);
if (friendFollowing.includes(targetPubkey)) { if (friendFollowing.includes(targetPubkey)) {
console.log(`[useTrustScore] ${targetPubkey.slice(0, 8)} is friend-of-friend: 60`);
return 60; return 60;
} }
} }
@ -86,16 +83,14 @@ export function useTrustScore(targetPubkey: string | undefined) {
try { try {
const metadata = JSON.parse(profileEvents[0].content); const metadata = JSON.parse(profileEvents[0].content);
if (metadata.nip05) { if (metadata.nip05) {
console.log(`[useTrustScore] ${targetPubkey.slice(0, 8)} has NIP-05: 30`);
return 30; return 30;
} }
} catch (e) { } catch {
// Ignore JSON parse errors // Ignore JSON parse errors
} }
} }
// No trust signals found // No trust signals found
console.log(`[useTrustScore] ${targetPubkey.slice(0, 8)} has no trust signals: 0`);
return 0; return 0;
} catch (error) { } catch (error) {
console.warn('[useTrustScore] Error calculating trust score:', error); console.warn('[useTrustScore] Error calculating trust score:', error);

View file

@ -727,13 +727,6 @@ export default function MapPage() {
enabled: showBtcMap, enabled: showBtcMap,
}); });
// Debug logging for BTC Map
useEffect(() => {
if (showBtcMap) {
console.log('[MapPage] BTC Map enabled, center:', mapCenter, 'loading:', btcMapLoading, 'places:', btcMapPlaces?.length, 'error:', btcMapError);
}
}, [showBtcMap, mapCenter, btcMapLoading, btcMapPlaces, btcMapError]);
const isLoading = spotsLoading || shopsLoading || marketplaceLoading || toursLoading; const isLoading = spotsLoading || shopsLoading || marketplaceLoading || toursLoading;
// Get user's location for proximity sorting // Get user's location for proximity sorting
@ -789,8 +782,6 @@ export default function MapPage() {
.filter(spot => !spot.isShop && spot.geohash) .filter(spot => !spot.isShop && spot.geohash)
.map(spot => spot.geohash); .map(spot => spot.geohash);
console.log('[MapPage] Spot geohashes:', geohashes);
console.log('[MapPage] Weather enabled:', weatherEnabled);
return geohashes; return geohashes;
}, [allLocations]); }, [allLocations]);