saveAccountsState method

Future<void> saveAccountsState()

Implementation

Future<void> saveAccountsState() async {
  final accounts = NostrWidgetsAccounts(accounts: []);

  for (var account in ndk.accounts.accounts.values) {
    if (account.signer is Nip07EventSigner) {
      accounts.accounts.add(
        NostrAccount(kind: AccountKinds.nip07, pubkey: account.pubkey),
      );
      continue;
    }

    if (account.signer is Nip55EventSigner) {
      // `signerSeed` holds the signer app package (Amber, Primal, ...) so
      // silent signing keeps working after restart.
      final signer = account.signer as Nip55EventSigner;
      accounts.accounts.add(
        NostrAccount(
          kind: AccountKinds.nip55,
          pubkey: account.pubkey,
          signerSeed: signer.nip55Signer.package,
        ),
      );
      continue;
    }

    if (account.signer is Nip46EventSigner) {
      final signer = account.signer as Nip46EventSigner;
      accounts.accounts.add(
        NostrAccount(
          kind: AccountKinds.bunker,
          pubkey: account.pubkey,
          signerSeed: jsonEncode(signer.connection),
        ),
      );
      continue;
    }

    if (account.type == AccountType.privateKey) {
      final privateKey = (account.signer as dynamic).privateKey as String?;
      if (privateKey == null) continue;
      accounts.accounts.add(
        NostrAccount(
          kind: AccountKinds.privkey,
          pubkey: account.pubkey,
          signerSeed: privateKey,
        ),
      );
      continue;
    }

    if (account.type == AccountType.publicKey) {
      accounts.accounts.add(
        NostrAccount(kind: AccountKinds.pubkey, pubkey: account.pubkey),
      );
      continue;
    }
  }

  accounts.loggedAccount = ndk.accounts.getPublicKey();

  final storage = FlutterSecureStorage();
  await storage.write(key: accountsKey, value: jsonEncode(accounts));
}