Merge branch 'main' into CW-855-Transactions-not-cleared-correctly-when-switching-wallets

This commit is contained in:
Serhii
2025-03-05 17:13:55 +02:00
70 changed files with 954 additions and 659 deletions
+1 -1
View File
@@ -310,7 +310,7 @@ class DFXBuyProvider extends BuyProvider {
final accessToken = await auth(cryptoCurrencyAddress);
final uri = Uri.https('services.dfx.swiss', actionType, {
final uri = Uri.https('app.dfx.swiss', actionType, {
'session': accessToken,
'lang': 'en',
'asset-out': isBuyAction ? quote.cryptoCurrency.toString() : quote.fiatCurrency.toString(),
@@ -59,7 +59,7 @@ class RobinhoodBuyProvider extends BuyProvider {
case WalletType.bitcoinCash:
return await wallet.signMessage(message, address: wallet.walletAddresses.address);
default:
throw Exception("WalletType is not available for Robinhood ${wallet.type}");
throw Exception("Wallet Type ${wallet.type.name} is not available for Robinhood");
}
}
+3
View File
@@ -281,6 +281,9 @@ class AddressValidator extends TextValidator {
}
}
static String get silentPaymentAddressPattern => SilentPaymentAddress.regex.pattern;
static String get mWebAddressPattern => MwebAddress.regex.pattern;
static String? getAddressFromStringPattern(CryptoCurrency type) {
String? pattern = null;
+2 -2
View File
@@ -1256,7 +1256,7 @@ Future<void> setup({
getIt.registerFactoryParam<OrderDetailsPage, Order, void>(
(Order order, _) => OrderDetailsPage(getIt.get<OrderDetailsViewModel>(param1: order)));
getIt.registerFactory(() => SupportViewModel());
getIt.registerFactory(() => SupportViewModel(getIt.get<SettingsStore>()));
getIt.registerFactory(() => SupportPage(getIt.get<SupportViewModel>()));
@@ -1418,4 +1418,4 @@ Future<void> setup({
getIt.registerFactory(() => SeedVerificationPage(getIt.get<WalletSeedViewModel>()));
_isSetupFinished = true;
}
}
+24 -26
View File
@@ -1,5 +1,6 @@
import 'package:basic_utils/basic_utils.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/widgets/alert_with_picker_option.dart';
import 'package:cake_wallet/src/widgets/picker.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -100,44 +101,41 @@ class Bip353Record {
Map<String, String> addressMap,
) async {
final entriesList = addressMap.entries.toList();
final displayItems = entriesList.map((e) {
final extendedKeyName = keyDisplayMap[e.key] ?? e.key;
final truncatedValue = _truncate(e.value, front: 6, back: 6);
return '$extendedKeyName : $truncatedValue';
final List<Map<String, String>> displayItems = entriesList.map((entry) {
final originalKey = entry.key;
final originalValue = entry.value;
final extendedKeyName = keyDisplayMap[originalKey] ?? originalKey;
final truncatedValue = _truncate(originalValue, front: 6, back: 6);
return {
'displayKey': extendedKeyName,
'displayValue': truncatedValue,
'originalKey': originalKey,
'originalValue': originalValue,
};
}).toList();
String? selectedDisplayItem;
String? selectedOriginalValue;
if (context.mounted) {
await showPopUp<void>(
context: context,
builder: (dialogContext) {
return Picker<String>(
selectedAtIndex: 0,
title:
'$bip353Name \n was successfully resolved to the following addresses, please choose one:',
items: displayItems,
onItemSelected: (String displayItem) {
selectedDisplayItem = displayItem;
return AlertWithPickerOption(
alertTitle: S.of(context).multiple_addresses_detected + '\n$bip353Name',
alertTitleTextSize: 14,
alertSubtitle: S.of(context).please_choose_one + ':',
options: displayItems,
onOptionSelected: (Map<String, String> chosenItem) {
selectedOriginalValue = chosenItem['originalValue'];
},
alertBarrierDismissible: true,
);
},
);
}
if (selectedDisplayItem == null) {
if (displayItems.isEmpty) {
return null;
}
selectedDisplayItem = displayItems[0];
}
final index = displayItems.indexOf(selectedDisplayItem!);
if (index < 0) {
return null;
}
return entriesList[index].value;
return selectedOriginalValue;
}
static String _truncate(String value, {int front = 6, int back = 6}) {
@@ -32,33 +32,56 @@ class AddressResolver {
static const unstoppableDomains = [
"888",
"academy",
"agency",
"altimist",
"anime",
"austin",
"bald",
"bay",
"benji",
"bet",
"binanceus",
"bitcoin",
"bitget",
"bitscrunch",
"blockchain",
"boomer",
"boston",
"ca",
"caw",
"cc",
"chat",
"chomp",
"clay",
"club",
"co",
"com",
"company",
"crypto",
"dao",
"design",
"dfz",
"digital",
"doga",
"donut",
"dream",
"email",
"emir",
"eth",
"ethermail",
"family",
"farms",
"finance",
"fun",
"fyi",
"games",
"global",
"go",
"group",
"guru",
"hi",
"hockey",
"host",
"info",
"io",
@@ -68,43 +91,78 @@ class AddressResolver {
"lfg",
"life",
"live",
"llc",
"ltc",
"ltd",
"manga",
"me",
"media",
"metropolis",
"miami",
"miku",
"money",
"moon",
"mumu",
"net",
"network",
"news",
"nft",
"npc",
"onchain",
"online",
"org",
"podcast",
"pog",
"polygon",
"press",
"privacy",
"pro",
"propykeys",
"pudgy",
"pw",
"quantum",
"rad",
"raiin",
"retardio",
"rip",
"rocks",
"secret",
"services",
"site",
"smobler",
"social",
"solutions",
"space",
"stepn",
"store",
"studio",
"systems",
"tball",
"tea",
"team",
"tech",
"technology",
"today",
"tribe",
"u",
"ubu",
"uno",
"unstoppable",
"vip",
"wallet",
"website",
"wif",
"wifi",
"witg",
"work",
"world",
"wrkx",
"wtf",
"x",
"xmr",
"xyz",
"zil",
"zone"
];
static String? extractAddressByType({required String raw, required CryptoCurrency type}) {
+5
View File
@@ -209,4 +209,9 @@ class CWEthereum extends Ethereum {
throw err;
}
}
@override
List<String> getDefaultTokenContractAddresses() {
return DefaultEthereumErc20Tokens().initialErc20Tokens.map((e) => e.contractAddress).toList();
}
}
+5
View File
@@ -208,4 +208,9 @@ class CWPolygon extends Polygon {
throw err;
}
}
@override
List<String> getDefaultTokenContractAddresses() {
return DefaultPolygonErc20Tokens().initialPolygonErc20Tokens.map((e) => e.contractAddress).toList();
}
}
+4 -1
View File
@@ -60,9 +60,12 @@ Future<void> startFiatRateUpdate(
tron!.getTronTokenCurrencies(appStore.wallet!).where((element) => element.enabled);
}
if (currencies != null) {
for (final currency in currencies) {
// skip potential scams:
if (currency.isPotentialScam) {
continue;
}
() async {
fiatConversionStore.prices[currency] = await FiatConversionService.fetchPrice(
crypto: currency,
+5
View File
@@ -154,4 +154,9 @@ class CWSolana extends Solana {
double? getEstimateFees(WalletBase wallet) {
return (wallet as SolanaWallet).estimatedFee;
}
@override
List<String> getDefaultTokenContractAddresses() {
return DefaultSPLTokens().initialSPLTokens.map((e) => e.mintAddress).toList();
}
}
+21 -3
View File
@@ -211,6 +211,21 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
.checkIfERC20TokenContractAddressIsAPotentialScamAddress(
_contractAddressController.text,
);
final isWhitelisted = await widget.homeSettingsViewModel
.checkIfTokenIsWhitelisted(_contractAddressController.text);
bool isPotentialScam = hasPotentialError;
final tokenSymbol = _tokenSymbolController.text.toUpperCase();
// check if the token symbol is the same as any of the base currencies symbols (ETH, SOL, POL, TRX, etc):
// if it is, then it's probably a scam unless it's in the whitelist
final baseCurrencySymbols =
CryptoCurrency.all.map((e) => e.title.toUpperCase()).toList();
if (baseCurrencySymbols.contains(tokenSymbol) && !isWhitelisted) {
isPotentialScam = true;
}
final actionCall = () async {
try {
await widget.homeSettingsViewModel.addToken(
@@ -219,6 +234,7 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
title: _tokenSymbolController.text.toUpperCase(),
decimals: int.parse(_tokenDecimalController.text),
iconPath: _tokenIconPathController.text,
isPotentialScam: isPotentialScam,
),
contractAddress: _contractAddressController.text,
);
@@ -226,7 +242,6 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
if (mounted) {
Navigator.pop(context);
}
} catch (e) {
showPopUp<void>(
context: context,
@@ -303,7 +318,8 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
if (token != null) {
final isZano = widget.homeSettingsViewModel.walletType == WalletType.zano;
if (_tokenNameController.text.isEmpty || isZano) _tokenNameController.text = token.name;
if (_tokenSymbolController.text.isEmpty || isZano) _tokenSymbolController.text = token.title;
if (_tokenSymbolController.text.isEmpty || isZano)
_tokenSymbolController.text = token.title;
if (_tokenIconPathController.text.isEmpty)
_tokenIconPathController.text = token.iconPath ?? '';
if (_tokenDecimalController.text.isEmpty || isZano)
@@ -338,7 +354,9 @@ class _EditTokenPageBodyState extends State<EditTokenPageBody> {
placeholder: S.of(context).token_contract_address,
options: [AddressTextFieldOption.paste],
buttonColor: Theme.of(context).hintColor,
validator: widget.homeSettingsViewModel.walletType == WalletType.zano ? null : AddressValidator(type: widget.homeSettingsViewModel.nativeToken).call,
validator: widget.homeSettingsViewModel.walletType == WalletType.zano
? null
: AddressValidator(type: widget.homeSettingsViewModel.nativeToken).call,
onPushPasteButton: (_) {
_pasteText();
},
@@ -18,176 +18,38 @@ class NavigationDock extends StatelessWidget {
@override
Widget build(BuildContext context) {
return dashboardViewModel.settingsStore.currentTheme.type == ThemeType.bright
? Positioned(
child: Observer(
builder: (_) {
return Container(
alignment: Alignment.bottomCenter,
height: 150,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(10),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(75),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(150),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor,
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
],
),
),
child: Container(
margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
child: Container(
height: 75,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(
color:
Theme.of(context).extension<BalancePageTheme>()!.cardBorderColor,
width: 1,
),
color: Theme.of(context)
.extension<SyncIndicatorTheme>()!
.syncedBackgroundColor,
),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: MainActions.all
.where((element) =>
element.canShow?.call(dashboardViewModel) ?? true)
.map(
(action) => Expanded(
child: Semantics(
button: true,
enabled:
(action.isEnabled?.call(dashboardViewModel) ?? true),
child: ActionButton(
key: ValueKey(
'dashboard_page_${action.name(context)}_action_button_key'),
image: Image.asset(
action.image,
height: 24,
width: 24,
color:
action.isEnabled?.call(dashboardViewModel) ?? true
? Theme.of(context)
.extension<DashboardPageTheme>()!
.mainActionsIconColor
: Theme.of(context)
.extension<BalancePageTheme>()!
.labelTextColor,
),
title: action.name(context),
onClick: () async =>
await action.onTap(context, dashboardViewModel),
textColor:
action.isEnabled?.call(dashboardViewModel) ?? true
? null
: Theme.of(context)
.extension<BalancePageTheme>()!
.labelTextColor,
),
),
),
)
.toList(),
),
),
),
),
),
),
);
},
return Positioned(
child: Observer(
builder: (_) {
return Container(
height: 150,
alignment: Alignment.bottomCenter,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: _getColors(context),
),
),
)
: Positioned(
child: Observer(
builder: (_) {
return Container(
alignment: Alignment.bottomCenter,
height: 150,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(5),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(50),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(125),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(150),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(200),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor,
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
],
),
),
child: Container(
margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
child: Container(
margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
child: Container(
height: 75,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(
color: Theme.of(context).extension<BalancePageTheme>()!.cardBorderColor,
width: 1,
),
color: Theme.of(context)
.extension<SyncIndicatorTheme>()!
.syncedBackgroundColor,
// boxShadow: [
// BoxShadow(
// color: Theme.of(context)
// .extension<BalancePageTheme>()!
// .cardBorderColor
// .withAlpha(50),
// spreadRadius: dashboardViewModel.getShadowSpread(),
// blurRadius: dashboardViewModel.getShadowBlur())
// ],
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
border: Border.all(
color: Theme.of(context).extension<BalancePageTheme>()!.cardBorderColor,
width: 1,
),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
color:
Theme.of(context).extension<SyncIndicatorTheme>()!.syncedBackgroundColor,
),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: IntrinsicHeight(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: MainActions.all
@@ -229,9 +91,57 @@ class NavigationDock extends StatelessWidget {
),
),
),
);
},
),
),
),
);
},
),
);
}
List<Color> _getColors(BuildContext context) {
final isBright = dashboardViewModel.settingsStore.currentTheme.type == ThemeType.bright;
return isBright
? <Color>[
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(10),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(75),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(150),
Theme.of(context).extension<DashboardPageTheme>()!.thirdGradientBackgroundColor,
Theme.of(context).extension<DashboardPageTheme>()!.thirdGradientBackgroundColor
]
: <Color>[
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(5),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(50),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(125),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(150),
Theme.of(context)
.extension<DashboardPageTheme>()!
.thirdGradientBackgroundColor
.withAlpha(200),
Theme.of(context).extension<DashboardPageTheme>()!.thirdGradientBackgroundColor,
Theme.of(context).extension<DashboardPageTheme>()!.thirdGradientBackgroundColor
];
}
}
@@ -31,7 +31,7 @@ class ActionButton extends StatelessWidget {
},
child: Container(
color: Colors.transparent,
padding: EdgeInsets.only(top: 5, bottom: 5, left: 0, right: 0),
padding: EdgeInsets.only(top: 5, bottom: 4, left: 0, right: 0),
alignment: alignment,
child: Column(
mainAxisSize: MainAxisSize.max,
@@ -136,7 +136,7 @@ class PinCodeState<T extends PinCodeWidget> extends State<T> {
},
child: Container(
color: Theme.of(context).colorScheme.background,
padding: EdgeInsets.only(left: 40.0, right: 40.0, bottom: 40.0),
padding: EdgeInsets.only(left: 40.0, right: 40.0, bottom: 60.0),
child: Column(
children: <Widget>[
Spacer(flex: 2),
@@ -146,7 +146,7 @@ class PinCodeState<T extends PinCodeWidget> extends State<T> {
fontWeight: FontWeight.w500,
color:
Theme.of(context).extension<CakeTextTheme>()!.titleColor)),
Spacer(flex: 3),
Spacer(flex: 8),
Container(
width: 180,
child: Row(
@@ -168,7 +168,7 @@ class PinCodeState<T extends PinCodeWidget> extends State<T> {
}),
),
),
Spacer(flex: 2),
Spacer(flex: 3),
if (widget.hasLengthSwitcher) ...[
TextButton(
onPressed: () {
@@ -204,8 +204,8 @@ class PinCodeState<T extends PinCodeWidget> extends State<T> {
childAspectRatio: _aspectRatio,
physics: const NeverScrollableScrollPhysics(),
children: List.generate(12, (index) {
const double marginRight = 15;
const double marginLeft = 15;
const double marginRight = 8;
const double marginLeft = 8;
if (index == 9) {
// Empty container
@@ -243,12 +243,12 @@ class PinCodeState<T extends PinCodeWidget> extends State<T> {
key: ValueKey('pin_code_button_${index}_key'),
onPressed: () => _push(index),
style: TextButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.background,
backgroundColor: Theme.of(context).cardColor,
shape: CircleBorder(),
),
child: Text('$index',
style: TextStyle(
fontSize: 30.0,
fontSize: 25.0,
fontWeight: FontWeight.w600,
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor)),
),
@@ -1,4 +1,3 @@
import 'dart:math';
import 'package:cake_wallet/di.dart';
@@ -21,6 +20,7 @@ import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobx/mobx.dart';
class AddressList extends StatefulWidget {
const AddressList({
@@ -37,7 +37,6 @@ class AddressList extends StatefulWidget {
}
class _AddressListState extends State<AddressList> {
bool showHiddenAddresses = false;
void _toggleHiddenAddresses() {
@@ -62,7 +61,7 @@ class _AddressListState extends State<AddressList> {
void updateItems() {
setState(() {
items = getItems(widget.addressListViewModel.items, showHiddenAddresses);
items = getItems(widget.addressListViewModel.forceRecomputeItems, showHiddenAddresses);
});
}
@@ -132,9 +131,10 @@ class _AddressListState extends State<AddressList> {
showTrailingButton: widget.addressListViewModel.showAddManualAddresses,
showSearchButton: true,
onSearchCallback: updateItems,
trailingButtonTap: () => Navigator.of(context).pushNamed(Routes.newSubaddress).then((value) {
updateItems(); // refresh the new address
}),
trailingButtonTap: () =>
Navigator.of(context).pushNamed(Routes.newSubaddress).then((value) {
updateItems(); // refresh the new address
}),
trailingIcon: Icon(
Icons.add,
size: 20,
@@ -149,7 +149,8 @@ class _AddressListState extends State<AddressList> {
cell = Container();
} else {
cell = Observer(builder: (_) {
final isCurrent = item.address == widget.addressListViewModel.address.address && editable;
final isCurrent =
item.address == widget.addressListViewModel.address.address && editable;
final backgroundColor = isCurrent
? Theme.of(context).extension<ReceivePageTheme>()!.currentTileBackgroundColor
: Theme.of(context).extension<ReceivePageTheme>()!.tilesBackgroundColor;
@@ -157,17 +158,17 @@ class _AddressListState extends State<AddressList> {
? Theme.of(context).extension<ReceivePageTheme>()!.currentTileTextColor
: Theme.of(context).extension<ReceivePageTheme>()!.tilesTextColor;
return AddressCell.fromItem(
item,
isCurrent: isCurrent,
hasBalance: widget.addressListViewModel.isBalanceAvailable,
hasReceived: widget.addressListViewModel.isReceivedAvailable,
// hasReceived:
backgroundColor: (kDebugMode && item.isHidden) ?
Theme.of(context).colorScheme.error :
(kDebugMode && item.isManual) ? Theme.of(context).colorScheme.error.withBlue(255) :
backgroundColor,
// hasReceived:
backgroundColor: (kDebugMode && item.isHidden)
? Theme.of(context).colorScheme.error
: (kDebugMode && item.isManual)
? Theme.of(context).colorScheme.error.withBlue(255)
: backgroundColor,
textColor: textColor,
onTap: (_) {
if (widget.onSelect != null) {
@@ -177,9 +178,11 @@ class _AddressListState extends State<AddressList> {
widget.addressListViewModel.setAddress(item);
},
onEdit: editable
? () => Navigator.of(context).pushNamed(Routes.newSubaddress, arguments: item).then((value) {
updateItems(); // refresh the new address
})
? () => Navigator.of(context)
.pushNamed(Routes.newSubaddress, arguments: item)
.then((value) {
updateItems(); // refresh the new address
})
: null,
isHidden: item.isHidden,
onHide: () => _hideAddress(item),
@@ -191,8 +194,8 @@ class _AddressListState extends State<AddressList> {
return index != 0
? cell
: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30), topRight: Radius.circular(30)),
borderRadius:
BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)),
child: cell,
);
},
@@ -203,5 +206,4 @@ class _AddressListState extends State<AddressList> {
await widget.addressListViewModel.toggleHideAddress(item);
updateItems();
}
}
+36
View File
@@ -1,4 +1,5 @@
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/entities/contact_record.dart';
import 'package:cake_wallet/core/execution_state.dart';
@@ -544,6 +545,10 @@ class SendPage extends BasePage {
);
newContactAddress = newContactAddress ?? sendViewModel.newContactAddress();
if (newContactAddress?.address != null && isRegularElectrumAddress(newContactAddress!.address)) {
newContactAddress = null;
}
if (sendViewModel.coinTypeToSpendFrom != UnspentCoinType.any) newContactAddress = null;
if (newContactAddress != null && sendViewModel.showAddressBookPopup) {
@@ -664,4 +669,35 @@ class SendPage extends BasePage {
),
context: context);
}
bool isRegularElectrumAddress(String address) {
final supportedTypes = [CryptoCurrency.btc, CryptoCurrency.ltc, CryptoCurrency.bch];
final excludedPatterns = [
RegExp(AddressValidator.silentPaymentAddressPattern),
RegExp(AddressValidator.mWebAddressPattern)
];
final trimmed = address.trim();
bool isValid = false;
for (var type in supportedTypes) {
final addressPattern = AddressValidator.getAddressFromStringPattern(type);
if (addressPattern != null) {
final regex = RegExp('^$addressPattern\$');
if (regex.hasMatch(trimmed)) {
isValid = true;
break;
}
}
}
for (var pattern in excludedPatterns) {
if (pattern.hasMatch(trimmed)) {
return false;
}
}
return isValid;
}
}
@@ -459,6 +459,14 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
}
});
reaction((_) => sendViewModel.selectedCryptoCurrency, (Currency currency) {
if (output.sendAll) {
output.setSendAll(sendViewModel.balance);
}
output.setCryptoAmount(cryptoAmountController.text);
});
reaction((_) => output.fiatAmount, (String amount) {
if (amount != fiatAmountController.text) {
fiatAmountController.text = amount;
@@ -20,7 +20,7 @@ class DesktopSettingsPage extends StatefulWidget {
}
class _DesktopSettingsPageState extends State<DesktopSettingsPage> {
final int itemCount = SettingActions.desktopSettings.length;
final int itemCount = SettingActions.all.length;
int? currentPage;
@@ -54,7 +54,7 @@ class _DesktopSettingsPageState extends State<DesktopSettingsPage> {
child: ListView.separated(
padding: EdgeInsets.only(top: 0),
itemBuilder: (_, index) {
final item = SettingActions.desktopSettings[index];
final item = SettingActions.all[index];
if (!widget.dashboardViewModel.hasSilentPayments &&
item.name(context) == S.of(context).silent_payments_settings) {
@@ -3,10 +3,8 @@ import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/src/screens/support_chat/widgets/chatwoot_widget.dart';
import 'package:cake_wallet/view_model/support_view_model.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:flutter/material.dart';
class SupportChatPage extends BasePage {
SupportChatPage(this.supportViewModel, {required this.secureStorage});
@@ -23,17 +21,16 @@ class SupportChatPage extends BasePage {
Widget body(BuildContext context) => FutureBuilder<String>(
future: getCookie(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
printV(snapshot.data);
if (snapshot.hasData)
return ChatwootWidget(
secureStorage,
supportUrl: supportViewModel.fetchUrl(authToken: snapshot.data!)
supportUrl: supportViewModel.fetchUrl(authToken: snapshot.data!),
appVersion: supportViewModel.appVersion,
);
return Container();
},
);
Future<String> getCookie() async {
return await secureStorage.read(key: COOKIE_KEY) ?? "";
}
Future<String> getCookie() async =>
await secureStorage.read(key: COOKIE_KEY) ?? "";
}
@@ -1,46 +1,50 @@
import 'dart:convert';
import 'package:cake_wallet/core/secure_storage.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
const COOKIE_KEY = 'chatwootCookie';
class ChatwootWidget extends StatefulWidget {
ChatwootWidget(this.secureStorage, {required this.supportUrl});
const ChatwootWidget(
this.secureStorage, {
required this.supportUrl,
required this.appVersion,
});
final SecureStorage secureStorage;
final String supportUrl;
final String appVersion;
@override
ChatwootWidgetState createState() => ChatwootWidgetState();
}
class ChatwootWidgetState extends State<ChatwootWidget> {
final GlobalKey _webViewkey = GlobalKey();
final GlobalKey _webViewKey = GlobalKey();
@override
Widget build(BuildContext context) => InAppWebView(
key: _webViewkey,
initialSettings: InAppWebViewSettings(
transparentBackground: true,
),
key: _webViewKey,
initialSettings: InAppWebViewSettings(transparentBackground: true),
initialUrlRequest: URLRequest(url: WebUri(widget.supportUrl)),
onWebViewCreated: (InAppWebViewController controller) {
controller.addWebMessageListener(
WebMessageListener(
jsObjectName: 'ReactNativeWebView',
onPostMessage: (WebMessage? message, WebUri? sourceOrigin, bool isMainFrame,
PlatformJavaScriptReplyProxy replyProxy) {
onPostMessage: (WebMessage? message, WebUri? sourceOrigin,
bool isMainFrame, PlatformJavaScriptReplyProxy replyProxy) {
final shortenedMessage = message?.data.toString().substring(16);
if (shortenedMessage != null && isJsonString(shortenedMessage)) {
if (shortenedMessage != null &&
_isJsonString(shortenedMessage)) {
final parsedMessage = jsonDecode(shortenedMessage);
final eventType = parsedMessage["event"];
if (eventType == 'loaded') {
final authToken = parsedMessage["config"]["authToken"];
printV(authToken);
storeCookie(authToken as String);
_storeCookie(authToken as String);
_setCustomAttributes(
controller, {"app_version": widget.appVersion});
}
}
},
@@ -49,7 +53,7 @@ class ChatwootWidgetState extends State<ChatwootWidget> {
},
);
bool isJsonString(String str) {
bool _isJsonString(String str) {
try {
jsonDecode(str);
} catch (e) {
@@ -58,7 +62,24 @@ class ChatwootWidgetState extends State<ChatwootWidget> {
return true;
}
Future<void> storeCookie(String value) async {
await widget.secureStorage.write(key: COOKIE_KEY, value: value);
/// Add additional contact attributes to the chatwoot chat.
/// IMPORTANT: You have to add the attribute key in the chatwoot settings
/// under: settings/custom-attributes
Future<void> _setCustomAttributes(
InAppWebViewController controller,
Map<String, dynamic> customAttributes,
) {
final attributeObject = {
"event": "set-custom-attributes",
"customAttributes": customAttributes,
};
return controller.postWebMessage(
message: WebMessage(
data: "chatwoot-widget:${jsonEncode(attributeObject)}",
),
);
}
Future<void> _storeCookie(String value) =>
widget.secureStorage.write(key: COOKIE_KEY, value: value);
}
@@ -0,0 +1,120 @@
import 'package:flutter/material.dart';
import 'package:cake_wallet/src/widgets/base_alert_dialog.dart';
import 'package:cake_wallet/themes/extensions/cake_text_theme.dart';
class AlertWithPickerOption extends BaseAlertDialog {
AlertWithPickerOption(
{required this.alertTitle,
required this.alertTitleTextSize,
required this.alertSubtitle,
required this.options,
this.onOptionSelected,
this.alertBarrierDismissible = true,
Key? key});
final String alertTitle;
final double alertTitleTextSize;
final String alertSubtitle;
final List<Map<String, String>> options;
final ValueChanged<Map<String, String>>? onOptionSelected;
final bool alertBarrierDismissible;
@override
String get titleText => alertTitle;
@override
double? get titleTextSize => alertTitleTextSize;
@override
String get contentText => alertSubtitle;
@override
bool get barrierDismissible => alertBarrierDismissible;
@override
Widget actionButtons(BuildContext context) => Container();
@override
bool get isBottomDividerExists => false;
@override
Widget content(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 16),
Text(
contentText,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
fontFamily: 'Lato',
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor,
decoration: TextDecoration.none),
),
const SizedBox(height: 4),
Container(
constraints: const BoxConstraints(maxHeight: 200),
child: ListView.separated(
shrinkWrap: true,
padding: EdgeInsets.zero,
separatorBuilder: (context, index) => const SizedBox(height: 8),
itemCount: options.length,
itemBuilder: (context, index) {
final item = options[index];
final displayKey = item['displayKey'] ?? '';
final displayValue = item['displayValue'] ?? '';
return GestureDetector(
onTap: () {
onOptionSelected?.call(item);
Navigator.of(context).pop();
},
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Theme.of(context).colorScheme.background),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
displayKey,
style: TextStyle(
fontSize: 12,
fontFamily: 'Lato',
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor,
decoration: TextDecoration.none,
),
),
Row(
children: [
Text(
displayValue,
style: TextStyle(
fontSize: 12,
fontFamily: 'Lato',
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor,
decoration: TextDecoration.none,
),
),
const SizedBox(width: 4),
Icon(
Icons.arrow_forward_ios,
size: 18,
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor,
),
],
),
],
),
),
);
},
),
),
],
);
}
}
+3 -1
View File
@@ -9,6 +9,8 @@ class BaseAlertDialog extends StatelessWidget {
String? get titleText => '';
double? get titleTextSize => 20;
String get contentText => '';
String get leftActionButtonText => '';
@@ -46,7 +48,7 @@ class BaseAlertDialog extends StatelessWidget {
titleText!,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
fontSize: titleTextSize,
fontFamily: 'Lato',
fontWeight: FontWeight.w600,
color: Theme.of(context).extension<CakeTextTheme>()!.titleColor,
+4 -14
View File
@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/routes.dart';
import 'package:flutter/material.dart';
@@ -20,20 +22,8 @@ class SettingActions {
walletSettingAction,
addressBookSettingAction,
silentPaymentsSettingAction,
litecoinMwebSettingAction,
exportOutputsAction,
securityBackupSettingAction,
privacySettingAction,
displaySettingAction,
otherSettingAction,
supportSettingAction,
];
static List<SettingActions> desktopSettings = [
connectionSettingAction,
walletSettingAction,
addressBookSettingAction,
silentPaymentsSettingAction,
if (Platform.isIOS || Platform.isAndroid) litecoinMwebSettingAction,
if (Platform.isIOS || Platform.isAndroid) exportOutputsAction,
securityBackupSettingAction,
privacySettingAction,
displaySettingAction,
+5
View File
@@ -133,4 +133,9 @@ class CWTron extends Tron {
void updateTronGridUsageState(WalletBase wallet, bool isEnabled) {
(wallet as TronWallet).updateScanProviderUsageState(isEnabled);
}
@override
List<String> getDefaultTokenContractAddresses() {
return DefaultTronTokens().initialTronTokens.map((e) => e.contractAddress).toList();
}
}
+1
View File
@@ -201,6 +201,7 @@ class ExceptionHandler {
"Connection closed before full header was received",
"Connection terminated during handshake",
"PERMISSION_NOT_GRANTED",
"OS Error: Permission denied",
"Failed host lookup:",
"CERTIFICATE_VERIFY_FAILED",
"Handshake error in client",
@@ -114,13 +114,12 @@ abstract class HomeSettingsViewModelBase with Store {
if (_balanceViewModel.wallet.type == WalletType.zano) {
await zano!.addZanoAssetById(_balanceViewModel.wallet, contractAddress);
}
_updateTokensList();
_updateFiatPrices(token);
} catch (e) {
throw e;
}
finally {
} finally {
isAddingToken = false;
}
}
@@ -189,6 +188,40 @@ abstract class HomeSettingsViewModelBase with Store {
}
}
bool checkIfTokenIsWhitelisted(String contractAddress) {
// get the default tokens for each currency type:
List<String> defaultTokenAddresses = [];
switch (_balanceViewModel.wallet.type) {
case WalletType.ethereum:
defaultTokenAddresses = ethereum!.getDefaultTokenContractAddresses();
break;
case WalletType.polygon:
defaultTokenAddresses = polygon!.getDefaultTokenContractAddresses();
break;
case WalletType.solana:
defaultTokenAddresses = solana!.getDefaultTokenContractAddresses();
break;
case WalletType.tron:
defaultTokenAddresses = tron!.getDefaultTokenContractAddresses();
break;
case WalletType.zano:
case WalletType.banano:
case WalletType.monero:
case WalletType.none:
case WalletType.bitcoin:
case WalletType.litecoin:
case WalletType.haven:
case WalletType.nano:
case WalletType.wownero:
case WalletType.bitcoinCash:
return false;
}
// check if the contractAddress is in the defaultTokenAddresses
bool isInWhitelist = defaultTokenAddresses.any((element) => element == contractAddress);
return isInWhitelist;
}
Future<bool> _isPotentialScamTokenViaMoralis(
String contractAddress,
String chainName,
@@ -363,6 +396,7 @@ abstract class HomeSettingsViewModelBase with Store {
CryptoCurrency get nativeToken => _balanceViewModel.wallet.currency;
void _updateFiatPrices(CryptoCurrency token) async {
if (token.isPotentialScam) return; // don't fetch price data for potential scam tokens
try {
_balanceViewModel.fiatConvertationStore.prices[token] =
await FiatConversionService.fetchPrice(
@@ -455,9 +489,10 @@ abstract class HomeSettingsViewModelBase with Store {
}
if (_balanceViewModel.wallet.type == WalletType.zano) {
tokens.addAll(zano!.getZanoAssets(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
tokens.addAll(zano!
.getZanoAssets(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
..sort(_sortFunc));
}
}
+8 -7
View File
@@ -102,7 +102,9 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
outputs
.add(Output(wallet, _settingsStore, _fiatConversationStore, () => selectedCryptoCurrency));
unspentCoinsListViewModel.initialSetup();
unspentCoinsListViewModel.initialSetup().then((_) {
unspentCoinsListViewModel.resetUnspentCoinsInfoSelections();
});
}
@observable
@@ -728,11 +730,10 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return S.current.insufficient_funds_for_tx;
}
return
'''${S.current.insufficient_funds_for_tx} \n\n'''
'''${S.current.balance}: ${parsedErrorMessageResult.balanceEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.balanceUsd} ${fiatFromSettings.name})\n\n'''
'''${S.current.transaction_cost}: ${parsedErrorMessageResult.txCostEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.txCostUsd} ${fiatFromSettings.name})\n\n'''
'''${S.current.overshot}: ${parsedErrorMessageResult.overshotEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.overshotUsd} ${fiatFromSettings.name})''';
return '''${S.current.insufficient_funds_for_tx} \n\n'''
'''${S.current.balance}: ${parsedErrorMessageResult.balanceEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.balanceUsd} ${fiatFromSettings.name})\n\n'''
'''${S.current.transaction_cost}: ${parsedErrorMessageResult.txCostEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.txCostUsd} ${fiatFromSettings.name})\n\n'''
'''${S.current.overshot}: ${parsedErrorMessageResult.overshotEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.overshotUsd} ${fiatFromSettings.name})''';
}
return errorMessage;
@@ -809,4 +810,4 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return false;
}
}
}
+8 -2
View File
@@ -1,16 +1,19 @@
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/view_model/settings/link_list_item.dart';
import 'package:cake_wallet/view_model/settings/settings_list_item.dart';
import 'package:cake_wallet/wallet_type_utils.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
part 'support_view_model.g.dart';
class SupportViewModel = SupportViewModelBase with _$SupportViewModel;
abstract class SupportViewModelBase with Store {
SupportViewModelBase()
final SettingsStore settingsStore;
SupportViewModelBase(this.settingsStore)
: items = [
LinkListItem(
title: 'Email',
@@ -116,5 +119,8 @@ abstract class SupportViewModelBase with Store {
return supportUrl;
}
String get appVersion =>
"${isMoneroOnly ? "Monero.com" : "Cake Wallet"} - ${settingsStore.appVersion}";
List<SettingsListItem> items;
}
@@ -68,7 +68,6 @@ abstract class UnspentCoinsListViewModelBase with Store {
bool get hasAdjustableFieldChanged => items.any(_hasAdjustableFieldChanged);
Future<void> saveUnspentCoinInfo(UnspentCoinsItem item) async {
try {
final existingInfo = _unspentCoinsInfo.values
@@ -79,7 +78,6 @@ abstract class UnspentCoinsListViewModelBase with Store {
existingInfo.isSending = item.isSending;
existingInfo.note = item.note;
await existingInfo.save();
_updateUnspentCoinsInfo();
} catch (e) {
@@ -167,6 +165,17 @@ abstract class UnspentCoinsListViewModelBase with Store {
items.addAll(unspents);
}
@action
void resetUnspentCoinsInfoSelections() {
// reset all unspent coins selections to true except frozen ones
for (final item in items) {
if (!item.isFrozen) {
item.isSending = true;
saveUnspentCoinInfo(item);
}
}
}
@action
void toggleSelectAll(bool value) {
for (final item in items) {
@@ -26,14 +26,14 @@ import 'package:cake_wallet/view_model/wallet_address_list/wallet_address_list_i
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cw_core/amount_converter.dart';
import 'package:cw_core/currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
part 'wallet_address_list_view_model.g.dart';
class WalletAddressListViewModel = WalletAddressListViewModelBase
with _$WalletAddressListViewModel;
class WalletAddressListViewModel = WalletAddressListViewModelBase with _$WalletAddressListViewModel;
abstract class PaymentURI {
PaymentURI({required this.amount, required this.address});
@@ -222,9 +222,7 @@ class ZanoURI extends PaymentURI {
}
}
abstract class WalletAddressListViewModelBase
extends WalletChangeListenerViewModel with Store {
abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewModel with Store {
WalletAddressListViewModelBase({
required AppStore appStore,
required this.yatStore,
@@ -245,8 +243,7 @@ abstract class WalletAddressListViewModelBase
_init();
selectedCurrency = walletTypeToCryptoCurrency(wallet.type);
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven]
.contains(wallet.type);
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven].contains(wallet.type);
}
static const String _cryptoNumberPattern = '0.00000000';
@@ -259,8 +256,7 @@ abstract class WalletAddressListViewModelBase
double? _fiatRate;
String _rawAmount = '';
List<Currency> get currencies =>
[walletTypeToCryptoCurrency(wallet.type), ...FiatCurrency.all];
List<Currency> get currencies => [walletTypeToCryptoCurrency(wallet.type), ...FiatCurrency.all];
String get buttonTitle {
if (isElectrumWallet) {
@@ -286,8 +282,8 @@ abstract class WalletAddressListViewModelBase
WalletType get type => wallet.type;
@computed
WalletAddressListItem get address => WalletAddressListItem(
address: wallet.walletAddresses.address, isPrimary: false);
WalletAddressListItem get address =>
WalletAddressListItem(address: wallet.walletAddresses.address, isPrimary: false);
@computed
PaymentURI get uri {
@@ -317,25 +313,23 @@ abstract class WalletAddressListViewModelBase
case WalletType.wownero:
return WowneroURI(amount: amount, address: address.address);
case WalletType.zano:
return ZanoURI(amount: amount, address: address.address);
return ZanoURI(amount: amount, address: address.address);
case WalletType.none:
throw Exception('Unexpected type: ${type.toString()}');
}
}
@computed
ObservableList<ListItem> get items => ObservableList<ListItem>()
..addAll(_baseItems)
..addAll(addressList);
@computed
ObservableList<ListItem> get addressList {
ObservableList<ListItem> _computeAddressList() {
final addressList = ObservableList<ListItem>();
if (wallet.type == WalletType.monero) {
final primaryAddress =
monero!.getSubaddressList(wallet).subaddresses.first;
final addressItems =
monero!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final primaryAddress = monero!.getSubaddressList(wallet).subaddresses.first;
final addressItems = monero!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final isPrimary = subaddress == primaryAddress;
return WalletAddressListItem(
@@ -351,10 +345,8 @@ abstract class WalletAddressListViewModelBase
}
if (wallet.type == WalletType.wownero) {
final primaryAddress =
wownero!.getSubaddressList(wallet).subaddresses.first;
final addressItems =
wownero!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final primaryAddress = wownero!.getSubaddressList(wallet).subaddresses.first;
final addressItems = wownero!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final isPrimary = subaddress == primaryAddress;
return WalletAddressListItem(
@@ -367,10 +359,8 @@ abstract class WalletAddressListViewModelBase
}
if (wallet.type == WalletType.haven) {
final primaryAddress =
haven!.getSubaddressList(wallet).subaddresses.first;
final addressItems =
haven!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final primaryAddress = haven!.getSubaddressList(wallet).subaddresses.first;
final addressItems = haven!.getSubaddressList(wallet).subaddresses.map((subaddress) {
final isPrimary = subaddress == primaryAddress;
return WalletAddressListItem(
@@ -384,8 +374,7 @@ abstract class WalletAddressListViewModelBase
if (isElectrumWallet) {
if (bitcoin!.hasSelectedSilentPayments(wallet)) {
final addressItems =
bitcoin!.getSilentPaymentAddresses(wallet).map((address) {
final addressItems = bitcoin!.getSilentPaymentAddresses(wallet).map((address) {
final isPrimary = address.id == 0;
return WalletAddressListItem(
@@ -436,8 +425,7 @@ abstract class WalletAddressListViewModelBase
if (wallet.type == WalletType.litecoin && addressItems.length >= 1000) {
// find the index of the last item with a txCount > 0
final addressItemsList = addressItems.toList();
int index = addressItemsList
.lastIndexWhere((item) => (item.txCount ?? 0) > 0);
int index = addressItemsList.lastIndexWhere((item) => (item.txCount ?? 0) > 0);
if (index == -1) {
index = 0;
}
@@ -451,22 +439,19 @@ abstract class WalletAddressListViewModelBase
if (wallet.type == WalletType.ethereum) {
final primaryAddress = ethereum!.getAddress(wallet);
addressList.add(WalletAddressListItem(
isPrimary: true, name: null, address: primaryAddress));
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.polygon) {
final primaryAddress = polygon!.getAddress(wallet);
addressList.add(WalletAddressListItem(
isPrimary: true, name: null, address: primaryAddress));
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.solana) {
final primaryAddress = solana!.getAddress(wallet);
addressList.add(WalletAddressListItem(
isPrimary: true, name: null, address: primaryAddress));
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.nano) {
@@ -480,21 +465,18 @@ abstract class WalletAddressListViewModelBase
if (wallet.type == WalletType.tron) {
final primaryAddress = tron!.getAddress(wallet);
addressList.add(WalletAddressListItem(
isPrimary: true, name: null, address: primaryAddress));
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
for (var i = 0; i < addressList.length; i++) {
if (!(addressList[i] is WalletAddressListItem)) continue;
(addressList[i] as WalletAddressListItem).isHidden = wallet
.walletAddresses.hiddenAddresses
(addressList[i] as WalletAddressListItem).isHidden = wallet.walletAddresses.hiddenAddresses
.contains((addressList[i] as WalletAddressListItem).address);
}
for (var i = 0; i < addressList.length; i++) {
if (!(addressList[i] is WalletAddressListItem)) continue;
(addressList[i] as WalletAddressListItem).isManual = wallet
.walletAddresses.manualAddresses
(addressList[i] as WalletAddressListItem).isManual = wallet.walletAddresses.manualAddresses
.contains((addressList[i] as WalletAddressListItem).address);
}
@@ -516,13 +498,28 @@ abstract class WalletAddressListViewModelBase
return addressList;
}
@computed
ObservableList<ListItem> get addressList {
return _computeAddressList();
}
List<ListItem> get forceRecomputeItems {
// necessary because the addressList contains non-observable items
List<ListItem> recomputed = [];
recomputed.addAll(_baseItems);
recomputed.addAll(_computeAddressList());
return recomputed;
}
Future<void> toggleHideAddress(WalletAddressListItem item) async {
if (item.isHidden) {
wallet.walletAddresses.hiddenAddresses
.removeWhere((element) => element == item.address);
item.isHidden = false;
wallet.walletAddresses.hiddenAddresses.removeWhere((element) => element == item.address);
} else {
item.isHidden = true;
wallet.walletAddresses.hiddenAddresses.add(item.address);
}
// update the address list:
await wallet.walletAddresses.saveAddressesInBox();
if (wallet.type == WalletType.monero) {
monero!
@@ -568,28 +565,22 @@ abstract class WalletAddressListViewModelBase
].contains(wallet.type);
@computed
bool get isElectrumWallet => [
WalletType.bitcoin,
WalletType.litecoin,
WalletType.bitcoinCash
].contains(wallet.type);
bool get isElectrumWallet =>
[WalletType.bitcoin, WalletType.litecoin, WalletType.bitcoinCash].contains(wallet.type);
@computed
bool get isBalanceAvailable => isElectrumWallet;
@computed
bool get isReceivedAvailable =>
[WalletType.monero, WalletType.wownero].contains(wallet.type);
bool get isReceivedAvailable => [WalletType.monero, WalletType.wownero].contains(wallet.type);
@computed
bool get isSilentPayments =>
wallet.type == WalletType.bitcoin &&
bitcoin!.hasSelectedSilentPayments(wallet);
wallet.type == WalletType.bitcoin && bitcoin!.hasSelectedSilentPayments(wallet);
@computed
bool get isAutoGenerateSubaddressEnabled =>
_settingsStore.autoGenerateSubaddressStatus !=
AutoGenerateSubaddressStatus.disabled &&
_settingsStore.autoGenerateSubaddressStatus != AutoGenerateSubaddressStatus.disabled &&
!isSilentPayments;
@computed
@@ -672,8 +663,7 @@ abstract class WalletAddressListViewModelBase
@action
void _convertAmountToCrypto() {
final cryptoCurrency = walletTypeToCryptoCurrency(wallet.type);
final fiatRate =
_fiatRate ?? (fiatConversionStore.prices[cryptoCurrency] ?? 0.0);
final fiatRate = _fiatRate ?? (fiatConversionStore.prices[cryptoCurrency] ?? 0.0);
if (fiatRate <= 0.0) {
dev.log("Invalid Fiat Rate $fiatRate");