2022-08-26 08:11:35 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:io';
|
2022-12-28 16:25:55 +00:00
|
|
|
import 'dart:math';
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
import 'package:cw_core/monero_transaction_priority.dart';
|
|
|
|
import 'package:cw_core/node.dart';
|
|
|
|
import 'package:cw_core/pending_transaction.dart';
|
2022-08-27 16:06:04 +00:00
|
|
|
import 'package:cw_core/sync_status.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:cw_core/transaction_direction.dart';
|
|
|
|
import 'package:cw_core/wallet_base.dart';
|
|
|
|
import 'package:cw_core/wallet_credentials.dart';
|
|
|
|
import 'package:cw_core/wallet_info.dart';
|
|
|
|
import 'package:cw_core/wallet_service.dart';
|
|
|
|
import 'package:cw_core/wallet_type.dart';
|
|
|
|
import 'package:cw_monero/api/exceptions/creation_transaction_exception.dart';
|
|
|
|
import 'package:cw_monero/monero_wallet.dart';
|
|
|
|
import 'package:cw_monero/pending_monero_transaction.dart';
|
|
|
|
import 'package:decimal/decimal.dart';
|
2022-12-28 16:25:55 +00:00
|
|
|
import 'package:flutter/cupertino.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:flutter_libmonero/core/key_service.dart';
|
|
|
|
import 'package:flutter_libmonero/core/wallet_creation_service.dart';
|
|
|
|
import 'package:flutter_libmonero/monero/monero.dart';
|
|
|
|
import 'package:flutter_libmonero/view_model/send/output.dart' as monero_output;
|
2023-01-12 03:09:08 +00:00
|
|
|
import 'package:isar/isar.dart';
|
2022-08-27 16:06:04 +00:00
|
|
|
import 'package:mutex/mutex.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:stackwallet/hive/db.dart';
|
2023-01-12 03:09:08 +00:00
|
|
|
import 'package:stackwallet/models/balance.dart';
|
|
|
|
import 'package:stackwallet/models/isar/models/isar_models.dart' as isar_models;
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:stackwallet/models/node_model.dart';
|
|
|
|
import 'package:stackwallet/models/paymint/fee_object_model.dart';
|
|
|
|
import 'package:stackwallet/services/coins/coin_service.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/blocks_remaining_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/updated_in_background_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart';
|
|
|
|
import 'package:stackwallet/services/event_bus/global_event_bus.dart';
|
2023-01-12 18:46:01 +00:00
|
|
|
import 'package:stackwallet/services/mixins/wallet_cache.dart';
|
|
|
|
import 'package:stackwallet/services/mixins/wallet_db.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:stackwallet/services/node_service.dart';
|
|
|
|
import 'package:stackwallet/utilities/constants.dart';
|
|
|
|
import 'package:stackwallet/utilities/default_nodes.dart';
|
|
|
|
import 'package:stackwallet/utilities/enums/coin_enum.dart';
|
|
|
|
import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart';
|
|
|
|
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
|
2022-11-23 18:31:31 +00:00
|
|
|
import 'package:stackwallet/utilities/format.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
import 'package:stackwallet/utilities/logger.dart';
|
|
|
|
import 'package:stackwallet/utilities/prefs.dart';
|
2022-11-12 22:04:16 +00:00
|
|
|
import 'package:stackwallet/utilities/stack_file_system.dart';
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
const int MINIMUM_CONFIRMATIONS = 10;
|
|
|
|
|
2023-01-12 18:46:01 +00:00
|
|
|
class MoneroWallet extends CoinServiceAPI with WalletCache, WalletDB {
|
2022-12-28 16:25:55 +00:00
|
|
|
final String _walletId;
|
|
|
|
final Coin _coin;
|
|
|
|
final SecureStorageInterface _secureStorage;
|
|
|
|
final Prefs _prefs;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
String _walletName;
|
|
|
|
bool _shouldAutoSync = false;
|
|
|
|
bool _isConnected = false;
|
|
|
|
bool _hasCalledExit = false;
|
|
|
|
bool refreshMutex = false;
|
|
|
|
bool longMutex = false;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
WalletService? walletService;
|
|
|
|
KeyService? keysStorage;
|
|
|
|
MoneroWalletBase? walletBase;
|
|
|
|
WalletCreationService? _walletCreationService;
|
|
|
|
Timer? _autoSaveTimer;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
Future<isar_models.Address?> get _currentReceivingAddress =>
|
|
|
|
isar.addresses.where().sortByDerivationIndexDesc().findFirst();
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<FeeObject>? _feeObject;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Mutex prepareSendMutex = Mutex();
|
|
|
|
Mutex estimateFeeMutex = Mutex();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
MoneroWallet({
|
|
|
|
required String walletId,
|
|
|
|
required String walletName,
|
|
|
|
required Coin coin,
|
|
|
|
required SecureStorageInterface secureStorage,
|
|
|
|
Prefs? prefs,
|
|
|
|
}) : _walletId = walletId,
|
|
|
|
_walletName = walletName,
|
|
|
|
_coin = coin,
|
|
|
|
_secureStorage = secureStorage,
|
|
|
|
_prefs = prefs ?? Prefs.instance;
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool get isFavorite {
|
|
|
|
try {
|
|
|
|
return DB.instance.get<dynamic>(boxName: walletId, key: "isFavorite")
|
|
|
|
as bool;
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"isFavorite fetch failed (returning false by default): $e\n$s",
|
|
|
|
level: LogLevel.Error);
|
|
|
|
return false;
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
set isFavorite(bool markFavorite) {
|
|
|
|
DB.instance.put<dynamic>(
|
|
|
|
boxName: walletId, key: "isFavorite", value: markFavorite);
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
bool get shouldAutoSync => _shouldAutoSync;
|
|
|
|
|
|
|
|
@override
|
|
|
|
set shouldAutoSync(bool shouldAutoSync) {
|
|
|
|
if (_shouldAutoSync != shouldAutoSync) {
|
|
|
|
_shouldAutoSync = shouldAutoSync;
|
2022-12-28 16:25:55 +00:00
|
|
|
// xmr wallets cannot be open at the same time
|
|
|
|
// leave following commented out for now
|
|
|
|
|
|
|
|
// if (!shouldAutoSync) {
|
|
|
|
// timer?.cancel();
|
|
|
|
// moneroAutosaveTimer?.cancel();
|
|
|
|
// timer = null;
|
|
|
|
// moneroAutosaveTimer = null;
|
|
|
|
// stopNetworkAlivePinging();
|
|
|
|
// } else {
|
|
|
|
// startNetworkAlivePinging();
|
|
|
|
// // Walletbase needs to be open for this to work
|
|
|
|
// refresh();
|
|
|
|
// }
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
String get walletName => _walletName;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// setter for updating on rename
|
|
|
|
@override
|
|
|
|
set walletName(String newName) => _walletName = newName;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
Coin get coin => _coin;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<String> confirmSend({required Map<String, dynamic> txData}) async {
|
2022-08-28 12:00:30 +00:00
|
|
|
try {
|
2022-12-28 16:25:55 +00:00
|
|
|
Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info);
|
|
|
|
final pendingMoneroTransaction =
|
|
|
|
txData['pendingMoneroTransaction'] as PendingMoneroTransaction;
|
|
|
|
try {
|
|
|
|
await pendingMoneroTransaction.commit();
|
|
|
|
Logging.instance.log(
|
|
|
|
"transaction ${pendingMoneroTransaction.id} has been sent",
|
|
|
|
level: LogLevel.Info);
|
|
|
|
return pendingMoneroTransaction.id;
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log("$walletName monero confirmSend: $e\n$s",
|
|
|
|
level: LogLevel.Error);
|
|
|
|
rethrow;
|
2022-08-28 12:00:30 +00:00
|
|
|
}
|
|
|
|
} catch (e, s) {
|
2022-12-28 16:25:55 +00:00
|
|
|
Logging.instance.log("Exception rethrown from confirmSend(): $e\n$s",
|
|
|
|
level: LogLevel.Info);
|
|
|
|
rethrow;
|
2022-08-28 12:00:30 +00:00
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
2022-08-27 16:06:04 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
2023-01-12 03:09:08 +00:00
|
|
|
Future<String> get currentReceivingAddress async =>
|
|
|
|
(await _currentReceivingAddress)!.value;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<int> estimateFeeFor(int satoshiAmount, int feeRate) async {
|
|
|
|
MoneroTransactionPriority priority;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
switch (feeRate) {
|
|
|
|
case 1:
|
|
|
|
priority = MoneroTransactionPriority.regular;
|
|
|
|
break;
|
|
|
|
case 2:
|
|
|
|
priority = MoneroTransactionPriority.medium;
|
|
|
|
break;
|
|
|
|
case 3:
|
|
|
|
priority = MoneroTransactionPriority.fast;
|
|
|
|
break;
|
|
|
|
case 4:
|
|
|
|
priority = MoneroTransactionPriority.fastest;
|
|
|
|
break;
|
|
|
|
case 0:
|
|
|
|
default:
|
|
|
|
priority = MoneroTransactionPriority.slow;
|
|
|
|
break;
|
2022-08-28 12:00:30 +00:00
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final fee = walletBase!.calculateEstimatedFee(priority, satoshiAmount);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
return fee;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<void> exit() async {
|
|
|
|
if (!_hasCalledExit) {
|
|
|
|
walletBase?.onNewBlock = null;
|
|
|
|
walletBase?.onNewTransaction = null;
|
|
|
|
walletBase?.syncStatusChanged = null;
|
|
|
|
_hasCalledExit = true;
|
|
|
|
_autoSaveTimer?.cancel();
|
|
|
|
await walletBase?.save(prioritySave: true);
|
|
|
|
walletBase?.close();
|
2023-01-12 18:46:01 +00:00
|
|
|
await isarClose();
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<FeeObject> get fees => _feeObject ??= _getFees();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<void> fullRescan(
|
|
|
|
int maxUnusedAddressGap,
|
|
|
|
int maxNumberOfIndexesToCheck,
|
|
|
|
) async {
|
|
|
|
var restoreHeight = walletBase?.walletInfo.restoreHeight;
|
|
|
|
highestPercentCached = 0;
|
|
|
|
await walletBase?.rescan(height: restoreHeight);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<bool> generateNewAddress() async {
|
2022-08-26 08:11:35 +00:00
|
|
|
try {
|
2023-01-12 03:09:08 +00:00
|
|
|
final currentReceiving = await _currentReceivingAddress;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
final newReceivingIndex = currentReceiving!.derivationIndex + 1;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
// Use new index to derive a new receiving address
|
|
|
|
final newReceivingAddress = await _generateAddressForChain(
|
|
|
|
0,
|
|
|
|
newReceivingIndex,
|
|
|
|
);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
// Add that new receiving address
|
|
|
|
await isar.writeTxn(() async {
|
|
|
|
await isar.addresses.put(newReceivingAddress);
|
|
|
|
});
|
2022-12-28 16:25:55 +00:00
|
|
|
|
|
|
|
return true;
|
2022-08-26 08:11:35 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2022-12-28 16:25:55 +00:00
|
|
|
"Exception rethrown from generateNewAddress(): $e\n$s",
|
2022-08-26 08:11:35 +00:00
|
|
|
level: LogLevel.Error);
|
2022-12-28 16:25:55 +00:00
|
|
|
return false;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
bool get hasCalledExit => _hasCalledExit;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<void> initializeExisting() async {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Opening existing ${coin.prettyName} wallet $walletName...",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if ((DB.instance.get<dynamic>(boxName: walletId, key: "id")) == null) {
|
|
|
|
throw Exception(
|
|
|
|
"Attempted to initialize an existing wallet using an unknown wallet ID!");
|
2022-08-27 16:06:04 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
walletService =
|
|
|
|
monero.createMoneroWalletService(DB.instance.moneroWalletInfoBox);
|
|
|
|
keysStorage = KeyService(_secureStorage);
|
2022-08-27 16:06:04 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
await _prefs.init();
|
2023-01-12 18:46:01 +00:00
|
|
|
await isarInit(walletId);
|
2022-12-28 16:25:55 +00:00
|
|
|
// final data =
|
|
|
|
// DB.instance.get<dynamic>(boxName: walletId, key: "latest_tx_model")
|
|
|
|
// as TransactionData?;
|
|
|
|
// if (data != null) {
|
|
|
|
// _transactionData = Future(() => data);
|
|
|
|
// }
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
String password;
|
|
|
|
try {
|
|
|
|
password = await keysStorage!.getWalletPassword(walletName: _walletId);
|
|
|
|
} catch (_) {
|
|
|
|
throw Exception("Monero password not found for $walletName");
|
|
|
|
}
|
|
|
|
walletBase = (await walletService!.openWallet(_walletId, password))
|
|
|
|
as MoneroWalletBase;
|
|
|
|
// walletBase!.onNewBlock = onNewBlock;
|
|
|
|
// walletBase!.onNewTransaction = onNewTransaction;
|
|
|
|
// walletBase!.syncStatusChanged = syncStatusChanged;
|
|
|
|
Logging.instance.log(
|
|
|
|
"Opened existing ${coin.prettyName} wallet $walletName",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
// Wallet already exists, triggers for a returning user
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
// String indexKey = "receivingIndex";
|
|
|
|
// final curIndex =
|
|
|
|
// await DB.instance.get<dynamic>(boxName: walletId, key: indexKey) as int;
|
|
|
|
// // Use new index to derive a new receiving address
|
|
|
|
// final newReceivingAddress = await _generateAddressForChain(0, curIndex);
|
|
|
|
// Logging.instance.log("xmr address in init existing: $newReceivingAddress",
|
|
|
|
// level: LogLevel.Info);
|
|
|
|
// _currentReceivingAddress = Future(() => newReceivingAddress);
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<void> initializeNew() async {
|
|
|
|
await _prefs.init();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
// this should never fail
|
2022-12-28 16:25:55 +00:00
|
|
|
if ((await _secureStorage.read(key: '${_walletId}_mnemonic')) != null) {
|
2022-08-26 08:11:35 +00:00
|
|
|
throw Exception(
|
|
|
|
"Attempted to overwrite mnemonic on generate new wallet!");
|
|
|
|
}
|
|
|
|
|
|
|
|
walletService =
|
|
|
|
monero.createMoneroWalletService(DB.instance.moneroWalletInfoBox);
|
2022-12-28 16:25:55 +00:00
|
|
|
keysStorage = KeyService(_secureStorage);
|
2022-08-26 08:11:35 +00:00
|
|
|
WalletInfo walletInfo;
|
|
|
|
WalletCredentials credentials;
|
|
|
|
try {
|
|
|
|
String name = _walletId;
|
|
|
|
final dirPath =
|
2022-12-28 16:25:55 +00:00
|
|
|
await _pathForWalletDir(name: name, type: WalletType.monero);
|
|
|
|
final path = await _pathForWallet(name: name, type: WalletType.monero);
|
2022-08-26 08:11:35 +00:00
|
|
|
credentials = monero.createMoneroNewWalletCredentials(
|
|
|
|
name: name,
|
|
|
|
language: "English",
|
|
|
|
);
|
|
|
|
|
|
|
|
// subtract a couple days to ensure we have a buffer for SWB
|
|
|
|
final bufferedCreateHeight = monero.getHeigthByDate(
|
|
|
|
date: DateTime.now().subtract(const Duration(days: 2)));
|
|
|
|
|
|
|
|
await DB.instance.put<dynamic>(
|
|
|
|
boxName: walletId, key: "restoreHeight", value: bufferedCreateHeight);
|
|
|
|
|
|
|
|
walletInfo = WalletInfo.external(
|
|
|
|
id: WalletBase.idFor(name, WalletType.monero),
|
|
|
|
name: name,
|
|
|
|
type: WalletType.monero,
|
|
|
|
isRecovery: false,
|
2022-11-09 06:16:21 +00:00
|
|
|
restoreHeight: bufferedCreateHeight,
|
2022-08-26 08:11:35 +00:00
|
|
|
date: DateTime.now(),
|
|
|
|
path: path,
|
|
|
|
dirPath: dirPath,
|
|
|
|
// TODO: find out what to put for address
|
|
|
|
address: '');
|
|
|
|
credentials.walletInfo = walletInfo;
|
|
|
|
|
|
|
|
_walletCreationService = WalletCreationService(
|
2022-12-28 16:25:55 +00:00
|
|
|
secureStorage: _secureStorage,
|
2022-08-26 08:11:35 +00:00
|
|
|
walletService: walletService,
|
|
|
|
keyService: keysStorage,
|
|
|
|
);
|
|
|
|
_walletCreationService?.changeWalletType();
|
|
|
|
// To restore from a seed
|
|
|
|
final wallet = await _walletCreationService?.create(credentials);
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
await _secureStorage.write(
|
2022-08-26 08:11:35 +00:00
|
|
|
key: '${_walletId}_mnemonic', value: wallet?.seed.trim());
|
|
|
|
walletInfo.address = wallet?.walletAddresses.address;
|
|
|
|
await DB.instance
|
|
|
|
.add<WalletInfo>(boxName: WalletInfo.boxName, value: walletInfo);
|
|
|
|
walletBase?.close();
|
|
|
|
walletBase = wallet as MoneroWalletBase;
|
2022-12-28 16:25:55 +00:00
|
|
|
// walletBase!.onNewBlock = onNewBlock;
|
|
|
|
// walletBase!.onNewTransaction = onNewTransaction;
|
|
|
|
// walletBase!.syncStatusChanged = syncStatusChanged;
|
2022-08-26 08:11:35 +00:00
|
|
|
} catch (e, s) {
|
2022-12-13 00:17:02 +00:00
|
|
|
//todo: come back to this
|
2022-12-28 16:25:55 +00:00
|
|
|
debugPrint("some nice searchable string thing");
|
2022-08-26 08:11:35 +00:00
|
|
|
debugPrint(e.toString());
|
|
|
|
debugPrint(s.toString());
|
2022-12-28 16:25:55 +00:00
|
|
|
walletBase?.close();
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
final node = await _getCurrentNode();
|
2022-08-26 08:11:35 +00:00
|
|
|
final host = Uri.parse(node.host).host;
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase!.connectToNode(
|
2022-08-26 08:11:35 +00:00
|
|
|
node: Node(uri: "$host:${node.port}", type: WalletType.monero));
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase!.startSync();
|
2022-08-26 08:11:35 +00:00
|
|
|
await DB.instance
|
|
|
|
.put<dynamic>(boxName: walletId, key: "id", value: _walletId);
|
|
|
|
|
|
|
|
await DB.instance
|
|
|
|
.put<dynamic>(boxName: walletId, key: "isFavorite", value: false);
|
|
|
|
|
|
|
|
// Generate and add addresses to relevant arrays
|
|
|
|
final initialReceivingAddress = await _generateAddressForChain(0, 0);
|
|
|
|
// final initialChangeAddress = await _generateAddressForChain(1, 0);
|
2023-01-12 18:46:01 +00:00
|
|
|
await isarInit(walletId);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
await isar.writeTxn(() async {
|
|
|
|
await isar.addresses.put(initialReceivingAddress);
|
|
|
|
});
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
walletBase?.close();
|
|
|
|
Logging.instance
|
|
|
|
.log("initializeNew for $walletName $walletId", level: LogLevel.Info);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
bool get isConnected => _isConnected;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
bool get isRefreshing => refreshMutex;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
// not used in xmr
|
|
|
|
Future<int> get maxFee => throw UnimplementedError();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
Future<List<String>> get mnemonic async {
|
|
|
|
final mnemonicString =
|
|
|
|
await _secureStorage.read(key: '${_walletId}_mnemonic');
|
|
|
|
if (mnemonicString == null) {
|
|
|
|
return [];
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
final List<String> data = mnemonicString.split(' ');
|
|
|
|
return data;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<Map<String, dynamic>> prepareSend({
|
|
|
|
required String address,
|
|
|
|
required int satoshiAmount,
|
|
|
|
Map<String, dynamic>? args,
|
|
|
|
}) async {
|
|
|
|
String toAddress = address;
|
|
|
|
try {
|
|
|
|
final feeRate = args?["feeRate"];
|
|
|
|
if (feeRate is FeeRateType) {
|
|
|
|
MoneroTransactionPriority feePriority;
|
|
|
|
switch (feeRate) {
|
|
|
|
case FeeRateType.fast:
|
|
|
|
feePriority = MoneroTransactionPriority.fast;
|
|
|
|
break;
|
|
|
|
case FeeRateType.average:
|
|
|
|
feePriority = MoneroTransactionPriority.regular;
|
|
|
|
break;
|
|
|
|
case FeeRateType.slow:
|
|
|
|
feePriority = MoneroTransactionPriority.slow;
|
|
|
|
break;
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<PendingTransaction>? awaitPendingTransaction;
|
|
|
|
try {
|
|
|
|
// check for send all
|
|
|
|
bool isSendAll = false;
|
2023-01-12 03:09:08 +00:00
|
|
|
final balance = await _availableBalance;
|
|
|
|
if (satoshiAmount == balance) {
|
2022-12-28 16:25:55 +00:00
|
|
|
isSendAll = true;
|
|
|
|
}
|
|
|
|
Logging.instance
|
|
|
|
.log("$toAddress $satoshiAmount $args", level: LogLevel.Info);
|
2023-01-12 03:09:08 +00:00
|
|
|
String amountToSend =
|
|
|
|
Format.satoshisToAmount(satoshiAmount, coin: coin)
|
|
|
|
.toStringAsFixed(Constants.decimalPlacesForCoin(coin));
|
2022-12-28 16:25:55 +00:00
|
|
|
Logging.instance
|
|
|
|
.log("$satoshiAmount $amountToSend", level: LogLevel.Info);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
monero_output.Output output = monero_output.Output(walletBase!);
|
|
|
|
output.address = toAddress;
|
|
|
|
output.sendAll = isSendAll;
|
|
|
|
output.setCryptoAmount(amountToSend);
|
2022-11-11 18:12:01 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
List<monero_output.Output> outputs = [output];
|
|
|
|
Object tmp = monero.createMoneroTransactionCreationCredentials(
|
|
|
|
outputs: outputs, priority: feePriority);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
await prepareSendMutex.protect(() async {
|
|
|
|
awaitPendingTransaction = walletBase!.createTransaction(tmp);
|
|
|
|
});
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log("Exception rethrown from prepareSend(): $e\n$s",
|
|
|
|
level: LogLevel.Warning);
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
PendingMoneroTransaction pendingMoneroTransaction =
|
|
|
|
await (awaitPendingTransaction!) as PendingMoneroTransaction;
|
2022-11-12 22:04:16 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
int realfee = Format.decimalAmountToSatoshis(
|
|
|
|
Decimal.parse(pendingMoneroTransaction.feeFormatted), coin);
|
|
|
|
debugPrint("fee? $realfee");
|
|
|
|
Map<String, dynamic> txData = {
|
|
|
|
"pendingMoneroTransaction": pendingMoneroTransaction,
|
|
|
|
"fee": realfee,
|
|
|
|
"addresss": toAddress,
|
|
|
|
"recipientAmt": satoshiAmount,
|
|
|
|
};
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Logging.instance.log("prepare send: $txData", level: LogLevel.Info);
|
|
|
|
return txData;
|
|
|
|
} else {
|
|
|
|
throw ArgumentError("Invalid fee rate argument provided!");
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log("Exception rethrown from prepare send(): $e\n$s",
|
|
|
|
level: LogLevel.Info);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (e.toString().contains("Incorrect unlocked balance")) {
|
|
|
|
throw Exception("Insufficient balance!");
|
|
|
|
} else if (e is CreationTransactionException) {
|
|
|
|
throw Exception("Insufficient funds to pay for transaction fee!");
|
|
|
|
} else {
|
|
|
|
throw Exception("Transaction failed with error code $e");
|
|
|
|
}
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> recoverFromMnemonic({
|
|
|
|
required String mnemonic,
|
|
|
|
required int maxUnusedAddressGap,
|
|
|
|
required int maxNumberOfIndexesToCheck,
|
|
|
|
required int height,
|
|
|
|
}) async {
|
|
|
|
await _prefs.init();
|
|
|
|
longMutex = true;
|
|
|
|
final start = DateTime.now();
|
|
|
|
try {
|
|
|
|
// Logging.instance.log("IS_INTEGRATION_TEST: $integrationTestFlag");
|
|
|
|
// if (!integrationTestFlag) {
|
|
|
|
// final features = await electrumXClient.getServerFeatures();
|
|
|
|
// Logging.instance.log("features: $features");
|
|
|
|
// if (_networkType == BasicNetworkType.main) {
|
|
|
|
// if (features['genesis_hash'] != GENESIS_HASH_MAINNET) {
|
|
|
|
// throw Exception("genesis hash does not match main net!");
|
|
|
|
// }
|
|
|
|
// } else if (_networkType == BasicNetworkType.test) {
|
|
|
|
// if (features['genesis_hash'] != GENESIS_HASH_TESTNET) {
|
|
|
|
// throw Exception("genesis hash does not match test net!");
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// check to make sure we aren't overwriting a mnemonic
|
|
|
|
// this should never fail
|
2022-12-28 16:25:55 +00:00
|
|
|
if ((await _secureStorage.read(key: '${_walletId}_mnemonic')) != null) {
|
2022-08-26 08:11:35 +00:00
|
|
|
longMutex = false;
|
|
|
|
throw Exception("Attempted to overwrite mnemonic on restore!");
|
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
await _secureStorage.write(
|
2022-08-26 08:11:35 +00:00
|
|
|
key: '${_walletId}_mnemonic', value: mnemonic.trim());
|
|
|
|
|
|
|
|
await DB.instance
|
|
|
|
.put<dynamic>(boxName: walletId, key: "restoreHeight", value: height);
|
|
|
|
|
|
|
|
walletService =
|
|
|
|
monero.createMoneroWalletService(DB.instance.moneroWalletInfoBox);
|
2022-12-28 16:25:55 +00:00
|
|
|
keysStorage = KeyService(_secureStorage);
|
2022-08-26 08:11:35 +00:00
|
|
|
WalletInfo walletInfo;
|
|
|
|
WalletCredentials credentials;
|
|
|
|
String name = _walletId;
|
|
|
|
final dirPath =
|
2022-12-28 16:25:55 +00:00
|
|
|
await _pathForWalletDir(name: name, type: WalletType.monero);
|
|
|
|
final path = await _pathForWallet(name: name, type: WalletType.monero);
|
2022-08-26 08:11:35 +00:00
|
|
|
credentials = monero.createMoneroRestoreWalletFromSeedCredentials(
|
|
|
|
name: name,
|
|
|
|
height: height,
|
|
|
|
mnemonic: mnemonic.trim(),
|
|
|
|
);
|
|
|
|
try {
|
|
|
|
walletInfo = WalletInfo.external(
|
|
|
|
id: WalletBase.idFor(name, WalletType.monero),
|
|
|
|
name: name,
|
|
|
|
type: WalletType.monero,
|
|
|
|
isRecovery: false,
|
|
|
|
restoreHeight: credentials.height ?? 0,
|
|
|
|
date: DateTime.now(),
|
|
|
|
path: path,
|
|
|
|
dirPath: dirPath,
|
|
|
|
// TODO: find out what to put for address
|
|
|
|
address: '');
|
|
|
|
credentials.walletInfo = walletInfo;
|
|
|
|
|
|
|
|
_walletCreationService = WalletCreationService(
|
2022-12-28 16:25:55 +00:00
|
|
|
secureStorage: _secureStorage,
|
2022-08-26 08:11:35 +00:00
|
|
|
walletService: walletService,
|
|
|
|
keyService: keysStorage,
|
|
|
|
);
|
|
|
|
_walletCreationService!.changeWalletType();
|
|
|
|
// To restore from a seed
|
|
|
|
final wallet =
|
|
|
|
await _walletCreationService!.restoreFromSeed(credentials);
|
|
|
|
walletInfo.address = wallet.walletAddresses.address;
|
|
|
|
await DB.instance
|
|
|
|
.add<WalletInfo>(boxName: WalletInfo.boxName, value: walletInfo);
|
|
|
|
walletBase?.close();
|
|
|
|
walletBase = wallet as MoneroWalletBase;
|
2022-12-28 16:25:55 +00:00
|
|
|
// walletBase!.onNewBlock = onNewBlock;
|
|
|
|
// walletBase!.onNewTransaction = onNewTransaction;
|
|
|
|
// walletBase!.syncStatusChanged = syncStatusChanged;
|
2023-01-12 18:54:22 +00:00
|
|
|
|
2022-08-26 08:11:35 +00:00
|
|
|
await DB.instance
|
|
|
|
.put<dynamic>(boxName: walletId, key: "id", value: _walletId);
|
2023-01-12 18:54:22 +00:00
|
|
|
|
2022-08-26 08:11:35 +00:00
|
|
|
await DB.instance
|
|
|
|
.put<dynamic>(boxName: walletId, key: "isFavorite", value: false);
|
|
|
|
} catch (e, s) {
|
|
|
|
debugPrint(e.toString());
|
|
|
|
debugPrint(s.toString());
|
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
final node = await _getCurrentNode();
|
2022-08-26 08:11:35 +00:00
|
|
|
final host = Uri.parse(node.host).host;
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase!.connectToNode(
|
2022-08-26 08:11:35 +00:00
|
|
|
node: Node(uri: "$host:${node.port}", type: WalletType.monero));
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase!.rescan(height: credentials.height);
|
|
|
|
walletBase!.close();
|
2022-08-26 08:11:35 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from recoverFromMnemonic(): $e\n$s",
|
|
|
|
level: LogLevel.Error);
|
|
|
|
longMutex = false;
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
longMutex = false;
|
|
|
|
|
|
|
|
final end = DateTime.now();
|
|
|
|
Logging.instance.log(
|
|
|
|
"$walletName Recovery time: ${end.difference(start).inMilliseconds} millis",
|
|
|
|
level: LogLevel.Info);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<void> refresh() async {
|
|
|
|
if (refreshMutex) {
|
|
|
|
Logging.instance.log("$walletId $walletName refreshMutex denied",
|
|
|
|
level: LogLevel.Info);
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
refreshMutex = true;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
WalletSyncStatus.syncing,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
2022-08-26 08:11:35 +00:00
|
|
|
);
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
await _refreshTransactions();
|
|
|
|
await _updateBalance();
|
2022-12-28 16:25:55 +00:00
|
|
|
|
|
|
|
await _checkCurrentReceivingAddressesForTransactions();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (walletBase?.syncStatus is SyncedSyncStatus) {
|
|
|
|
refreshMutex = false;
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
WalletSyncStatus.synced,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<bool> testNetworkConnection() async {
|
|
|
|
return await walletBase?.isConnected() ?? false;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
bool _isActive = false;
|
|
|
|
|
2022-08-26 08:11:35 +00:00
|
|
|
@override
|
|
|
|
void Function(bool)? get onIsActiveWalletChanged => (isActive) async {
|
2022-12-28 16:25:55 +00:00
|
|
|
if (_isActive == isActive) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
_isActive = isActive;
|
|
|
|
|
2022-08-26 08:11:35 +00:00
|
|
|
if (isActive) {
|
2022-12-28 16:25:55 +00:00
|
|
|
_hasCalledExit = false;
|
2022-08-26 08:11:35 +00:00
|
|
|
String? password;
|
|
|
|
try {
|
|
|
|
password =
|
|
|
|
await keysStorage?.getWalletPassword(walletName: _walletId);
|
|
|
|
} catch (e, s) {
|
|
|
|
throw Exception("Password not found $e, $s");
|
|
|
|
}
|
|
|
|
walletBase = (await walletService?.openWallet(_walletId, password!))
|
|
|
|
as MoneroWalletBase?;
|
2022-12-28 16:25:55 +00:00
|
|
|
|
|
|
|
walletBase!.onNewBlock = onNewBlock;
|
|
|
|
walletBase!.onNewTransaction = onNewTransaction;
|
|
|
|
walletBase!.syncStatusChanged = syncStatusChanged;
|
|
|
|
|
2022-08-26 08:11:35 +00:00
|
|
|
if (!(await walletBase!.isConnected())) {
|
2022-12-28 16:25:55 +00:00
|
|
|
final node = await _getCurrentNode();
|
2022-08-26 08:11:35 +00:00
|
|
|
final host = Uri.parse(node.host).host;
|
|
|
|
await walletBase?.connectToNode(
|
|
|
|
node: Node(uri: "$host:${node.port}", type: WalletType.monero));
|
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase?.startSync();
|
2022-08-27 16:06:04 +00:00
|
|
|
await refresh();
|
2022-12-28 16:25:55 +00:00
|
|
|
_autoSaveTimer?.cancel();
|
|
|
|
_autoSaveTimer = Timer.periodic(
|
2023-01-02 22:43:04 +00:00
|
|
|
const Duration(seconds: 193),
|
2022-12-28 16:25:55 +00:00
|
|
|
(_) async => await walletBase?.save(),
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
await exit();
|
|
|
|
// _autoSaveTimer?.cancel();
|
|
|
|
// await walletBase?.save(prioritySave: true);
|
|
|
|
// walletBase?.close();
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-01-02 15:13:00 +00:00
|
|
|
Future<void> _updateCachedBalance(int sats) async {
|
|
|
|
await DB.instance.put<dynamic>(
|
|
|
|
boxName: walletId,
|
|
|
|
key: "cachedMoneroBalanceSats",
|
|
|
|
value: sats,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
int _getCachedBalance() =>
|
|
|
|
DB.instance.get<dynamic>(
|
|
|
|
boxName: walletId,
|
|
|
|
key: "cachedMoneroBalanceSats",
|
|
|
|
) as int? ??
|
|
|
|
0;
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
Future<void> _updateBalance() async {
|
|
|
|
final total = await _totalBalance;
|
|
|
|
final available = await _availableBalance;
|
|
|
|
_balance = Balance(
|
|
|
|
coin: coin,
|
|
|
|
total: total,
|
|
|
|
spendable: available,
|
|
|
|
blockedTotal: 0,
|
|
|
|
pendingSpendable: total - available,
|
|
|
|
);
|
2023-01-12 19:21:03 +00:00
|
|
|
await updateCachedBalance(walletId, _balance!);
|
2023-01-12 03:09:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<int> get _availableBalance async {
|
|
|
|
try {
|
|
|
|
int runningBalance = 0;
|
|
|
|
for (final entry in walletBase!.balance!.entries) {
|
|
|
|
runningBalance += entry.value.unlockedBalance;
|
|
|
|
}
|
|
|
|
return runningBalance;
|
|
|
|
} catch (_) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<int> get _totalBalance async {
|
2023-01-02 15:13:00 +00:00
|
|
|
try {
|
|
|
|
final balanceEntries = walletBase?.balance?.entries;
|
|
|
|
if (balanceEntries != null) {
|
|
|
|
int bal = 0;
|
|
|
|
for (var element in balanceEntries) {
|
|
|
|
bal = bal + element.value.fullBalance;
|
|
|
|
}
|
|
|
|
await _updateCachedBalance(bal);
|
2023-01-12 03:09:08 +00:00
|
|
|
return bal;
|
2023-01-02 15:13:00 +00:00
|
|
|
} else {
|
|
|
|
final transactions = walletBase!.transactionHistory!.transactions;
|
|
|
|
int transactionBalance = 0;
|
|
|
|
for (var tx in transactions!.entries) {
|
|
|
|
if (tx.value.direction == TransactionDirection.incoming) {
|
|
|
|
transactionBalance += tx.value.amount!;
|
|
|
|
} else {
|
|
|
|
transactionBalance += -tx.value.amount! - tx.value.fee!;
|
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 15:13:00 +00:00
|
|
|
await _updateCachedBalance(transactionBalance);
|
2023-01-12 03:09:08 +00:00
|
|
|
return transactionBalance;
|
2023-01-02 15:13:00 +00:00
|
|
|
}
|
|
|
|
} catch (_) {
|
2023-01-12 03:09:08 +00:00
|
|
|
return _getCachedBalance();
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-11-07 16:24:08 +00:00
|
|
|
@override
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<void> updateNode(bool shouldRefresh) async {
|
|
|
|
final node = await _getCurrentNode();
|
2022-11-07 16:24:08 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final host = Uri.parse(node.host).host;
|
|
|
|
await walletBase?.connectToNode(
|
|
|
|
node: Node(uri: "$host:${node.port}", type: WalletType.monero));
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// TODO: is this sync call needed? Do we need to notify ui here?
|
|
|
|
await walletBase?.startSync();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (shouldRefresh) {
|
|
|
|
await refresh();
|
|
|
|
}
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
2022-12-30 14:57:17 +00:00
|
|
|
Future<void> updateSentCachedTxData(Map<String, dynamic> txData) async {
|
2022-12-28 16:25:55 +00:00
|
|
|
// not used for xmr
|
2022-12-30 14:57:17 +00:00
|
|
|
return;
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
bool validateAddress(String address) => walletBase!.validateAddress(address);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
@override
|
|
|
|
String get walletId => _walletId;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
Future<isar_models.Address> _generateAddressForChain(
|
|
|
|
int chain,
|
|
|
|
int index,
|
|
|
|
) async {
|
2022-12-28 16:25:55 +00:00
|
|
|
//
|
|
|
|
String address = walletBase!.getTransactionAddress(chain, index);
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
return isar_models.Address()
|
|
|
|
..derivationIndex = index
|
|
|
|
..value = address
|
|
|
|
..publicKey = []
|
|
|
|
..type = isar_models.AddressType.cryptonote
|
|
|
|
..subType = chain == 0
|
|
|
|
? isar_models.AddressSubType.receiving
|
|
|
|
: isar_models.AddressSubType.change;
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<FeeObject> _getFees() async {
|
|
|
|
// TODO: not use random hard coded values here
|
|
|
|
return FeeObject(
|
|
|
|
numberOfBlocksFast: 10,
|
|
|
|
numberOfBlocksAverage: 15,
|
|
|
|
numberOfBlocksSlow: 20,
|
|
|
|
fast: MoneroTransactionPriority.fast.raw!,
|
|
|
|
medium: MoneroTransactionPriority.regular.raw!,
|
|
|
|
slow: MoneroTransactionPriority.slow.raw!,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
Future<void> _refreshTransactions() async {
|
2022-12-28 16:25:55 +00:00
|
|
|
await walletBase!.updateTransactions();
|
|
|
|
final transactions = walletBase?.transactionHistory!.transactions;
|
|
|
|
|
|
|
|
// final cachedTransactions =
|
|
|
|
// DB.instance.get<dynamic>(boxName: walletId, key: 'latest_tx_model')
|
|
|
|
// as TransactionData?;
|
|
|
|
// int latestTxnBlockHeight =
|
|
|
|
// DB.instance.get<dynamic>(boxName: walletId, key: "storedTxnDataHeight")
|
|
|
|
// as int? ??
|
|
|
|
// 0;
|
|
|
|
|
|
|
|
// final txidsList = DB.instance
|
|
|
|
// .get<dynamic>(boxName: walletId, key: "cachedTxids") as List? ??
|
|
|
|
// [];
|
|
|
|
//
|
|
|
|
// final Set<String> cachedTxids = Set<String>.from(txidsList);
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
final List<isar_models.Transaction> txns = [];
|
2022-12-28 16:25:55 +00:00
|
|
|
|
|
|
|
if (transactions != null) {
|
|
|
|
for (var tx in transactions.entries) {
|
|
|
|
// cachedTxids.add(tx.value.id);
|
2023-01-12 03:09:08 +00:00
|
|
|
// Logging.instance.log(
|
|
|
|
// "${tx.value.accountIndex} ${tx.value.addressIndex} ${tx.value.amount} ${tx.value.date} "
|
|
|
|
// "${tx.value.direction} ${tx.value.fee} ${tx.value.height} ${tx.value.id} ${tx.value.isPending} ${tx.value.key} "
|
|
|
|
// "${tx.value.recipientAddress}, ${tx.value.additionalInfo} con:${tx.value.confirmations}"
|
|
|
|
// " ${tx.value.keyIndex}",
|
|
|
|
// level: LogLevel.Info);
|
|
|
|
|
|
|
|
final int txHeight = tx.value.height ?? 0;
|
|
|
|
final txn = isar_models.Transaction();
|
|
|
|
txn.txid = tx.value.id;
|
|
|
|
txn.timestamp = (tx.value.date.millisecondsSinceEpoch ~/ 1000);
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (tx.value.direction == TransactionDirection.incoming) {
|
|
|
|
final addressInfo = tx.value.additionalInfo;
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
txn.address = walletBase?.getTransactionAddress(
|
|
|
|
addressInfo!['accountIndex'] as int,
|
|
|
|
addressInfo['addressIndex'] as int,
|
|
|
|
) ??
|
|
|
|
"";
|
|
|
|
|
|
|
|
txn.type = isar_models.TransactionType.incoming;
|
2022-12-28 16:25:55 +00:00
|
|
|
} else {
|
2023-01-12 03:09:08 +00:00
|
|
|
txn.address = "";
|
|
|
|
txn.type = isar_models.TransactionType.outgoing;
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
txn.amount = tx.value.amount ?? 0;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
// TODO: other subtypes
|
|
|
|
txn.subType = isar_models.TransactionSubType.none;
|
|
|
|
|
|
|
|
txn.fee = tx.value.fee ?? 0;
|
|
|
|
|
|
|
|
txn.height = txHeight;
|
|
|
|
|
|
|
|
txn.isCancelled = false;
|
|
|
|
txn.slateId = null;
|
|
|
|
txn.otherData = null;
|
|
|
|
|
|
|
|
txns.add(txn);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
await isar.writeTxn(() async {
|
|
|
|
await isar.transactions.putAll(txns);
|
|
|
|
});
|
|
|
|
|
|
|
|
// // sort by date ----
|
|
|
|
// midSortedArray
|
|
|
|
// .sort((a, b) => (b["timestamp"] as int) - (a["timestamp"] as int));
|
|
|
|
// Logging.instance.log(midSortedArray, level: LogLevel.Info);
|
|
|
|
//
|
|
|
|
// // buildDateTimeChunks
|
|
|
|
// final Map<String, dynamic> result = {"dateTimeChunks": <dynamic>[]};
|
|
|
|
// final dateArray = <dynamic>[];
|
|
|
|
//
|
|
|
|
// for (int i = 0; i < midSortedArray.length; i++) {
|
|
|
|
// final txObject = midSortedArray[i];
|
|
|
|
// final date = extractDateFromTimestamp(txObject["timestamp"] as int);
|
|
|
|
// final txTimeArray = [txObject["timestamp"], date];
|
|
|
|
//
|
|
|
|
// if (dateArray.contains(txTimeArray[1])) {
|
|
|
|
// result["dateTimeChunks"].forEach((dynamic chunk) {
|
|
|
|
// if (extractDateFromTimestamp(chunk["timestamp"] as int) ==
|
|
|
|
// txTimeArray[1]) {
|
|
|
|
// if (chunk["transactions"] == null) {
|
|
|
|
// chunk["transactions"] = <Map<String, dynamic>>[];
|
|
|
|
// }
|
|
|
|
// chunk["transactions"].add(txObject);
|
|
|
|
// }
|
|
|
|
// });
|
|
|
|
// } else {
|
|
|
|
// dateArray.add(txTimeArray[1]);
|
|
|
|
// final chunk = {
|
|
|
|
// "timestamp": txTimeArray[0],
|
|
|
|
// "transactions": [txObject],
|
|
|
|
// };
|
|
|
|
// result["dateTimeChunks"].add(chunk);
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// // final transactionsMap = cachedTransactions?.getAllTransactions() ?? {};
|
|
|
|
// final Map<String, Transaction> transactionsMap = {};
|
|
|
|
// transactionsMap
|
|
|
|
// .addAll(TransactionData.fromJson(result).getAllTransactions());
|
|
|
|
//
|
|
|
|
// final txModel = TransactionData.fromMap(transactionsMap);
|
|
|
|
//
|
|
|
|
// // await DB.instance.put<dynamic>(
|
|
|
|
// // boxName: walletId,
|
|
|
|
// // key: 'storedTxnDataHeight',
|
|
|
|
// // value: latestTxnBlockHeight);
|
|
|
|
// // await DB.instance.put<dynamic>(
|
|
|
|
// // boxName: walletId, key: 'latest_tx_model', value: txModel);
|
|
|
|
// // await DB.instance.put<dynamic>(
|
|
|
|
// // boxName: walletId,
|
|
|
|
// // key: 'cachedTxids',
|
|
|
|
// // value: cachedTxids.toList(growable: false));
|
|
|
|
//
|
|
|
|
// return txModel;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<String> _pathForWalletDir({
|
|
|
|
required String name,
|
|
|
|
required WalletType type,
|
|
|
|
}) async {
|
|
|
|
Directory root = await StackFileSystem.applicationRootDirectory();
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final prefix = walletTypeToString(type).toLowerCase();
|
|
|
|
final walletsDir = Directory('${root.path}/wallets');
|
|
|
|
final walletDire = Directory('${walletsDir.path}/$prefix/$name');
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (!walletDire.existsSync()) {
|
|
|
|
walletDire.createSync(recursive: true);
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
return walletDire.path;
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<String> _pathForWallet({
|
|
|
|
required String name,
|
|
|
|
required WalletType type,
|
|
|
|
}) async =>
|
|
|
|
await _pathForWalletDir(name: name, type: type)
|
|
|
|
.then((path) => '$path/$name');
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<NodeModel> _getCurrentNode() async {
|
|
|
|
return NodeService(secureStorageInterface: _secureStorage)
|
|
|
|
.getPrimaryNodeFor(coin: coin) ??
|
|
|
|
DefaultNodes.getNodeFor(coin);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
void onNewBlock() {
|
|
|
|
//
|
|
|
|
print("=============================");
|
2022-12-30 22:15:03 +00:00
|
|
|
print("New Block! :: $walletName");
|
2022-12-28 16:25:55 +00:00
|
|
|
print("=============================");
|
2023-01-02 22:43:39 +00:00
|
|
|
_refreshTxDataHelper();
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
void onNewTransaction() {
|
|
|
|
//
|
|
|
|
print("=============================");
|
2022-12-30 22:15:03 +00:00
|
|
|
print("New Transaction! :: $walletName");
|
2022-12-28 16:25:55 +00:00
|
|
|
print("=============================");
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// call this here?
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
UpdatedInBackgroundEvent(
|
|
|
|
"New data found in $walletId $walletName in background!",
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2023-01-02 22:43:39 +00:00
|
|
|
bool _txRefreshLock = false;
|
|
|
|
int _lastCheckedHeight = -1;
|
|
|
|
int _txCount = 0;
|
|
|
|
|
|
|
|
Future<void> _refreshTxDataHelper() async {
|
|
|
|
if (_txRefreshLock) return;
|
|
|
|
_txRefreshLock = true;
|
|
|
|
|
|
|
|
final syncStatus = walletBase?.syncStatus;
|
|
|
|
|
|
|
|
if (syncStatus != null && syncStatus is SyncingSyncStatus) {
|
|
|
|
final int blocksLeft = syncStatus.blocksLeft;
|
|
|
|
final tenKChange = blocksLeft ~/ 10000;
|
|
|
|
|
|
|
|
// only refresh transactions periodically during a sync
|
|
|
|
if (_lastCheckedHeight == -1 || tenKChange < _lastCheckedHeight) {
|
|
|
|
_lastCheckedHeight = tenKChange;
|
|
|
|
await _refreshTxData();
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
await _refreshTxData();
|
|
|
|
}
|
|
|
|
|
|
|
|
_txRefreshLock = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _refreshTxData() async {
|
2023-01-12 03:09:08 +00:00
|
|
|
await _refreshTransactions();
|
|
|
|
final count = await isar.transactions.count();
|
2023-01-02 22:43:39 +00:00
|
|
|
|
|
|
|
if (count > _txCount) {
|
|
|
|
_txCount = count;
|
2023-01-12 03:09:08 +00:00
|
|
|
await _updateBalance();
|
2023-01-02 22:43:39 +00:00
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
UpdatedInBackgroundEvent(
|
|
|
|
"New transaction data found in $walletId $walletName!",
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
void syncStatusChanged() async {
|
|
|
|
final syncStatus = walletBase?.syncStatus;
|
|
|
|
if (syncStatus != null) {
|
|
|
|
if (syncStatus.progress() == 1) {
|
|
|
|
refreshMutex = false;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
WalletSyncStatus? status;
|
|
|
|
_isConnected = true;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (syncStatus is SyncingSyncStatus) {
|
|
|
|
final int blocksLeft = syncStatus.blocksLeft;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// ensure at least 1 to prevent math errors
|
|
|
|
final int height = max(1, syncStatus.height);
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final nodeHeight = height + blocksLeft;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final percent = height / nodeHeight;
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
final highest = max(highestPercentCached, percent);
|
2022-11-23 18:31:31 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// update cached
|
|
|
|
if (highestPercentCached < percent) {
|
|
|
|
highestPercentCached = percent;
|
|
|
|
}
|
2022-08-26 08:11:35 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
RefreshPercentChangedEvent(
|
|
|
|
highest,
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
BlocksRemainingEvent(
|
|
|
|
blocksLeft,
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
} else if (syncStatus is SyncedSyncStatus) {
|
|
|
|
status = WalletSyncStatus.synced;
|
|
|
|
} else if (syncStatus is NotConnectedSyncStatus) {
|
|
|
|
status = WalletSyncStatus.unableToSync;
|
|
|
|
_isConnected = false;
|
|
|
|
} else if (syncStatus is StartingSyncStatus) {
|
|
|
|
status = WalletSyncStatus.syncing;
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
RefreshPercentChangedEvent(
|
|
|
|
highestPercentCached,
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
} else if (syncStatus is FailedSyncStatus) {
|
|
|
|
status = WalletSyncStatus.unableToSync;
|
|
|
|
_isConnected = false;
|
|
|
|
} else if (syncStatus is ConnectingSyncStatus) {
|
|
|
|
status = WalletSyncStatus.syncing;
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
RefreshPercentChangedEvent(
|
|
|
|
highestPercentCached,
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
} else if (syncStatus is ConnectedSyncStatus) {
|
|
|
|
status = WalletSyncStatus.syncing;
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
RefreshPercentChangedEvent(
|
|
|
|
highestPercentCached,
|
|
|
|
walletId,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
} else if (syncStatus is LostConnectionSyncStatus) {
|
|
|
|
status = WalletSyncStatus.unableToSync;
|
|
|
|
_isConnected = false;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (status != null) {
|
|
|
|
GlobalEventBus.instance.fire(
|
|
|
|
WalletSyncStatusChangedEvent(
|
|
|
|
status,
|
|
|
|
walletId,
|
|
|
|
coin,
|
|
|
|
),
|
|
|
|
);
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<void> _checkCurrentReceivingAddressesForTransactions() async {
|
|
|
|
try {
|
|
|
|
await _checkReceivingAddressForTransactions();
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from _checkCurrentReceivingAddressesForTransactions(): $e\n$s",
|
|
|
|
level: LogLevel.Error);
|
|
|
|
rethrow;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|
|
|
|
}
|
2022-09-06 01:18:45 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
Future<void> _checkReceivingAddressForTransactions() async {
|
2022-09-06 01:18:45 +00:00
|
|
|
try {
|
2022-12-28 16:25:55 +00:00
|
|
|
int highestIndex = -1;
|
|
|
|
for (var element
|
|
|
|
in walletBase!.transactionHistory!.transactions!.entries) {
|
|
|
|
if (element.value.direction == TransactionDirection.incoming) {
|
|
|
|
int curAddressIndex =
|
|
|
|
element.value.additionalInfo!['addressIndex'] as int;
|
|
|
|
if (curAddressIndex > highestIndex) {
|
|
|
|
highestIndex = curAddressIndex;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-09-06 01:18:45 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// Check the new receiving index
|
2023-01-12 03:09:08 +00:00
|
|
|
final currentReceiving = await _currentReceivingAddress;
|
|
|
|
final curIndex = currentReceiving!.derivationIndex;
|
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
if (highestIndex >= curIndex) {
|
|
|
|
// First increment the receiving index
|
2023-01-12 03:09:08 +00:00
|
|
|
final newReceivingIndex = curIndex + 1;
|
2022-09-06 01:18:45 +00:00
|
|
|
|
2022-12-28 16:25:55 +00:00
|
|
|
// Use new index to derive a new receiving address
|
|
|
|
final newReceivingAddress =
|
|
|
|
await _generateAddressForChain(0, newReceivingIndex);
|
2022-09-06 01:18:45 +00:00
|
|
|
|
2023-01-12 03:09:08 +00:00
|
|
|
// Add that new receiving address
|
|
|
|
await isar.writeTxn(() async {
|
|
|
|
await isar.addresses.put(newReceivingAddress);
|
|
|
|
});
|
2022-12-28 16:25:55 +00:00
|
|
|
}
|
|
|
|
} on SocketException catch (se, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"SocketException caught in _checkReceivingAddressForTransactions(): $se\n$s",
|
|
|
|
level: LogLevel.Error);
|
|
|
|
return;
|
2022-09-06 01:18:45 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2022-12-28 16:25:55 +00:00
|
|
|
"Exception rethrown from _checkReceivingAddressForTransactions(): $e\n$s",
|
2022-09-06 01:18:45 +00:00
|
|
|
level: LogLevel.Error);
|
2022-12-28 16:25:55 +00:00
|
|
|
rethrow;
|
2022-09-06 01:18:45 +00:00
|
|
|
}
|
|
|
|
}
|
2022-12-28 16:25:55 +00:00
|
|
|
|
|
|
|
double get highestPercentCached =>
|
|
|
|
DB.instance.get<dynamic>(boxName: walletId, key: "highestPercentCached")
|
|
|
|
as double? ??
|
|
|
|
0;
|
|
|
|
|
|
|
|
set highestPercentCached(double value) => DB.instance.put<dynamic>(
|
|
|
|
boxName: walletId,
|
|
|
|
key: "highestPercentCached",
|
|
|
|
value: value,
|
|
|
|
);
|
2023-01-10 23:50:22 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
// TODO: implement storedChainHeight
|
|
|
|
int get storedChainHeight => throw UnimplementedError();
|
2023-01-12 03:09:08 +00:00
|
|
|
|
|
|
|
@override
|
2023-01-12 19:21:03 +00:00
|
|
|
Balance get balance => _balance ??= getCachedBalance(walletId, coin);
|
2023-01-12 03:09:08 +00:00
|
|
|
Balance? _balance;
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<List<isar_models.Transaction>> get transactions =>
|
|
|
|
isar.transactions.where().sortByTimestampDesc().findAll();
|
|
|
|
|
|
|
|
@override
|
|
|
|
// TODO: implement utxos
|
|
|
|
Future<List<isar_models.UTXO>> get utxos => throw UnimplementedError();
|
2023-01-12 03:23:21 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
Isar get isarInstance => isar;
|
2022-08-26 08:11:35 +00:00
|
|
|
}
|