Skip to content
Snippets Groups Projects
shared_prefs_helper.dart 7.57 KiB
import 'dart:convert';

import 'package:durt/durt.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:polkadart_keyring/polkadart_keyring.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'data/models/wallet.dart';
import 'data/models/wallet_themes.dart';
import 'g1/g1_helper.dart';
import 'ui/logger.dart';

class SharedPreferencesHelper with ChangeNotifier {
  factory SharedPreferencesHelper() {
    return _instance;
  }

  SharedPreferencesHelper._internal() {
    SharedPreferences.getInstance().then((SharedPreferences value) {
      _prefs = value;
      _migrateToSecureStorage();
    });
  }

  static const FlutterSecureStorage _secureStorage = FlutterSecureStorage();

  List<Wallet> wallets = <Wallet>[];
  Map<String, CesiumWallet> cesiumVolatileCards = <String, CesiumWallet>{};
  late SharedPreferences _prefs;

  static final SharedPreferencesHelper _instance =
  SharedPreferencesHelper._internal();

  // Legacy keys
  static const String _seedKey = 'seed';
  static const String _pubKey = 'pub';
  static const String _legacyAccountsKey = 'cesiumCards';
  static const String _legacyCurrentAccountIndex = 'current_wallet_index';

  // new keys
  static const String _accountsKey = 'duniter_accounts';
  static const String _currentAccountIndex = 'current_account_index';

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
    await _migrateToSecureStorage();

    // Load data from secure storage
    final String? json = await _secureStorage.read(key: _accountsKey);
    if (json != null) {
      final List<dynamic> list = jsonDecode(json) as List<dynamic>;
      wallets = list
          .map((dynamic e) => Wallet.fromJson(e as Map<String, dynamic>))
          .toList();
    }
  }

  Future<void> _migrateToSecureStorage() async {
    // Check if data is already in secure storage
    final bool isMigrated = await _secureStorage.containsKey(key: _accountsKey);

    if (!isMigrated) {
      // Migrate cesiumCards
      final String? json = _prefs.getString(_legacyAccountsKey);
      if (json != null) {
        await _secureStorage.write(key: _accountsKey, value: json);
      }

      // Migrate current wallet index