Skip to content

RelayPool

Manages connections to multiple Nostr relays, deduplicating connections and aggregating subscriptions.

Import

ts
import { RelayPool } from 'nostr-core'

Constructor

ts
new RelayPool(opts?: {
  websocketImplementation?: typeof WebSocket
  maxWaitForConnection?: number
})
ParameterTypeDefaultDescription
opts.websocketImplementationtypeof WebSocket?-Custom WebSocket class
opts.maxWaitForConnectionnumber?3000Default connection timeout in ms

Methods

ensureRelay

ts
await pool.ensureRelay(url: string, opts?: {
  connectionTimeout?: number
}): Promise<Relay>

Gets an existing relay connection or creates a new one. Sets publishTimeout to 5 seconds on new relays.

ParameterTypeDescription
urlstringRelay URL
opts.connectionTimeoutnumber?Override connection timeout

Returns: Relay

subscribe

ts
pool.subscribe(
  relayUrls: string[],
  filter: Filter,
  params: PoolSubscribeParams
): SubCloser

Subscribes to the same filter across multiple relays.

ParameterTypeDescription
relayUrlsstring[]Relay URLs to subscribe on
filterFilterEvent filter
paramsPoolSubscribeParamsCallbacks and options

The oneose callback fires only when all relays have sent EOSE.

Returns: SubCloser - object with a close(reason?: string) method.

publish

ts
await pool.publish(relayUrls: string[], event: NostrEvent): Promise<string[]>

Publishes an event to multiple relays. Failed publishes are silently dropped.

ParameterTypeDescription
relayUrlsstring[]Relay URLs to publish to
eventNostrEventSigned event

Returns: string[] - array of successful relay responses.

querySync

ts
await pool.querySync(
  relayUrls: string[],
  filter: Filter,
  params?: { maxWait?: number }
): Promise<NostrEvent[]>

Queries multiple relays and returns all matching events once EOSE is received from all relays.

ParameterTypeDescription
relayUrlsstring[]Relay URLs
filterFilterEvent filter
params.maxWaitnumber?Connection timeout

Returns: NostrEvent[]

listConnectionStatus

ts
pool.listConnectionStatus(): Map<string, boolean>

Returns: Map<string, boolean> - relay URL to connected status.

close

ts
pool.close(relayUrls?: string[]): void

Closes specified relay connections, or all connections if no URLs provided.

Types

SubCloser

ts
type SubCloser = {
  close: (reason?: string) => void
}

PoolSubscribeParams

ts
type PoolSubscribeParams = SubscriptionParams & {
  maxWait?: number
  id?: string
  label?: string
}
FieldTypeDescription
onevent(evt: NostrEvent) => voidCalled for each event
oneose() => voidCalled when all relays finish
onclose(reason: string) => voidCalled on subscription close
eoseTimeoutnumber?EOSE timeout per relay
maxWaitnumber?Connection timeout
idstring?Custom subscription ID
labelstring?Label for the subscription

Released under the MIT License.