stack_wallet/lib/wallets/isar/models/wallet_info.dart

512 lines
15 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'package:isar/isar.dart';
import 'package:uuid/uuid.dart';
import '../../../app_config.dart';
import '../../../models/balance.dart';
import '../../../models/isar/models/blockchain_data/address.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../isar_id_interface.dart';
import 'wallet_info_meta.dart';
part 'wallet_info.g.dart';
2023-09-18 21:28:31 +00:00
@Collection(accessor: "walletInfo", inheritance: false)
2023-11-01 19:00:36 +00:00
class WalletInfo implements IsarId {
@override
Id id = Isar.autoIncrement;
@Index(unique: true, replace: false)
final String walletId;
2024-01-15 15:42:49 +00:00
final String name;
@enumerated
final AddressType mainAddressType;
/// The highest index [mainAddressType] receiving address of the wallet
2024-01-15 15:42:49 +00:00
final String cachedReceivingAddress;
/// Only exposed for Isar. Use the [cachedBalance] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
2024-01-15 15:42:49 +00:00
final String? cachedBalanceString;
2023-11-16 23:26:41 +00:00
/// Only exposed for Isar. Use the [cachedBalanceSecondary] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
2024-01-15 15:42:49 +00:00
final String? cachedBalanceSecondaryString;
2023-11-16 23:26:41 +00:00
/// Only exposed for Isar. Use the [cachedBalanceTertiary] getter.
// Only exposed for isar as Amount cannot be stored in isar easily
2024-01-15 15:42:49 +00:00
final String? cachedBalanceTertiaryString;
2023-11-16 23:26:41 +00:00
/// Only exposed for Isar. Use the [coin] getter.
// Only exposed for isar to avoid dealing with storing enums as Coin can change
2024-01-15 15:42:49 +00:00
final String coinName;
/// User set favourites ordering. No restrictions are placed on uniqueness.
/// Reordering logic in the ui code should ensure this is unique.
2023-09-18 21:28:31 +00:00
///
/// Also represents if the wallet is a favourite. Any number greater then -1
/// denotes a favourite. Any number less than 0 means it is not a favourite.
2024-01-15 15:42:49 +00:00
final int favouriteOrderIndex;
/// The highest block height the wallet has scanned.
2024-01-15 15:42:49 +00:00
final int cachedChainHeight;
/// The block at which this wallet was or should be restored from
2024-01-15 15:42:49 +00:00
final int restoreHeight;
2024-01-15 15:42:49 +00:00
final String? otherDataJsonString;
//============================================================================
2023-09-18 21:28:31 +00:00
//=============== Getters ====================================================
bool get isFavourite => favouriteOrderIndex > -1;
2023-11-06 17:23:03 +00:00
List<String> get tokenContractAddresses {
if (otherData[WalletInfoKeys.tokenContractAddresses] is List) {
return List<String>.from(
otherData[WalletInfoKeys.tokenContractAddresses] as List,
);
} else {
return [];
}
}
2023-09-18 21:28:31 +00:00
2023-11-16 23:26:41 +00:00
/// Special case for coins such as firo lelantus
2023-09-18 21:28:31 +00:00
@ignore
2023-11-16 23:26:41 +00:00
Balance get cachedBalanceSecondary {
if (cachedBalanceSecondaryString == null) {
2024-05-15 21:20:45 +00:00
return Balance.zeroFor(currency: coin);
2023-11-16 23:26:41 +00:00
} else {
2024-05-15 21:20:45 +00:00
return Balance.fromJson(
2024-05-27 23:56:22 +00:00
cachedBalanceSecondaryString!,
coin.fractionDigits,
);
2023-11-16 23:26:41 +00:00
}
}
/// Special case for coins such as firo spark
@ignore
Balance get cachedBalanceTertiary {
if (cachedBalanceTertiaryString == null) {
2024-05-15 21:20:45 +00:00
return Balance.zeroFor(currency: coin);
2023-11-16 23:26:41 +00:00
} else {
2024-05-15 21:20:45 +00:00
return Balance.fromJson(
2024-05-27 23:56:22 +00:00
cachedBalanceTertiaryString!,
coin.fractionDigits,
);
2023-09-18 21:28:31 +00:00
}
}
@ignore
CryptoCurrency get coin => AppConfig.getCryptoCurrencyFor(coinName)!;
@ignore
Balance get cachedBalance {
if (cachedBalanceString == null) {
2024-05-15 21:20:45 +00:00
return Balance.zeroFor(currency: coin);
} else {
2024-05-15 21:20:45 +00:00
return Balance.fromJson(cachedBalanceString!, coin.fractionDigits);
}
}
2023-09-18 21:28:31 +00:00
@ignore
Map<String, dynamic> get otherData => otherDataJsonString == null
? {}
: Map<String, dynamic>.from(jsonDecode(otherDataJsonString!) as Map);
Future<bool> isMnemonicVerified(Isar isar) async =>
(await isar.walletInfoMeta.where().walletIdEqualTo(walletId).findFirst())
?.isMnemonicVerified ==
true;
//============================================================================
2023-11-16 23:26:41 +00:00
//============= Updaters ================================================
Future<void> updateBalance({
required Balance newBalance,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
2024-01-15 15:42:49 +00:00
if (thisInfo.cachedBalanceString != newEncoded) {
2023-11-16 23:26:41 +00:00
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
cachedBalanceString: newEncoded,
),
);
2023-11-16 23:26:41 +00:00
});
}
}
Future<void> updateBalanceSecondary({
required Balance newBalance,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
2023-11-16 23:26:41 +00:00
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
2024-01-15 15:42:49 +00:00
if (thisInfo.cachedBalanceSecondaryString != newEncoded) {
2023-11-16 23:26:41 +00:00
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
cachedBalanceSecondaryString: newEncoded,
),
);
2023-11-16 23:26:41 +00:00
});
}
}
Future<void> updateBalanceTertiary({
required Balance newBalance,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
2023-11-16 23:26:41 +00:00
final newEncoded = newBalance.toJsonIgnoreCoin();
// only update if there were changes to the balance
2024-01-15 15:42:49 +00:00
if (thisInfo.cachedBalanceTertiaryString != newEncoded) {
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
cachedBalanceTertiaryString: newEncoded,
),
);
});
}
}
/// copies this with a new chain height and updates the db
Future<void> updateCachedChainHeight({
required int newHeight,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the height
2024-01-15 15:42:49 +00:00
if (thisInfo.cachedChainHeight != newHeight) {
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
cachedChainHeight: newHeight,
),
);
});
}
}
2023-11-01 19:00:36 +00:00
/// update favourite wallet and its index it the ui list.
/// When [customIndexOverride] is not null the [flag] will be ignored.
Future<void> updateIsFavourite(
bool flag, {
required Isar isar,
int? customIndexOverride,
}) async {
final int index;
if (customIndexOverride != null) {
index = customIndexOverride;
} else if (flag) {
final highest = await isar.walletInfo
.where()
.sortByFavouriteOrderIndexDesc()
.favouriteOrderIndexProperty()
.findFirst();
index = (highest ?? 0) + 1;
2023-11-01 19:00:36 +00:00
} else {
index = -1;
}
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
2023-11-01 19:00:36 +00:00
// only update if there were changes to the height
2024-01-15 15:42:49 +00:00
if (thisInfo.favouriteOrderIndex != index) {
2023-11-01 19:00:36 +00:00
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
favouriteOrderIndex: index,
),
);
2023-11-01 19:00:36 +00:00
});
}
}
/// copies this with a new name and updates the db
Future<void> updateName({
required String newName,
required Isar isar,
}) async {
// don't allow empty names
if (newName.isEmpty) {
throw Exception("Empty wallet name not allowed!");
}
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
2023-11-01 19:00:36 +00:00
// only update if there were changes to the name
2024-01-15 15:42:49 +00:00
if (thisInfo.name != newName) {
2023-11-01 19:00:36 +00:00
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
name: newName,
),
);
2023-11-01 19:00:36 +00:00
});
}
}
/// copies this with a new name and updates the db
Future<void> updateReceivingAddress({
required String newAddress,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the name
2024-01-15 15:42:49 +00:00
if (thisInfo.cachedReceivingAddress != newAddress) {
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
cachedReceivingAddress: newAddress,
),
);
});
}
}
2023-11-15 21:59:01 +00:00
/// update [otherData] with the map entries in [newEntries]
Future<void> updateOtherData({
required Map<String, dynamic> newEntries,
required Isar isar,
}) async {
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
2023-11-15 21:59:01 +00:00
final Map<String, dynamic> newMap = {};
2024-01-15 15:42:49 +00:00
newMap.addAll(thisInfo.otherData);
2023-11-15 21:59:01 +00:00
newMap.addAll(newEntries);
final encodedNew = jsonEncode(newMap);
// only update if there were changes
2024-01-15 15:42:49 +00:00
if (thisInfo.otherDataJsonString != encodedNew) {
2023-11-15 21:59:01 +00:00
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
otherDataJsonString: encodedNew,
),
);
2023-11-15 21:59:01 +00:00
});
}
}
/// Can be dangerous. Don't use unless you know the consequences
Future<void> setMnemonicVerified({
required Isar isar,
}) async {
final meta =
await isar.walletInfoMeta.where().walletIdEqualTo(walletId).findFirst();
if (meta == null) {
await isar.writeTxn(() async {
await isar.walletInfoMeta.put(
WalletInfoMeta(
walletId: walletId,
isMnemonicVerified: true,
),
);
});
} else if (meta.isMnemonicVerified == false) {
await isar.writeTxn(() async {
await isar.walletInfoMeta.deleteByWalletId(walletId);
await isar.walletInfoMeta.put(
WalletInfoMeta(
walletId: walletId,
isMnemonicVerified: true,
),
);
});
} else {
throw Exception(
"setMnemonicVerified() called on already"
" verified wallet: $name, $walletId",
);
}
}
/// copies this with a new name and updates the db
Future<void> updateRestoreHeight({
required int newRestoreHeight,
required Isar isar,
}) async {
// don't allow empty names
if (newRestoreHeight < 0) {
throw Exception("Negative restore height not allowed!");
}
2024-01-15 15:42:49 +00:00
// try to get latest instance of this from db
final thisInfo = await isar.walletInfo.get(id) ?? this;
// only update if there were changes to the name
2024-01-15 15:42:49 +00:00
if (thisInfo.restoreHeight != newRestoreHeight) {
await isar.writeTxn(() async {
2024-01-15 15:42:49 +00:00
await isar.walletInfo.delete(thisInfo.id);
await isar.walletInfo.put(
thisInfo.copyWith(
restoreHeight: newRestoreHeight,
),
);
});
}
}
2024-01-10 16:08:12 +00:00
/// copies this with a new name and updates the db
Future<void> updateContractAddresses({
required Set<String> newContractAddresses,
required Isar isar,
}) async {
2024-01-11 17:19:23 +00:00
await updateOtherData(
newEntries: {
WalletInfoKeys.tokenContractAddresses: newContractAddresses.toList(),
},
isar: isar,
);
2024-01-10 16:08:12 +00:00
}
2023-09-18 21:28:31 +00:00
//============================================================================
WalletInfo({
required this.walletId,
2024-01-15 15:42:49 +00:00
required this.name,
required this.mainAddressType,
2024-01-15 15:42:49 +00:00
required this.coinName,
// cachedReceivingAddress should never actually be empty in practice as
// on wallet init it will be set
2024-01-15 15:42:49 +00:00
this.cachedReceivingAddress = "",
this.favouriteOrderIndex = -1,
this.cachedChainHeight = 0,
this.restoreHeight = 0,
this.cachedBalanceString,
this.cachedBalanceSecondaryString,
this.cachedBalanceTertiaryString,
this.otherDataJsonString,
}) : assert(
AppConfig.coins.map((e) => e.identifier).contains(coinName),
2024-01-15 15:42:49 +00:00
);
WalletInfo copyWith({
String? name,
AddressType? mainAddressType,
String? cachedReceivingAddress,
2023-11-15 15:15:17 +00:00
String? cachedBalanceString,
2023-11-16 23:32:47 +00:00
String? cachedBalanceSecondaryString,
String? cachedBalanceTertiaryString,
2024-01-15 15:42:49 +00:00
String? coinName,
int? favouriteOrderIndex,
int? cachedChainHeight,
int? restoreHeight,
2023-11-15 15:15:17 +00:00
String? otherDataJsonString,
2024-01-15 15:42:49 +00:00
}) {
return WalletInfo(
walletId: walletId,
name: name ?? this.name,
mainAddressType: mainAddressType ?? this.mainAddressType,
cachedReceivingAddress:
cachedReceivingAddress ?? this.cachedReceivingAddress,
cachedBalanceString: cachedBalanceString ?? this.cachedBalanceString,
cachedBalanceSecondaryString:
cachedBalanceSecondaryString ?? this.cachedBalanceSecondaryString,
cachedBalanceTertiaryString:
cachedBalanceTertiaryString ?? this.cachedBalanceTertiaryString,
coinName: coinName ?? this.coinName,
favouriteOrderIndex: favouriteOrderIndex ?? this.favouriteOrderIndex,
cachedChainHeight: cachedChainHeight ?? this.cachedChainHeight,
restoreHeight: restoreHeight ?? this.restoreHeight,
otherDataJsonString: otherDataJsonString ?? this.otherDataJsonString,
)..id = id;
}
static WalletInfo createNew({
2024-05-15 21:20:45 +00:00
required CryptoCurrency coin,
required String name,
int restoreHeight = 0,
String? walletIdOverride,
String? otherDataJsonString,
}) {
return WalletInfo(
2024-05-15 21:20:45 +00:00
coinName: coin.identifier,
walletId: walletIdOverride ?? const Uuid().v1(),
name: name,
2023-11-14 15:57:48 +00:00
mainAddressType: coin.primaryAddressType,
restoreHeight: restoreHeight,
otherDataJsonString: otherDataJsonString,
);
}
@Deprecated("Legacy support")
2023-11-09 22:27:17 +00:00
factory WalletInfo.fromJson(
Map<String, dynamic> jsonObject,
AddressType mainAddressType,
) {
final coin = AppConfig.getCryptoCurrencyFor(
2024-05-15 21:20:45 +00:00
jsonObject["coin"] as String,
)!;
return WalletInfo(
2024-05-15 21:20:45 +00:00
coinName: coin.identifier,
walletId: jsonObject["id"] as String,
name: jsonObject["name"] as String,
mainAddressType: mainAddressType,
);
}
@Deprecated("Legacy support")
Map<String, String> toMap() {
return {
"name": name,
"id": walletId,
2024-05-15 21:20:45 +00:00
"coin": coin.identifier,
};
}
@Deprecated("Legacy support")
String toJsonString() {
return jsonEncode(toMap());
}
@override
String toString() {
return "WalletInfo: ${toJsonString()}";
}
}
2023-09-18 21:28:31 +00:00
abstract class WalletInfoKeys {
static const String tokenContractAddresses = "tokenContractAddressesKey";
static const String epiccashData = "epiccashDataKey";
2023-11-15 21:59:01 +00:00
static const String bananoMonkeyImageBytes = "monkeyImageBytesKey";
static const String tezosDerivationPath = "tezosDerivationPathKey";
2024-01-15 15:42:49 +00:00
static const String lelantusCoinIsarRescanRequired =
"lelantusCoinIsarRescanRequired";
static const String enableLelantusScanning = "enableLelantusScanningKey";
2023-09-18 21:28:31 +00:00
}