mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-10-26 06:08:40 +01:00
* 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>
569 lines
18 KiB
Dart
569 lines
18 KiB
Dart
import 'package:cake_wallet/bitcoin/bitcoin.dart';
|
|
import 'package:cake_wallet/core/utilities.dart';
|
|
import 'package:cake_wallet/entities/balance_display_mode.dart';
|
|
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
|
|
import 'package:cake_wallet/entities/fiat_api_mode.dart';
|
|
import 'package:cake_wallet/entities/fiat_currency.dart';
|
|
import 'package:cake_wallet/entities/sort_balance_types.dart';
|
|
import 'package:cake_wallet/generated/i18n.dart';
|
|
import 'package:cake_wallet/reactions/wallet_connect.dart';
|
|
import 'package:cake_wallet/evm/evm.dart';
|
|
import 'package:cake_wallet/solana/solana.dart';
|
|
import 'package:cake_wallet/tron/tron.dart';
|
|
import 'package:cake_wallet/zano/zano.dart';
|
|
import 'package:cw_core/amount/money.dart';
|
|
import 'package:cw_core/crypto_amount_format.dart';
|
|
import 'package:cw_core/transaction_history.dart';
|
|
import 'package:cw_core/utils/print_verbose.dart';
|
|
import 'package:cw_core/wallet_base.dart';
|
|
import 'package:cake_wallet/store/app_store.dart';
|
|
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
|
|
import 'package:cake_wallet/store/settings_store.dart';
|
|
import 'package:cw_core/balance.dart';
|
|
import 'package:cw_core/crypto_currency.dart';
|
|
import 'package:cw_core/erc20_token.dart';
|
|
import 'package:cw_core/spl_token.dart';
|
|
import 'package:cw_core/transaction_info.dart';
|
|
import 'package:cw_core/wallet_type.dart';
|
|
import 'package:mobx/mobx.dart';
|
|
|
|
part 'balance_view_model.g.dart';
|
|
|
|
class BalanceRecord {
|
|
const BalanceRecord({
|
|
required this.raw,
|
|
required this.availableBalance,
|
|
required this.additionalBalance,
|
|
required this.secondAvailableBalance,
|
|
required this.secondAdditionalBalance,
|
|
required this.frozenBalance,
|
|
required this.fiatAvailableBalanceRaw,
|
|
required this.fiatAdditionalBalanceRaw,
|
|
required this.fiatFrozenBalanceRaw,
|
|
required this.fiatSecondAvailableBalanceRaw,
|
|
required this.fiatSecondAdditionalBalanceRaw,
|
|
required this.asset,
|
|
required this.secondAsset,
|
|
required this.fiatCurrency,
|
|
required this.formattedAssetTitle,
|
|
this.languageCode,
|
|
});
|
|
|
|
final Balance raw;
|
|
|
|
final String fiatAvailableBalanceRaw;
|
|
final String fiatAdditionalBalanceRaw;
|
|
final String fiatFrozenBalanceRaw;
|
|
final String fiatSecondAvailableBalanceRaw;
|
|
final String fiatSecondAdditionalBalanceRaw;
|
|
|
|
final String additionalBalance;
|
|
final String availableBalance;
|
|
final String frozenBalance;
|
|
final String secondAvailableBalance;
|
|
final String secondAdditionalBalance;
|
|
final CryptoCurrency asset;
|
|
final CryptoCurrency secondAsset;
|
|
final FiatCurrency? fiatCurrency;
|
|
final String formattedAssetTitle;
|
|
final String? languageCode;
|
|
|
|
String get combinedAvailableBalance =>
|
|
(raw.available + (raw.secondAvailable ?? Money.zero(raw.available.currency)))
|
|
.toString()
|
|
.withMaxDecimals(8);
|
|
|
|
String get combinedFiatAvailableBalance => fiatCurrency != null
|
|
? "$fiatCurrency " +
|
|
_withLocalSeperator(((double.tryParse(fiatAvailableBalanceRaw) ?? 0) +
|
|
(double.tryParse(fiatSecondAvailableBalanceRaw) ?? 0))
|
|
.toStringAsFixed(2))
|
|
: "";
|
|
|
|
String get fiatAvailableBalance =>
|
|
fiatCurrency != null ? "$fiatCurrency ${_withLocalSeperator(fiatAvailableBalanceRaw)}" : "";
|
|
|
|
String get fiatAdditionalBalance =>
|
|
fiatCurrency != null ? "$fiatCurrency ${_withLocalSeperator(fiatAdditionalBalanceRaw)}" : "";
|
|
|
|
String get fiatFrozenBalance =>
|
|
fiatCurrency != null ? "$fiatCurrency ${_withLocalSeperator(fiatFrozenBalanceRaw)}" : "";
|
|
|
|
String get fiatSecondAvailableBalance => fiatCurrency != null
|
|
? "$fiatCurrency ${_withLocalSeperator(fiatSecondAvailableBalanceRaw)}"
|
|
: "";
|
|
|
|
String get fiatSecondAdditionalBalance => fiatCurrency != null
|
|
? "$fiatCurrency ${_withLocalSeperator(fiatSecondAdditionalBalanceRaw)}"
|
|
: "";
|
|
|
|
String _withLocalSeperator(String rawAmount) =>
|
|
languageCode == null ? rawAmount : rawAmount.withLocalSeperator(languageCode);
|
|
}
|
|
|
|
class BalanceViewModel = BalanceViewModelBase with _$BalanceViewModel;
|
|
|
|
abstract class BalanceViewModelBase with Store {
|
|
BalanceViewModelBase(
|
|
{required this.appStore, required this.settingsStore, required this.fiatConversionStore})
|
|
: isReversing = false,
|
|
isShowCard = appStore.wallet?.walletInfo.isShowIntroCakePayCard ?? false,
|
|
wallet = appStore.wallet! {
|
|
reaction((_) => appStore.wallet, (wallet) {
|
|
_onWalletChange(wallet);
|
|
_checkMweb();
|
|
});
|
|
|
|
_checkMweb();
|
|
|
|
reaction((_) => settingsStore.mwebAlwaysScan, (_) => _checkMweb());
|
|
}
|
|
|
|
void _checkMweb() {
|
|
if (wallet.type == WalletType.litecoin) {
|
|
mwebEnabled = bitcoin!.getMwebEnabled(wallet);
|
|
}
|
|
}
|
|
|
|
final AppStore appStore;
|
|
final SettingsStore settingsStore;
|
|
final FiatConversionStore fiatConversionStore;
|
|
|
|
@observable
|
|
bool isReversing;
|
|
|
|
@observable
|
|
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> wallet;
|
|
|
|
@computed
|
|
double get price {
|
|
final price = fiatConversionStore.prices[appStore.wallet!.currency];
|
|
|
|
// price should update on next fetch:
|
|
if (price == null) return 0;
|
|
|
|
return price;
|
|
}
|
|
|
|
@computed
|
|
BalanceDisplayMode get savedDisplayMode => settingsStore.balanceDisplayMode;
|
|
|
|
@computed
|
|
bool get isFiatDisabled => settingsStore.fiatApiMode == FiatApiMode.disabled;
|
|
|
|
@computed
|
|
bool get isHomeScreenSettingsEnabled =>
|
|
isEVMCompatibleChain(wallet.type) ||
|
|
[WalletType.solana, WalletType.tron, WalletType.zano].contains(wallet.type);
|
|
|
|
@computed
|
|
bool get isEVMCompatible => isEVMCompatibleChain(wallet.type);
|
|
|
|
@computed
|
|
bool get hasAccounts => [WalletType.monero, WalletType.wownero].contains(wallet.type);
|
|
|
|
@computed
|
|
SortBalanceBy get sortBalanceBy => settingsStore.sortBalanceBy;
|
|
|
|
@computed
|
|
bool get pinNativeToken => settingsStore.pinNativeTokenAtTop;
|
|
|
|
@computed
|
|
String get asset {
|
|
if (isEVMCompatibleChain(wallet.type)) {
|
|
final currentChain = evm!.getCurrentChain(wallet);
|
|
if (currentChain != null) {
|
|
return currentChain.name;
|
|
}
|
|
|
|
return walletTypeToString(wallet.type);
|
|
}
|
|
|
|
final typeFormatted = walletTypeToString(wallet.type);
|
|
|
|
switch (wallet.type) {
|
|
case WalletType.haven:
|
|
return '$typeFormatted Assets';
|
|
default:
|
|
return typeFormatted;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
BalanceDisplayMode get displayMode {
|
|
if (isReversing) {
|
|
if (savedDisplayMode == BalanceDisplayMode.hiddenBalance) {
|
|
return BalanceDisplayMode.displayableBalance;
|
|
} else {
|
|
return BalanceDisplayMode.hiddenBalance;
|
|
}
|
|
}
|
|
|
|
return savedDisplayMode;
|
|
}
|
|
|
|
@computed
|
|
String get availableBalanceLabel {
|
|
if (displayMode == BalanceDisplayMode.hiddenBalance) {
|
|
return S.current.show_balance;
|
|
} else {
|
|
return S.current.xmr_available_balance;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
String get additionalBalanceLabel {
|
|
switch (wallet.type) {
|
|
case WalletType.haven:
|
|
case WalletType.ethereum:
|
|
case WalletType.polygon:
|
|
case WalletType.base:
|
|
case WalletType.arbitrum:
|
|
case WalletType.bsc:
|
|
case WalletType.solana:
|
|
case WalletType.tron:
|
|
return S.current.xmr_full_balance;
|
|
case WalletType.nano:
|
|
case WalletType.banano:
|
|
return S.current.receivable_balance;
|
|
default:
|
|
return S.current.unconfirmed;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
String get secondAvailableBalanceLabel {
|
|
switch (wallet.type) {
|
|
case WalletType.litecoin:
|
|
return S.current.mweb_confirmed;
|
|
default:
|
|
return S.current.confirmed;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
String get secondAdditionalBalanceLabel {
|
|
switch (wallet.type) {
|
|
case WalletType.litecoin:
|
|
return S.current.mweb_unconfirmed;
|
|
default:
|
|
return S.current.unconfirmed;
|
|
}
|
|
}
|
|
|
|
Money additionalBalance(CryptoCurrency cryptoCurrency) {
|
|
final balance = _currencyBalance(cryptoCurrency);
|
|
|
|
if (displayMode == BalanceDisplayMode.hiddenBalance || balance.unavailable.isZero)
|
|
return Money.zero(cryptoCurrency);
|
|
|
|
return balance.unavailable;
|
|
}
|
|
|
|
@computed
|
|
Map<CryptoCurrency, BalanceRecord> get balances {
|
|
return wallet.balance.map((key, value) {
|
|
var secondAsset = key == CryptoCurrency.ltc ? CryptoCurrency.ltcmweb : key;
|
|
|
|
if (displayMode == BalanceDisplayMode.hiddenBalance) {
|
|
final fiatCurrency = settingsStore.fiatCurrency;
|
|
return MapEntry(
|
|
key,
|
|
BalanceRecord(
|
|
raw: value,
|
|
availableBalance: '●●●●●●',
|
|
additionalBalance: '',
|
|
frozenBalance: '',
|
|
secondAvailableBalance: '●●●●●●',
|
|
secondAdditionalBalance: '●●●●●●',
|
|
fiatAdditionalBalanceRaw: '●●●●●',
|
|
fiatAvailableBalanceRaw: '●●●●●',
|
|
fiatFrozenBalanceRaw: '',
|
|
fiatSecondAvailableBalanceRaw: '●●●●●',
|
|
fiatSecondAdditionalBalanceRaw: '●●●●●',
|
|
asset: key,
|
|
secondAsset: secondAsset,
|
|
fiatCurrency: isFiatDisabled ? null : fiatCurrency,
|
|
formattedAssetTitle: _formatterAsset(key),
|
|
),
|
|
);
|
|
}
|
|
final price = key.isPotentialScam
|
|
? 0.0
|
|
: fiatConversionStore.prices[key == CryptoCurrency.btcln ? CryptoCurrency.btc : key] ?? 0;
|
|
|
|
// if (price == null) {
|
|
// throw Exception('Price is null for: $key');
|
|
// }
|
|
|
|
final availableFiatBalance =
|
|
isFiatDisabled ? '' : _getFiatBalance(price: price, cryptoAmount: value.available);
|
|
|
|
final additionalFiatBalance =
|
|
isFiatDisabled ? '' : _getFiatBalance(price: price, cryptoAmount: value.unavailable);
|
|
|
|
final frozenFiatBalance =
|
|
isFiatDisabled ? '' : _getFiatBalance(price: price, cryptoAmount: value.frozen);
|
|
|
|
final secondAvailableFiatBalance =
|
|
isFiatDisabled ? '' : _getFiatBalance(price: price, cryptoAmount: value.secondAvailable);
|
|
|
|
final secondAdditionalFiatBalance = isFiatDisabled
|
|
? ''
|
|
: _getFiatBalance(price: price, cryptoAmount: value.secondUnavailable);
|
|
|
|
return MapEntry(
|
|
key,
|
|
BalanceRecord(
|
|
raw: value,
|
|
availableBalance: _getFormattedCryptoAmount(value.available),
|
|
fiatAvailableBalanceRaw: availableFiatBalance,
|
|
additionalBalance: _getFormattedCryptoAmount(value.unavailable),
|
|
fiatAdditionalBalanceRaw: additionalFiatBalance,
|
|
frozenBalance: _getFormattedCryptoAmount(value.frozen),
|
|
fiatFrozenBalanceRaw: frozenFiatBalance,
|
|
secondAvailableBalance: _getFormattedCryptoAmount(value.secondAvailable),
|
|
fiatSecondAvailableBalanceRaw: secondAvailableFiatBalance,
|
|
secondAdditionalBalance: _getFormattedCryptoAmount(value.secondUnavailable),
|
|
fiatSecondAdditionalBalanceRaw: secondAdditionalFiatBalance,
|
|
asset: key,
|
|
secondAsset: secondAsset,
|
|
fiatCurrency: isFiatDisabled ? null : settingsStore.fiatCurrency,
|
|
formattedAssetTitle: _formatterAsset(key),
|
|
languageCode: settingsStore.languageCode,
|
|
),
|
|
);
|
|
});
|
|
}
|
|
|
|
@observable
|
|
bool mwebEnabled = false;
|
|
|
|
bool hasAdditionalBalance(CryptoCurrency currency) {
|
|
final isWalletTypeActivated = _hasAdditionalBalanceForWalletType(wallet.type);
|
|
final isNotZeroAmount = !additionalBalance(currency).isZero;
|
|
|
|
return isWalletTypeActivated && isNotZeroAmount;
|
|
}
|
|
|
|
@computed
|
|
bool get hasSecondAdditionalBalance {
|
|
if (wallet.type == WalletType.litecoin && mwebEnabled) {
|
|
return (wallet.balance[CryptoCurrency.ltc]?.secondUnavailable ?? 0) != 0;
|
|
} else if (wallet.type == WalletType.bitcoin) {
|
|
return (wallet.balance[CryptoCurrency.btc]?.secondUnavailable ?? 0) != 0;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
@computed
|
|
bool get hasSecondAvailableBalance {
|
|
switch (wallet.type) {
|
|
case WalletType.bitcoin:
|
|
return true;
|
|
case WalletType.litecoin:
|
|
return mwebEnabled;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
bool _hasAdditionalBalanceForWalletType(WalletType type) => [
|
|
WalletType.monero,
|
|
WalletType.wownero,
|
|
WalletType.zano,
|
|
WalletType.decred,
|
|
WalletType.zcash
|
|
].contains(type);
|
|
|
|
String _getFormattedCryptoAmount(Money? amount) {
|
|
if (amount == null) return "";
|
|
|
|
return appStore.amountParsingProxy
|
|
.asDisplayString(amount)
|
|
.withLocalSeperator(settingsStore.languageCode);
|
|
}
|
|
|
|
@computed
|
|
List<BalanceRecord> get formattedBalances {
|
|
final balance = balances.values.toList();
|
|
|
|
balance.sort((BalanceRecord a, BalanceRecord b) {
|
|
if (wallet.currency == CryptoCurrency.xhv) {
|
|
if (b.asset == CryptoCurrency.xhv) return 1;
|
|
|
|
if (b.asset == CryptoCurrency.xusd) {
|
|
if (a.asset == CryptoCurrency.xhv) return -1;
|
|
return 1;
|
|
}
|
|
|
|
if (b.asset == CryptoCurrency.xbtc) return 1;
|
|
if (b.asset == CryptoCurrency.xeur) return 1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
if (pinNativeToken) {
|
|
if (b.asset == wallet.currency) return 1;
|
|
if (a.asset == wallet.currency) return -1;
|
|
}
|
|
|
|
final isTokenWallet = isEVMCompatibleChain(wallet.type) || wallet.type == WalletType.solana;
|
|
|
|
if (isTokenWallet) {
|
|
final aIsToken = a.asset is Erc20Token || a.asset is SPLToken;
|
|
final bIsToken = b.asset is Erc20Token || b.asset is SPLToken;
|
|
|
|
final aHasBalance = (double.tryParse(a.availableBalance) ?? 0) > 0;
|
|
final bHasBalance = (double.tryParse(b.availableBalance) ?? 0) > 0;
|
|
|
|
// Adding this so tokens with balance come before tokens without balance
|
|
if (aIsToken && bIsToken) {
|
|
if (aHasBalance && !bHasBalance) return -1;
|
|
if (!aHasBalance && bHasBalance) return 1;
|
|
}
|
|
}
|
|
|
|
switch (sortBalanceBy) {
|
|
case SortBalanceBy.FiatBalance:
|
|
final aFiatBalance = _getFiatBalance(
|
|
price: fiatConversionStore.prices[a.asset] ?? 0, cryptoAmount: a.raw.available);
|
|
final bFiatBalance = _getFiatBalance(
|
|
price: fiatConversionStore.prices[b.asset] ?? 0, cryptoAmount: b.raw.available);
|
|
|
|
return (double.tryParse(bFiatBalance) ?? 0)
|
|
.compareTo((double.tryParse(aFiatBalance)) ?? 0);
|
|
case SortBalanceBy.GrossBalance:
|
|
return (double.tryParse(b.availableBalance) ?? 0)
|
|
.compareTo(double.tryParse(a.availableBalance) ?? 0);
|
|
case SortBalanceBy.Alphabetical:
|
|
return a.asset.title.compareTo(b.asset.title);
|
|
}
|
|
});
|
|
|
|
return balance;
|
|
}
|
|
|
|
BalanceRecord? getMainBalanceRecord(bool lightningMode) {
|
|
if (lightningMode) {
|
|
return formattedBalances.elementAtOrNull(1);
|
|
}
|
|
|
|
if (wallet.walletInfo.favoriteTokenAddress != null) {
|
|
return formattedBalances.firstWhereOrNull((item) =>
|
|
(getTokenAddressBasedOnWallet(item.asset) ==
|
|
wallet.walletInfo.favoriteTokenAddress)) ??
|
|
formattedBalances.elementAtOrNull(0);
|
|
}
|
|
|
|
return formattedBalances.elementAtOrNull(0);
|
|
}
|
|
|
|
String? getTokenAddressBasedOnWallet(CryptoCurrency asset) {
|
|
if (wallet.type == WalletType.tron) {
|
|
return tron!.getTokenAddress(asset);
|
|
}
|
|
|
|
if (wallet.type == WalletType.solana) {
|
|
return solana!.getTokenAddress(asset);
|
|
}
|
|
|
|
if (isEVMCompatibleChain(wallet.type) && asset is Erc20Token) {
|
|
return evm!.getTokenAddress(asset);
|
|
}
|
|
|
|
if (wallet.type == WalletType.zano) {
|
|
return zano!.getZanoAssetAddress(asset);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
@computed
|
|
bool get showCombinedBalance {
|
|
if (wallet.type == WalletType.bitcoin) return false;
|
|
if (balances.values.length == 1) return false;
|
|
|
|
return wallet.walletInfo.showCombinedBalance;
|
|
}
|
|
|
|
@computed
|
|
String get combinedFiatBalance {
|
|
if (displayMode == BalanceDisplayMode.hiddenBalance) {
|
|
return "●●●●●";
|
|
}
|
|
|
|
double ret = 0.0;
|
|
for (final curr in wallet.balance.keys) {
|
|
final record = wallet.balance[curr]!;
|
|
final available = record.available - (record.secondAvailable ?? Money.zero(curr));
|
|
final price = fiatConversionStore.prices[curr] ?? 0;
|
|
printV(record.available);
|
|
ret += double.tryParse(calculateFiatAmount(price: price, cryptoAmount: available.toString())
|
|
.replaceAll(",", "")) ??
|
|
0;
|
|
}
|
|
return ret.toStringAsFixed(2).withLocalSeperator(settingsStore.languageCode);
|
|
}
|
|
|
|
Balance _currencyBalance(CryptoCurrency cryptoCurrency) {
|
|
final balance = wallet.balance[cryptoCurrency];
|
|
|
|
if (balance == null) throw Exception('No balance for ${wallet.currency}');
|
|
|
|
return balance;
|
|
}
|
|
|
|
@observable
|
|
bool isShowCard;
|
|
|
|
ReactionDisposer? _onCurrentWalletChangeReaction;
|
|
|
|
@action
|
|
void _onWalletChange(
|
|
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo>? wallet) {
|
|
if (wallet == null) return;
|
|
|
|
this.wallet = wallet;
|
|
_onCurrentWalletChangeReaction?.reaction.dispose();
|
|
isShowCard = wallet.walletInfo.isShowIntroCakePayCard;
|
|
}
|
|
|
|
@action
|
|
Future<void> disableIntroCakePayCard() async {
|
|
const cardDisplayStatus = false;
|
|
wallet.walletInfo.showIntroCakePayCard = cardDisplayStatus;
|
|
await wallet.walletInfo.save();
|
|
isShowCard = cardDisplayStatus;
|
|
}
|
|
|
|
@action
|
|
void switchBalanceValue() {
|
|
if (settingsStore.balanceDisplayMode == BalanceDisplayMode.displayableBalance) {
|
|
settingsStore.balanceDisplayMode = BalanceDisplayMode.hiddenBalance;
|
|
settingsStore.balanceHideCounter++;
|
|
} else {
|
|
settingsStore.balanceDisplayMode = BalanceDisplayMode.displayableBalance;
|
|
}
|
|
}
|
|
|
|
String _getFiatBalance({required double price, Money? cryptoAmount}) {
|
|
if (cryptoAmount == null) {
|
|
return '0.00';
|
|
}
|
|
|
|
return calculateFiatAmount(price: price, cryptoAmount: cryptoAmount.toString(), raw: true);
|
|
}
|
|
|
|
String _formatterAsset(CryptoCurrency asset) {
|
|
final assetString = asset.toString();
|
|
if (wallet.type == WalletType.haven &&
|
|
asset != CryptoCurrency.xhv &&
|
|
assetString[0].toUpperCase() == 'X') {
|
|
return assetString.replaceFirst('X', 'x');
|
|
}
|
|
|
|
return appStore.amountParsingProxy.getCryptoSymbol(asset);
|
|
}
|
|
}
|