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.nip55) {
      ndk.accounts.addAccount(
        pubkey: account.pubkey,
        type: AccountType.externalSigner,
        signer: Nip55EventSigner(
          publicKey: account.pubkey,
          // restore the signer app package captured at login (null for
          // legacy accounts -> Android routes through a compatible signer).
          nip55Signer: Nip55Signer(package: account.signerSeed),
        ),
      );
      continue;
    }

    if (account.kind == AccountKinds.bunker) {
      final signer = Nip46EventSigner(
        connection: BunkerConnection.fromJson(
          jsonDecode(account.signerSeed!),
        ),
        requests: ndk.requests,
        broadcast: ndk.broadcast,
        eventSignerFactory: ndk.config.eventSignerFactory,
        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: ndk.config.eventSignerFactory.create(
          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: ndk.config.eventSignerFactory.create(
          privateKey: account.signerSeed!,
          publicKey: pubkey,
        ),
      );
      continue;
    }
  }

  if (accounts.loggedAccount == null) return;
  if (!ndk.accounts.hasAccount(accounts.loggedAccount!)) return;
  try {
    ndk.accounts.switchAccount(pubkey: accounts.loggedAccount!);
  } catch (_) {
    // stored logged account could not be restored (e.g. stale/corrupted
    // state); ignore rather than crash app startup.
  }
}