Files
hash-wallet/cw_monero/lib/api/wallet.dart
T
75f3fe735b Introduce Money class and refactor currency handling (#3157)
* feat: add `Money` class for precise currency handling and amount parsing

- Introduced `Money` class for handling money values with fixed-point precision.
- Added parsing and comparison methods to `CryptoCurrency` and `FiatCurrency` interfaces.
- Implemented `smartAmountSanitizer` for format normalization.

Includes extensive unit tests for validation.

* refactor: optimize Money class with new factories and string formatting improvements

* refactor: unify balance handling with `Money` refactor

* refactor: update `ElectrumBalance` and transaction logic to use `Money` for currency precision

* refactor: standardize balance handling with `Money` across `Monero`, `Wownero`, and `Zano` wallets

* refactor: migrate EVM balance and transaction handling to `Money` for consistent currency precision

* refactor: migrate Decred balance and transaction handling to `Money` for consistent currency precision

* refactor: migrate nano balance and transaction handling to `Money` for consistent currency precision

* refactor: migrate Solana balance and transaction logic to `Money` for precise currency handling

* refactor: migrate Tron balance and transaction handling to `Money` for consistent currency precision

* refactor: migrate Zcash balance and transaction handling to `Money` for consistent currency precision

* refactor: adjust lib to handle money

* refactor: remove legacy Decred amount formatting and migrate to `Money`

* refactor: migrate pending transaction amount and fee to `Money`

* refactor: migrate dEuro savings and transaction logic to `Money` for improved precision and consistency

* refactor: migrate Bitcoin and lightning transaction logic to `Money` for consistent currency precision

* refactor: migrate Wownero, EVM, Zano, and Zcash transaction logic to `Money` for consistent and precise currency handling

* refactor: standardize balance handling across wallets, migrate to `Money.zero` and refine `Balance` class for consistency

* refactor: migrate Solana transaction and wallet logic to `Money` for consistent and precise currency handling

* refactor: improve fiat balance and formatting for consistency on dashboard

* fix: fiat input mode switching and standardize crypto amount display logic

* fix: cw_evm generator

* refactor: migrate exchange amount handling to `Money` for improved precision and consistency

* test: remove redundant and commented-out tests, tidy test cases, and apply minor formatting adjustments

* fix using Money wrapper in BridgeViewModel and USDT0Service

* refactor: streamline `AmountConverter` and `LightningWallet`, add `cw_core` tests to GitHub workflow, and remove unused/deprecated logic

* refactor: enhance `changeReceiveAmount` with `isCanonical` support, improve null handling, and refine amount parsing logic

* minor fix

* try/catch the lightning log file error

* feat: add copy-to-clipboard functionality for transaction amounts, fix typo in trailing widget method name (#3219)

* Cw 1234 disallow sp and mweb addresses as refund for swaps (#3187)

* disallow SP and MWEB for swaps

* Simplify address selection in addressForExchange

Refactor addressForExchange method to simplify address selection logic.

* validate refund and receive address types

* localize address validation messages

* minor ui fix [skip ci]

* minor fix [skip ci]

* Revert "localize address validation messages"

* fix translations

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* refactor: replace manual amount sanitization with `sanitized()` extension across the codebase, add unit tests for `AmountSanitizer`

* fix: correct `sanitized()` test expectations for decimal handling in `amount_sanitizer_test.dart`

* refactor: fee display logic and append currency symbol in `send_confirm_sheet.dart`

* refactor: simplify `ZcashBalance` class by replacing custom fields with inherited properties, update references accordingly

* refactor: replace hardcoded USDT contract address with `DefaultTronTokens` lookup, improve maintainability

* refactor: replace `currency` with `inputAmount.currency` in Solana transaction signing methods to avoid inconsistency

* fix: handle null `fee` in `electrum_transaction_info.dart` to prevent potential runtime errors

* refactor: replace raw fee and amount handling with `Money` object for improved consistency and maintainability

* fix: limit fiat balance display to 2 decimal places in `balance_view_model.dart`

* refactor: replace raw `amount` and `fee` types with `Money` in Solana transaction methods for consistency and precision

* refactor: replace raw `amount` and `fee` handling with `Money` and improve balance calculation consistency across view models

* refactor: replace raw balance strings with `Money` and simplify `UnconfirmedBalanceModal` widget logic

* refactor: replace `print` with `printV` for better logging, add equality and hashCode overrides to `ERC20Currency` for object comparison

* feat: prepare deuro savings migration

* feat: add V1 savings migration support and improve formatting consistency in DEuro view model

* feat: add V1 savings withdrawal support and update associated UI components and logic

* refactor: replace `Image.asset` with `CakeImageWidget`, update balance string handling, and streamline address validation logic

* refactor: use `Money.tryParse` with fallback to `Money.zero` in `NanoBalance.fromRawString` for safer balance parsing

* refactor: replace `ERC20Currency` with `Erc20Token` for consistency and remove unused `evm_erc20_currency.dart` file

* refactor: add computed `hasDepositAmount` for deposit null-checks, optimize balance handling in `zano_wallet`, update Breez SDK to v0.14.0, and implement equality/hashCode for `Currency`

* refactor: rename `amountSats` to `amount` in `PrepareLnurlPayRequest` for consistency

* revert: downgrade Breez SDK to v0.11.0 in `pubspec.yaml` and update relevant references in `pubspec.lock`

* fix: use `cryptoAmount.copyWith` for currency consistency and replace `Image.asset` with `CakeImageWidget` in swap address modal

* fix: ensure currency consistency by using `cryptoAmount.copyWith` in Solana and EVM wallet transactions

* refactor: simplify CSV row generation logic by removing `_splitAmountCurrency` and streamlining amount/fee handling

* fix: LateInitializationError Field 'sdk' has not been initialized

* fix: use `Money.tryParse` for safer parsing of deposit and receive amounts

* chore: remove debug print statement

* refactor: update transaction processing to consistently use `Money` for amounts and fees

* refactor: improve currency and amount handling, simplify logic, and enhance code readability in Send and Swap pages

* refactor: integrate `DecimalInputFormatter` for consistent decimal input across Send and Swap pages, simplify input handling logic

* fix: "fiatMode" per output on sendPage

* refactor: make transaction_details_height applicable more readable

* fix: use correct base unit for deposit

* refactor: use Money in estimateFakeSendAllTxAmount method

* fix decred frozen balance
minor fixes

* fix decred frozen balance
minor fixes

* fix: automatically switch to lightning if lnurl or invoice detected

* fix: getBolt11Amount test cases

* fix: standardise crypto amount formatting and display

* fix: use base unit for Tron transaction fee parsing
* refactor: hardcode fractional digits to 8 in `AmountParsingProxy` display methods
* refactor: ensure consistent 8-decimal precision for fee formatting in `PendingTransaction`
* fix: use `AmountParsingProxy` for available balance display in exchange view model
* fix: improve amount formatting and layout in swap and send confirmation sheets
* chore: remove redundant decimal truncation in balance view model and send confirmation sheet

* fix: allow for editing text field if it is filled with "ALL"

* fix: allow for editing text field if it is filled with "ALL"

* fix: update currency detection logic for lightning mode

* avoid potential infinite loop [skip ci]

* fix: getDisplayCryptoAmount

* fix: update estimated fee calculation

* chore: simplify fee calculation logic [skip-ci]

* fix value display in hidden mode

* fix stale state in send confirm sheet

* fix decimals for mweb

* fix available balance display for sol/trx on swap

* restore proper hint text

* fix swap receive amount calculation for xno

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
Co-authored-by: Serhii <17529954+serhii-bor@users.noreply.github.com>
Co-authored-by: Robert Malikowski <malikowskirobert@gmail.com>
2026-06-30 02:45:44 +03:00

439 lines
13 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:isolate';
import 'dart:math';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/setup_wallet_exception.dart';
import 'package:cw_monero/api/get_all_unspent.dart';
import 'package:monero/monero.dart' as monero;
import 'package:mutex/mutex.dart';
import 'package:polyseed/polyseed.dart';
bool debugMonero = false;
int getSyncingHeight() {
// final height = monero.MONERO_cw_WalletListener_height(getWlptr());
if (currentWallet == null) return 0;
final h2 = currentWallet!.blockChainHeight();
// printV("height: $height / $h2");
return h2;
}
bool isNeededToRefresh() {
final wl = getWlptr();
if (wl == null) return false;
final ret = wl.isNeedToRefresh();
wl.resetNeedToRefresh();
return ret;
}
bool isNewTransactionExist() {
final wlptr = getWlptr();
if (wlptr == null) return false;
final ret = wlptr.isNewTransactionExist();
wlptr.resetIsNewTransactionExist();
return ret;
}
String getFilename() => currentWallet!.filename();
String getSeed() {
// monero.Wallet_setCacheAttribute(wptr!, key: "cakewallet.seed", value: seed);
final cakepolyseed =
currentWallet!.getCacheAttribute(key: "cakewallet.seed");
final cakepassphrase = getPassphrase();
final weirdPolyseed = currentWallet!.getPolyseed(passphrase: cakepassphrase);
if (weirdPolyseed != "") return weirdPolyseed;
if (cakepolyseed != "") {
if (cakepassphrase != "") {
try {
final lang = PolyseedLang.getByPhrase(cakepolyseed);
final coin = PolyseedCoin.POLYSEED_MONERO;
final ps = Polyseed.decode(cakepolyseed, lang, coin);
if (ps.isEncrypted || cakepassphrase == "") return ps.encode(lang, coin);
ps.crypt(cakepassphrase);
return ps.encode(lang, coin);
} catch (e) {
printV(e);
}
}
return cakepolyseed;
}
final bip39 = currentWallet!.getCacheAttribute(key: "cakewallet.seed.bip39");
if(bip39.isNotEmpty) return bip39;
final legacy = getSeedLegacy(null);
return legacy;
}
String? getSeedLanguage(String? language) {
switch (language) {
case "Chinese (Traditional)": language = "Chinese (simplified)"; break;
case "Chinese (Simplified)": language = "Chinese (simplified)"; break;
case "Korean": language = "English"; break;
case "Czech": language = "English"; break;
case "Japanese": language = "English"; break;
}
return language;
}
String getSeedLegacy(String? language) {
final cakepassphrase = getPassphrase();
language = getSeedLanguage(language);
var legacy = currentWallet!.seed(seedOffset: cakepassphrase);
if (currentWallet!.status() != 0) {
if (currentWallet!.errorString().contains("seed_language")) {
currentWallet!.setSeedLanguage(language: "English");
legacy = currentWallet!.seed(seedOffset: cakepassphrase);
}
}
if (language != null) {
currentWallet!.setSeedLanguage(language: language);
final status = currentWallet!.status();
if (status != 0) {
final err = currentWallet!.errorString();
if (legacy.isNotEmpty) {
return "$err\n\n$legacy";
}
return err;
}
legacy = currentWallet!.seed(seedOffset: cakepassphrase);
}
if (currentWallet!.status() != 0) {
final err = currentWallet!.errorString();
if (legacy.isNotEmpty) {
return "$err\n\n$legacy";
}
return err;
}
return legacy;
}
String getPassphrase() => currentWallet?.getCacheAttribute(key: "cakewallet.passphrase") ?? "";
Map<int, Map<int, Map<int, String>>> addressCache = {};
String getAddress({int accountIndex = 0, int addressIndex = 0}) {
// this is a workaround for when we switch the wallet pointer,
// it should never reach UI but should be good enough to prevent gray screen
// or other errors because of forced null check.
if (currentWallet == null) return "<wallet not ready ($accountIndex:$addressIndex)>";
// printV("getaddress: ${accountIndex}/${addressIndex}: ${monero.Wallet_numSubaddresses(wptr!, accountIndex: accountIndex)}: ${monero.Wallet_address(wptr!, accountIndex: accountIndex, addressIndex: addressIndex)}");
// this could be a while loop, but I'm in favor of making it if to not cause freezes
if (currentWallet!.numSubaddresses(accountIndex: accountIndex)-1 < addressIndex) {
if (currentWallet!.numSubaddressAccounts() < accountIndex) {
currentWallet!.addSubaddressAccount();
} else {
currentWallet!.addSubaddress(accountIndex: accountIndex);
}
}
addressCache[currentWallet!.ffiAddress()] ??= {};
addressCache[currentWallet!.ffiAddress()]![accountIndex] ??= {};
addressCache[currentWallet!.ffiAddress()]![accountIndex]![addressIndex] ??= currentWallet!.address(
accountIndex: accountIndex, addressIndex: addressIndex);
return addressCache[currentWallet!.ffiAddress()]![accountIndex]![addressIndex]!;
}
Money getFullBalance({int accountIndex = 0}) =>
Money.fromInt(currentWallet?.balance(accountIndex: accountIndex) ?? 0, CryptoCurrency.xmr);
Money getUnlockedBalance({int accountIndex = 0}) => Money.fromInt(
currentWallet?.unlockedBalance(accountIndex: accountIndex) ?? 0, CryptoCurrency.xmr);
int getCurrentHeight() => currentWallet?.blockChainHeight() ?? 0;
int cachedNodeHeight = 0;
bool isHeightRefreshing = false;
int getNodeHeightSync() {
if (isHeightRefreshing == false) {
if (cachedNodeHeight != 0 && getWlptr()?.height() == 1) {
return cachedNodeHeight;
}
(() async {
try {
isHeightRefreshing = true;
final wptrAddress = currentWallet!.ffiAddress();
cachedNodeHeight = await Isolate.run(() async {
return monero.Wallet_daemonBlockChainHeight(Pointer.fromAddress(wptrAddress));
});
} catch (_) {
} finally {
isHeightRefreshing = false;
}
})();
}
return cachedNodeHeight;
}
Future<bool> isConnected() async {
final wptrAddress = currentWallet!.ffiAddress();
return await Isolate.run(() => monero.Wallet_connected(Pointer.fromAddress(wptrAddress))) == 1;
}
Future<bool> setupNodeSync(
{required String address,
String? login,
String? password,
bool useSSL = false,
bool isLightWallet = false,
String? socksProxyAddress}) async {
printV('''
{
wptr!,
daemonAddress: $address,
useSsl: $useSSL,
proxyAddress: $socksProxyAddress ?? '',
daemonUsername: $login ?? '',
daemonPassword: $password ?? ''
}
''');
final addr = currentWallet!.ffiAddress();
printV("init: start");
await Isolate.run(() {
monero.Wallet_init(Pointer.fromAddress(addr),
daemonAddress: address,
useSsl: useSSL,
proxyAddress: socksProxyAddress ?? '',
daemonUsername: login ?? '',
daemonPassword: password ?? '');
});
printV("init: end");
final status = currentWallet!.status();
if (status != 0) {
final error = currentWallet!.errorString();
if (error != "no tx keys found for this txid") {
printV("error: $error");
throw SetupWalletException(message: error);
}
}
if (true) {
currentWallet!.init3(
argv0: '',
defaultLogBaseName: 'moneroc',
console: true,
logPath: '',
);
}
return status == 0;
}
void startRefreshSync() {
currentWallet!.startRefresh();
}
void setRefreshFromBlockHeight({required int height}) {
currentWallet!.setRefreshFromBlockHeight(
refresh_from_block_height: height);
}
void setRecoveringFromSeed({required bool isRecovery}) {
currentWallet!.setRecoveringFromSeed(recoveringFromSeed: isRecovery);
currentWallet!.store();
}
final storeMutex = Mutex();
int lastStorePointer = 0;
int lastStoreHeight = 0;
void storeSync({bool force = false}) async {
final addr = currentWallet!.ffiAddress();
final synchronized = await Isolate.run(() {
return monero.Wallet_synchronized(Pointer.fromAddress(addr));
});
if (lastStorePointer == addr &&
lastStoreHeight + 75000 > currentWallet!.blockChainHeight() &&
!synchronized &&
!force) {
return;
}
lastStorePointer = currentWallet!.ffiAddress();
lastStoreHeight = currentWallet!.blockChainHeight();
await storeMutex.acquire();
await Isolate.run(() {
monero.Wallet_store(Pointer.fromAddress(addr));
});
storeMutex.release();
}
void setPasswordSync(String password) {
currentWallet!.setPassword(password: password);
final status = currentWallet!.status();
if (status != 0) {
throw Exception(currentWallet!.errorString());
}
}
void closeCurrentWallet() {
currentWallet!.stop();
}
String getSecretViewKey() => currentWallet?.secretViewKey() ?? "";
String getPublicViewKey() => currentWallet?.publicViewKey() ?? "";
String getSecretSpendKey() => currentWallet?.secretSpendKey() ?? "";
String getPublicSpendKey() => currentWallet?.publicSpendKey() ?? "";
class SyncListener {
SyncListener(this.onNewBlock, this.onNewTransaction)
: _cachedBlockchainHeight = 0,
_lastKnownBlockHeight = 0,
_initialSyncHeight = 0 {
_start();
}
void Function(int, int, double) onNewBlock;
void Function() onNewTransaction;
Timer? _updateSyncInfoTimer;
int _cachedBlockchainHeight;
int _lastKnownBlockHeight;
int _initialSyncHeight;
Future<int> getNodeHeightOrUpdate(int baseHeight) async {
if (_cachedBlockchainHeight < baseHeight || _cachedBlockchainHeight == 0) {
_cachedBlockchainHeight = await getNodeHeight();
}
return _cachedBlockchainHeight;
}
void _start() {
_cachedBlockchainHeight = 0;
_lastKnownBlockHeight = 0;
_initialSyncHeight = 0;
_updateSyncInfoTimer ??=
Timer.periodic(Duration(milliseconds: 1200), (_) async {
if (isNewTransactionExist()) {
onNewTransaction();
}
var syncHeight = getSyncingHeight();
if (syncHeight <= 0) {
syncHeight = getCurrentHeight();
}
if (_initialSyncHeight <= 0) {
_initialSyncHeight = syncHeight;
}
// in case when node didn't report new height yet
// it is a workaround for moving height request to another isolate
final nodeHeight = await getNodeHeightOrUpdate(syncHeight);
if (nodeHeight == 0) {
return;
}
final bchHeight = max(nodeHeight, syncHeight);
// printV("syncHeight: $syncHeight, _lastKnownBlockHeight: $_lastKnownBlockHeight, bchHeight: $bchHeight");
if (_lastKnownBlockHeight == syncHeight) {
return;
}
_lastKnownBlockHeight = syncHeight;
final track = bchHeight - _initialSyncHeight;
final diff = track - (bchHeight - syncHeight);
final ptc = diff <= 0 ? 0.0 : diff / track;
final left = bchHeight - syncHeight;
if ((syncHeight < 0 || left < 0)) {
printV("not calling onNewBlock: syncHeight: $syncHeight, left: $left");
return;
}
// 1. Actual new height; 2. Blocks left to finish; 3. Progress in percents;
onNewBlock.call(syncHeight, left, ptc);
});
}
void stop() => _updateSyncInfoTimer?.cancel();
}
SyncListener setListeners(void Function(int, int, double) onNewBlock,
void Function() onNewTransaction) {
final listener = SyncListener(onNewBlock, onNewTransaction);
// setListenerNative();
return listener;
}
void onStartup() {}
void _storeSync(Object _) => storeSync();
Future<bool> _setupNodeSync(Map<String, Object?> args) async {
final address = args['address'] as String;
final login = (args['login'] ?? '') as String;
final password = (args['password'] ?? '') as String;
final useSSL = args['useSSL'] as bool;
final isLightWallet = args['isLightWallet'] as bool;
final socksProxyAddress = (args['socksProxyAddress'] ?? '') as String;
return setupNodeSync(
address: address,
login: login,
password: password,
useSSL: useSSL,
isLightWallet: isLightWallet,
socksProxyAddress: socksProxyAddress);
}
void startRefresh() => startRefreshSync();
Future<void> store() async => _storeSync(0);
Future<int> getNodeHeight() async => getNodeHeightSync();
void rescanBlockchainAsync() => currentWallet!.rescanBlockchainAsync();
String getSubaddressLabel(int accountIndex, int addressIndex) {
return currentWallet!.getSubaddressLabel(
accountIndex: accountIndex, addressIndex: addressIndex);
}
Future setTrustedDaemon(bool trusted) async =>
currentWallet!.setTrustedDaemon(arg: trusted);
Future<bool> trustedDaemon() async => currentWallet!.trustedDaemon();
String signMessage(String message, {String address = ""}) =>
currentWallet!.signMessage(message: message, address: address);
bool verifyMessage(String message, String address, String signature) =>
currentWallet!.verifySignedMessage(message: message, address: address, signature: signature);
Map<String, List<int>> debugCallLength() => monero.debugCallLength;
Map<String, dynamic> getWalletCacheDebug() {
try {
final jsonString = monero.MONERO_Wallet_serializeCacheToJson(Pointer.fromAddress(currentWallet!.ffiAddress()));
final blob = json.decode(jsonString);
blob['cake:unspent'] = getAllUnspent();
return blob;
} catch (e) {
return {
"error": e.toString(),
};
}
}