CW-1208: Pay Anything EVM enahancements (#2600)

* feat: Pay Anything EVM enahancements

* ifx: Add baseEth to address validator switch case

* fix: Error detecting other wallet types

* feat: Preserve QR amount and other data through evm chain selection flow

* Update container color to surfaceContainer

* feat: Add support for Bitcoin Lightning Network detection

- Identify Base QR codes when scanned
- Display all available currencies for network
- Enhance detector to recognize lightning addresses

* fix: Update token selection for currently selected wallet

* fix: Improve token matching logic for EVM networks

* feat: Update selected currency when wallet is switched

* ui: Add chain badge to the swap confirmation bottomsheet

* fix: Asks to switch wallets even if the current wallet type is the same as the QR. Fix merge conflicts too

* fix: Handle matching logic internally and general cleanups

* fix: Terminate flow if address is not a valid parsed address

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
This commit is contained in:
David Adegoke
2025-11-11 21:15:54 +01:00
committed by GitHub
co-authored by Omar Hatem tuxsudo
parent c74f0e5f82
commit 238022c466
43 changed files with 764 additions and 73 deletions
@@ -6,6 +6,7 @@ import 'package:cake_wallet/src/screens/receive/widgets/currency_input_field.dar
import 'package:cake_wallet/src/widgets/bottom_sheet/payment_confirmation_bottom_sheet.dart';
import 'package:cake_wallet/src/widgets/bottom_sheet/wallet_switcher_bottom_sheet.dart';
import 'package:cake_wallet/src/widgets/bottom_sheet/swap_confirmation_bottom_sheet.dart';
import 'package:cake_wallet/src/widgets/bottom_sheet/evm_payment_flow_bottom_sheet.dart';
import 'package:cake_wallet/src/widgets/bottom_sheet/info_bottom_sheet_widget.dart';
import 'package:cake_wallet/src/widgets/picker.dart';
import 'package:cake_wallet/src/widgets/standard_checkbox.dart';
@@ -166,6 +167,13 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
result,
);
break;
case PaymentFlowType.evmNetworkSelection:
await _showEVMPaymentFlow(
paymentViewModel,
walletSwitcherViewModel,
paymentRequest,
);
break;
case PaymentFlowType.currentWalletCompatible:
case PaymentFlowType.error:
case PaymentFlowType.incompatible:
@@ -198,6 +206,7 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
paymentViewModel,
walletSwitcherViewModel,
paymentRequest,
result,
),
onChangeWallet: () => _handleChangeWallet(
paymentViewModel,
@@ -211,10 +220,43 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
);
}
Future<void> _showEVMPaymentFlow(
PaymentViewModel paymentViewModel,
WalletSwitcherViewModel walletSwitcherViewModel,
PaymentRequest paymentRequest,
) async {
await showModalBottomSheet<void>(
context: context,
isDismissible: true,
isScrollControlled: true,
builder: (BuildContext context) {
return EVMPaymentFlowBottomSheet(
paymentViewModel: paymentViewModel,
paymentRequest: paymentRequest,
onNext: (PaymentFlowResult newResult) {
if (newResult.addressDetectionResult!.detectedWalletType ==
paymentViewModel.currentWalletType) {
sendViewModel.setSelectedCryptoCurrency(
newResult.addressDetectionResult!.detectedCurrency!.title);
} else {
_showPaymentConfirmation(
paymentViewModel,
walletSwitcherViewModel,
paymentRequest,
newResult,
);
}
},
);
},
);
}
Future<void> _handleSelectWallet(
PaymentViewModel paymentViewModel,
WalletSwitcherViewModel walletSwitcherViewModel,
PaymentRequest paymentRequest,
PaymentFlowResult result,
) async {
Navigator.of(context).pop();
@@ -233,6 +275,9 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
final success = await walletSwitcherViewModel.switchToSelectedWallet();
if (success) {
await sendViewModel.wallet.updateBalance();
sendViewModel
.setSelectedCryptoCurrency(result.addressDetectionResult!.detectedCurrency!.title);
_applyPaymentRequest(paymentRequest);
}
}
@@ -269,6 +314,10 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
if (loadingBottomSheetContext != null && loadingBottomSheetContext!.mounted) {
Navigator.of(loadingBottomSheetContext!).pop();
}
await sendViewModel.wallet.updateBalance();
sendViewModel
.setSelectedCryptoCurrency(result.addressDetectionResult!.detectedCurrency!.title);
_applyPaymentRequest(paymentRequest);
}
}
@@ -397,6 +446,8 @@ class SendCardState extends State<SendCard> with AutomaticKeepAliveClientMixin<S
final address =
output.isParsedAddress ? output.extractedAddress : output.address;
if (address.contains('@')) return;
await _handlePaymentFlow(
address,
PaymentRequest(
@@ -0,0 +1,309 @@
import 'package:cake_wallet/core/universal_address_detector.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/src/screens/exchange/widgets/currency_picker.dart';
import 'package:cake_wallet/src/widgets/bottom_sheet/base_bottom_sheet_widget.dart';
import 'package:cake_wallet/src/widgets/cake_image_widget.dart';
import 'package:cake_wallet/src/widgets/picker.dart';
import 'package:cake_wallet/src/widgets/primary_button.dart';
import 'package:cake_wallet/utils/payment_request.dart';
import 'package:cake_wallet/utils/qr_util.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cake_wallet/utils/token_utilities.dart';
import 'package:cake_wallet/view_model/payment/payment_view_model.dart';
import 'package:cake_wallet/wallet_types.g.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
class EVMPaymentFlowBottomSheet extends BaseBottomSheet {
EVMPaymentFlowBottomSheet({
Key? key,
required this.paymentViewModel,
required this.paymentRequest,
required this.onNext,
}) : super(
titleText: '',
footerType: FooterType.none,
maxHeight: 900,
);
final PaymentViewModel paymentViewModel;
final PaymentRequest paymentRequest;
final Function(PaymentFlowResult) onNext;
@override
Widget contentWidget(BuildContext context) {
return _EVMPaymentFlowContent(
paymentViewModel: paymentViewModel,
paymentRequest: paymentRequest,
onNext: onNext,
);
}
}
class _EVMPaymentFlowContent extends StatefulWidget {
const _EVMPaymentFlowContent({
required this.paymentViewModel,
required this.paymentRequest,
required this.onNext,
});
final PaymentViewModel paymentViewModel;
final PaymentRequest paymentRequest;
final Function(PaymentFlowResult) onNext;
@override
State<_EVMPaymentFlowContent> createState() => _EVMPaymentFlowContentState();
}
class _EVMPaymentFlowContentState extends State<_EVMPaymentFlowContent> {
WalletType? selectedNetwork;
CryptoCurrency? selectedToken;
@override
void initState() {
super.initState();
selectedNetwork = WalletType.ethereum;
_autoSelectToken();
}
Future<void> _autoSelectToken() async {
if (selectedNetwork == null) return;
try {
final tokens = await TokenUtilities.getAvailableTokensForNetwork(selectedNetwork!);
if (tokens.isNotEmpty) {
setState(() {
selectedToken = tokens.first;
});
}
} catch (e) {
printV('Auto-select token error: $e');
}
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CakeImageWidget(
imageUrl: 'assets/images/eth_chain_mono.svg',
width: 50,
height: 50,
color: Theme.of(context).colorScheme.onSurface,
),
const SizedBox(height: 24),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(
'${S.current.ethereum_ecosystem}\n${S.current.address_detected.toLowerCase()}',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Theme.of(context).colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 36),
Text(
S.current.evm_ecosystem_description,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurfaceVariant,
letterSpacing: 0.0,
),
),
const SizedBox(height: 32),
EVMTileWidget(
value: selectedNetwork != null
? walletTypeToString(selectedNetwork!)
: S.current.select_network,
imagePath: selectedNetwork != null ? getChainMonoImage(selectedNetwork!) : null,
color: selectedNetwork != null ? Theme.of(context).colorScheme.primary : null,
enabled: true,
onTap: () => _showNetworkSelection(context),
),
const SizedBox(height: 16),
EVMTileWidget(
imagePath: selectedToken != null ? selectedToken!.iconPath : null,
value: selectedToken != null ? selectedToken!.title : S.current.select_token,
enabled: selectedNetwork != null,
onTap: () => _showTokenSelection(context),
color: selectedToken == null ? Theme.of(context).colorScheme.primary : null,
),
const SizedBox(height: 32),
PrimaryButton(
text: S.current.restore_next,
color: Theme.of(context).colorScheme.primary,
textColor: Theme.of(context).colorScheme.onPrimary,
onPressed: selectedNetwork != null && selectedToken != null
? () async => await _handleNext(context)
: null,
),
const SizedBox(height: 48),
],
),
);
}
void _showNetworkSelection(BuildContext context) async {
final evmNetworks =
availableWalletTypes.where((walletType) => isEVMCompatibleChain(walletType)).toList();
final selectedIndex = evmNetworks.indexOf(selectedNetwork ?? WalletType.ethereum);
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return Picker(
items: evmNetworks,
displayItem: (WalletType network) => walletTypeToString(network),
selectedAtIndex: selectedIndex,
title: S.current.select_network,
closeOnItemSelected: true,
hasTitleSpacing: true,
images: evmNetworks
.map((network) => CakeImageWidget(
imageUrl: getChainMonoImage(network),
width: 20,
height: 20,
color: Theme.of(context).colorScheme.primary))
.toList(),
onItemSelected: (WalletType network) {
setState(() {
selectedNetwork = network;
selectedToken = null;
});
_autoSelectToken();
},
);
},
);
}
void _showTokenSelection(BuildContext context) async {
if (selectedNetwork == null) return;
try {
final availableTokens = await TokenUtilities.getAvailableTokensForNetwork(selectedNetwork!);
if (availableTokens.isEmpty) return;
final selectedIndex = selectedToken != null ? availableTokens.indexOf(selectedToken!) : 0;
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return CurrencyPicker(
selectedAtIndex: selectedIndex >= 0 ? selectedIndex : 0,
items: availableTokens.cast<Currency>(),
hintText: S.current.add_token,
onItemSelected: (Currency currency) {
setState(() {
selectedToken = currency as CryptoCurrency;
});
},
);
},
);
} catch (e) {
printV('Error showing token selection: $e');
}
}
Future<void> _handleNext(BuildContext context) async {
if (selectedNetwork == null || selectedToken == null) return;
Navigator.of(context).pop();
final compatibleWallets = await widget.paymentViewModel.getWalletsByType(selectedNetwork!);
final newResult = PaymentFlowResult.evmNetworkSelection(
AddressDetectionResult(
address: widget.paymentRequest.address,
detectedWalletType: selectedNetwork!,
detectedCurrency: selectedToken!,
isValid: true,
amount: widget.paymentRequest.amount,
note: widget.paymentRequest.note,
scheme: widget.paymentRequest.scheme,
pjUri: widget.paymentRequest.pjUri,
callbackUrl: widget.paymentRequest.callbackUrl,
callbackMessage: widget.paymentRequest.callbackMessage,
),
compatibleWallets: compatibleWallets,
wallet: compatibleWallets.isNotEmpty ? compatibleWallets.first : null,
);
widget.paymentViewModel.detectedWalletType = selectedNetwork!;
widget.onNext(newResult);
}
}
class EVMTileWidget extends StatelessWidget {
const EVMTileWidget({
super.key,
required this.value,
required this.enabled,
required this.onTap,
this.imagePath,
this.color,
});
final String value;
final bool enabled;
final VoidCallback? onTap;
final String? imagePath;
final Color? color;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: enabled ? onTap : null,
borderRadius: BorderRadius.circular(12),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Theme.of(context).colorScheme.surfaceContainer,
),
child: Row(
children: [
if (imagePath != null) ...[
CakeImageWidget(
imageUrl: imagePath!,
color: color,
width: 20,
height: 20,
),
const SizedBox(width: 16),
],
Expanded(
child: Text(
value,
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
Icon(
Icons.keyboard_arrow_down,
size: 24,
color: Theme.of(context).colorScheme.primary,
),
],
),
),
);
}
}
@@ -88,11 +88,16 @@ class _PaymentConfirmationContent extends StatelessWidget {
final currencyName = walletTypeToString(paymentViewModel.detectedWalletType!);
final currentWalletName = walletTypeToString(paymentViewModel.currentWalletType);
final hasMultipleWallets = paymentFlowResult.type == PaymentFlowType.multipleWallets;
final noAvailableWallets = paymentFlowResult.type == PaymentFlowType.noWallets;
final hasSingleWallet = paymentFlowResult.type == PaymentFlowType.singleWallet ||
paymentFlowResult.wallets.length == 1;
final hasAtLeastOneWallet =
paymentFlowResult.type == PaymentFlowType.singleWallet || hasMultipleWallets;
final hasMultipleWallets = paymentFlowResult.type == PaymentFlowType.multipleWallets ||
paymentFlowResult.wallets.length > 1;
final noAvailableWallets = paymentFlowResult.type == PaymentFlowType.noWallets ||
paymentFlowResult.wallets.isEmpty;
final hasAtLeastOneWallet = hasSingleWallet || hasMultipleWallets;
final isMwebOrSpAddress =
_isMwebOrSpAddress(paymentFlowResult.addressDetectionResult?.address ?? '');
@@ -103,34 +108,78 @@ class _PaymentConfirmationContent extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
walletTypeToCryptoCurrency(paymentViewModel.detectedWalletType!).iconPath!,
width: 118,
height: 118,
),
const SizedBox(height: 20),
Text(
'$currencyName ${S.current.address_detected.toLowerCase()}',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Theme.of(context).colorScheme.onSurface,
letterSpacing: 0.0,
if (paymentFlowResult.type == PaymentFlowType.evmNetworkSelection) ...[
Stack(
clipBehavior: Clip.none,
children: [
Image.asset(
paymentFlowResult.addressDetectionResult!.detectedCurrency!.iconPath!,
width: 70,
height: 70,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
Text(
'''Looks like you scanned a $currencyName address.\n\n'''
'''Would you like to ${!noAvailableWallets ? 'switch to a $currencyName wallet or' : ''} swap $currentWalletName for $currencyName for this payment?''',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurfaceVariant,
letterSpacing: 0.0,
Positioned(
bottom: 0,
right: 0,
child: Image.asset(
walletTypeToCryptoCurrency(paymentViewModel.detectedWalletType!).iconPath!,
width: 32,
height: 32,
),
),
),
],
),
const SizedBox(height: 20),
Text(
'${paymentFlowResult.addressDetectionResult?.detectedCurrency} (${walletTypeToString(paymentFlowResult.walletType!)})',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Theme.of(context).colorScheme.onSurface,
letterSpacing: 0.0,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
Text(
'''Would you like to ${!noAvailableWallets ? 'switch to a $currencyName wallet or' : ''} swap $currentWalletName for ${paymentFlowResult.addressDetectionResult?.detectedCurrency} (${walletTypeToString(paymentFlowResult.walletType!)}) for this payment?''',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurfaceVariant,
letterSpacing: 0.0,
),
),
] else ...[
Image.asset(
walletTypeToCryptoCurrency(paymentViewModel.detectedWalletType!).iconPath!,
width: 118,
height: 118,
),
const SizedBox(height: 20),
Text(
'$currencyName ${S.current.address_detected.toLowerCase()}',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Theme.of(context).colorScheme.onSurface,
letterSpacing: 0.0,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
Text(
'''Looks like you scanned a $currencyName address.\n\n'''
'''Would you like to ${!noAvailableWallets ? 'switch to a $currencyName wallet or' : ''} swap $currentWalletName for $currencyName for this payment?''',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: 16,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurfaceVariant,
letterSpacing: 0.0,
),
),
],
const SizedBox(height: 72),
if (hasAtLeastOneWallet) ...[
if (!isMwebOrSpAddress) ...[
@@ -137,7 +137,7 @@ class SwapConfirmationContentState extends State<SwapConfirmationContent> {
@override
Widget build(BuildContext context) {
final detectedCurrency = walletTypeToCryptoCurrency(widget.paymentFlowResult.walletType!);
final detectedCurrency = widget.paymentFlowResult.detectedCurrency!;
return Form(
key: _formKey,
@@ -158,11 +158,25 @@ class SwapConfirmationContentState extends State<SwapConfirmationContent> {
const SizedBox(width: 12),
Icon(Icons.arrow_forward, size: 24),
const SizedBox(width: 12),
CakeImageWidget(
imageUrl:
detectedCurrency.iconPath!,
width: 32,
height: 32,
Stack(
clipBehavior: Clip.none,
children: [
CakeImageWidget(
imageUrl: detectedCurrency.iconPath!,
width: 32,
height: 32,
),
Positioned(
bottom: -4,
right: -4,
child: CakeImageWidget(
imageUrl: walletTypeToCryptoCurrency(widget.paymentFlowResult.walletType!)
.iconPath!,
width: 16,
height: 16,
),
),
],
),
],
),
@@ -414,7 +428,8 @@ class SwapConfirmationContentState extends State<SwapConfirmationContent> {
}
});
exchangeViewModel.receiveCurrency = walletTypeToCryptoCurrency(paymentFlowResult.walletType!);
exchangeViewModel.receiveCurrency = paymentFlowResult.detectedCurrency!;
await exchangeViewModel.fetchFiatPrice(exchangeViewModel.receiveCurrency);
exchangeViewModel.receiveAddress = _addressController.text;
@@ -272,13 +272,13 @@ class _SwapDetailsContent extends StatelessWidget {
children: [
_SwapDetailsTile(
label: 'You Send',
value: '${trade.amount} ${trade.from?.title ?? ''}',
value: '${trade.amount} ${trade.from?.title ?? trade.userCurrencyFrom?.title ?? ''}',
valueFiatFormatted: exchangeTradeViewModel.sendAmountFiatFormatted,
),
const SizedBox(height: 8),
_SwapDetailsTile(
label: 'You Get',
value: '${trade.receiveAmount ?? '0'} ${trade.to?.title ?? ''}',
value: '${trade.receiveAmount ?? '0'} ${trade.to?.title ?? trade.userCurrencyTo?.title ?? ''}',
valueFiatFormatted: exchangeTradeViewModel
.getReceiveAmountFiatFormatted(trade.receiveAmount ?? '0.0'),
),
+12 -5
View File
@@ -18,7 +18,9 @@ class Picker<Item> extends StatefulWidget {
required this.onItemSelected,
this.title,
this.displayItem,
this.images = const <Image>[],
this.displayItemColor,
this.displayItemFontSize,
this.images = const <Widget>[],
this.description,
this.mainAxisAlignment = MainAxisAlignment.start,
this.isGridView = false,
@@ -34,6 +36,7 @@ class Picker<Item> extends StatefulWidget {
this.borderColor,
this.onSliderChanged,
this.matchingCriteria,
this.hasTitleSpacing = false,
}) : assert(hintText == null || matchingCriteria != null) {
// make sure that if the search field is enabled then there is a searching criteria provided
if (sliderValue != null && maxValue != null) {
@@ -45,12 +48,14 @@ class Picker<Item> extends StatefulWidget {
final int selectedAtIndex;
final List<Item> items;
final List<Image> images;
final List<Widget> images;
final String? title;
final String? description;
final Function(Item) onItemSelected;
final MainAxisAlignment mainAxisAlignment;
final String Function(Item)? displayItem;
final Color? displayItemColor;
final double? displayItemFontSize;
final bool isGridView;
final bool isSeparated;
final String? hintText;
@@ -64,7 +69,7 @@ class Picker<Item> extends StatefulWidget {
final Function(double)? onSliderChanged;
final bool Function(Item, String)? matchingCriteria;
final double? maxValue;
final bool hasTitleSpacing;
@override
_PickerState<Item> createState() => _PickerState<Item>(items, images, onItemSelected);
}
@@ -74,9 +79,9 @@ class _PickerState<Item> extends State<Picker<Item>> {
final Function(Item) onItemSelected;
List<Item> items;
List<Image> images;
List<Widget> images;
List<Item> filteredItems = [];
List<Image> filteredImages = [];
List<Widget> filteredImages = [];
final TextEditingController searchController = TextEditingController();
ScrollController controller = ScrollController();
@@ -163,6 +168,7 @@ class _PickerState<Item> extends State<Picker<Item>> {
),
),
),
widget.hasTitleSpacing ? const SizedBox(height: 24) : const SizedBox.shrink(),
Padding(
padding: EdgeInsets.symmetric(horizontal: padding),
child: Container(
@@ -342,6 +348,7 @@ class _PickerState<Item> extends State<Picker<Item>> {
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontWeight: FontWeight.w600,
decoration: TextDecoration.none,
color: widget.displayItemColor,
),
),
),