2025-06-02 21:44:52 -05:00
|
|
|
import React, { useEffect, useRef } from 'react';
|
2025-04-16 21:43:54 -05:00
|
|
|
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
|
|
|
|
import { NostrContext } from '@nostrify/react';
|
2025-06-02 21:44:52 -05:00
|
|
|
import { useQueryClient } from '@tanstack/react-query';
|
2025-06-04 10:04:39 -05:00
|
|
|
import { useAppConfig } from '@/hooks/useAppConfig';
|
2025-04-16 21:43:54 -05:00
|
|
|
|
|
|
|
interface NostrProviderProps {
|
|
|
|
children: React.ReactNode;
|
|
|
|
}
|
|
|
|
|
|
|
|
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
2025-06-02 21:44:52 -05:00
|
|
|
const { children } = props;
|
2025-06-04 10:04:39 -05:00
|
|
|
const { config } = useAppConfig();
|
2025-06-02 21:44:52 -05:00
|
|
|
|
|
|
|
const queryClient = useQueryClient();
|
2025-04-16 21:43:54 -05:00
|
|
|
|
|
|
|
// Create NPool instance only once
|
|
|
|
const pool = useRef<NPool | undefined>(undefined);
|
|
|
|
|
2025-06-02 21:44:52 -05:00
|
|
|
// Use refs so the pool always has the latest data
|
|
|
|
const relayUrl = useRef<string>(config.relayUrl);
|
|
|
|
|
|
|
|
// Update refs when config changes
|
|
|
|
useEffect(() => {
|
|
|
|
relayUrl.current = config.relayUrl;
|
|
|
|
queryClient.resetQueries();
|
2025-06-04 10:04:39 -05:00
|
|
|
}, [config.relayUrl, queryClient]);
|
2025-06-02 21:44:52 -05:00
|
|
|
|
|
|
|
// Initialize NPool only once
|
2025-04-16 21:43:54 -05:00
|
|
|
if (!pool.current) {
|
|
|
|
pool.current = new NPool({
|
|
|
|
open(url: string) {
|
|
|
|
return new NRelay1(url);
|
|
|
|
},
|
|
|
|
reqRouter(filters) {
|
2025-06-02 21:44:52 -05:00
|
|
|
return new Map([[relayUrl.current, filters]]);
|
2025-04-16 21:43:54 -05:00
|
|
|
},
|
|
|
|
eventRouter(_event: NostrEvent) {
|
2025-06-04 10:04:39 -05:00
|
|
|
return [relayUrl.current];
|
2025-04-16 21:43:54 -05:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<NostrContext.Provider value={{ nostr: pool.current }}>
|
|
|
|
{children}
|
|
|
|
</NostrContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default NostrProvider;
|