restoreAccountsState method

Future<void> restoreAccountsState()

Implementation

Future<void> restoreAccountsState() async {
  final storage = FlutterSecureStorage();

  final storedAccounts = await storage.read(key: accountsKey);

  if (storedAccounts == null) return;

  final accounts = NostrWidgetsAccounts.fromJson(jsonDecode(storedAccounts));

  for (var account in accounts.accounts) {
    if (account.kind == AccountKinds.nip07) {
      final signer = Nip07EventSigner(cachedPublicKey: account.pubkey);
      ndk.accounts.addAccount(
        pubkey: account.pubkey,
        type: AccountType.externalSigner,
        signer: signer,
      );
      continue;
    }

    if (account.kind == AccountKinds.amber) {
      final amber = Amberflutter();
      final amberFlutterDS = AmberFlutterDS(amber);

      ndk.accounts.addAccount(
        pubkey: account.pubkey,
        type: AccountType.externalSigner,
        signer: AmberEventSigner(
          publicKey: account.pubkey,
          amberFlutterDS: amberFlutterDS,
        ),
      );
      continue;
    }

    if (account.kind == AccountKinds.bunker) {
      final signer = Nip46EventSigner(
        connection: BunkerConnection.fromJson(
          jsonDecode(account.signerSeed!),
        ),
        requests: ndk.requests,
        broadcast: ndk.broadcast,
        cachedPublicKey: account.pubkey,
      );
      ndk.accounts.addAccount(
        pubkey: account.pubkey,
        type: AccountType.externalSigner,
        signer: signer,
      );
      continue;
    }

    if (account.kind == AccountKinds.pubkey) {
      ndk.accounts.addAccount(
        pubkey: account.pubkey,
        type: AccountType.publicKey,
        signer: Bip340EventSigner(
          privateKey: null,
          publicKey: account.pubkey,
        ),
      );
      continue;
    }

    if (account.kind == AccountKinds.privkey) {
      final pubkey = Bip340.getPublicKey(account.signerSeed!);
      ndk.accounts.addAccount(
        pubkey: pubkey,
        type: AccountType.privateKey,
        signer: Bip340EventSigner(
          privateKey: account.signerSeed!,
          publicKey: pubkey,
        ),
      );
      continue;
    }
  }

  if (accounts.loggedAccount == null) return;
  if (!ndk.accounts.hasAccount(accounts.loggedAccount!)) return;
  ndk.accounts.switchAccount(pubkey: accounts.loggedAccount!);
}