2023-01-12 18:46:01 +00:00
|
|
|
import 'package:isar/isar.dart';
|
|
|
|
import 'package:stackwallet/models/isar/models/isar_models.dart';
|
|
|
|
import 'package:stackwallet/utilities/stack_file_system.dart';
|
2023-01-13 21:36:19 +00:00
|
|
|
import 'package:tuple/tuple.dart';
|
2023-01-12 18:46:01 +00:00
|
|
|
|
|
|
|
mixin WalletDB {
|
|
|
|
Isar? _isar;
|
|
|
|
|
|
|
|
Isar get isar => _isar!;
|
|
|
|
|
|
|
|
/// open the db if it was not already open
|
|
|
|
/// returns true if the db was not yet open
|
|
|
|
/// returns false if the db was already open
|
|
|
|
Future<bool> isarInit(String walletId) async {
|
|
|
|
if (_isar != null && isar.isOpen) return false;
|
|
|
|
_isar = await Isar.open(
|
|
|
|
[
|
|
|
|
TransactionSchema,
|
|
|
|
TransactionNoteSchema,
|
|
|
|
InputSchema,
|
|
|
|
OutputSchema,
|
|
|
|
UTXOSchema,
|
|
|
|
AddressSchema,
|
|
|
|
],
|
|
|
|
directory: (await StackFileSystem.applicationIsarDirectory()).path,
|
2023-01-13 17:11:41 +00:00
|
|
|
inspector: true,
|
2023-01-12 18:46:01 +00:00
|
|
|
name: walletId,
|
|
|
|
);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> isarClose() async => await _isar?.close() ?? false;
|
2023-01-13 21:36:19 +00:00
|
|
|
|
|
|
|
Future<void> addNewTransactionData(
|
|
|
|
List<Tuple4<Transaction, List<Output>, List<Input>, Address?>>
|
|
|
|
transactionsData) async {
|
|
|
|
await isar.writeTxn(() async {
|
|
|
|
for (final data in transactionsData) {
|
|
|
|
final tx = data.item1;
|
|
|
|
|
|
|
|
// save transaction
|
|
|
|
await isar.transactions.put(tx);
|
|
|
|
|
|
|
|
// link and save outputs
|
|
|
|
if (data.item2.isNotEmpty) {
|
|
|
|
await isar.outputs.putAll(data.item2);
|
|
|
|
tx.outputs.addAll(data.item2);
|
|
|
|
await tx.outputs.save();
|
|
|
|
}
|
|
|
|
|
|
|
|
// link and save inputs
|
|
|
|
if (data.item3.isNotEmpty) {
|
|
|
|
await isar.inputs.putAll(data.item3);
|
|
|
|
tx.inputs.addAll(data.item3);
|
|
|
|
await tx.inputs.save();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (data.item4 != null) {
|
2023-01-13 22:11:34 +00:00
|
|
|
final address = await isar.addresses
|
|
|
|
.where()
|
|
|
|
.valueEqualTo(data.item4!.value)
|
|
|
|
.findFirst();
|
|
|
|
|
2023-01-13 21:36:19 +00:00
|
|
|
// check if address exists in db and add if it does not
|
2023-01-13 22:11:34 +00:00
|
|
|
if (address == null) {
|
2023-01-13 21:36:19 +00:00
|
|
|
await isar.addresses.put(data.item4!);
|
|
|
|
}
|
2023-01-13 22:11:34 +00:00
|
|
|
|
2023-01-13 21:36:19 +00:00
|
|
|
// link and save address
|
2023-01-13 22:11:34 +00:00
|
|
|
tx.address.value = address ?? data.item4!;
|
2023-01-13 21:36:19 +00:00
|
|
|
await tx.address.save();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2023-01-12 18:46:01 +00:00
|
|
|
}
|