CW-489 Skip Warning if all monero utxo are selected (#1106)

This commit is contained in:
Konstantin Ullrich 2023-09-28 19:49:46 +02:00 committed by GitHub
parent 9eb6867ab9
commit dc36c31197
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -37,10 +37,10 @@ const moneroBlockSize = 1000;
class MoneroWallet = MoneroWalletBase with _$MoneroWallet; class MoneroWallet = MoneroWalletBase with _$MoneroWallet;
abstract class MoneroWalletBase extends WalletBase<MoneroBalance, abstract class MoneroWalletBase
MoneroTransactionHistory, MoneroTransactionInfo> with Store { extends WalletBase<MoneroBalance, MoneroTransactionHistory, MoneroTransactionInfo> with Store {
MoneroWalletBase({required WalletInfo walletInfo, MoneroWalletBase(
required Box<UnspentCoinsInfo> unspentCoinsInfo}) {required WalletInfo walletInfo, required Box<UnspentCoinsInfo> unspentCoinsInfo})
: balance = ObservableMap<CryptoCurrency, MoneroBalance>.of({ : balance = ObservableMap<CryptoCurrency, MoneroBalance>.of({
CryptoCurrency.xmr: MoneroBalance( CryptoCurrency.xmr: MoneroBalance(
fullBalance: monero_wallet.getFullBalance(accountIndex: 0), fullBalance: monero_wallet.getFullBalance(accountIndex: 0),
@ -112,12 +112,12 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> init() async { Future<void> init() async {
await walletAddresses.init(); await walletAddresses.init();
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of( balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
<CryptoCurrency, MoneroBalance>{ currency: MoneroBalance(
currency: MoneroBalance( fullBalance: monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id),
fullBalance: monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id), unlockedBalance:
unlockedBalance: monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id)) monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id))
}); });
_setListeners(); _setListeners();
await updateTransactions(); await updateTransactions();
@ -125,15 +125,14 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
monero_wallet.setRecoveringFromSeed(isRecovery: walletInfo.isRecovery); monero_wallet.setRecoveringFromSeed(isRecovery: walletInfo.isRecovery);
if (monero_wallet.getCurrentHeight() <= 1) { if (monero_wallet.getCurrentHeight() <= 1) {
monero_wallet.setRefreshFromBlockHeight( monero_wallet.setRefreshFromBlockHeight(height: walletInfo.restoreHeight);
height: walletInfo.restoreHeight);
} }
} }
_autoSaveTimer = Timer.periodic( _autoSaveTimer =
Duration(seconds: _autoSaveInterval), Timer.periodic(Duration(seconds: _autoSaveInterval), (_) async => await save());
(_) async => await save());
} }
@override @override
Future<void>? updateBalance() => null; Future<void>? updateBalance() => null;
@ -153,7 +152,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
login: node.login, login: node.login,
password: node.password, password: node.password,
useSSL: node.isSSL, useSSL: node.isSSL,
isLightWallet: false, // FIXME: hardcoded value isLightWallet: false,
// FIXME: hardcoded value
socksProxyAddress: node.socksProxyAddress); socksProxyAddress: node.socksProxyAddress);
monero_wallet.setTrustedDaemon(node.trusted); monero_wallet.setTrustedDaemon(node.trusted);
@ -189,7 +189,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final outputs = _credentials.outputs; final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1; final hasMultiDestination = outputs.length > 1;
final unlockedBalance = final unlockedBalance =
monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
var allInputsAmount = 0; var allInputsAmount = 0;
PendingTransactionDescription pendingTransactionDescription; PendingTransactionDescription pendingTransactionDescription;
@ -208,56 +208,42 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
inputs.add(utx.keyImage); inputs.add(utx.keyImage);
} }
} }
final spendAllCoins = inputs.length == unspentCoins.length;
if (inputs.isEmpty) {
throw MoneroTransactionNoInputsException(0);
}
if (hasMultiDestination) { if (hasMultiDestination) {
if (outputs.any((item) => item.sendAll if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
|| (item.formattedCryptoAmount ?? 0) <= 0)) {
throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.'); throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
} }
final int totalAmount = outputs.fold(0, (acc, value) => final int totalAmount =
acc + (value.formattedCryptoAmount ?? 0)); outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
final estimatedFee = calculateEstimatedFee(_credentials.priority, totalAmount); final estimatedFee = calculateEstimatedFee(_credentials.priority, totalAmount);
if (unlockedBalance < totalAmount) { 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 (allInputsAmount < totalAmount + estimatedFee) { if (!spendAllCoins && (allInputsAmount < totalAmount + estimatedFee)) {
throw MoneroTransactionNoInputsException(inputs.length); throw MoneroTransactionNoInputsException(inputs.length);
} }
final moneroOutputs = outputs.map((output) { final moneroOutputs = outputs.map((output) {
final outputAddress = output.isParsedAddress final outputAddress = output.isParsedAddress ? output.extractedAddress : output.address;
? output.extractedAddress
: output.address;
return MoneroOutput( return MoneroOutput(
address: outputAddress!, address: outputAddress!, amount: output.cryptoAmount!.replaceAll(',', '.'));
amount: output.cryptoAmount!.replaceAll(',', '.'));
}).toList(); }).toList();
pendingTransactionDescription = pendingTransactionDescription = await transaction_history.createTransactionMultDest(
await transaction_history.createTransactionMultDest(
outputs: moneroOutputs, outputs: moneroOutputs,
priorityRaw: _credentials.priority.serialize(), priorityRaw: _credentials.priority.serialize(),
accountIndex: walletAddresses.account!.id, accountIndex: walletAddresses.account!.id,
preferredInputs: inputs); preferredInputs: inputs);
} else { } else {
final output = outputs.first; final output = outputs.first;
final address = output.isParsedAddress final address = output.isParsedAddress ? output.extractedAddress : output.address;
? output.extractedAddress final amount = output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
: output.address; final formattedAmount = output.sendAll ? null : output.formattedCryptoAmount;
final amount = output.sendAll
? null
: output.cryptoAmount!.replaceAll(',', '.');
final formattedAmount = output.sendAll
? null
: output.formattedCryptoAmount;
if ((formattedAmount != null && unlockedBalance < formattedAmount) || if ((formattedAmount != null && unlockedBalance < formattedAmount) ||
(formattedAmount == null && unlockedBalance <= 0)) { (formattedAmount == null && unlockedBalance <= 0)) {
@ -268,8 +254,9 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
final estimatedFee = calculateEstimatedFee(_credentials.priority, formattedAmount); final estimatedFee = calculateEstimatedFee(_credentials.priority, formattedAmount);
if ((formattedAmount != null && allInputsAmount < (formattedAmount + estimatedFee)) || if (!spendAllCoins &&
(formattedAmount == null && allInputsAmount != unlockedBalance)) { ((formattedAmount != null && allInputsAmount < (formattedAmount + estimatedFee)) ||
formattedAmount == null)) {
throw MoneroTransactionNoInputsException(inputs.length); throw MoneroTransactionNoInputsException(inputs.length);
} }
@ -327,10 +314,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
try { try {
// -- rename the waller folder -- // -- rename the waller folder --
final currentWalletDir = final currentWalletDir = Directory(await pathForWalletDir(name: name, type: type));
Directory(await pathForWalletDir(name: name, type: type)); final newWalletDirPath = await pathForWalletDir(name: newWalletName, type: type);
final newWalletDirPath =
await pathForWalletDir(name: newWalletName, type: type);
await currentWalletDir.rename(newWalletDirPath); await currentWalletDir.rename(newWalletDirPath);
// -- use new waller folder to rename files with old names still -- // -- use new waller folder to rename files with old names still --
@ -340,8 +325,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final currentKeysFile = File('$renamedWalletPath.keys'); final currentKeysFile = File('$renamedWalletPath.keys');
final currentAddressListFile = File('$renamedWalletPath.address.txt'); final currentAddressListFile = File('$renamedWalletPath.address.txt');
final newWalletPath = final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await pathForWallet(name: newWalletName, type: type);
if (currentCacheFile.existsSync()) { if (currentCacheFile.existsSync()) {
await currentCacheFile.rename(newWalletPath); await currentCacheFile.rename(newWalletPath);
@ -359,8 +343,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final currentKeysFile = File('$currentWalletPath.keys'); final currentKeysFile = File('$currentWalletPath.keys');
final currentAddressListFile = File('$currentWalletPath.address.txt'); final currentAddressListFile = File('$currentWalletPath.address.txt');
final newWalletPath = final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await pathForWallet(name: newWalletName, type: type);
// Copies current wallet files into new wallet name's dir and files // Copies current wallet files into new wallet name's dir and files
if (currentCacheFile.existsSync()) { if (currentCacheFile.existsSync()) {
@ -426,8 +409,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
if (unspentCoins.isNotEmpty) { if (unspentCoins.isNotEmpty) {
unspentCoins.forEach((coin) { unspentCoins.forEach((coin) {
final coinInfoList = unspentCoinsInfo.values.where((element) => final coinInfoList = unspentCoinsInfo.values
element.walletId.contains(id) && element.hash.contains(coin.hash)); .where((element) => element.walletId.contains(id) && element.hash.contains(coin.hash));
if (coinInfoList.isNotEmpty) { if (coinInfoList.isNotEmpty) {
final coinInfo = coinInfoList.first; final coinInfo = coinInfoList.first;
@ -447,16 +430,15 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> _addCoinInfo(MoneroUnspent coin) async { Future<void> _addCoinInfo(MoneroUnspent coin) async {
final newInfo = UnspentCoinsInfo( final newInfo = UnspentCoinsInfo(
walletId: id, walletId: id,
hash: coin.hash, hash: coin.hash,
isFrozen: coin.isFrozen, isFrozen: coin.isFrozen,
isSending: coin.isSending, isSending: coin.isSending,
noteRaw: coin.note, noteRaw: coin.note,
address: coin.address, address: coin.address,
value: coin.value, value: coin.value,
vout: 0, vout: 0,
keyImage: coin.keyImage keyImage: coin.keyImage);
);
await unspentCoinsInfo.add(newInfo); await unspentCoinsInfo.add(newInfo);
} }
@ -464,8 +446,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> _refreshUnspentCoinsInfo() async { Future<void> _refreshUnspentCoinsInfo() async {
try { try {
final List<dynamic> keys = <dynamic>[]; final List<dynamic> keys = <dynamic>[];
final currentWalletUnspentCoins = unspentCoinsInfo.values final currentWalletUnspentCoins =
.where((element) => element.walletId.contains(id)); unspentCoinsInfo.values.where((element) => element.walletId.contains(id));
if (currentWalletUnspentCoins.isNotEmpty) { if (currentWalletUnspentCoins.isNotEmpty) {
currentWalletUnspentCoins.forEach((element) { currentWalletUnspentCoins.forEach((element) {
@ -486,16 +468,14 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
String getTransactionAddress(int accountIndex, int addressIndex) => String getTransactionAddress(int accountIndex, int addressIndex) =>
monero_wallet.getAddress( monero_wallet.getAddress(accountIndex: accountIndex, addressIndex: addressIndex);
accountIndex: accountIndex,
addressIndex: addressIndex);
@override @override
Future<Map<String, MoneroTransactionInfo>> fetchTransactions() async { Future<Map<String, MoneroTransactionInfo>> fetchTransactions() async {
transaction_history.refreshTransactions(); transaction_history.refreshTransactions();
return _getAllTransactionsOfAccount(walletAddresses.account?.id).fold<Map<String, MoneroTransactionInfo>>( return _getAllTransactionsOfAccount(walletAddresses.account?.id)
<String, MoneroTransactionInfo>{}, .fold<Map<String, MoneroTransactionInfo>>(<String, MoneroTransactionInfo>{},
(Map<String, MoneroTransactionInfo> acc, MoneroTransactionInfo tx) { (Map<String, MoneroTransactionInfo> acc, MoneroTransactionInfo tx) {
acc[tx.id] = tx; acc[tx.id] = tx;
return acc; return acc;
}); });
@ -523,12 +503,11 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
return monero_wallet.getSubaddressLabel(accountIndex, addressIndex); return monero_wallet.getSubaddressLabel(accountIndex, addressIndex);
} }
List<MoneroTransactionInfo> _getAllTransactionsOfAccount(int? accountIndex) => List<MoneroTransactionInfo> _getAllTransactionsOfAccount(int? accountIndex) => transaction_history
transaction_history .getAllTransactions()
.getAllTransactions() .map((row) => MoneroTransactionInfo.fromRow(row))
.map((row) => MoneroTransactionInfo.fromRow(row)) .where((element) => element.accountIndex == (accountIndex ?? 0))
.where((element) => element.accountIndex == (accountIndex ?? 0)) .toList();
.toList();
void _setListeners() { void _setListeners() {
_listener?.stop(); _listener?.stop();
@ -550,8 +529,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
int _getHeightDistance(DateTime date) { int _getHeightDistance(DateTime date) {
final distance = final distance = DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
final daysTmp = (distance / 86400).round(); final daysTmp = (distance / 86400).round();
final days = daysTmp < 1 ? 1 : daysTmp; final days = daysTmp < 1 ? 1 : daysTmp;
@ -582,11 +560,9 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
} }
Future<void> _askForUpdateTransactionHistory() async => Future<void> _askForUpdateTransactionHistory() async => await updateTransactions();
await updateTransactions();
int _getFullBalance() => int _getFullBalance() => monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
int _getUnlockedBalance() => int _getUnlockedBalance() =>
monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
@ -595,8 +571,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
var frozenBalance = 0; var frozenBalance = 0;
for (var coin in unspentCoinsInfo.values) { for (var coin in unspentCoinsInfo.values) {
if (coin.isFrozen) if (coin.isFrozen) frozenBalance += coin.value;
frozenBalance += coin.value;
} }
return frozenBalance; return frozenBalance;
@ -617,9 +592,9 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
syncStatus = SyncedSyncStatus(); syncStatus = SyncedSyncStatus();
if (!_hasSyncAfterStartup) { if (!_hasSyncAfterStartup) {
_hasSyncAfterStartup = true; _hasSyncAfterStartup = true;
await save(); await save();
} }
if (walletInfo.isRecovery) { if (walletInfo.isRecovery) {
await setAsRecovered(); await setAsRecovered();
@ -644,12 +619,12 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
void _updateSubAddress(bool enableAutoGenerate, {Account? account}) { void _updateSubAddress(bool enableAutoGenerate, {Account? account}) {
if (enableAutoGenerate) { if (enableAutoGenerate) {
walletAddresses.updateUnusedSubaddress( walletAddresses.updateUnusedSubaddress(
accountIndex: account?.id ?? 0, accountIndex: account?.id ?? 0,
defaultLabel: account?.label ?? '', defaultLabel: account?.label ?? '',
); );
} else { } else {
walletAddresses.updateSubaddressList(accountIndex: account?.id ?? 0); walletAddresses.updateSubaddressList(accountIndex: account?.id ?? 0);
} }
} }
} }