[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; 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( MoneroWalletBase(
{required WalletInfo walletInfo, {required WalletInfo walletInfo,
required Box<UnspentCoinsInfo> unspentCoinsInfo, required Box<UnspentCoinsInfo> unspentCoinsInfo,
@ -71,16 +71,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
transactionHistory = MoneroTransactionHistory(); transactionHistory = MoneroTransactionHistory();
walletAddresses = MoneroWalletAddresses(walletInfo, transactionHistory); walletAddresses = MoneroWalletAddresses(walletInfo, transactionHistory);
_onAccountChangeReaction = _onAccountChangeReaction = reaction((_) => walletAddresses.account, (Account? account) {
reaction((_) => walletAddresses.account, (Account? account) {
if (account == null) return; if (account == null) return;
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
MoneroBalance>{
currency: MoneroBalance( currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance(accountIndex: account.id), fullBalance: monero_wallet.getFullBalance(accountIndex: account.id),
unlockedBalance: unlockedBalance: monero_wallet.getUnlockedBalance(accountIndex: account.id))
monero_wallet.getUnlockedBalance(accountIndex: account.id))
}); });
_updateSubAddress(isEnabledAutoGenerateSubaddress, account: account); _updateSubAddress(isEnabledAutoGenerateSubaddress, account: account);
_askForUpdateTransactionHistory(); _askForUpdateTransactionHistory();
@ -135,7 +132,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
passphrase: monero_wallet.getPassphrase()); passphrase: monero_wallet.getPassphrase());
int? get restoreHeight => 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; monero_wallet.SyncListener? _listener;
ReactionDisposer? _onAccountChangeReaction; ReactionDisposer? _onAccountChangeReaction;
@ -148,13 +146,11 @@ 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(<CryptoCurrency, balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
MoneroBalance>{
currency: MoneroBalance( currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance( fullBalance: monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id),
accountIndex: walletAddresses.account!.id), unlockedBalance:
unlockedBalance: monero_wallet.getUnlockedBalance( monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id))
accountIndex: walletAddresses.account!.id))
}); });
_setListeners(); _setListeners();
await updateTransactions(); await updateTransactions();
@ -163,15 +159,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), (_) async => await save()); Timer.periodic(Duration(seconds: _autoSaveInterval), (_) async => await save());
// update transaction details after restore // update transaction details after restore
walletAddresses.subaddressList.update(accountIndex: walletAddresses.account?.id??0); walletAddresses.subaddressList.update(accountIndex: walletAddresses.account?.id ?? 0);
} }
@override @override
@ -274,9 +269,9 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
// viewOnlyBalance - balance that we can spend // viewOnlyBalance - balance that we can spend
// TODO(mrcyjanek): remove hasUnknownKeyImages when we cleanup coin control // TODO(mrcyjanek): remove hasUnknownKeyImages when we cleanup coin control
return (monero.Wallet_viewOnlyBalance(wptr!, return (monero.Wallet_viewOnlyBalance(wptr!, accountIndex: walletAddresses.account!.id) <
accountIndex: walletAddresses.account!.id) < amount) || amount) ||
monero.Wallet_hasUnknownKeyImages(wptr!); monero.Wallet_hasUnknownKeyImages(wptr!);
} }
@override @override
@ -285,8 +280,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final inputs = <String>[]; final inputs = <String>[];
final outputs = _credentials.outputs; final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1; final hasMultiDestination = outputs.length > 1;
final unlockedBalance = monero_wallet.getUnlockedBalance( final unlockedBalance =
accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
PendingTransactionDescription pendingTransactionDescription; PendingTransactionDescription pendingTransactionDescription;
@ -305,44 +300,35 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
if (hasMultiDestination) { if (hasMultiDestination) {
if (outputs.any( if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
(item) => item.sendAll || (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( final int totalAmount =
0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)); outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
if (unlockedBalance < totalAmount) { if (unlockedBalance < totalAmount) {
throw MoneroTransactionCreationException( throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
'You do not have enough XMR to send this amount.');
} }
if (inputs.isEmpty) MoneroTransactionCreationException( if (inputs.isEmpty) MoneroTransactionCreationException('No inputs selected');
'No inputs selected');
final moneroOutputs = outputs.map((output) { final moneroOutputs = outputs.map((output) {
final outputAddress = final outputAddress = output.isParsedAddress ? output.extractedAddress : output.address;
output.isParsedAddress ? 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 = final address = output.isParsedAddress ? output.extractedAddress : output.address;
output.isParsedAddress ? output.extractedAddress : output.address; final amount = output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
final amount =
output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
// if ((formattedAmount != null && unlockedBalance < formattedAmount) || // if ((formattedAmount != null && unlockedBalance < formattedAmount) ||
// (formattedAmount == null && unlockedBalance <= 0)) { // (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}.'); // 'You do not have enough unlocked balance. Unlocked: $formattedBalance. Transaction amount: ${output.cryptoAmount}.');
// } // }
if (inputs.isEmpty) MoneroTransactionCreationException( if (inputs.isEmpty) MoneroTransactionCreationException('No inputs selected');
'No inputs selected'); pendingTransactionDescription = await transaction_history.createTransaction(
pendingTransactionDescription = address: address!,
await transaction_history.createTransaction( amount: amount,
address: address!, priorityRaw: _credentials.priority.serialize(),
amount: amount, accountIndex: walletAddresses.account!.id,
priorityRaw: _credentials.priority.serialize(), preferredInputs: inputs);
accountIndex: walletAddresses.account!.id,
preferredInputs: inputs);
} }
// final status = monero.PendingTransaction_status(pendingTransactionDescription); // final status = monero.PendingTransaction_status(pendingTransactionDescription);
@ -426,43 +410,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
printV("wallet closed"); printV("wallet closed");
} }
try { 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 currentWalletPath = await pathForWallet(name: name, type: type);
final currentCacheFile = File(currentWalletPath); final currentCacheFile = File(currentWalletPath);
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()) {
@ -477,12 +431,37 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
// Delete old name's dir and files // Delete old name's dir and files
await Directory(currentWalletDirPath).delete(recursive: true); 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 @override
Future<void> changePassword(String password) async => Future<void> changePassword(String password) async => monero_wallet.setPasswordSync(password);
monero_wallet.setPasswordSync(password);
Future<int> getNodeHeight() async => monero_wallet.getNodeHeight(); Future<int> getNodeHeight() async => monero_wallet.getNodeHeight();
@ -517,7 +496,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
for (var i = 0; i < coinCount; i++) { for (var i = 0; i < coinCount; i++) {
final coin = getCoin(i); final coin = getCoin(i);
final coinSpent = monero.CoinsInfo_spent(coin); 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( final unspent = MoneroUnspent(
monero.CoinsInfo_address(coin), monero.CoinsInfo_address(coin),
monero.CoinsInfo_hash(coin), monero.CoinsInfo_hash(coin),
@ -590,15 +570,13 @@ 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.where( final currentWalletUnspentCoins = unspentCoinsInfo.values.where((element) =>
(element) => element.walletId.contains(id) && element.accountIndex == walletAddresses.account!.id);
element.walletId.contains(id) &&
element.accountIndex == walletAddresses.account!.id);
if (currentWalletUnspentCoins.isNotEmpty) { if (currentWalletUnspentCoins.isNotEmpty) {
currentWalletUnspentCoins.forEach((element) { currentWalletUnspentCoins.forEach((element) {
final existUnspentCoins = unspentCoins final existUnspentCoins =
.where((coin) => element.keyImage!.contains(coin.keyImage!)); unspentCoins.where((coin) => element.keyImage!.contains(coin.keyImage!));
if (existUnspentCoins.isEmpty) { if (existUnspentCoins.isEmpty) {
keys.add(element.key); keys.add(element.key);
@ -615,15 +593,13 @@ 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 (await _getAllTransactionsOfAccount(walletAddresses.account?.id)) return (await _getAllTransactionsOfAccount(walletAddresses.account?.id))
.fold<Map<String, MoneroTransactionInfo>>( .fold<Map<String, MoneroTransactionInfo>>(<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;
@ -652,15 +628,12 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
monero_wallet.getSubaddressLabel(accountIndex, addressIndex); monero_wallet.getSubaddressLabel(accountIndex, addressIndex);
Future<List<MoneroTransactionInfo>> _getAllTransactionsOfAccount(int? accountIndex) async => Future<List<MoneroTransactionInfo>> _getAllTransactionsOfAccount(int? accountIndex) async =>
(await transaction_history (await transaction_history.getAllTransactions())
.getAllTransactions())
.map( .map(
(row) => MoneroTransactionInfo( (row) => MoneroTransactionInfo(
row.hash, row.hash,
row.blockheight, row.blockheight,
row.isSpend row.isSpend ? TransactionDirection.outgoing : TransactionDirection.incoming,
? TransactionDirection.outgoing
: TransactionDirection.incoming,
row.timeStamp, row.timeStamp,
row.isPending, row.isPending,
row.amount, row.amount,
@ -709,8 +682,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;
@ -731,24 +703,20 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
void _askForUpdateBalance() { void _askForUpdateBalance() {
final unlockedBalance = _getUnlockedBalance(); final unlockedBalance = _getUnlockedBalance();
final fullBalance = monero_wallet.getFullBalance( final fullBalance = monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
accountIndex: walletAddresses.account!.id);
final frozenBalance = _getFrozenBalance(); final frozenBalance = _getFrozenBalance();
if (balance[currency]!.fullBalance != fullBalance || if (balance[currency]!.fullBalance != fullBalance ||
balance[currency]!.unlockedBalance != unlockedBalance || balance[currency]!.unlockedBalance != unlockedBalance ||
balance[currency]!.frozenBalance != frozenBalance) { balance[currency]!.frozenBalance != frozenBalance) {
balance[currency] = MoneroBalance( balance[currency] = MoneroBalance(
fullBalance: fullBalance, fullBalance: fullBalance, unlockedBalance: unlockedBalance, frozenBalance: frozenBalance);
unlockedBalance: unlockedBalance,
frozenBalance: frozenBalance);
} }
} }
Future<void> _askForUpdateTransactionHistory() async => Future<void> _askForUpdateTransactionHistory() async => await updateTransactions();
await updateTransactions();
int _getUnlockedBalance() => monero_wallet.getUnlockedBalance( int _getUnlockedBalance() =>
accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
int _getFrozenBalance() { int _getFrozenBalance() {
var frozenBalance = 0; var frozenBalance = 0;
@ -829,8 +797,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
void setLedgerConnection(LedgerConnection connection) { void setLedgerConnection(LedgerConnection connection) {
final dummyWPtr = wptr ?? final dummyWPtr = wptr ?? monero.WalletManager_openWallet(wmPtr, path: '', password: '');
monero.WalletManager_openWallet(wmPtr, path: '', password: '');
enableLedgerExchange(dummyWPtr, connection); enableLedgerExchange(dummyWPtr, connection);
} }
} }