sendEventToRelaysAsync method

  1. @override
Future<NostrEventOkCommand> sendEventToRelaysAsync(
  1. NostrEvent event, {
  2. required Duration timeout,
  3. List<String>? relays,
})
override

This method is responsible for sending an event to all relays that you did registered with the init method, and gets you a Future of NostrEventOkCommand that will be triggered when the event is accepted by the relays.

Implementation

@override
Future<NostrEventOkCommand> sendEventToRelaysAsync(
  NostrEvent event, {
  required Duration timeout,
  List<String>? relays,
}) async {
  await _registerNewRelays(relays ?? relaysList!);

  var isSomeOkTriggered = false;

  final completers = <Completer<NostrEventOkCommand>>[];

  _runFunctionOverRelationIteration((relay) {
    final relayUrl = relay.url;

    if (relays?.containsRelay(relayUrl) ?? true) {
      final completer = Completer<NostrEventOkCommand>();
      completers.add(completer);

      Future.delayed(timeout, () {
        if (!isSomeOkTriggered) {
          throw TimeoutException(
            'the event with id: ${event.id} has timed out after: ${timeout.inSeconds} seconds',
          );
        }
      });

      final serialized = event.serialized();

      if (event.id == null) {
        throw Exception('event id cannot be null');
      }

      _registerOnOklCallBack(
        associatedEventId: event.id!,
        relay: relayUrl,
        onOk: (relay, ok) {
          isSomeOkTriggered = true;
          completer.complete(ok);
        },
      );

      relay.socket.sink.add(serialized);
      utils.log(
        'event with id: ${event.id} is sent to relay with url: $relayUrl',
      );
    }
  });

  return Future.any(completers.map((e) => e.future));
}