import type { Event, Filter } from 'nostr-tools' import { SimplePool } from 'nostr-tools' import { getPrimaryRelaySync } from './config' /** * Subscribe to events with timeout */ export function subscribeWithTimeout( pool: SimplePool, filters: Filter[], parser: (event: Event) => T | null, timeout: number = 5000 ): Promise { return new Promise((resolve) => { const resolved = { value: false } const relayUrl = getPrimaryRelaySync() const sub = pool.sub([relayUrl], filters) let timeoutId: NodeJS.Timeout | null = null const cleanup = () => { if (timeoutId) { clearTimeout(timeoutId) } sub.unsub() } const resolveOnce = (value: T | null) => { if (resolved.value) { return } resolved.value = true cleanup() resolve(value) } sub.on('event', (event: Event) => resolveOnce(parser(event))) sub.on('eose', () => resolveOnce(null)) timeoutId = setTimeout(() => resolveOnce(null), timeout) }) }