connectWithNostrConnect method

Future<BunkerConnection?> connectWithNostrConnect(
  1. NostrConnect nostrConnect, {
  2. dynamic authCallback(
    1. String
    )?,
})

Connects to a bunker using a nostr connect URL (nostrconnect://) authCallback is called with the auth URL if the bunker requires authentication

Implementation

Future<BunkerConnection?> connectWithNostrConnect(
  NostrConnect nostrConnect, {
  Function(String)? authCallback,
}) async {
  final relays = nostrConnect.relays;
  final secret = nostrConnect.secret;

  if (relays.isEmpty) {
    throw ArgumentError('At least one relay is required in bunker URL');
  }

  final keyPair = nostrConnect.keyPair;
  final localEventSigner = Bip340EventSigner(
    privateKey: keyPair.privateKey,
    publicKey: keyPair.publicKey,
  );

  final subscription = _requests.subscription(
    explicitRelays: relays,
    filters: [
      Filter(
        kinds: [BunkerRequest.kKind],
        pTags: [localEventSigner.publicKey],
        since: someTimeAgo(),
      ),
    ],
  );
  BunkerConnection? result;

  await for (final event in subscription.stream
      .timeout(Duration(seconds: kMaxWaitingTimeForConnectionSeconds))) {
    final decryptedContent = await localEventSigner.decryptNip44(
      ciphertext: event.content,
      senderPubKey: event.pubKey,
    );

    final response = jsonDecode(decryptedContent!);

    if (response["result"] == secret) {
      result = BunkerConnection(
        privateKey: localEventSigner.privateKey!,
        remotePubkey: event.pubKey,
        relays: relays,
      );
      break;
    }
  }
  await _requests.closeSubscription(subscription.requestId);
  return result;
}