Nostr WoT

Запросы и состояние реле

Руководство по интеграции и справочник API: Запросы и состояние реле.

Этот подробный справочник API поддерживается на английском языке и соответствует указанному коду SDK. Примеры с переменными приложения требуют ваших ключей, средства подписи, хранилища или интерфейса.

RelayPool

Wrap a compatible PoolLike transport with configured relay URLs, batching, subscriptions and connection status. RelayPool is not a drop-in SimplePool replacement; pass a SimplePool instance through pool or initialize one with ensurePool.

ts
import { SimplePool } from "nostr-tools";
import { RelayPool } from "nostr-wot-sdk/relay";

const pool = new RelayPool({
  urls: ["wss://relay.damus.io", "wss://nos.lol"],
  pool: new SimplePool(),
});
const subscription = pool.subscribe(
  { kinds: [1], limit: 50 },
  { onEvent: event => console.log(event.id) },
);
await pool.publish(signedEvent);
subscription.close();
pool.destroy();

query(filter) batches reads; queryImmediate(filter) flushes immediately. getUrls, setUrls, addRelay and removeRelay manage relay selection. getStatuses returns a map of connection booleans, and getConnectedCount counts connected relays. A subscription reports connected, eose or disconnected; close its returned handle on teardown. Calling subscribe before initializing the underlying pool throws.

QueryBatcher

Merge compatible reads over a supplied transport. The default debounce window is 100 ms; the default first-event timeout is 3000 ms and maximum subscription wait is 5000 ms. Supply options to the constructor's second argument.

ts
import { SimplePool } from "nostr-tools";
import { QueryBatcher } from "nostr-wot-sdk/relay";

const transport = new SimplePool();
const urls = ["wss://relay.damus.io"];
const batcher = new QueryBatcher(transport, { debounceMs: 100 });
const events = await batcher.query(urls, { kinds: [0], authors: [pubkey] });
batcher.destroy();
transport.close(urls);

Use queryImmediate when a user action should not wait for debounce. nostr-wot-sdk/data also exposes its higher-level shared subscription coalescer for applications using the social-data fetchers.

RelayStats

Track success counts, failures, average latency and backoff per relay. Persistence is optional and injected through init(adapter); there is no default localStorage persistence.

ts
import { RelayStats } from "nostr-wot-sdk/relay";

const stats = new RelayStats();
await stats.init();
stats.recordSuccess("wss://relay.damus.io", 142);
stats.recordFailure("wss://nos.lol");
const metrics = stats.getMetrics("wss://relay.damus.io");
const urls = stats.getPrioritizedUrls(["wss://relay.damus.io", "wss://nos.lol"]);
stats.destroy();

getAllMetrics reads all relay metrics, isBackedOff reports active backoff, and persist saves through the configured adapter. Destroy the tracker when its owner is disposed.

RelayManager

RelayManager is an abstract feed-lifecycle base class that composes a pool, batcher and statistics. Subclass it and implement getRelayUrls, persistRelayUrls, getTimeWindowSeconds and getLatestCachedTimestamp to connect application settings and caches. For a general-purpose relay client, use RelayPool directly.

React

tsx
import { SimplePool } from "nostr-tools";
import { RelayProvider, useRelayStatuses } from "nostr-wot-sdk/relay/react";

<RelayProvider urls={["wss://relay.damus.io"]} createPool={() => new SimplePool()}>
  <StatusBadge />
</RelayProvider>;

function StatusBadge() {
  const { connectedCount, statuses } = useRelayStatuses();
  return <span>{connectedCount}/{statuses.size} relays</span>;
}

useRelayPool returns the RelayPool instance, useQueryBatcher returns its batcher, and useRelayStats returns a tracker or null when statistics are disabled. These hooks require RelayProvider. Install React separately when using this entry point.

Справочник API