mirror of
https://github.com/purrgrammer/grimoire.git
synced 2026-04-09 23:16:50 +02:00
9e11fb590f75185ffa5f036d2de60940b24aea96
* feat: add donate CTA and supporter recognition system Adds donation call-to-action and visual recognition for Grimoire supporters who zap the project. **UserMenu Changes:** - Add "Support Grimoire ⚡" button that opens ZapWindow with preset donation address - Add monthly goal tracker with progress bar (currently showing placeholder values) - Integrate Lightning address (grimoire@coinos.io) and donation pubkey from members list **Supporter Tracking System:** - Create supporters service to monitor kind 9735 (zap receipt) events - Track users who zap Grimoire donation address - Cache supporter info (pubkey, total sats, zap count, last zap timestamp) in localStorage - Reactive updates via RxJS BehaviorSubject - Initialize tracking on app startup **Visual Flair for Supporters:** - Add useIsSupporter hook for checking supporter status - Style supporter usernames with yellow/gold color - Add filled ⚡ zap icon badge next to supporter names - Only applies to non-Grimoire members (members keep their existing gradient badges) **Implementation Details:** - Constants: GRIMOIRE_DONATE_PUBKEY and GRIMOIRE_LIGHTNING_ADDRESS in grimoire-members.ts - Service automatically processes zap receipts and persists supporter data - Monthly goal tracker uses placeholder values (42k/500k sats, 8.4% progress) - Future: Make goal dynamic by calculating from actual zap receipts Related to zap feature implementation in #141, #144, #145 * feat: migrate donation tracking to IndexedDB with monthly calculations Replaces in-memory Map + localStorage with proper Dexie database storage for accurate monthly donation tracking. **Database Changes (Version 17):** - Add `grimoireZaps` table to store individual zap receipts - Schema: eventId (PK), senderPubkey, amountSats, timestamp, comment - Indexes on senderPubkey and timestamp for efficient queries **Supporters Service:** - Store each zap receipt as separate DB record with full metadata - Track individual zap timestamps (not just latest per user) - Cache total and monthly donations for synchronous access - Refresh cache on new zaps for reactive UI updates **Monthly Calculations:** - `getMonthlyDonations()` - Last 30 days (rolling window) - `getCurrentMonthDonations()` - Current calendar month - Both use indexed DB queries for efficiency - Cached values updated on each new zap **UserMenu:** - Set monthly goal to 210M sats (2.1 BTC) - Dynamic progress calculation from actual zap data - Reactive updates when new donations arrive - Number formatting: 1M+ → "2.1M", 1k+ → "42k" **Benefits:** - Accurate historical tracking with timestamps - Efficient monthly queries using DB indexes - No data loss on localStorage quota issues - Foundation for supporter leaderboards and analytics * fix: properly await async zap processing in subscription Changes processZapReceipt calls from forEach to Promise.all to ensure async DB operations complete before processing next batch of events. Prevents race conditions where zaps might not be properly stored in DB if multiple events arrive simultaneously. * perf: optimize Dexie queries for donation tracking Replaces inefficient toArray() + reduce patterns with direct Dexie iteration APIs for better memory efficiency and performance. **Optimizations:** 1. **Supporter Count** - Use `uniqueKeys()` instead of loading all records - Before: Load all → create Set → get size - After: `orderBy('senderPubkey').uniqueKeys().length` - ~90% memory reduction for large datasets 2. **Aggregation Queries** - Use `.each()` iterator pattern - `getTotalDonationsAsync()` - Stream records, accumulate sum - `getMonthlyDonationsAsync()` - Indexed query + iteration - `getCurrentMonthDonations()` - Indexed query + iteration - `getSupporterInfo()` - Per-pubkey indexed query with iteration - `getAllSupporters()` - Stream all, group in Map, sort 3. **Cache Refresh** - Optimized `refreshSupporters()` - uniqueKeys for supporter set - Direct iteration for total/monthly sums - Single indexed query for monthly window **Monthly Goal:** - Update from 210M sats to 210k sats (0.0021 BTC) - More achievable target for initial launch **Benefits:** - Lower memory usage (no intermediate arrays) - Faster queries (direct iteration vs map/reduce) - Better scalability with growing zap history - Leverages Dexie's indexed cursors for efficiency * refactor: singleton supporters service with optimized Dexie queries Complete refactor of donation tracking to proper singleton pattern with relay-based subscriptions and zero in-memory caching. **Singleton Service Pattern:** - Class-based SupportersService matching relay-liveness/accounts patterns - Single `init()` method initializes subscriptions - Observable `supporters$` for reactive UI updates - Proper cleanup with `destroy()` method **Relay-Based Subscription:** - Fetch Grimoire's inbox relays via relayListCache - Subscribe to zaps using `#p` tag filter (NIP-57 recipient tag) - Use createTimelineLoader with proper relay hints - Fallback to aggregator relays if no inbox relays found - Dual subscription: loader + event store timeline for comprehensive coverage **Optimized Dexie Schema:** - Add compound index: `[senderPubkey+timestamp]` - Enables efficient per-user date range queries - Schema: `&eventId, senderPubkey, timestamp, [senderPubkey+timestamp]` **Zero In-Memory Caching:** - Remove cachedTotalDonations and cachedMonthlyDonations - All queries go directly to IndexedDB - Use Dexie iteration APIs (`.each()`, `.uniqueKeys()`) - Compound index queries for monthly aggregations **Premium Supporter Detection:** - New threshold: 2.1k sats/month = premium supporter - `isPremiumSupporter()` uses compound index query - `getMonthlySupporterInfo()` returns monthly stats per user **Badge Logic Updates:** - Premium supporters (2.1k+/month): Zap badge in username color - Regular supporters: Yellow text + yellow filled zap icon - useIsSupporter returns `{ isSupporter, isPremiumSupporter }` **UserMenu Updates:** - Use async `getMonthlyDonations()` with useState/useEffect - Subscribe to `supporters$` to trigger monthly recalculation - Remove synchronous function calls **Key Benefits:** - Proper singleton lifecycle management - Accurate relay selection for zap discovery - No memory overhead from caching - Efficient compound index queries - Scales to thousands of zaps without performance degradation * fix: fetch Grimoire relay list before subscribing to zaps Ensures kind 10002 relay list is loaded before subscribing to zap receipts, preventing fallback to aggregators only. **Problem:** At startup, relayListCache was empty, so getInboxRelays() returned null and service fell back to aggregator relays only, missing zaps published to Grimoire's actual inbox relays. **Solution:** 1. Explicitly fetch Grimoire's kind 10002 relay list using addressLoader 2. Wait up to 5 seconds for relay list to load 3. Then get inbox relays from populated cache 4. Subscribe to those relays + aggregators **Flow:** init() → subscribeToZapReceipts() → fetch kind 10002 (5s timeout) → getInboxRelays() from cache → subscribe to inbox relays + aggregators → keep subscription open for live updates Fixes startup zap loading issue. * feat: compact support section with manual refresh and full clickability Makes the entire support section clickable to open zap dialog and adds manual refresh button for donation stats. **Changes:** - Entire support section now clickable (opens zap dialog) - Add refresh button with spinning animation - Remove 'Help us build...' tagline for more compact design - Keep just title, stats, and progress bar - Manual refresh re-fetches Grimoire relay list and reloads zaps **Layout:** Click anywhere to donate, click refresh icon to manually sync zaps. * refactor: replace BehaviorSubject with Dexie useLiveQuery for reactive supporter tracking Replace manual BehaviorSubject pattern with Dexie's built-in useLiveQuery hook for reactive database queries. This simplifies the code and leverages Dexie's optimized change detection. Changes: - Remove BehaviorSubject from SupportersService - Remove refreshSupporters() method and all calls to it - Update useIsSupporter hook to use useLiveQuery for supporter pubkeys - Update GrimoireWelcome to use useLiveQuery for monthly donations - Update UserMenu to use useLiveQuery for monthly donations - Remove unused imports (cn, useEffect, useState) and fields (initialized) Benefits: - Less code to maintain (no manual observable management) - Automatic reactivity when DB changes - Better performance with Dexie's built-in change detection * fix: improve cold start zap loading and fix subscription memory leak Fixes several issues with zap loading on cold start: 1. Memory leak fix: Timeline subscription wasn't being stored or cleaned up - Now properly add timeline subscription to main subscription for cleanup 2. Better cold start handling: - Increase timeout from 5s to 10s for relay list fetching - Add 100ms delay after addressLoader to let relayListCache update - Add more detailed logging to debug cold start issues 3. Improved logging: - Show which relays are being used for subscription - Log when processing zap events from eventStore - Better error messages with context These changes should help diagnose why zaps aren't loading on cold start and prevent memory leaks from unclosed subscriptions. * feat: add hardcoded relay fallback for instant cold start zap loading Add hardcoded relays (wss://nos.lol, wss://lightning.red) to immediately start loading zaps on cold start, without waiting for relay list fetch. Changes: - Add GRIMOIRE_ZAP_RELAYS constant with hardcoded reliable relays - Refactor subscribeToZapReceipts() to start with hardcoded relays immediately - Move relay list fetching to separate non-blocking method fetchAndMergeRelayList() - Relay list fetch now happens in parallel with subscription (non-blocking) - Still fetch and log additional relays from kind 10002 in background This ensures zaps load immediately on app start rather than waiting for relay list to be fetched from network. * fix: remove dead relay.nostr.band and add detailed zap processing logs Remove relay.nostr.band from all relay lists as it's dead. Changes: - Remove from AGGREGATOR_RELAYS in loaders.ts - Remove from NIP-53 fallback relays - Update all test files to use alternative relays Add detailed logging to debug progress bar showing 0: - Log each zap processing step (validation, recipient check, sender check) - Log duplicate zaps, invalid zaps, and 0-sat zaps - Log existing zap count in DB on init - Add timestamps to successful zap recordings This will help diagnose why the progress bar shows 0 even though zaps are being fetched. * fix: reduce zap query limit from 1000 to 500 to avoid relay rejections Many relays reject REQ filters with limit > 500. This was likely causing the zap subscription to fail silently on some relays, resulting in no zaps being fetched and the progress bar showing 0. Reduced limit from 1000 to 500 to be compatible with more relays. * fix: remove lightning.red and aggregator relays, add monthly calculation debug logs Changes: - Remove wss://lightning.red from hardcoded relays (only use wss://nos.lol) - Remove aggregator relays from zap subscription (don't use for fetching zaps) - Remove AGGREGATOR_RELAYS import Add debug logging to diagnose progress bar issue: - GrimoireWelcome: Log count and total of zaps found in last 30 days - UserMenu: Log count and total of zaps found in last 30 days - Show cutoff date in GrimoireWelcome log This will help identify if: 1. Zaps are being stored in DB 2. Zaps are within the 30-day window 3. Monthly calculation is running and finding the zaps * fix: subscribe to eventStore.insert$ to catch zaps in real-time The previous approach using eventStore.timeline() was only emitting once with the initial state (0 events) and not re-emitting when new zaps were added to the store. Changed to subscribe to eventStore.insert$ which fires for every new event added to the store. This catches zaps as they arrive from relays in real-time. Changes: - Subscribe to eventStore.insert$ instead of eventStore.timeline() - Filter events for kind 9735 with #p tag matching Grimoire pubkey - Process each zap as it's inserted into the store - Add logging to show when zaps are received from insert$ stream This should fix the progress bar showing 0 even though zaps are being fetched from relays. * fix: also subscribe to eventStore.timeline() to process existing zaps The insert$ stream only fires for NEW events being added. If events were already in the eventStore (from cache or previous session), we wouldn't see them. Now subscribing to both: - insert$ - catches new events in real-time as they're added - timeline() - emits ALL matching events (existing + new) This ensures we process: 1. Zaps already in the eventStore from previous sessions 2. Zaps that loaded from relays before our subscription was active 3. New zaps arriving in real-time Added logging to distinguish between new (insert$) and all (timeline) events. * fix: subscribe directly to loader observable to process zaps as they arrive Complete rethink of the zap sync strategy. The issue was that we were subscribing to eventStore.timeline() and eventStore.insert$ which were not working as expected. The TimelineLoader returns Observable<NostrEvent> that emits individual events as they arrive from relays. We should subscribe directly to this. Changes: - Remove eventStore.timeline() and eventStore.insert$ subscriptions - Subscribe directly to loader().subscribe() with next/error/complete handlers - Process each event in the next() handler as it arrives from relays - Log each zap received from loader for debugging - Remove unused eventStore import This is the simplest and most direct approach - process events exactly as the loader emits them from the relays. * chore: merge main and remove debug logging for production Merged latest changes from main branch and removed all debug logging added during development to make the code production-ready. Changes: - Merged origin/main into branch - Removed console.log statements from supporters service init/subscribe - Removed debug logging from processZapReceipt method - Removed debug logging from fetchAndMergeRelayList method - Removed debug logging from GrimoireWelcome monthly calculation - Removed debug logging from UserMenu monthly calculation - Kept only error logging for production debugging The donation system is now production-ready with clean, minimal logging. * fix: remove yellow text color from regular supporters, keep only badge Regular supporters (who zapped but not 2.1k+/month) should only show the yellow zap badge next to their name, not have their username colored yellow. Changes: - Remove yellow text color (text-yellow-500) from regular supporters - Regular supporters now: normal username color + yellow zap badge - Premium supporters still: normal username color + badge in username color - Updated component documentation to reflect this change This provides cleaner visual hierarchy where only Grimoire team members get special username colors (gradient), while supporters are distinguished by their badge alone. --------- Co-authored-by: Claude <noreply@anthropic.com>
…
Grimoire
A Nostr protocol explorer and developer tool with a tiling window manager interface.
Features
- Tiling Windows - Each window is a Nostr "app" (profile viewer, event feed, NIP docs, etc.)
- Command Palette - Unix-style commands via
Cmd+Kto open apps and navigate - Multi-workspace - Virtual desktops with independent layouts
- Real-time - Reactive event subscriptions with automatic updates
Stack
React 19, TypeScript, Vite, TailwindCSS, Jotai, Dexie, Applesauce
Getting Started
npm install
npm run dev
Scripts
| Command | Description |
|---|---|
npm run dev |
Start dev server |
npm run build |
Build for production |
npm test |
Run tests in watch mode |
npm run lint |
Lint code |
npm run format |
Format code |
License
MIT
Languages
TypeScript
98.9%
CSS
0.8%
JavaScript
0.3%