[skip-ci] wip

This commit is contained in:
Matthew Fosse 2025-02-07 08:34:49 -08:00
parent 09ad827a68
commit 5f3b601dd3

View file

@ -48,8 +48,8 @@ const MIN_RESTORE_HEIGHT = 1000;
class MoneroWallet = MoneroWalletBase with _$MoneroWallet;
abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
MoneroTransactionHistory, MoneroTransactionInfo> with Store {
abstract class MoneroWalletBase
extends WalletBase<MoneroBalance, MoneroTransactionHistory, MoneroTransactionInfo> with Store {
MoneroWalletBase(
{required WalletInfo walletInfo,
required Box<UnspentCoinsInfo> unspentCoinsInfo,
@ -71,16 +71,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
transactionHistory = MoneroTransactionHistory();
walletAddresses = MoneroWalletAddresses(walletInfo, transactionHistory);
_onAccountChangeReaction =
reaction((_) => walletAddresses.account, (Account? account) {
_onAccountChangeReaction = reaction((_) => walletAddresses.account, (Account? account) {
if (account == null) return;
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency,
MoneroBalance>{
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance(accountIndex: account.id),
unlockedBalance:
monero_wallet.getUnlockedBalance(accountIndex: account.id))
unlockedBalance: monero_wallet.getUnlockedBalance(accountIndex: account.id))
});
_updateSubAddress(isEnabledAutoGenerateSubaddress, account: account);
_askForUpdateTransactionHistory();
@ -135,7 +132,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
passphrase: monero_wallet.getPassphrase());
int? get restoreHeight =>
transactionHistory.transactions.values.firstOrNull?.height ?? monero.Wallet_getRefreshFromBlockHeight(wptr!);
transactionHistory.transactions.values.firstOrNull?.height ??
monero.Wallet_getRefreshFromBlockHeight(wptr!);
monero_wallet.SyncListener? _listener;
ReactionDisposer? _onAccountChangeReaction;
@ -148,13 +146,11 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> init() async {
await walletAddresses.init();
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency,
MoneroBalance>{
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance(
accountIndex: walletAddresses.account!.id),
unlockedBalance: monero_wallet.getUnlockedBalance(
accountIndex: walletAddresses.account!.id))
fullBalance: monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id),
unlockedBalance:
monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id))
});
_setListeners();
await updateTransactions();
@ -163,15 +159,14 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
monero_wallet.setRecoveringFromSeed(isRecovery: walletInfo.isRecovery);
if (monero_wallet.getCurrentHeight() <= 1) {
monero_wallet.setRefreshFromBlockHeight(
height: walletInfo.restoreHeight);
monero_wallet.setRefreshFromBlockHeight(height: walletInfo.restoreHeight);
}
}
_autoSaveTimer = Timer.periodic(
Duration(seconds: _autoSaveInterval), (_) async => await save());
_autoSaveTimer =
Timer.periodic(Duration(seconds: _autoSaveInterval), (_) async => await save());
// update transaction details after restore
walletAddresses.subaddressList.update(accountIndex: walletAddresses.account?.id??0);
walletAddresses.subaddressList.update(accountIndex: walletAddresses.account?.id ?? 0);
}
@override
@ -274,9 +269,9 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
}
// viewOnlyBalance - balance that we can spend
// TODO(mrcyjanek): remove hasUnknownKeyImages when we cleanup coin control
return (monero.Wallet_viewOnlyBalance(wptr!,
accountIndex: walletAddresses.account!.id) < amount) ||
monero.Wallet_hasUnknownKeyImages(wptr!);
return (monero.Wallet_viewOnlyBalance(wptr!, accountIndex: walletAddresses.account!.id) <
amount) ||
monero.Wallet_hasUnknownKeyImages(wptr!);
}
@override
@ -285,8 +280,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final inputs = <String>[];
final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1;
final unlockedBalance = monero_wallet.getUnlockedBalance(
accountIndex: walletAddresses.account!.id);
final unlockedBalance =
monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
PendingTransactionDescription pendingTransactionDescription;
@ -305,44 +300,35 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
}
if (hasMultiDestination) {
if (outputs.any(
(item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
throw MoneroTransactionCreationException(
'You do not have enough XMR to send this amount.');
if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
}
final int totalAmount = outputs.fold(
0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
final int totalAmount =
outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
if (unlockedBalance < totalAmount) {
throw MoneroTransactionCreationException(
'You do not have enough XMR to send this amount.');
throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
}
if (inputs.isEmpty) MoneroTransactionCreationException(
'No inputs selected');
if (inputs.isEmpty) MoneroTransactionCreationException('No inputs selected');
final moneroOutputs = outputs.map((output) {
final outputAddress =
output.isParsedAddress ? output.extractedAddress : output.address;
final outputAddress = output.isParsedAddress ? output.extractedAddress : output.address;
return MoneroOutput(
address: outputAddress!,
amount: output.cryptoAmount!.replaceAll(',', '.'));
address: outputAddress!, amount: output.cryptoAmount!.replaceAll(',', '.'));
}).toList();
pendingTransactionDescription =
await transaction_history.createTransactionMultDest(
outputs: moneroOutputs,
priorityRaw: _credentials.priority.serialize(),
accountIndex: walletAddresses.account!.id,
preferredInputs: inputs);
pendingTransactionDescription = await transaction_history.createTransactionMultDest(
outputs: moneroOutputs,
priorityRaw: _credentials.priority.serialize(),
accountIndex: walletAddresses.account!.id,
preferredInputs: inputs);
} else {
final output = outputs.first;
final address =
output.isParsedAddress ? output.extractedAddress : output.address;
final amount =
output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
final address = output.isParsedAddress ? output.extractedAddress : output.address;
final amount = output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
// if ((formattedAmount != null && unlockedBalance < formattedAmount) ||
// (formattedAmount == null && unlockedBalance <= 0)) {
@ -352,15 +338,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
// 'You do not have enough unlocked balance. Unlocked: $formattedBalance. Transaction amount: ${output.cryptoAmount}.');
// }
if (inputs.isEmpty) MoneroTransactionCreationException(
'No inputs selected');
pendingTransactionDescription =
await transaction_history.createTransaction(
address: address!,
amount: amount,
priorityRaw: _credentials.priority.serialize(),
accountIndex: walletAddresses.account!.id,
preferredInputs: inputs);
if (inputs.isEmpty) MoneroTransactionCreationException('No inputs selected');
pendingTransactionDescription = await transaction_history.createTransaction(
address: address!,
amount: amount,
priorityRaw: _credentials.priority.serialize(),
accountIndex: walletAddresses.account!.id,
preferredInputs: inputs);
}
// final status = monero.PendingTransaction_status(pendingTransactionDescription);
@ -426,43 +410,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
printV("wallet closed");
}
try {
// -- rename the waller folder --
final currentWalletDir =
Directory(await pathForWalletDir(name: name, type: type));
final newWalletDirPath =
await pathForWalletDir(name: newWalletName, type: type);
await currentWalletDir.rename(newWalletDirPath);
// -- use new waller folder to rename files with old names still --
final renamedWalletPath = newWalletDirPath + '/$name';
final currentCacheFile = File(renamedWalletPath);
final currentKeysFile = File('$renamedWalletPath.keys');
final currentAddressListFile = File('$renamedWalletPath.address.txt');
final newWalletPath =
await pathForWallet(name: newWalletName, type: type);
if (currentCacheFile.existsSync()) {
await currentCacheFile.rename(newWalletPath);
}
if (currentKeysFile.existsSync()) {
await currentKeysFile.rename('$newWalletPath.keys');
}
if (currentAddressListFile.existsSync()) {
await currentAddressListFile.rename('$newWalletPath.address.txt');
}
await backupWalletFiles(newWalletName);
} catch (e) {
final currentWalletPath = await pathForWallet(name: name, type: type);
final currentCacheFile = File(currentWalletPath);
final currentKeysFile = File('$currentWalletPath.keys');
final currentAddressListFile = File('$currentWalletPath.address.txt');
final newWalletPath =
await pathForWallet(name: newWalletName, type: type);
final newWalletPath = await pathForWallet(name: newWalletName, type: type);
// Copies current wallet files into new wallet name's dir and files
if (currentCacheFile.existsSync()) {
@ -477,12 +431,37 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
// Delete old name's dir and files
await Directory(currentWalletDirPath).delete(recursive: true);
await backupWalletFiles(newWalletName);
} catch (e) {
printV("Error renaming wallet files: $e");
// final currentWalletPath = await pathForWallet(name: name, type: type);
// final currentCacheFile = File(currentWalletPath);
// final currentKeysFile = File('$currentWalletPath.keys');
// final currentAddressListFile = File('$currentWalletPath.address.txt');
// final newWalletPath =
// await pathForWallet(name: newWalletName, type: type);
// // Copies current wallet files into new wallet name's dir and files
// if (currentCacheFile.existsSync()) {
// await currentCacheFile.copy(newWalletPath);
// }
// if (currentKeysFile.existsSync()) {
// await currentKeysFile.copy('$newWalletPath.keys');
// }
// if (currentAddressListFile.existsSync()) {
// await currentAddressListFile.copy('$newWalletPath.address.txt');
// }
// // Delete old name's dir and files
// await Directory(currentWalletDirPath).delete(recursive: true);
}
}
@override
Future<void> changePassword(String password) async =>
monero_wallet.setPasswordSync(password);
Future<void> changePassword(String password) async => monero_wallet.setPasswordSync(password);
Future<int> getNodeHeight() async => monero_wallet.getNodeHeight();
@ -517,7 +496,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
for (var i = 0; i < coinCount; i++) {
final coin = getCoin(i);
final coinSpent = monero.CoinsInfo_spent(coin);
if (coinSpent == false && monero.CoinsInfo_subaddrAccount(coin) == walletAddresses.account!.id) {
if (coinSpent == false &&
monero.CoinsInfo_subaddrAccount(coin) == walletAddresses.account!.id) {
final unspent = MoneroUnspent(
monero.CoinsInfo_address(coin),
monero.CoinsInfo_hash(coin),
@ -590,15 +570,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> _refreshUnspentCoinsInfo() async {
try {
final List<dynamic> keys = <dynamic>[];
final currentWalletUnspentCoins = unspentCoinsInfo.values.where(
(element) =>
element.walletId.contains(id) &&
element.accountIndex == walletAddresses.account!.id);
final currentWalletUnspentCoins = unspentCoinsInfo.values.where((element) =>
element.walletId.contains(id) && element.accountIndex == walletAddresses.account!.id);
if (currentWalletUnspentCoins.isNotEmpty) {
currentWalletUnspentCoins.forEach((element) {
final existUnspentCoins = unspentCoins
.where((coin) => element.keyImage!.contains(coin.keyImage!));
final existUnspentCoins =
unspentCoins.where((coin) => element.keyImage!.contains(coin.keyImage!));
if (existUnspentCoins.isEmpty) {
keys.add(element.key);
@ -615,15 +593,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
}
String getTransactionAddress(int accountIndex, int addressIndex) =>
monero_wallet.getAddress(
accountIndex: accountIndex, addressIndex: addressIndex);
monero_wallet.getAddress(accountIndex: accountIndex, addressIndex: addressIndex);
@override
Future<Map<String, MoneroTransactionInfo>> fetchTransactions() async {
transaction_history.refreshTransactions();
return (await _getAllTransactionsOfAccount(walletAddresses.account?.id))
.fold<Map<String, MoneroTransactionInfo>>(
<String, MoneroTransactionInfo>{},
.fold<Map<String, MoneroTransactionInfo>>(<String, MoneroTransactionInfo>{},
(Map<String, MoneroTransactionInfo> acc, MoneroTransactionInfo tx) {
acc[tx.id] = tx;
return acc;
@ -652,15 +628,12 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
monero_wallet.getSubaddressLabel(accountIndex, addressIndex);
Future<List<MoneroTransactionInfo>> _getAllTransactionsOfAccount(int? accountIndex) async =>
(await transaction_history
.getAllTransactions())
(await transaction_history.getAllTransactions())
.map(
(row) => MoneroTransactionInfo(
row.hash,
row.blockheight,
row.isSpend
? TransactionDirection.outgoing
: TransactionDirection.incoming,
row.isSpend ? TransactionDirection.outgoing : TransactionDirection.incoming,
row.timeStamp,
row.isPending,
row.amount,
@ -709,8 +682,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
}
int _getHeightDistance(DateTime date) {
final distance =
DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
final distance = DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
final daysTmp = (distance / 86400).round();
final days = daysTmp < 1 ? 1 : daysTmp;
@ -731,24 +703,20 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
void _askForUpdateBalance() {
final unlockedBalance = _getUnlockedBalance();
final fullBalance = monero_wallet.getFullBalance(
accountIndex: walletAddresses.account!.id);
final fullBalance = monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
final frozenBalance = _getFrozenBalance();
if (balance[currency]!.fullBalance != fullBalance ||
balance[currency]!.unlockedBalance != unlockedBalance ||
balance[currency]!.frozenBalance != frozenBalance) {
balance[currency] = MoneroBalance(
fullBalance: fullBalance,
unlockedBalance: unlockedBalance,
frozenBalance: frozenBalance);
fullBalance: fullBalance, unlockedBalance: unlockedBalance, frozenBalance: frozenBalance);
}
}
Future<void> _askForUpdateTransactionHistory() async =>
await updateTransactions();
Future<void> _askForUpdateTransactionHistory() async => await updateTransactions();
int _getUnlockedBalance() => monero_wallet.getUnlockedBalance(
accountIndex: walletAddresses.account!.id);
int _getUnlockedBalance() =>
monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
int _getFrozenBalance() {
var frozenBalance = 0;
@ -829,8 +797,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
}
void setLedgerConnection(LedgerConnection connection) {
final dummyWPtr = wptr ??
monero.WalletManager_openWallet(wmPtr, path: '', password: '');
final dummyWPtr = wptr ?? monero.WalletManager_openWallet(wmPtr, path: '', password: '');
enableLedgerExchange(dummyWPtr, connection);
}
}