cake_wallet/cw_nano/lib/nano_transaction_history.dart

74 lines
2.4 KiB
Dart
Raw Normal View History

2023-07-27 17:02:10 +00:00
import 'dart:convert';
2023-07-24 20:23:09 +00:00
import 'dart:core';
2023-07-27 17:02:10 +00:00
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_nano/file.dart';
import 'package:flutter/material.dart';
2023-07-24 20:23:09 +00:00
import 'package:mobx/mobx.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_nano/nano_transaction_info.dart';
part 'nano_transaction_history.g.dart';
2023-07-27 17:02:10 +00:00
const transactionsHistoryFileName = 'transactions.json';
2023-07-24 20:23:09 +00:00
2023-07-27 17:02:10 +00:00
class NanoTransactionHistory = NanoTransactionHistoryBase with _$NanoTransactionHistory;
2023-07-24 20:23:09 +00:00
abstract class NanoTransactionHistoryBase
extends TransactionHistoryBase<NanoTransactionInfo> with Store {
2023-07-27 17:02:10 +00:00
NanoTransactionHistoryBase({required this.walletInfo, required String password})
: _password = password {
2023-07-24 20:23:09 +00:00
transactions = ObservableMap<String, NanoTransactionInfo>();
}
2023-07-27 17:02:10 +00:00
final WalletInfo walletInfo;
String _password;
Future<void> init() async => await _load();
2023-07-24 20:23:09 +00:00
@override
2023-07-27 17:02:10 +00:00
Future<void> save() async {
try {
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
final path = '$dirPath/$transactionsHistoryFileName';
final data = json.encode({'transactions': transactions});
await writeData(path: path, password: _password, data: data);
} catch (e) {
print('Error while save nano transaction history: ${e.toString()}');
}
}
2023-07-24 20:23:09 +00:00
@override
2023-07-27 17:02:10 +00:00
void addOne(NanoTransactionInfo transaction) => transactions[transaction.id] = transaction;
2023-07-24 20:23:09 +00:00
@override
2023-07-25 15:21:49 +00:00
void addMany(Map<String, NanoTransactionInfo> transactions) =>
2023-07-24 20:23:09 +00:00
this.transactions.addAll(transactions);
2023-07-27 17:02:10 +00:00
Future<Map<String, dynamic>> _read() async {
final dirPath = await pathForWalletDir(name: walletInfo.name, type: walletInfo.type);
final path = '$dirPath/$transactionsHistoryFileName';
final content = await read(path: path, password: _password);
return json.decode(content) as Map<String, dynamic>;
}
Future<void> _load() async {
try {
final content = await _read();
final txs = content['transactions'] as Map<String, dynamic>? ?? {};
txs.entries.forEach((entry) {
final val = entry.value;
if (val is Map<String, dynamic>) {
final tx = NanoTransactionInfo.fromJson(val);
_update(tx);
}
});
} catch (e) {
print(e);
}
}
void _update(NanoTransactionInfo transaction) => transactions[transaction.id] = transaction;
2023-07-24 20:23:09 +00:00
}