CW-1523-AnyPay Redesign (#3383)
What changed, and why it matters
This is a large user-interface redesign for Cake Wallet's 'AnyPay' payment flow. It changes how the app parses payment QR codes and links for Ethereum, Solana, and Tron, adds network selection, and integrates swaps when the scanned payment is on a different network than the current wallet. The commit also fixes several amount-formatting bugs for tokens that do not use 18 decimal places, which could previously cause wrong payment amounts to be sent.
Review the new URI parsing logic against the added unit tests, verify that resolveTokenAmount correctly applies token decimals everywhere, and ensure the new navigation/state disposal does not leave stale reactions or wallet-switch race conditions. No immediate emergency patch is indicated, but a focused security test of cross-chain payment and swap flows is warranted.
Security signals we found
Amount scaling bug fix for non-18-decimal ERC-20 tokens
New network/chain selection guards and unsupported-network alerts
Token contract lookup and unsupported-token alert before applying amount
URI parsing now preserves raw uint256 for tokens instead of always dividing by 1e18
Large UI refactor with new navigation and state disposal changes
Evidence from the diff
The commit refactors send/swap flows and ERC-681/Solana/Tron URI parsing. Key changes: ERC681URI now distinguishes raw atomic token amounts from display amounts and supports arbitrary tokenDecimals; it emits a uint256 only when decimals are 18 or a raw amount is known, preventing old clients from mis-scaling non-18-decimal tokens. Payment request handling now routes EVM addresses through chain selection, applies token-decimal-aware amounts via resolveTokenAmount, and guards unsupported networks/tokens with alerts. Swap flow can be launched pre-filled from a payment request. Unit tests were added for Tron, Solana, and ERC-681 URI round-trips.
Changed components
cw_core/lib/payment_uris.dartcw_core/test/payment_uris_test.dartlib/new-ui/pages/send_page.dartlib/new-ui/pages/swap_page.dartlib/utils/payment_request.dartlib/utils/token_utilities.dartlib/view_model/send/send_view_model.dartlib/view_model/payment/payment_view_model.dartInspect captured patch +4514 / −2662
diff --git a/cw_core/lib/currency_for_wallet_type.dart b/cw_core/lib/currency_for_wallet_type.dart
index a0a1d38a..c31aa5b2 100644
--- a/cw_core/lib/currency_for_wallet_type.dart
+++ b/cw_core/lib/currency_for_wallet_type.dart
@@ -111,3 +111,48 @@ String getCryptoCurrencyIconForWalletListItem(WalletType type,
return walletTypeToCryptoCurrency(type, isTestnet: isTestnet, chainId: chainId).iconPath ?? "";
}
+
+String? symbolIconPathForWalletType(WalletType type) {
+ const prefix = "assets/new-ui/card_icons/symbol_icons";
+ switch (type) {
+ case WalletType.monero:
+ return "$prefix/xmr-symbol.svg";
+ case WalletType.bitcoin:
+ return "$prefix/btc-symbol.svg";
+ case WalletType.litecoin:
+ return "$prefix/ltc-symbol.svg";
+ case WalletType.ethereum:
+ return "$prefix/eth-symbol.svg";
+ case WalletType.base:
+ return "$prefix/base-symbol.svg";
+ case WalletType.arbitrum:
+ return "$prefix/arb-symbol.svg";
+ case WalletType.bsc:
+ return "$prefix/bnb-symbol.svg";
+ case WalletType.bitcoinCash:
+ return "$prefix/bch-symbol.svg";
+ case WalletType.polygon:
+ return "$prefix/pol-symbol.svg";
+ case WalletType.solana:
+ return "$prefix/sol-symbol.svg";
+ case WalletType.tron:
+ return "$prefix/trx-symbol.svg";
+ case WalletType.zano:
+ return "$prefix/zano-symbol.svg";
+ case WalletType.decred:
+ return "$prefix/dcr-symbol.svg";
+ case WalletType.dogecoin:
+ return "$prefix/doge-symbol.svg";
+ case WalletType.zcash:
+ return "$prefix/zec-symbol.svg";
+ case WalletType.nano:
+ return "$prefix/xno-symbol.svg";
+ case WalletType.wownero:
+ case WalletType.haven:
+ case WalletType.banano:
+ case WalletType.none:
+ return null;
+ }
+}
+
+bool isMonochromeSymbolIcon(String path) => path.contains("/symbol_icons/");
diff --git a/cw_core/lib/payment_uris.dart b/cw_core/lib/payment_uris.dart
index 43d452f8..4ca12bdc 100644
--- a/cw_core/lib/payment_uris.dart
+++ b/cw_core/lib/payment_uris.dart
@@ -254,6 +254,8 @@ class ERC681URI extends PaymentURI {
required super.address,
required super.amount,
required this.contractAddress,
+ this.tokenDecimals = 18,
+ this.rawTokenAmount,
});
factory ERC681URI.fromUri(Uri uri) {
@@ -261,15 +263,31 @@ class ERC681URI extends PaymentURI {
final chainId = _getChainID(uri.path);
final address = isContract ? uri.queryParameters["address"] ?? "" : targetAddress;
- final amountParam = isContract ? uri.queryParameters["uint256"] : uri.queryParameters["value"];
var formatedAmount = "";
+ String? rawTokenAmount;
- if (amountParam != null) {
- final normalized = _normalizeToIntegerWei(amountParam);
- formatedAmount = formatFixed(BigInt.parse(normalized), 18);
- } else {
+ if (isContract) {
formatedAmount = uri.queryParameters["amount"] ?? "";
+ final uint256Param = uri.queryParameters["uint256"];
+ if (uint256Param != null) {
+ final raw = uint256Param.replaceAll(",", ".").trim();
+ if (!_scientificPattern.hasMatch(raw) && raw.contains(".")) {
+ if (formatedAmount.isEmpty) {
+ formatedAmount = raw;
+ }
+ } else {
+ rawTokenAmount = _normalizeToIntegerWei(raw);
+ }
+ }
+ } else {
+ final valueParam = uri.queryParameters["value"];
+ if (valueParam != null) {
+ final normalized = _normalizeToIntegerWei(valueParam);
+ formatedAmount = formatFixed(BigInt.parse(normalized), 18);
+ } else {
+ formatedAmount = uri.queryParameters["amount"] ?? "";
+ }
}
return ERC681URI(
@@ -277,11 +295,16 @@ class ERC681URI extends PaymentURI {
address: address,
amount: formatedAmount,
contractAddress: isContract ? targetAddress : null,
+ rawTokenAmount: rawTokenAmount,
);
}
final int chainId;
final String? contractAddress;
+ final int tokenDecimals;
+ final String? rawTokenAmount;
+
+ static final RegExp _scientificPattern = RegExp(r"^[+-]?(\d+\.?\d*|\d*\.?\d+)[eE][+-]?\d+$");
@override
String toString() {
@@ -302,8 +325,17 @@ class ERC681URI extends PaymentURI {
if (contractAddress != null) {
params["address"] = address;
+ // only emit an atomic uint256 when it is unambiguous, either stored raw or 18 decimals,
+ // old app versions divide any uint256 by 1e18 so other tokens rely on the amount param
+ final uint256 = rawTokenAmount ??
+ (tokenDecimals == 18 && amount.isNotEmpty
+ ? _expandDecimal(amount.replaceAll(",", "."), 18)
+ : null);
+ if (uint256 != null && uint256.isNotEmpty) {
+ params["uint256"] = uint256;
+ }
if (amount.isNotEmpty) {
- params["uint256"] = _formatAmountForERC20(amount);
+ params["amount"] = amount.replaceAll(",", ".");
}
} else {
if (amount.isNotEmpty) {
@@ -318,19 +350,6 @@ class ERC681URI extends PaymentURI {
return uri;
}
- /// Formats amount for ERC-20 token transfers (in atomic units)
- String _formatAmountForERC20(String amount) {
- try {
- // Convert decimal amount to BigInt (assuming 18 decimals)
- final amountDouble = double.parse(amount.replaceAll(",", "."));
- final amountBigInt = BigInt.from(amountDouble * 1e18);
- return amountBigInt.toString();
- } catch (e) {
- // Fallback to original amount if parsing fails
- return amount.replaceAll(",", ".");
- }
- }
-
/// Formats amount for native ETH payments (in wei using scientific notation)
String _formatAmountForNative(String amount) {
try {
@@ -374,8 +393,7 @@ class ERC681URI extends PaymentURI {
}
// Then we check if it's a scientific notation
- final sci = RegExp(r"^[+-]?(\d+\.?\d*|\d*\.?\d+)[eE][+-]?\d+$");
- if (sci.hasMatch(raw)) {
+ if (_scientificPattern.hasMatch(raw)) {
final mantissaStr = raw.toLowerCase().split("e")[0];
final exp = int.parse(raw.toLowerCase().split("e")[1]);
return _expandDecimal(mantissaStr, exp);
diff --git a/cw_core/test/payment_uris_test.dart b/cw_core/test/payment_uris_test.dart
new file mode 100644
index 00000000..88e5e4a4
--- /dev/null
+++ b/cw_core/test/payment_uris_test.dart
@@ -0,0 +1,222 @@
+import "package:cw_core/payment_uris.dart";
+import "package:flutter_test/flutter_test.dart";
+
+void main() {
+ group("TronURI", () {
+ const address = "TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL";
+ const contract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
+
+ test("includes the TRC20 contract as the token param", () {
+ final uri = TronURI(amount: "1.5", address: address, contractAddress: contract);
+
+ expect(uri.toString(), "tron:$address?amount=1.5&token=$contract");
+ });
+
+ test("omits the token param for native TRX", () {
+ final uri = TronURI(amount: "1.5", address: address);
+
+ expect(uri.toString(), "tron:$address?amount=1.5");
+ expect(uri.toString().contains("token="), false);
+ });
+
+ test("includes the token param when there is no amount", () {
+ final uri = TronURI(amount: "", address: address, contractAddress: contract);
+
+ expect(uri.toString(), "tron:$address?token=$contract");
+ });
+
+ test("converts a comma decimal separator in the amount", () {
+ final uri = TronURI(amount: "1,5", address: address);
+
+ expect(uri.toString(), "tron:$address?amount=1.5");
+ });
+
+ test("emits a bare address without amount or contract", () {
+ final uri = TronURI(amount: "", address: address);
+
+ expect(uri.toString(), "tron:$address");
+ });
+ });
+
+ group("SolanaURI", () {
+ const address = "4Nd1mYvNQyJ8BDVXLgkvSGpVdQMZ3hxwVFkfwXNq6Wgk";
+ const mint = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";
+
+ test("includes the SPL mint as the spl-token param", () {
+ final uri = SolanaURI(amount: "2", address: address, contractAddress: mint);
+
+ expect(uri.toString(), "solana:$address?amount=2&spl-token=$mint");
+ });
+
+ test("omits the spl-token param for native SOL", () {
+ final uri = SolanaURI(amount: "2", address: address);
+
+ expect(uri.toString(), "solana:$address?amount=2");
+ expect(uri.toString().contains("spl-token="), false);
+ });
+
+ test("includes the spl-token param when there is no amount", () {
+ final uri = SolanaURI(amount: "", address: address, contractAddress: mint);
+
+ expect(uri.toString(), "solana:$address?spl-token=$mint");
+ });
+
+ test("converts a comma decimal separator in the amount", () {
+ final uri = SolanaURI(amount: "0,5", address: address);
+
+ expect(uri.toString(), "solana:$address?amount=0.5");
+ });
+
+ test("emits a bare address without amount or mint", () {
+ final uri = SolanaURI(amount: "", address: address);
+
+ expect(uri.toString(), "solana:$address");
+ });
+ });
+
+ group("ERC681URI", () {
+ const recipient = "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6";
+ const contract = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
+
+ test("builds a plain native transfer on mainnet", () {
+ final uri = ERC681URI(chainId: 1, address: recipient, amount: "", contractAddress: null);
+
+ expect(uri.toString(), "ethereum:$recipient");
+ });
+
+ test("appends the chainId for non-mainnet native transfers", () {
+ final uri = ERC681URI(chainId: 137, address: recipient, amount: "", contractAddress: null);
+
+ expect(uri.toString(), "ethereum:$recipient@137");
+ });
+
+ test("emits the native amount in ERC-681 scientific notation", () {
+ final uri = ERC681URI(chainId: 1, address: recipient, amount: "1", contractAddress: null);
+
+ expect(uri.toString(), "ethereum:$recipient?value=1.0e18");
+ });
+
+ test("builds the transfer form for a token", () {
+ final uri =
+ ERC681URI(chainId: 137, address: recipient, amount: "", contractAddress: contract);
+
+ expect(uri.toString(), "ethereum:$contract@137/transfer?address=$recipient");
+ });
+
+ test("parses the transfer form back into recipient, contract and chainId", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse("ethereum:$contract@1/transfer?address=$recipient&uint256=1000000"),
+ );
+
+ expect(parsed.address, recipient);
+ expect(parsed.contractAddress, contract);
+ expect(parsed.chainId, 1);
+ expect(parsed.rawTokenAmount, "1000000");
+ expect(parsed.amount, "");
+ });
+
+ test("keeps the uint256 raw so the caller can apply the token decimals", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse(
+ "ethereum:0xdAC17F958D2ee523a2206206994597C13D831ec7@1/transfer?address=$recipient&uint256=1000000",
+ ),
+ );
+
+ expect(parsed.rawTokenAmount, "1000000");
+ expect(parsed.amount, "");
+ });
+
+ test("prefers the amount param over the uint256 when both are present", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse(
+ "ethereum:$contract@1/transfer?address=$recipient&uint256=1000000000000000000&amount=1",
+ ),
+ );
+
+ expect(parsed.amount, "1");
+ expect(parsed.rawTokenAmount, "1000000000000000000");
+ });
+
+ test("treats a uint256 with a decimal point as a display amount", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse("ethereum:$contract@1/transfer?address=$recipient&uint256=1.5"),
+ );
+
+ expect(parsed.amount, "1.5");
+ expect(parsed.rawTokenAmount, null);
+ });
+
+ test("parses a native transfer with chainId", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse("ethereum:$recipient@137?value=2000000000000000000"),
+ );
+
+ expect(parsed.address, recipient);
+ expect(parsed.contractAddress, null);
+ expect(parsed.chainId, 137);
+ expect(parsed.amount, "2");
+ });
+
+ test("emits the uint256 and the amount param for an 18 decimal token", () {
+ final uri =
+ ERC681URI(chainId: 137, address: recipient, amount: "1", contractAddress: contract);
+
+ expect(
+ uri.toString(),
+ "ethereum:$contract@137/transfer?address=$recipient&uint256=1000000000000000000&amount=1",
+ );
+ });
+
+ test("omits the uint256 for tokens that do not use 18 decimals", () {
+ final uri = ERC681URI(
+ chainId: 137,
+ address: recipient,
+ amount: "1.5",
+ contractAddress: contract,
+ tokenDecimals: 6,
+ );
+
+ expect(uri.toString(), "ethereum:$contract@137/transfer?address=$recipient&amount=1.5");
+ });
+
+ test("emits a stored raw token amount verbatim", () {
+ final uri = ERC681URI(
+ chainId: 1,
+ address: recipient,
+ amount: "",
+ contractAddress: contract,
+ tokenDecimals: 6,
+ rawTokenAmount: "1000000",
+ );
+
+ expect(uri.toString(), "ethereum:$contract/transfer?address=$recipient&uint256=1000000");
+ });
+
+ test("parses a scientific notation value", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse("ethereum:$recipient@1?value=2.014e18"),
+ );
+
+ expect(parsed.amount, "2.014");
+ });
+
+ test("parses a Cake style amount param", () {
+ final parsed = ERC681URI.fromUri(
+ Uri.parse("ethereum:$recipient?amount=1.5"),
+ );
+
+ expect(parsed.address, recipient);
+ expect(parsed.amount, "1.5");
+ expect(parsed.chainId, 1);
+ });
+
+ test("defaults to mainnet when the chainId is absent", () {
+ final parsed = ERC681URI.fromUri(Uri.parse("ethereum:$recipient"));
+
+ expect(parsed.address, recipient);
+ expect(parsed.contractAddress, null);
+ expect(parsed.chainId, 1);
+ expect(parsed.amount, "");
+ });
+ });
+}
diff --git a/lib/new-ui/pages/send_page.dart b/lib/new-ui/pages/send_page.dart
index 1b379df8..1500e2ca 100644
--- a/lib/new-ui/pages/send_page.dart
+++ b/lib/new-ui/pages/send_page.dart
@@ -1,19 +1,27 @@
+import "package:cake_wallet/core/address_resolver/address_resolver_service.dart";
import "package:cake_wallet/core/address_resolver/parsed_address.dart";
import "package:cake_wallet/core/address_validator.dart";
import "package:cake_wallet/core/auth_service.dart";
import "package:cake_wallet/core/execution_state.dart";
import "package:cake_wallet/core/open_crypto_pay/open_cryptopay_service.dart";
+import "package:cake_wallet/core/universal_address_detector.dart";
import "package:cake_wallet/di.dart";
import "package:cake_wallet/entities/contact_record.dart";
import "package:cake_wallet/entities/priority_for_wallet_type.dart";
import "package:cake_wallet/evm/evm.dart";
-import "package:cake_wallet/exchange/trade.dart";
import "package:cake_wallet/generated/i18n.dart";
import "package:cake_wallet/main.dart";
import "package:cake_wallet/monero/monero.dart";
import "package:cake_wallet/new-ui/modal_navigator.dart";
import "package:cake_wallet/new-ui/pages/coin_control_page.dart";
+import "package:cake_wallet/new-ui/pages/swap_page.dart";
import "package:cake_wallet/new-ui/widgets/animated_dropdown.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/evm_address_detected_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/recipient_network_row.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/select_recipient_network_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/send_to_network_page.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/swap_from_network_page.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/switch_network_wallet_page.dart";
import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart";
import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_sheet.dart";
import "package:cake_wallet/new-ui/widgets/currency_picker/fiat_currency_picker_sheet.dart";
@@ -32,22 +40,21 @@ import "package:cake_wallet/new-ui/widgets/send_page/send_amount_input.dart";
import "package:cake_wallet/new-ui/widgets/send_page/send_confirm_sheet.dart";
import "package:cake_wallet/new-ui/widgets/send_page/send_memo_input.dart";
import "package:cake_wallet/new-ui/widgets/send_page/send_syncing_indicator.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_from_send_args.dart";
import "package:cake_wallet/reactions/wallet_connect.dart";
import "package:cake_wallet/routes.dart" show Routes;
import "package:cake_wallet/src/screens/connect_device/connect_device_page.dart";
import "package:cake_wallet/src/widgets/alert_with_one_action.dart";
import "package:cake_wallet/src/widgets/bottom_sheet/info_bottom_sheet_widget.dart";
-import "package:cake_wallet/src/widgets/bottom_sheet/payment_confirmation_bottom_sheet.dart";
-import "package:cake_wallet/src/widgets/bottom_sheet/swap_confirmation_bottom_sheet.dart";
-import "package:cake_wallet/src/widgets/bottom_sheet/token_selection_bottom_sheet.dart";
-import "package:cake_wallet/src/widgets/bottom_sheet/wallet_switcher_bottom_sheet.dart";
import "package:cake_wallet/src/widgets/cake_image_widget.dart";
import "package:cake_wallet/src/widgets/new_list_row/list_item_regular_row_widget.dart";
import "package:cake_wallet/src/widgets/standard_checkbox.dart";
import "package:cake_wallet/store/app_store.dart";
import "package:cake_wallet/utils/payment_request.dart";
import "package:cake_wallet/utils/show_pop_up.dart";
+import "package:cake_wallet/utils/token_utilities.dart";
import "package:cake_wallet/view_model/contact_list/contact_list_view_model.dart";
+import "package:cake_wallet/view_model/exchange/exchange_view_model.dart";
import "package:cake_wallet/view_model/payment/payment_view_model.dart";
import "package:cake_wallet/view_model/send/output.dart";
import "package:cake_wallet/view_model/send/send_view_model.dart";
@@ -56,7 +63,9 @@ import "package:cake_wallet/view_model/wallet_switcher_view_model.dart";
import "package:cw_core/amount/amount_sanitizer.dart";
import "package:cw_core/amount/money.dart";
import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
import "package:cw_core/lnurl.dart";
+import "package:cw_core/payment_uris.dart";
import "package:cw_core/transaction_priority.dart";
import "package:cw_core/unspent_coin_type.dart";
import "package:cw_core/utils/print_verbose.dart";
@@ -236,42 +245,66 @@ class _NewSendPageState extends State<NewSendPage> {
}
});
- if (widget.initialPaymentRequest != null &&
- widget.sendViewModel.walletCurrencyName ==
- widget.initialPaymentRequest!.scheme.toLowerCase()) {
- _addressControllers[0].text = widget.initialPaymentRequest!.address;
- _amountControllers[0].text = widget.initialPaymentRequest!.amount;
- // _memoControllers[0].text = widget.initialPaymentRequest!.note;
- _applyNote(widget.initialPaymentRequest!.note, 0);
-
- final contractAddress = widget.initialPaymentRequest!.contractAddress;
- if (contractAddress != null && contractAddress.isNotEmpty) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) {
- widget.sendViewModel.fetchTokenForContractAddress(contractAddress);
- }
- });
- }
- }
+ if (widget.initialPaymentRequest != null) {
+ if (_isInitialRequestTypeSameAsCurrentWallet()) {
+ _addressControllers[0].text = widget.initialPaymentRequest!.address;
+ // _memoControllers[0].text = widget.initialPaymentRequest!.note;
+ _applyNote(widget.initialPaymentRequest!.note, 0);
+ final contractAddress = widget.initialPaymentRequest!.contractAddress;
+ if (contractAddress != null && contractAddress.isNotEmpty) {
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ if (!mounted) {
+ return;
+ }
+ final token = await TokenUtilities.findTokenByAddress(
+ walletType: widget.sendViewModel.wallet.type,
+ address: contractAddress,
+ );
+ if (!mounted) {
+ return;
+ }
- /// if the current wallet doesn't match the one in the qr code
- if (widget.initialPaymentRequest != null &&
- widget.sendViewModel.walletCurrencyName !=
- widget.initialPaymentRequest!.scheme.toLowerCase()) {
- WidgetsBinding.instance.addPostFrameCallback(
- (timeStamp) {
- if (mounted) {
- final prefix = widget.initialPaymentRequest!.scheme.isNotEmpty
- ? "${widget.initialPaymentRequest!.scheme}:"
- : "";
- final amount = widget.initialPaymentRequest!.amount.isNotEmpty
- ? "?amount=${widget.initialPaymentRequest!.amount}"
- : "";
- final uri = prefix + widget.initialPaymentRequest!.address + amount;
- _handlePaymentFlow(uri, widget.initialPaymentRequest!);
- }
- },
- );
+ if (token == null) {
+ _showUnsupportedTokenAlert();
+ return;
+ }
+ await widget.sendViewModel.fetchTokenForContractAddress(contractAddress);
+ if (!mounted) {
+ return;
+ }
+ _amountControllers[0].text =
+ widget.initialPaymentRequest!.resolveTokenAmount(token) ?? "";
+ });
+ } else {
+ _amountControllers[0].text = widget.initialPaymentRequest!.amount;
+ }
+ } else {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (timeStamp) {
+ if (mounted) {
+ final paymentRequest = widget.initialPaymentRequest!;
+ final scheme = paymentRequest.scheme.toLowerCase();
+ final String uri;
+ if (scheme.isEmpty || scheme == "lightning") {
+ uri = paymentRequest.address;
+ } else if (scheme == "ethereum") {
+ uri = ERC681URI(
+ address: paymentRequest.address,
+ amount: paymentRequest.amount,
+ contractAddress: paymentRequest.contractAddress,
+ chainId: paymentRequest.chainId ?? _currentEvmChainIdOrMainnet(),
+ rawTokenAmount: paymentRequest.rawTokenAmount,
+ ).toString();
+ } else {
+ final amount =
+ paymentRequest.amount.isNotEmpty ? "?amount=${paymentRequest.amount}" : "";
+ uri = "${paymentRequest.scheme}:${paymentRequest.address}$amount";
+ }
+ _handlePaymentFlow(uri, paymentRequest);
+ }
+ },
+ );
+ }
}
_addressFocusNode.addListener(() async {
@@ -480,6 +513,12 @@ class _NewSendPageState extends State<NewSendPage> {
selectedCurrency:
widget.sendViewModel.selectedCryptoCurrency,
),
+ if (widget.sendViewModel.isEVMWallet &&
+ _hasEvmRecipient(output))
+ RecipientNetworkSelector(
+ wallet: widget.sendViewModel.wallet,
+ onTap: _presentRecipientNetworkPicker,
+ ),
],
),
Column(
@@ -943,6 +982,7 @@ class _NewSendPageState extends State<NewSendPage> {
selected: widget.sendViewModel.selectedCryptoCurrency,
filterByNetwork: widget.sendViewModel.walletType,
balanceByAsset: balanceByAsset,
+ useSingleNetworkLayout: true,
symbolResolver: widget.sendViewModel.amountParsingProxy.getCryptoSymbol,
onSelected: (currency) {
widget.sendViewModel.selectedCryptoCurrency = currency;
@@ -963,8 +1003,101 @@ class _NewSendPageState extends State<NewSendPage> {
} catch (_) {}
}
+ static final RegExp _evmAddressRegExp = RegExp(r"^0x[0-9a-fA-F]{40}$");
+
+ bool _hasEvmRecipient(Output output) {
+ final address = output.isParsedAddress ? output.extractedAddress : output.address;
+ return _evmAddressRegExp.hasMatch(address.trim());
+ }
+
+ Future<void> _presentRecipientNetworkPicker(ChainInfo currentChain) async {
+ if (evm == null) {
+ return;
+ }
+
+ final chains = evm!.getAllChains();
+ final networks = chains.map((chain) {
+ final walletType =
+ evm!.getWalletTypeByChainId(chain.chainId) ?? widget.sendViewModel.wallet.type;
+ return RecipientNetworkItem(
+ chainId: chain.chainId,
+ name: chain.name,
+ iconPath: symbolIconPathForWalletType(walletType) ?? "",
+ );
+ }).toList();
+
+ final selectedChainId = await SelectRecipientNetworkSheet.show(
+ context: context,
+ networks: networks,
+ currentChainId: currentChain.chainId,
+ );
+
+ if (selectedChainId == null || selectedChainId == currentChain.chainId) {
+ return;
+ }
+
+ final target = chains.firstWhere(
+ (chain) => chain.chainId == selectedChainId,
+ orElse: () => currentChain,
+ );
+ if (target.chainId == currentChain.chainId) {
+ return;
+ }
+
+ await _handleManualNetworkSelection(target);
+ }
+
+ Future<void> _handleManualNetworkSelection(ChainInfo target) async {
+ final address = _addressControllers[_selectedOutput].text.trim();
+ final amount = _amountControllers[_selectedOutput].text;
+ final note = _memoControllers[_selectedOutput].text;
+ final paymentRequest = PaymentRequest(address, amount, note, "", null);
+ await _handleEvmNetworkFlow(target, paymentRequest);
+ }
+
+ bool _isInitialRequestTypeSameAsCurrentWallet() {
+ final req = widget.initialPaymentRequest;
+ if (req == null) {
+ return false;
+ }
+
+ final currentType = widget.sendViewModel.wallet.type;
+ if (evm != null && isEVMCompatibleChain(currentType)) {
+ final targetChainId = _evmTargetChainId(req);
+ if (targetChainId != null) {
+ return targetChainId == _currentEvmChainIdOrMainnet();
+ }
+ }
+ return widget.sendViewModel.walletCurrencyName == req.scheme.toLowerCase();
+ }
+
+ int? _evmTargetChainId(PaymentRequest req) {
+ final scheme = req.scheme.toLowerCase();
+ if (scheme == "ethereum") {
+ if (req.chainId != null) {
+ return req.chainId;
+ }
+
+ return _currentEvmChainIdOrMainnet();
+ }
+ try {
+ return getChainIdByCryptoCurrency(CryptoCurrency.fromString(scheme));
+ } catch (_) {
+ return null;
+ }
+ }
+
+ int _currentEvmChainIdOrMainnet() {
+ final wallet = widget.sendViewModel.wallet;
+ if (evm != null && isEVMCompatibleChain(wallet.type)) {
+ return evm!.getSelectedChainId(wallet) ?? evm!.getChainIdByWalletType(wallet.type);
+ }
+ return 1;
+ }
+
Future<void> _handlePaymentFlow(String uri, PaymentRequest paymentRequest) async {
- if (uri.contains("@") || paymentRequest.address.contains("@")) {
+ final isEip681 = uri.toLowerCase().startsWith("ethereum:");
+ if (!isEip681 && (uri.contains("@") || paymentRequest.address.contains("@"))) {
return;
}
@@ -1003,29 +1136,36 @@ class _NewSendPageState extends State<NewSendPage> {
);
break;
case PaymentFlowType.evmNetworkSelection:
- await _showTokenSelectionFlow(
- widget.paymentViewModel,
- widget.walletSwitcherViewModel,
- paymentRequest,
- fixedNetwork: result.walletType,
- );
+ if (result.chainId != null && evm!.getChainInfoByChainId(result.chainId!) == null) {
+ _showUnsupportedNetworkAlert(result.chainId!);
+ return;
+ }
+
+ final targetChainId =
+ paymentRequest.scheme.isNotEmpty ? _evmTargetChainId(paymentRequest) : null;
+ final targetChain =
+ targetChainId != null ? evm!.getChainInfoByChainId(targetChainId) : null;
+ final currentChainId = isEVMCompatibleChain(widget.sendViewModel.wallet.type)
+ ? _currentEvmChainIdOrMainnet()
+ : null;
+ final isCrossChain = targetChain != null && targetChain.chainId != currentChainId;
+
+ if (isCrossChain) {
+ await _handleEvmNetworkFlow(targetChain, paymentRequest);
+ } else if (widget.sendViewModel.isEVMWallet) {
+ _applyPaymentRequest(paymentRequest);
+ } else {
+ await _showEvmNetworkPicker(paymentRequest, result.walletType);
+ }
break;
case PaymentFlowType.solanaTokenSelection:
- await _showTokenSelectionFlow(
- widget.paymentViewModel,
- widget.walletSwitcherViewModel,
- paymentRequest,
- fixedNetwork: WalletType.solana,
- );
- break;
case PaymentFlowType.tronTokenSelection:
- await _showTokenSelectionFlow(
+ await _showPaymentConfirmation(
widget.paymentViewModel,
widget.walletSwitcherViewModel,
paymentRequest,
- fixedNetwork: WalletType.tron,
+ result,
);
-
break;
case PaymentFlowType.currentWalletCompatible:
case PaymentFlowType.error:
@@ -1039,287 +1179,391 @@ class _NewSendPageState extends State<NewSendPage> {
}
}
- Future<void> _showPaymentConfirmation(
- PaymentViewModel paymentViewModel,
- WalletSwitcherViewModel walletSwitcherViewModel,
- PaymentRequest paymentRequest,
- PaymentFlowResult result,
- ) async {
- if (!context.mounted) {
+ void _showUnsupportedNetworkAlert(int chainId) {
+ if (!mounted) {
return;
}
- await showModalBottomSheet<void>(
+ showPopUp<void>(
context: context,
- isDismissible: true,
- isScrollControlled: true,
- builder: (context) => PaymentConfirmationBottomSheet(
- paymentFlowResult: result,
- paymentViewModel: paymentViewModel,
- walletSwitcherViewModel: walletSwitcherViewModel,
- paymentRequest: paymentRequest,
- onSelectWallet: () => _handleSelectWallet(
- paymentViewModel,
- walletSwitcherViewModel,
- paymentRequest,
- result,
- ),
- onChangeWallet: () => _handleChangeWallet(
- paymentViewModel,
- walletSwitcherViewModel,
- paymentRequest,
- result,
- ),
- onSwap: (bottomSheetContext) =>
- _handleSwapFlow(paymentViewModel, result, bottomSheetContext),
- onSwitchNetwork: () => _handleSwitchNetwork(
- paymentViewModel,
- walletSwitcherViewModel,
- paymentRequest,
- result,
- ),
+ builder: (context) => AlertWithOneAction(
+ alertTitle: S.of(context).error,
+ alertContent: S.of(context).unsupported_network_requested(chainId.toString()),
+ buttonText: S.of(context).ok,
+ buttonAction: () => Navigator.of(context).pop(),
),
);
}
- Future<void> _showTokenSelectionFlow(
+ Future<void> _showPaymentConfirmation(
PaymentViewModel paymentViewModel,
WalletSwitcherViewModel walletSwitcherViewModel,
- PaymentRequest paymentRequest, {
- WalletType? fixedNetwork,
- }) async {
- if (!context.mounted) {
+ PaymentRequest paymentRequest,
+ PaymentFlowResult result,
+ ) async {
+ if (!mounted || result.walletType == null) {
return;
}
- await showModalBottomSheet<void>(
- context: context,
- isDismissible: true,
- isScrollControlled: true,
- builder: (context) => TokenSelectionBottomSheet(
- paymentViewModel: paymentViewModel,
- paymentRequest: paymentRequest,
- fixedNetwork: fixedNetwork,
- onNext: (newResult) {
- final selectedChainId = newResult.chainId;
- final isCompatible =
- selectedChainId == evm?.getSelectedChainId(widget.sendViewModel.wallet);
-
- if (isCompatible) {
- widget.sendViewModel.setSelectedCryptoCurrency(
- newResult.addressDetectionResult!.detectedCurrency!.title,
- );
- _applyPaymentRequest(paymentRequest);
- } else {
- _showPaymentConfirmation(
- paymentViewModel,
- walletSwitcherViewModel,
+ final destinationType = result.walletType!;
+ final isEvmTarget = isEVMCompatibleChain(destinationType);
+ final destinationChainId = result.chainId;
+ final destinationNetworkName = networkDisplayName(destinationType, destinationChainId);
+ final destinationNetworkIcon = symbolIconPathForWalletType(destinationType) ?? "";
+
+ final currentType = widget.sendViewModel.wallet.type;
+ final currentChainId =
+ isEVMCompatibleChain(currentType) && evm != null ? _currentEvmChainIdOrMainnet() : null;
+ final currentNetworkName = networkDisplayName(currentType, currentChainId);
+ final currentNetworkIcon = symbolIconPathForWalletType(currentType) ?? "";
+
+ final hasSingleWallet =
+ result.type == PaymentFlowType.singleWallet || result.wallets.length == 1;
+ final hasMultipleWallets =
+ result.type == PaymentFlowType.multipleWallets || result.wallets.length > 1;
+ final hasWallet = hasSingleWallet || hasMultipleWallets || result.wallet != null;
+
+ final decisionTitle = isEvmTarget
+ ? S.of(context).send_to_network(destinationNetworkName)
+ : S.of(context).network_address_detected(destinationNetworkName);
+ final swapConfirmTitle = isEvmTarget
+ ? S.of(context).swap_from_network(currentNetworkName)
+ : S.of(context).network_address_detected(destinationNetworkName);
+ final swapConfirmPrimary = isEvmTarget
+ ? S.of(context).continue_to_swap
+ : S.of(context).swap_from_network(currentNetworkName);
+
+ if (hasWallet) {
+ await Navigator.of(context).push<void>(
+ CupertinoPageRoute(
+ builder: (pageContext) => SendToNetworkPage(
+ title: decisionTitle,
+ destinationNetworkName: destinationNetworkName,
+ destinationIconPath: destinationNetworkIcon,
+ currentNetworkName: currentNetworkName,
+ onSwitchWallet: () => _onSwitchWalletSelected(
+ pageContext,
+ result,
paymentRequest,
- newResult,
- );
- }
- },
- ),
- );
+ destinationNetworkName,
+ destinationNetworkIcon,
+ hasMultipleWallets,
+ ),
+ onSwap: () => _onSwapSelected(pageContext, result, paymentRequest),
+ ),
+ ),
+ );
+ } else {
+ await Navigator.of(context).push<void>(
+ CupertinoPageRoute(
+ builder: (pageContext) => SwapFromNetworkPage(
+ title: swapConfirmTitle,
+ primaryButtonText: swapConfirmPrimary,
+ primaryHasSwapIcon: !isEvmTarget,
+ destinationNetworkName: destinationNetworkName,
+ destinationNetworkIconPath: destinationNetworkIcon,
+ currentNetworkName: currentNetworkName,
+ currentNetworkIconPath: currentNetworkIcon,
+ onProceed: () => _onSwapSelected(pageContext, result, paymentRequest),
+ ),
+ ),
+ );
+ }
}
- Future<void> _handleSelectWallet(
- PaymentViewModel paymentViewModel,
- WalletSwitcherViewModel walletSwitcherViewModel,
+ Future<void> _onSwapSelected(
+ BuildContext pageContext,
+ PaymentFlowResult result,
PaymentRequest paymentRequest,
+ ) async {
+ await _handleSwapFlow(result, pageContext, paymentRequest);
+ }
+
+ Future<void> _onSwitchWalletSelected(
+ BuildContext pageContext,
PaymentFlowResult result,
+ PaymentRequest paymentRequest,
+ String destName,
+ String destIcon,
+ bool hasMultipleWallets,
) async {
- Navigator.of(context).pop();
+ WalletInfo? destinationWalletInfo;
+ if (hasMultipleWallets) {
+ destinationWalletInfo = await SwitchNetworkWalletPage.push(
+ context: pageContext,
+ networkName: destName,
+ targetIconPath: destIcon,
+ wallets: result.wallets,
+ );
+ if (destinationWalletInfo == null) {
+ return;
+ }
+ } else {
+ destinationWalletInfo =
+ result.wallet ?? (result.wallets.isNotEmpty ? result.wallets.first : null);
+ }
- await showModalBottomSheet<WalletInfo>(
- context: context,
- isDismissible: true,
- isScrollControlled: true,
- builder: (dialogContext) => WalletSwitcherBottomSheet(
- viewModel: walletSwitcherViewModel,
- filterWalletType: paymentViewModel.detectedWalletType,
- ),
- );
+ if (destinationWalletInfo == null) {
+ return;
+ }
- final success = await walletSwitcherViewModel.switchToSelectedWallet();
+ // We may have awaited the wallet picker above, so make sure the decision page
+ // is still around before we reach into its navigator.
+ if (!pageContext.mounted) {
+ return;
+ }
+ if (Navigator.of(pageContext).canPop()) {
+ Navigator.of(pageContext).pop();
+ }
+ if (!mounted) {
+ return;
+ }
+ await _completeWalletSwitch(destinationWalletInfo, result, paymentRequest);
+ }
- if (success) {
- if (isEVMCompatibleChain(widget.sendViewModel.wallet.type) && result.chainId != null) {
- final appStore = getIt.get<AppStore>();
- final node = appStore.settingsStore.getCurrentNode(
- widget.sendViewModel.wallet.type,
- chainId: result.chainId,
- );
- await evm!.selectChain(widget.sendViewModel.wallet, result.chainId!, node: node);
+ Future<void> _applyPaymentSelectingCurrency(
+ PaymentRequest paymentRequest,
+ CryptoCurrency? fallbackCurrency,
+ ) async {
+ String? amountOverride;
+ final contract = paymentRequest.contractAddress;
+ if (contract != null && contract.isNotEmpty) {
+ final token = await TokenUtilities.findTokenByAddress(
+ walletType: widget.sendViewModel.wallet.type,
+ address: contract,
+ );
+ if (!mounted) {
+ return;
}
- await widget.sendViewModel.wallet.updateBalance();
-
- final detectedCurrency = result.addressDetectionResult!.detectedCurrency;
- if (detectedCurrency != null) {
- widget.sendViewModel.setSelectedCryptoCurrency(detectedCurrency.title);
+ if (token == null) {
+ _showUnsupportedTokenAlert();
+ return;
}
-
- _applyPaymentRequest(paymentRequest);
+ await widget.sendViewModel.fetchTokenForContractAddress(contract);
+ amountOverride = paymentRequest.resolveTokenAmount(token);
+ } else if (fallbackCurrency != null) {
+ widget.sendViewModel.setSelectedCryptoCurrency(fallbackCurrency.title);
+ }
+ if (!mounted) {
+ return;
}
+ _applyPaymentRequest(paymentRequest, amountOverride: amountOverride);
}
- Future<void> _handleChangeWallet(
- PaymentViewModel paymentViewModel,
- WalletSwitcherViewModel walletSwitcherViewModel,
- PaymentRequest paymentRequest,
+ Future<void> _completeWalletSwitch(
+ WalletInfo wallet,
PaymentFlowResult result,
+ PaymentRequest paymentRequest,
) async {
- if (mounted && Navigator.of(context).canPop()) {
- Navigator.of(context).pop();
+ widget.walletSwitcherViewModel.selectWallet(wallet);
+ final success = await widget.walletSwitcherViewModel.switchToSelectedWallet();
+ if (!success) {
+ _showNetworkSwitchFailedAlert();
+ return;
+ }
+ if (!mounted) {
+ return;
}
- if (result.type == PaymentFlowType.singleWallet && result.wallet != null) {
- walletSwitcherViewModel.selectWallet(result.wallet!);
- final success = await walletSwitcherViewModel.switchToSelectedWallet();
- if (success) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) {
- showModalBottomSheet<void>(
- context: context,
- isDismissible: false,
- builder: (context) {
- loadingBottomSheetContext = context;
- return LoadingBottomSheet(
- titleText: S.of(context).loading_your_wallet,
- );
- },
- );
+ bool completedFlow = false;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || completedFlow) {
+ return;
+ }
+ showModalBottomSheet<void>(
+ context: context,
+ isDismissible: false,
+ builder: (BuildContext sheetContext) {
+ if (completedFlow) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (Navigator.canPop(sheetContext)) {
+ Navigator.of(sheetContext).pop();
+ }
+ });
+ return const SizedBox.shrink();
}
- });
-
- // If EVM wallet and chainId is specified, switch to that chain
- if (isEVMCompatibleChain(widget.sendViewModel.wallet.type) && result.chainId != null) {
- final appStore = getIt.get<AppStore>();
- final node = appStore.settingsStore.getCurrentNode(
- widget.sendViewModel.wallet.type,
- chainId: result.chainId,
- );
- await evm!.selectChain(widget.sendViewModel.wallet, result.chainId!, node: node);
- }
+ loadingBottomSheetContext = sheetContext;
+ return LoadingBottomSheet(titleText: S.of(sheetContext).loading_your_wallet);
+ },
+ );
+ });
- await Future.delayed(const Duration(seconds: 2));
- if (loadingBottomSheetContext != null &&
- loadingBottomSheetContext!.mounted &&
- Navigator.canPop(loadingBottomSheetContext!)) {
- Navigator.of(loadingBottomSheetContext!).pop();
- }
+ bool chainSwitchFailed = false;
+ try {
+ if (evm != null &&
+ isEVMCompatibleChain(widget.sendViewModel.wallet.type) &&
+ result.chainId != null) {
+ final appStore = getIt.get<AppStore>();
+ final node = appStore.settingsStore
+ .getCurrentNode(widget.sendViewModel.wallet.type, chainId: result.chainId);
+ await evm!.selectChain(widget.sendViewModel.wallet, result.chainId!, node: node);
+ }
+ } catch (e, s) {
+ chainSwitchFailed = true;
+ printV("completeWalletSwitch failed: $e\n$s");
+ }
+ if (!chainSwitchFailed) {
+ try {
await widget.sendViewModel.wallet.updateBalance();
- widget.sendViewModel
- .setSelectedCryptoCurrency(result.addressDetectionResult!.detectedCurrency!.title);
- _applyPaymentRequest(paymentRequest);
+ } catch (e) {
+ printV("balance refresh after network switch failed: $e");
}
- } else if (result.wallets.isNotEmpty && result.wallets.length == 1) {
- walletSwitcherViewModel.selectWallet(result.wallets.first);
- final success = await walletSwitcherViewModel.switchToSelectedWallet();
- if (success) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (context.mounted) {
- showModalBottomSheet<void>(
- context: context,
- isDismissible: false,
- builder: (context) {
- loadingBottomSheetContext = context;
- return LoadingBottomSheet(
- titleText: S.of(context).loading_your_wallet,
- );
- },
- );
- }
- });
-
- // If EVM wallet and chainId is specified, switch to that chain
- if (isEVMCompatibleChain(widget.sendViewModel.wallet.type) && result.chainId != null) {
- final appStore = getIt.get<AppStore>();
- final node = appStore.settingsStore.getCurrentNode(
- widget.sendViewModel.wallet.type,
- chainId: result.chainId,
- );
- await evm!.selectChain(widget.sendViewModel.wallet, result.chainId!, node: node);
- }
+ }
- await Future.delayed(const Duration(seconds: 2));
- if (loadingBottomSheetContext != null && loadingBottomSheetContext!.mounted) {
- Navigator.of(loadingBottomSheetContext!).pop();
- }
+ completedFlow = true;
+ if (loadingBottomSheetContext != null &&
+ loadingBottomSheetContext!.mounted &&
+ Navigator.canPop(loadingBottomSheetContext!)) {
+ Navigator.of(loadingBottomSheetContext!).pop();
+ }
+ loadingBottomSheetContext = null;
- await widget.sendViewModel.wallet.updateBalance();
- widget.sendViewModel
- .setSelectedCryptoCurrency(result.addressDetectionResult!.detectedCurrency!.title);
- _applyPaymentRequest(paymentRequest);
- }
+ if (!mounted) {
+ return;
}
+
+ if (chainSwitchFailed) {
+ _showNetworkSwitchFailedAlert();
+ return;
+ }
+
+ await _applyPaymentSelectingCurrency(
+ paymentRequest,
+ result.addressDetectionResult?.detectedCurrency,
+ );
}
- Future<void> _handleSwitchNetwork(
- PaymentViewModel paymentViewModel,
- WalletSwitcherViewModel walletSwitcherViewModel,
+ void _showNetworkSwitchFailedAlert() {
+ if (!mounted) {
+ return;
+ }
+
+ showPopUp<void>(
+ context: context,
+ builder: (context) => AlertWithOneAction(
+ alertTitle: S.of(context).error,
+ alertContent: S.of(context).network_switch_failed,
+ buttonText: S.of(context).ok,
+ buttonAction: () => Navigator.of(context).pop(),
+ ),
+ );
+ }
+
+ void _showUnsupportedTokenAlert() {
+ if (!mounted) {
+ return;
+ }
+
+ showPopUp<void>(
+ context: context,
+ builder: (context) => AlertWithOneAction(
+ alertTitle: S.of(context).error,
+ alertContent: S.of(context).unsupported_token_requested,
+ buttonText: S.of(context).ok,
+ buttonAction: () => Navigator.of(context).pop(),
+ ),
+ );
+ }
+
+ Future<void> _showEvmNetworkPicker(
PaymentRequest paymentRequest,
- PaymentFlowResult result,
+ WalletType? fixedNetwork,
) async {
- if (result.type != PaymentFlowType.evmNetworkSelection || result.wallet == null) {
+ if (!mounted || evm == null || fixedNetwork == null || !isEVMCompatibleChain(fixedNetwork)) {
return;
}
- if (context.mounted && Navigator.of(context).canPop()) {
- Navigator.of(context).pop();
+ final chains = evm!.getAllChains();
+ final networks = chains.map((chain) {
+ final walletType = evm!.getWalletTypeByChainId(chain.chainId) ?? fixedNetwork;
+ return RecipientNetworkItem(
+ chainId: chain.chainId,
+ name: chain.name,
+ iconPath: getCryptoCurrencyIconForWalletListItem(walletType, chainId: chain.chainId),
+ chainBadgeIconPath: symbolIconPathForWalletType(walletType),
+ );
+ }).toList();
+
+ final selectedChainId =
+ await EvmAddressDetectedSheet.show(context: context, networks: networks);
+ if (!mounted || selectedChainId == null) {
+ return;
}
- try {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (context.mounted) {
- showModalBottomSheet<void>(
- context: context,
- isDismissible: false,
- builder: (context) {
- loadingBottomSheetContext = context;
- return LoadingBottomSheet(titleText: S.of(context).loading_your_wallet);
- },
- );
- }
- });
+ final target = chains.firstWhere(
+ (chain) => chain.chainId == selectedChainId,
+ orElse: () => chains.first,
+ );
+ await _handleEvmNetworkFlow(target, paymentRequest);
+ }
- await paymentViewModel.selectChain();
+ Future<void> _handleEvmNetworkFlow(ChainInfo target, PaymentRequest paymentRequest) async {
+ if (evm == null || !mounted) {
+ return;
+ }
- await Future.delayed(const Duration(seconds: 2));
- if (loadingBottomSheetContext != null && loadingBottomSheetContext!.mounted) {
- Navigator.of(loadingBottomSheetContext!).pop();
- }
+ final targetType = evm!.getWalletTypeByChainId(target.chainId);
+ if (targetType == null) {
+ _showUnsupportedNetworkAlert(target.chainId);
+ return;
+ }
- await widget.sendViewModel.wallet.updateBalance();
- final detectedCurrency = result.addressDetectionResult?.detectedCurrency;
- if (detectedCurrency != null) {
- widget.sendViewModel.setSelectedCryptoCurrency(detectedCurrency.title);
- }
- _applyPaymentRequest(paymentRequest);
- } catch (e) {
- if (loadingBottomSheetContext != null && loadingBottomSheetContext!.mounted) {
- Navigator.of(loadingBottomSheetContext!).pop();
- }
- printV("Switch network error: $e");
+ final detection = AddressDetectionResult(
+ address: paymentRequest.address,
+ detectedWalletType: targetType,
+ detectedCurrency: target.currency,
+ chainId: target.chainId,
+ amount: paymentRequest.amount,
+ note: paymentRequest.note,
+ scheme: "",
+ isValid: true,
+ );
+ widget.paymentViewModel.applyManualEvmSelection(detection);
+
+ final currentType = widget.sendViewModel.wallet.type;
+ final currentChainId = isEVMCompatibleChain(currentType) ? _currentEvmChainIdOrMainnet() : null;
+ if (currentChainId != null && target.chainId == currentChainId) {
+ await _applyPaymentSelectingCurrency(paymentRequest, target.currency);
+ return;
}
+
+ final compatibleWallets = await widget.paymentViewModel.getWalletsByType(targetType);
+ if (!mounted) {
+ return;
+ }
+
+ final result = PaymentFlowResult.evmNetworkSelection(
+ detection,
+ compatibleWallets: compatibleWallets,
+ wallet: compatibleWallets.isNotEmpty ? compatibleWallets.first : null,
+ );
+
+ await _showPaymentConfirmation(
+ widget.paymentViewModel,
+ widget.walletSwitcherViewModel,
+ paymentRequest,
+ result,
+ );
}
- /// Apply payment request to current form
- void _applyPaymentRequest(PaymentRequest paymentRequest) {
+ void _applyPaymentRequest(PaymentRequest paymentRequest, {String? amountOverride}) {
if (widget.sendViewModel.usePayjoin) {
widget.sendViewModel.payjoinUri = paymentRequest.pjUri;
}
_addressControllers[_selectedOutput].text = paymentRequest.address;
- if (paymentRequest.amount.isNotEmpty) {
+ final amountToApply = amountOverride ?? paymentRequest.amount;
+ if (amountToApply.isNotEmpty) {
try {
_amountControllers[_selectedOutput].text =
widget.sendViewModel.amountParsingProxy.getDisplayCryptoAmount(
- paymentRequest.amount,
+ amountToApply,
widget.sendViewModel.selectedCryptoCurrency,
);
- } catch (e) {}
+ } catch (e) {
+ printV('applyPaymentRequest: failed to parse amount "$amountToApply": $e');
+ }
}
// _memoControllers[_selectedOutput].text = paymentRequest.note;
@@ -1327,24 +1571,77 @@ class _NewSendPageState extends State<NewSendPage> {
}
Future<void> _handleSwapFlow(
- PaymentViewModel paymentViewModel,
PaymentFlowResult result,
- BuildContext bottomSheetContext,
+ BuildContext presentContext,
+ PaymentRequest paymentRequest,
) async {
- Navigator.of(bottomSheetContext).pop();
+ if (!mounted) {
+ return;
+ }
- await Future.delayed(const Duration(milliseconds: 100));
+ final destWalletType = result.walletType;
+ if (destWalletType == null) {
+ return;
+ }
- if (!mounted) {
+ CryptoCurrency? resolvedToken;
+ final contract = paymentRequest.contractAddress;
+ if (contract != null && contract.isNotEmpty) {
+ resolvedToken = await TokenUtilities.findTokenByAddress(
+ walletType: destWalletType,
+ address: contract,
+ );
+ }
+ if (!mounted || !presentContext.mounted) {
return;
}
- final bottomSheet = getIt.get<SwapConfirmationBottomSheet>(param1: result);
- await showModalBottomSheet<Trade?>(
- context: context,
- isDismissible: true,
- isScrollControlled: true,
- builder: (context) => bottomSheet,
+ if (contract != null && contract.isNotEmpty && resolvedToken == null) {
+ _showUnsupportedTokenAlert();
+ return;
+ }
+
+ final receiveCurrency = resolvedToken ??
+ result.detectedCurrency ??
+ walletTypeToCryptoCurrency(destWalletType, chainId: result.chainId);
+
+ final receiveAmountValue = resolvedToken != null
+ ? paymentRequest.resolveTokenAmount(resolvedToken)
+ : (paymentRequest.amount.isNotEmpty ? paymentRequest.amount : null);
+ final receiveAmount =
+ receiveAmountValue != null ? Money.tryParse(receiveAmountValue, receiveCurrency) : null;
+
+ final isFiatDisabled = widget.sendViewModel.isFiatDisabled;
+ final depositBalanceByAsset = <CryptoCurrency, CurrencyPickerBalance>{
+ for (final r in widget.sendViewModel.balanceViewModel.formattedBalances)
+ r.asset: CurrencyPickerBalance(
+ amount: "${r.availableBalance} ${r.asset.title}",
+ fiat: isFiatDisabled ? null : "${r.fiatAvailableBalanceRaw} ${r.fiatCurrency?.symbol}",
+ fiatValue: isFiatDisabled ? null : double.tryParse(r.fiatAvailableBalanceRaw),
+ ),
+ };
+
+ final page = NewSwapPage(
+ getIt.get<ExchangeViewModel>(),
+ widget.authService,
+ getIt.get<AddressResolverService>(),
+ null,
+ walletSwitcherViewModel: widget.walletSwitcherViewModel,
+ fromSend: SwapFromSendArgs(
+ recipientAddress: result.addressDetectionResult?.address ?? "",
+ receiveCurrency: receiveCurrency,
+ targetWalletType: destWalletType,
+ depositBalanceByAsset: depositBalanceByAsset,
+ receiveAmount: receiveAmount,
+ ),
+ );
+ await Navigator.of(presentContext).push<void>(
+ CupertinoPageRoute(
+ builder: (context) => Material(
+ color: Theme.of(context).colorScheme.surface,
+ child: SafeArea(bottom: false, child: page),
+ ),
+ ),
);
}
diff --git a/lib/new-ui/pages/swap_page.dart b/lib/new-ui/pages/swap_page.dart
index 6d3d7049..d1744780 100644
--- a/lib/new-ui/pages/swap_page.dart
+++ b/lib/new-ui/pages/swap_page.dart
@@ -1,59 +1,57 @@
-import 'package:cake_wallet/core/address_resolver/address_resolver_service.dart';
-import 'package:cake_wallet/core/address_validator.dart';
-import 'package:cake_wallet/core/amount_validator.dart';
-import 'package:cake_wallet/core/auth_service.dart';
-import 'package:cake_wallet/di.dart';
-import 'package:cake_wallet/entities/qr_scanner.dart';
-import 'package:cake_wallet/exchange/exchange_trade_state.dart';
-import 'package:cake_wallet/exchange/provider/chainflip_exchange_provider.dart';
-import 'package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart';
-import 'package:cake_wallet/generated/i18n.dart';
-import 'package:cake_wallet/new-ui/widgets/keyboard_hide_overlay.dart';
-import 'package:cake_wallet/new-ui/widgets/modern_button.dart';
-import 'package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart';
-import 'package:cake_wallet/new-ui/widgets/send_page/fiat_amount_bar.dart';
-import 'package:cake_wallet/new-ui/widgets/send_page/send_memo_input.dart';
-import 'package:cake_wallet/new-ui/widgets/send_page/send_syncing_indicator.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/provider_selector_page.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/refund_address_modal.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/swap_address_selection_modal.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/swap_confirm_sheet.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/swap_limit_popup.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_sheet.dart';
-import 'package:cake_wallet/new-ui/widgets/swap_page/swap_options_page.dart';
-import 'package:cake_wallet/src/screens/exchange/widgets/present_provider_picker.dart';
-import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
-import 'package:cake_wallet/src/widgets/alert_with_two_actions.dart';
-import 'package:cake_wallet/src/widgets/cake_image_widget.dart';
-import 'package:cake_wallet/src/widgets/primary_button.dart';
-import 'package:cake_wallet/utils/debounce.dart';
-import 'package:cake_wallet/utils/decimal_input_formatter.dart';
-import 'package:cake_wallet/utils/payment_request.dart';
-import 'package:cake_wallet/utils/permission_handler.dart';
-import 'package:cw_core/wallet_info.dart';
-import 'package:flutter/services.dart';
-import 'package:permission_handler/permission_handler.dart';
-import 'package:cake_wallet/utils/show_pop_up.dart';
-import 'package:cake_wallet/view_model/exchange/exchange_trade_view_model.dart';
-import 'package:cake_wallet/view_model/exchange/exchange_view_model.dart';
-import 'package:cake_wallet/view_model/wallet_switcher_view_model.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/currencies_with_memo.dart';
-import 'package:cw_core/currency.dart';
-import 'package:cw_core/sync_status.dart';
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:cw_core/wallet_type.dart';
-import 'package:flutter/cupertino.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter_mobx/flutter_mobx.dart';
-import 'package:mobx/mobx.dart';
-import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
+import "package:cake_wallet/core/address_resolver/address_resolver_service.dart";
+import "package:cake_wallet/core/address_validator.dart";
+import "package:cake_wallet/core/amount_validator.dart";
+import "package:cake_wallet/core/auth_service.dart";
+import "package:cake_wallet/di.dart";
+import "package:cake_wallet/exchange/exchange_trade_state.dart";
+import "package:cake_wallet/exchange/provider/chainflip_exchange_provider.dart";
+import "package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart";
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/keyboard_hide_overlay.dart";
+import "package:cake_wallet/new-ui/widgets/modern_button.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/new-ui/widgets/send_page/send_syncing_indicator.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/anypay_swap_footer.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/provider_selector_page.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_amount_box.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_confirm_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_from_send_args.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_limit_popup.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_options_page.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_section_header.dart";
+import "package:cake_wallet/src/screens/exchange/widgets/present_provider_picker.dart";
+import "package:cake_wallet/src/widgets/alert_with_one_action.dart";
+import "package:cake_wallet/src/widgets/alert_with_two_actions.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cake_wallet/src/widgets/primary_button.dart";
+import "package:cake_wallet/utils/debounce.dart";
+import "package:cake_wallet/utils/payment_request.dart";
+import "package:cake_wallet/utils/show_pop_up.dart";
+import "package:cake_wallet/view_model/exchange/exchange_trade_view_model.dart";
+import "package:cake_wallet/view_model/exchange/exchange_view_model.dart";
+import "package:cake_wallet/view_model/wallet_switcher_view_model.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:cw_core/sync_status.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter/cupertino.dart";
+import "package:flutter/material.dart";
+import "package:flutter/services.dart";
+import "package:flutter_mobx/flutter_mobx.dart";
+import "package:mobx/mobx.dart";
+import "package:modal_bottom_sheet/modal_bottom_sheet.dart";
class NewSwapPage extends StatefulWidget {
NewSwapPage(
- this.exchangeViewModel, this.authService, this.adrResService, this.initialPaymentRequest,
- {required this.walletSwitcherViewModel, CryptoCurrency? initialCurrency}) {
+ this.exchangeViewModel,
+ this.authService,
+ this.adrResService,
+ this.initialPaymentRequest, {
+ required this.walletSwitcherViewModel,
+ CryptoCurrency? initialCurrency,
+ this.fromSend,
+ }) {
depositWalletName = exchangeViewModel.depositCurrency == CryptoCurrency.xmr
? exchangeViewModel.wallet.name
: null;
@@ -70,6 +68,7 @@ class NewSwapPage extends StatefulWidget {
final AuthService authService;
final AddressResolverService adrResService;
final PaymentRequest? initialPaymentRequest;
+ final SwapFromSendArgs? fromSend;
late final String? depositWalletName;
late final String? receiveWalletName;
@@ -85,8 +84,9 @@ class _NewSwapPageState extends State<NewSwapPage> {
final _depositAddressFocus = FocusNode();
final _receiveAmountFocus = FocusNode();
final _receiveAddressFocus = FocusNode();
- final _receiveAmountDebounce = Debounce(Duration(milliseconds: 500));
- Debounce _depositAmountDebounce = Debounce(Duration(milliseconds: 500));
+ final _receiveAmountDebounce = Debounce(const Duration(milliseconds: 500));
+ Debounce _depositAmountDebounce = Debounce(const Duration(milliseconds: 500));
+ final List<ReactionDisposer> _disposers = [];
bool get _shouldWaitTillSynced =>
[CryptoCurrency.xmr, CryptoCurrency.btc, CryptoCurrency.ltc]
@@ -101,6 +101,10 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) {
+ return;
+ }
+
// if (!widget.exchangeViewModel.decentralizedExchangesPromptDismissed) {
// showMaterialModalBottomSheet(
// context: context,
@@ -129,7 +133,10 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
widget.exchangeViewModel.isFixedRateMode = false;
widget.exchangeViewModel.isSendAllEnabled = false;
- Future.delayed(Duration(milliseconds: 200)).then((_) {
+ Future.delayed(const Duration(milliseconds: 200)).then((_) {
+ if (!mounted) {
+ return;
+ }
if (double.tryParse(depositFiatAmountController.text) != null) {
widget.exchangeViewModel
.setDepositAmountFromFiat(fiatAmount: depositFiatAmountController.text);
@@ -138,16 +145,21 @@ class _NewSwapPageState extends State<NewSwapPage> {
});
});
receiveFiatAmountController.addListener(() {
- if (!receiveKey.currentState!.amountFocusNode.hasFocus) return;
+ if (!receiveKey.currentState!.amountFocusNode.hasFocus) {
+ return;
+ }
widget.exchangeViewModel.enableFixedRateMode();
widget.exchangeViewModel.isSendAllEnabled = false;
- Future.delayed(Duration(milliseconds: 200)).then((_) {
+ Future.delayed(const Duration(milliseconds: 200)).then((_) {
+ if (!mounted) {
+ return;
+ }
if (double.tryParse(receiveFiatAmountController.text) != null) {
String text = receiveFiatAmountController.text;
if (text.contains(".")) {
- text = text.replaceAll(RegExp(r'0+$'), '');
- text = text.replaceAll(RegExp(r'\.$'), '');
+ text = text.replaceAll(RegExp(r"0+$"), "");
+ text = text.replaceAll(RegExp(r"\.$"), "");
}
widget.exchangeViewModel
.setReceiveAmountFromFiat(fiatAmount: receiveFiatAmountController.text);
@@ -155,97 +167,121 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
});
});
- reaction((_) => widget.exchangeViewModel.isFixedRateMode, (val) {
- Future.delayed(Duration(seconds: 3)).then((_) {
+ _disposers.add(reaction((_) => widget.exchangeViewModel.isFixedRateMode, (val) {
+ Future.delayed(const Duration(seconds: 3)).then((_) {
if (val) {
- if (depositKey.currentState?.mounted == true)
+ if (depositKey.currentState?.mounted == true) {
depositKey.currentState!.updateFiatAmount();
+ }
} else {
- if (receiveKey.currentState?.mounted == true)
+ if (receiveKey.currentState?.mounted == true) {
receiveKey.currentState!.updateFiatAmount();
+ }
}
});
- });
+ }));
- reaction((_) => widget.exchangeViewModel.depositAmount, (String amount) {
- if (depositKey.currentState!.amountFocusNode.hasFocus) return;
+ _disposers.add(reaction((_) => widget.exchangeViewModel.depositAmount, (String amount) {
+ if (depositKey.currentState!.amountFocusNode.hasFocus) {
+ return;
+ }
if (widget.exchangeViewModel.isSendAllEnabled) {
depositAmountController.text = S.of(context).all;
} else if (depositAmountController.text != amount && amount != S.of(context).all) {
depositAmountController.text = amount;
}
- });
+ }));
_onCurrencyChange(
- widget.exchangeViewModel.receiveCurrency, widget.exchangeViewModel, receiveKey);
+ widget.exchangeViewModel.receiveCurrency,
+ widget.exchangeViewModel,
+ receiveKey,
+ );
_onCurrencyChange(
- widget.exchangeViewModel.depositCurrency, widget.exchangeViewModel, depositKey);
-
- reaction(
- (_) => widget.exchangeViewModel.wallet.name,
- (_) => _onWalletNameChange(
- widget.exchangeViewModel, widget.exchangeViewModel.receiveCurrency, receiveKey));
+ widget.exchangeViewModel.depositCurrency,
+ widget.exchangeViewModel,
+ depositKey,
+ );
- reaction(
- (_) => widget.exchangeViewModel.wallet.name,
- (_) => _onWalletNameChange(
- widget.exchangeViewModel, widget.exchangeViewModel.depositCurrency, depositKey));
+ _disposers.add(reaction(
+ (_) => widget.exchangeViewModel.wallet.name,
+ (_) => _onWalletNameChange(
+ widget.exchangeViewModel,
+ widget.exchangeViewModel.receiveCurrency,
+ receiveKey,
+ ),
+ ));
+
+ _disposers.add(reaction(
+ (_) => widget.exchangeViewModel.wallet.name,
+ (_) => _onWalletNameChange(
+ widget.exchangeViewModel,
+ widget.exchangeViewModel.depositCurrency,
+ depositKey,
+ ),
+ ));
- reaction(
+ _disposers.add(reaction(
(_) => widget.exchangeViewModel.receiveCurrency,
(currency) => _onCurrencyChange(currency, widget.exchangeViewModel, receiveKey),
- );
+ ));
- reaction(
+ _disposers.add(reaction(
(_) => widget.exchangeViewModel.depositCurrency,
(currency) => _onCurrencyChange(currency, widget.exchangeViewModel, depositKey),
- );
+ ));
- reaction((_) => widget.exchangeViewModel.depositAddress, (String address) {
+ _disposers.add(reaction((_) => widget.exchangeViewModel.depositAddress, (String address) {
if (depositKey.currentState!.addressController.text != address) {
depositKey.currentState!.addressController.text = address;
}
- });
+ }));
- reaction((_) => widget.exchangeViewModel.isDepositAddressEnabled, (isEnabled) {});
+ _disposers
+ .add(reaction((_) => widget.exchangeViewModel.isDepositAddressEnabled, (isEnabled) {}));
- reaction((_) => widget.exchangeViewModel.receiveAmount, (String amount) {
+ _disposers.add(reaction((_) => widget.exchangeViewModel.receiveAmount, (String amount) {
if (receiveKey.currentState!.amountController.text != amount) {
receiveKey.currentState!.amountController.text = amount;
}
- });
+ }));
- reaction((_) => widget.exchangeViewModel.receiveAddress, (String address) {
+ _disposers.add(reaction((_) => widget.exchangeViewModel.receiveAddress, (String address) {
if (receiveKey.currentState!.addressController.text != address) {
receiveKey.currentState!.addressController.text = address;
}
- });
+ }));
- reaction((_) => widget.exchangeViewModel.isReceiveAmountEditable,
- (bool isReceiveAmountEditable) {});
+ _disposers.add(reaction(
+ (_) => widget.exchangeViewModel.isReceiveAmountEditable,
+ (bool isReceiveAmountEditable) {},
+ ));
- reaction((_) => widget.exchangeViewModel.tradeState, (ExchangeTradeState state) {
+ _disposers
+ .add(reaction((_) => widget.exchangeViewModel.tradeState, (ExchangeTradeState state) {
if (state is TradeIsCreatedFailure) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
showPopUp<void>(
- context: context,
- builder: (BuildContext context) {
- return AlertWithOneAction(
- key: ValueKey('exchange_page_trade_creation_failure_dialog_key'),
- buttonKey:
- ValueKey('exchange_page_trade_creation_failure_dialog_button_key'),
- alertTitle: S.of(context).provider_error(state.title),
- alertContent: state.error,
- buttonText: S.of(context).ok,
- buttonAction: () => Navigator.of(context).pop());
- });
+ context: context,
+ builder: (BuildContext context) => AlertWithOneAction(
+ key: const ValueKey("exchange_page_trade_creation_failure_dialog_key"),
+ buttonKey:
+ const ValueKey("exchange_page_trade_creation_failure_dialog_button_key"),
+ alertTitle: S.of(context).provider_error(state.title),
+ alertContent: state.error,
+ buttonText: S.of(context).ok,
+ buttonAction: () => Navigator.of(context).pop(),
+ ),
+ );
}
});
}
if (state is TradeIsCreatedSuccessfully) {
- if (widget.exchangeViewModel.tradeStarted) return;
+ if (widget.exchangeViewModel.tradeStarted) {
+ return;
+ }
final receiveAmount = widget.exchangeViewModel.receiveAmount;
// FIXME we don't know why a reset is/was needed here, it messes up ui so i removed it
// widget.exchangeViewModel.reset();
@@ -263,27 +299,44 @@ class _NewSwapPageState extends State<NewSwapPage> {
receiveAmount: receiveAmount,
);
showMaterialModalBottomSheet(
- context: context, builder: (context) => page, backgroundColor: Colors.transparent);
+ context: context,
+ builder: (context) => page,
+ backgroundColor: Colors.transparent,
+ );
}
- });
+ }));
- reaction((_) => widget.exchangeViewModel.bestRate, (double rate) {
+ _disposers.add(reaction((_) => widget.exchangeViewModel.bestRate, (double rate) {
if (widget.exchangeViewModel.isFixedRateMode) {
widget.exchangeViewModel.changeReceiveAmount(amount: receiveAmountController.text);
} else {
printV("bestrate");
- if ((depositKey.currentState?._fiatInputMode ?? false) ||
+ if ((depositKey.currentState?.fiatInputMode ?? false) ||
depositAmountController.text.isEmpty ||
- depositAmountController.text == S.current.all)
+ depositAmountController.text == S.current.all) {
widget.exchangeViewModel
.changeDepositAmount(amount: widget.exchangeViewModel.depositAmount);
- else
+ } else {
widget.exchangeViewModel.changeDepositAmount(amount: depositAmountController.text);
+ }
}
- });
+ }));
+
+ _disposers.add(reaction((_) => widget.exchangeViewModel.forcedProviderRate, (double rate) {
+ if (widget.exchangeViewModel.forcedProvider != null && rate == 0) {
+ return;
+ }
+ if (widget.exchangeViewModel.isFixedRateMode) {
+ widget.exchangeViewModel.changeReceiveAmount(amount: receiveAmountController.text);
+ } else if (depositAmountController.text.isNotEmpty &&
+ depositAmountController.text != S.current.all) {
+ widget.exchangeViewModel.changeDepositAmount(amount: depositAmountController.text);
+ }
+ }));
depositAddressController.addListener(
- () => widget.exchangeViewModel.depositAddress = depositAddressController.text);
+ () => widget.exchangeViewModel.depositAddress = depositAddressController.text,
+ );
depositAmountController.addListener(() {
if (depositAmountController.text != widget.exchangeViewModel.depositAmount &&
@@ -295,8 +348,8 @@ class _NewSwapPageState extends State<NewSwapPage> {
.any((provider) => provider is ChainflipExchangeProvider);
_depositAmountDebounce = isThorChain || isChainflip
- ? Debounce(Duration(milliseconds: 1000))
- : Debounce(Duration(milliseconds: 500));
+ ? Debounce(const Duration(milliseconds: 1000))
+ : Debounce(const Duration(milliseconds: 500));
_depositAmountDebounce.run(() {
widget.exchangeViewModel.calculateBestRate();
@@ -315,7 +368,8 @@ class _NewSwapPageState extends State<NewSwapPage> {
});
receiveAddressController.addListener(
- () => widget.exchangeViewModel.receiveAddress = receiveAddressController.text);
+ () => widget.exchangeViewModel.receiveAddress = receiveAddressController.text,
+ );
receiveAmountController.addListener(() {
if (receiveAmountController.text != widget.exchangeViewModel.receiveAmount) {
@@ -331,8 +385,9 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
});
- reaction((_) => widget.exchangeViewModel.wallet.walletAddresses.addressForExchange,
- (String address) {
+ _disposers.add(
+ reaction((_) => widget.exchangeViewModel.wallet.walletAddresses.addressForExchange,
+ (String address) {
if (widget.exchangeViewModel.depositCurrency == CryptoCurrency.xmr) {
depositKey.currentState!.changeAddress(address: address);
}
@@ -340,7 +395,7 @@ class _NewSwapPageState extends State<NewSwapPage> {
// if (widget.exchangeViewModel.receiveCurrency == CryptoCurrency.xmr) {
// receiveKey.currentState!.changeAddress(address: address);
// }
- });
+ }));
_depositAddressFocus.addListener(() async {
if (!_depositAddressFocus.hasFocus && depositAddressController.text.isNotEmpty) {
@@ -378,15 +433,33 @@ class _NewSwapPageState extends State<NewSwapPage> {
widget.exchangeViewModel.setCanonicalReceiveAmount(widget.initialPaymentRequest!.amount);
widget.exchangeViewModel.receiveAddress = widget.initialPaymentRequest!.address;
} catch (e) {
- printV('error: ${e.toString()}');
+ printV("error: ${e.toString()}");
// TODO
}
}
+
+ if (widget.fromSend != null) {
+ widget.exchangeViewModel.changeReceiveCurrency(currency: widget.fromSend!.receiveCurrency);
+ widget.exchangeViewModel.receiveAddress = widget.fromSend!.recipientAddress;
+ widget.exchangeViewModel.depositAddress =
+ widget.exchangeViewModel.wallet.walletAddresses.addressForExchange;
+ widget.exchangeViewModel.enableFixedRateMode();
+ final receiveAmount = widget.fromSend!.receiveAmount;
+ if (receiveAmount != null) {
+ widget.exchangeViewModel.setCanonicalReceiveAmount(receiveAmount.toString());
+ }
+ widget.exchangeViewModel.calculateBestRate();
+ }
});
}
@override
void dispose() {
+ for (final disposer in _disposers) {
+ disposer();
+ }
+ _receiveAmountDebounce.cancel();
+ _depositAmountDebounce.cancel();
_depositAmountFocus.dispose();
_depositAddressFocus.dispose();
_receiveAmountFocus.dispose();
@@ -395,23 +468,33 @@ class _NewSwapPageState extends State<NewSwapPage> {
super.dispose();
}
- void _onCurrencyChange(CryptoCurrency currency, ExchangeViewModel exchangeViewModel,
- GlobalKey<SwapAmountBoxState> key) {
+ void _onCurrencyChange(
+ CryptoCurrency currency,
+ ExchangeViewModel exchangeViewModel,
+ GlobalKey<SwapAmountBoxState> key,
+ ) {
final isCurrentTypeWallet = exchangeViewModel.useSameWalletAddress(currency);
- if (key == depositKey && !isCurrentTypeWallet) exchangeViewModel.isSendFromExternal = true;
- if (key == depositKey && isCurrentTypeWallet) exchangeViewModel.isSendFromExternal = false;
+ if (key == depositKey && !isCurrentTypeWallet) {
+ exchangeViewModel.isSendFromExternal = true;
+ }
+ if (key == depositKey && isCurrentTypeWallet) {
+ exchangeViewModel.isSendFromExternal = false;
+ }
if (key == depositKey) {
key.currentState!.changeAddress(
address:
- isCurrentTypeWallet ? exchangeViewModel.wallet.walletAddresses.addressForExchange : '',
+ isCurrentTypeWallet ? exchangeViewModel.wallet.walletAddresses.addressForExchange : "",
);
}
}
- void _onWalletNameChange(ExchangeViewModel exchangeViewModel, CryptoCurrency currency,
- GlobalKey<SwapAmountBoxState> key) {
+ void _onWalletNameChange(
+ ExchangeViewModel exchangeViewModel,
+ CryptoCurrency currency,
+ GlobalKey<SwapAmountBoxState> key,
+ ) {
final isCurrentTypeWallet = exchangeViewModel.useSameWalletAddress(currency);
if (isCurrentTypeWallet) {
@@ -419,12 +502,15 @@ class _NewSwapPageState extends State<NewSwapPage> {
exchangeViewModel.wallet.walletAddresses.addressForExchange;
} else if (key.currentState!.addressController.text ==
exchangeViewModel.wallet.walletAddresses.addressForExchange) {
- key.currentState!.addressController.text = '';
+ key.currentState!.addressController.text = "";
}
}
Future<String> fetchParsedAddress(
- BuildContext context, String domain, CryptoCurrency currency) async {
+ BuildContext context,
+ String domain,
+ CryptoCurrency currency,
+ ) async {
printV("$domain");
final parsedAddress = await widget.adrResService
.resolve(query: domain, wallet: widget.exchangeViewModel.wallet, currency: currency);
@@ -434,62 +520,78 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
void _showFeeAlert(BuildContext context) async {
- await Future<void>.delayed(Duration(seconds: 1));
+ await Future<void>.delayed(const Duration(seconds: 1));
if (!context.mounted) {
return;
}
final confirmed = await showPopUp<bool>(
- context: context,
- builder: (dialogContext) {
- return AlertWithTwoActions(
- alertTitle: S.of(context).low_fee,
- alertContent: S.of(context).low_fee_alert,
- leftButtonText: S.of(context).ignor,
- rightButtonText: S.of(context).use_suggested,
- actionLeftButton: () => Navigator.of(dialogContext).pop(false),
- actionRightButton: () => Navigator.of(dialogContext).pop(true));
- }) ??
+ context: context,
+ builder: (dialogContext) => AlertWithTwoActions(
+ alertTitle: S.of(context).low_fee,
+ alertContent: S.of(context).low_fee_alert,
+ leftButtonText: S.of(context).ignor,
+ rightButtonText: S.of(context).use_suggested,
+ actionLeftButton: () => Navigator.of(dialogContext).pop(false),
+ actionRightButton: () => Navigator.of(dialogContext).pop(true),
+ ),
+ ) ??
false;
if (confirmed) {
widget.exchangeViewModel.feesViewModel.setDefaultTransactionPriority();
}
}
- void disposeBestRateSync() => widget.exchangeViewModel.bestRateSync.cancel();
-
@override
Widget build(BuildContext context) {
+ final colorScheme = Theme.of(context).colorScheme;
+
+ final fromSend = widget.fromSend;
+ final fromType = widget.exchangeViewModel.wallet.type;
+ final fromName = walletTypeToString(fromType);
+ final fromIcon = symbolIconPathForWalletType(fromType) ?? "";
+
+ final targetType = fromSend?.targetWalletType;
+ final toName = targetType != null ? walletTypeToString(targetType) : "";
+ final toIcon = (targetType != null ? symbolIconPathForWalletType(targetType) : null) ?? "";
+
return KeyboardHideOverlay(
unfocusOnTap: true,
child: Container(
decoration: BoxDecoration(
- color: Theme.of(context).colorScheme.surface,
- borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
+ color: colorScheme.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
),
child: Column(
children: [
ModalTopBar(
- title: S.of(context).swap,
- leadingIcon: Icon(Icons.close),
+ title:
+ fromSend != null ? S.of(context).swap_from_network(fromName) : S.of(context).swap,
+ leadingIcon: Icon(fromSend != null ? Icons.arrow_back_ios_new : Icons.close),
leadingSemanticLabel: S.of(context).close,
onLeadingPressed: Navigator.of(context).maybePop,
- trailingIcon: CakeImageWidget(
- imageUrl: "assets/new-ui/options.svg",
- colorFilter:
- ColorFilter.mode(Theme.of(context).colorScheme.primary, BlendMode.srcIn),
- ),
+ trailingIcon: fromSend != null
+ ? null
+ : CakeImageWidget(
+ imageUrl: "assets/new-ui/options.svg",
+ colorFilter: ColorFilter.mode(colorScheme.primary, BlendMode.srcIn),
+ ),
trailingSemanticLabel: S.of(context).configure,
onTrailingPressed: () {
- Navigator.of(context).push(CupertinoPageRoute(
+ Navigator.of(context).push(
+ CupertinoPageRoute(
builder: (context) => Material(
- child: SwapOptionsPage(exchangeViewModel: widget.exchangeViewModel))));
+ child: SwapOptionsPage(exchangeViewModel: widget.exchangeViewModel),
+ ),
+ ),
+ );
},
),
+ const SizedBox(height: 24),
Expanded(
child: SafeArea(
child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 18.0),
+ padding: const EdgeInsets.symmetric(horizontal: 18),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
@@ -503,137 +605,211 @@ class _NewSwapPageState extends State<NewSwapPage> {
controller: ModalScrollController.of(context),
child: Column(
children: [
+ if (fromSend != null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: SwapSectionHeader(
+ label: S.of(context).from,
+ networkName: fromName,
+ networkIconPath: fromIcon,
+ ),
+ ),
Observer(
builder: (_) => SwapAmountBox(
isReceiverCard: false,
walletSwitcherViewModel: widget.walletSwitcherViewModel,
exchangeViewModel: widget.exchangeViewModel,
- onDispose: disposeBestRateSync,
hasAllAmount: widget.exchangeViewModel.hasAllAmount,
allAmount: widget.exchangeViewModel.hasAllAmount
? () => widget.exchangeViewModel.enableSendAllAmount()
: null,
key: depositKey,
- title: S.of(context).send,
+ title: fromSend != null ? "" : S.of(context).send,
+ sourceSelectorMode: fromSend != null,
+ walletName: fromSend != null
+ ? widget.exchangeViewModel.wallet.name
+ : null,
+ balanceByAsset: fromSend?.depositBalanceByAsset,
+ useSingleNetworkLayout: fromSend != null,
+ filteredNetwork: fromSend != null
+ ? widget.exchangeViewModel.wallet.type
+ : null,
currency: widget.exchangeViewModel.depositCurrency,
useBaseUnit: widget.exchangeViewModel.useDepositBaseUnit,
hasRefundAddress: true,
currencies: widget.exchangeViewModel.depositCurrencies,
onCurrencySelected: (currency) {
- if (currency is CryptoCurrency) {
- widget.exchangeViewModel
- .changeDepositCurrency(currency: currency);
+ if (currency is! CryptoCurrency) {
+ return;
+ }
+ final vm = widget.exchangeViewModel;
+ if (fromSend == null) {
+ vm.changeDepositCurrency(currency: currency);
+ return;
+ }
+ final keepReceive = vm.receiveAmount;
+ vm.changeDepositCurrency(currency: currency);
+ vm.enableFixedRateMode();
+ if (keepReceive.isNotEmpty) {
+ vm.changeReceiveAmount(amount: keepReceive);
+ } else {
+ vm.calculateBestRate();
}
},
- currencyValueValidator: (value) {
- return !widget.exchangeViewModel.isFixedRateMode &&
- value != S.of(context).all
- ? AmountValidator(
- isAutovalidate: true,
- currency: widget.exchangeViewModel.isFixedRateMode
- ? widget.exchangeViewModel.receiveCurrency
- : widget.exchangeViewModel.depositCurrency,
- minValue:
- widget.exchangeViewModel.limits.min.toString(),
- maxValue:
- widget.exchangeViewModel.limits.max.toString(),
- amountParsingProxy:
- widget.exchangeViewModel.amountParsingProxy,
- ).call(value)
- : null;
- },
+ currencyValueValidator: (value) => !widget
+ .exchangeViewModel.isFixedRateMode &&
+ value != S.of(context).all
+ ? AmountValidator(
+ isAutovalidate: true,
+ currency: widget.exchangeViewModel.isFixedRateMode
+ ? widget.exchangeViewModel.receiveCurrency
+ : widget.exchangeViewModel.depositCurrency,
+ minValue:
+ widget.exchangeViewModel.limits.min.toString(),
+ maxValue:
+ widget.exchangeViewModel.limits.max.toString(),
+ amountParsingProxy:
+ widget.exchangeViewModel.amountParsingProxy,
+ ).call(value)
+ : null,
addressTextFieldValidator: AddressValidator(
- type: widget.exchangeViewModel.depositCurrency),
+ type: widget.exchangeViewModel.depositCurrency,
+ ),
onPushPasteButton: (context) async {
- final clipboard = await Clipboard.getData('text/plain');
+ final clipboard = await Clipboard.getData("text/plain");
widget.exchangeViewModel.depositAddress =
- clipboard?.text ?? '';
+ clipboard?.text ?? "";
final domain = widget.exchangeViewModel.depositAddress;
widget.exchangeViewModel.depositAddress =
- await fetchParsedAddress(context, domain,
- widget.exchangeViewModel.depositCurrency);
+ await fetchParsedAddress(
+ context,
+ domain,
+ widget.exchangeViewModel.depositCurrency,
+ );
},
onPushAddressBookButton: (context) async {
final domain = widget.exchangeViewModel.depositAddress;
widget.exchangeViewModel.depositAddress =
- await fetchParsedAddress(context, domain,
- widget.exchangeViewModel.depositCurrency);
+ await fetchParsedAddress(
+ context,
+ domain,
+ widget.exchangeViewModel.depositCurrency,
+ );
},
),
),
SwapLimitPopup(exchangeViewModel: widget.exchangeViewModel),
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 12.0),
- child: Stack(
- alignment: Alignment.center,
+ if (fromSend != null)
+ Column(
children: [
- Container(
- height: 1,
- width: double.infinity,
- color: Theme.of(context).colorScheme.surfaceContainerHigh,
- ),
- ModernButton.svg(
- size: 36,
- iconSize: 24,
- svgPath: "assets/new-ui/swap_amounts.svg",
- onPressed: widget.exchangeViewModel.reverseSwapDirection,
+ const SizedBox(height: 24),
+ Icon(
+ Icons.arrow_downward,
+ size: 24,
+ color: colorScheme.onSurfaceVariant,
semanticLabel: S.of(context).swap_reverse_direction,
),
+ const SizedBox(height: 24),
],
+ )
+ else
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Container(
+ height: 1,
+ width: double.infinity,
+ color: colorScheme.surfaceContainerHigh,
+ ),
+ ModernButton.svg(
+ size: 36,
+ iconSize: 24,
+ svgPath: "assets/new-ui/swap_amounts.svg",
+ onPressed:
+ widget.exchangeViewModel.reverseSwapDirection,
+ ),
+ ],
+ ),
+ ),
+ if (fromSend != null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: SwapSectionHeader(
+ label: S.of(context).to,
+ networkName: toName,
+ networkIconPath: toIcon,
+ ),
),
- ),
Observer(
builder: (_) => SwapAmountBox(
isReceiverCard: true,
walletSwitcherViewModel: widget.walletSwitcherViewModel,
exchangeViewModel: widget.exchangeViewModel,
- onDispose: disposeBestRateSync,
key: receiveKey,
- title: S.of(context).receive,
+ title: fromSend != null ? "" : S.of(context).receive,
+ filteredNetwork:
+ fromSend != null ? fromSend.targetWalletType : null,
currencies: widget.exchangeViewModel.receiveCurrencies,
currency: widget.exchangeViewModel.receiveCurrency,
useBaseUnit: widget.exchangeViewModel.useReceiveBaseUnit,
onCurrencySelected: (currency) {
- if (currency is CryptoCurrency) {
- widget.exchangeViewModel
- .changeReceiveCurrency(currency: currency);
+ if (currency is! CryptoCurrency) {
+ return;
+ }
+ final vm = widget.exchangeViewModel;
+ final keepAddress = vm.receiveAddress;
+ vm.changeReceiveCurrency(currency: currency);
+ if (fromSend != null) {
+ if (keepAddress.isNotEmpty) {
+ vm.receiveAddress = keepAddress;
+ }
+ vm.enableFixedRateMode();
+ vm.calculateBestRate();
}
},
- currencyValueValidator: (value) {
- return widget.exchangeViewModel.isFixedRateMode
- ? AmountValidator(
- isAutovalidate: true,
- currency: widget.exchangeViewModel.receiveCurrency,
- minValue:
- widget.exchangeViewModel.limits.min.toString(),
- maxValue:
- widget.exchangeViewModel.limits.max.toString(),
- amountParsingProxy:
- widget.exchangeViewModel.amountParsingProxy,
- ).call(value)
- : null;
- },
+ currencyValueValidator: (value) => widget
+ .exchangeViewModel.isFixedRateMode
+ ? AmountValidator(
+ isAutovalidate: true,
+ currency: widget.exchangeViewModel.receiveCurrency,
+ minValue:
+ widget.exchangeViewModel.limits.min.toString(),
+ maxValue:
+ widget.exchangeViewModel.limits.max.toString(),
+ amountParsingProxy:
+ widget.exchangeViewModel.amountParsingProxy,
+ ).call(value)
+ : null,
addressTextFieldValidator: AddressValidator(
- type: widget.exchangeViewModel.receiveCurrency),
+ type: widget.exchangeViewModel.receiveCurrency,
+ ),
onPushPasteButton: (context) async {
- final clipboard = await Clipboard.getData('text/plain');
+ final clipboard = await Clipboard.getData("text/plain");
widget.exchangeViewModel.receiveAddress =
- clipboard?.text ?? '';
+ clipboard?.text ?? "";
final domain = widget.exchangeViewModel.receiveAddress;
widget.exchangeViewModel.receiveAddress =
- await fetchParsedAddress(context, domain,
- widget.exchangeViewModel.receiveCurrency);
+ await fetchParsedAddress(
+ context,
+ domain,
+ widget.exchangeViewModel.receiveCurrency,
+ );
},
onPushAddressBookButton: (context) async {
final domain = widget.exchangeViewModel.receiveAddress;
widget.exchangeViewModel.receiveAddress =
- await fetchParsedAddress(context, domain,
- widget.exchangeViewModel.receiveCurrency);
+ await fetchParsedAddress(
+ context,
+ domain,
+ widget.exchangeViewModel.receiveCurrency,
+ );
},
),
- )
+ ),
],
),
),
@@ -647,15 +823,18 @@ class _NewSwapPageState extends State<NewSwapPage> {
children: [
if (widget.exchangeViewModel.status is! SyncedSyncStatus)
SendSyncingIndicator(status: widget.exchangeViewModel.status),
- if (widget.exchangeViewModel.isFixedRateMode)
- Text(S.of(context).exchange_rate_is_fixed,
- style: TextStyle(
- color: Theme.of(context).colorScheme.onSurfaceVariant,
- fontSize: 12)),
- SwapProviderPreview(exchangeViewModel: widget.exchangeViewModel),
+ if (fromSend == null && widget.exchangeViewModel.isFixedRateMode)
+ Text(
+ S.of(context).exchange_rate_is_fixed,
+ style: TextStyle(color: colorScheme.onSurfaceVariant, fontSize: 12),
+ ),
+ if (fromSend != null)
+ AnyPaySwapFooter(exchangeViewModel: widget.exchangeViewModel)
+ else
+ SwapProviderPreview(exchangeViewModel: widget.exchangeViewModel),
Observer(
builder: (_) => LoadingPrimaryButton(
- key: ValueKey('exchange_page_exchange_button_key'),
+ key: const ValueKey("exchange_page_exchange_button_key"),
text: widget.exchangeViewModel.isAvailableInSelected
? S.of(context).swap
: S.of(context).change_selected_exchanges,
@@ -667,15 +846,13 @@ class _NewSwapPageState extends State<NewSwapPage> {
if (_shouldWaitTillSynced) {
showPopUp<void>(
context: context,
- builder: (BuildContext context) {
- return AlertWithOneAction(
- alertTitle: S.of(context).exchange,
- alertContent:
- S.of(context).exchange_sync_alert_content,
- buttonText: S.of(context).ok,
- buttonAction: () => Navigator.of(context).pop(),
- );
- },
+ builder: (BuildContext context) => AlertWithOneAction(
+ alertTitle: S.of(context).exchange,
+ alertContent:
+ S.of(context).exchange_sync_alert_content,
+ buttonText: S.of(context).ok,
+ buttonAction: () => Navigator.of(context).pop(),
+ ),
);
} else {
final check =
@@ -693,22 +870,22 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
}
: () => PresentProviderPicker(
- exchangeViewModel: widget.exchangeViewModel)
- .presentProviderPicker(context),
- color: Theme.of(context).colorScheme.primary,
- textColor: Theme.of(context).colorScheme.onPrimary,
+ exchangeViewModel: widget.exchangeViewModel,
+ ).presentProviderPicker(context),
+ color: colorScheme.primary,
+ textColor: colorScheme.onPrimary,
isDisabled: _swapButtonDisabled(),
isLoading: widget.exchangeViewModel.tradeState is TradeIsCreating,
),
),
],
),
- )
+ ),
],
),
),
),
- )
+ ),
],
),
),
@@ -716,673 +893,118 @@ class _NewSwapPageState extends State<NewSwapPage> {
}
bool _swapButtonDisabled() {
- if (widget.exchangeViewModel.selectedProviders.isEmpty) return true;
+ if (widget.exchangeViewModel.selectedProviders.isEmpty) {
+ return true;
+ }
- if (widget.exchangeViewModel.receiveAddress.isEmpty) return true;
+ if (widget.exchangeViewModel.receiveAddress.isEmpty) {
+ return true;
+ }
- if (widget.exchangeViewModel.status is! SyncedSyncStatus) return true;
+ if (widget.exchangeViewModel.status is! SyncedSyncStatus) {
+ return true;
+ }
- if (widget.exchangeViewModel.depositAmount.isEmpty) return true;
+ if (widget.exchangeViewModel.depositAmount.isEmpty) {
+ return true;
+ }
return false;
}
}
class SwapProviderPreview extends StatelessWidget {
- const SwapProviderPreview({super.key, required this.exchangeViewModel});
+ const SwapProviderPreview({
+ required this.exchangeViewModel,
+ super.key,
+ });
final ExchangeViewModel exchangeViewModel;
@override
- Widget build(BuildContext context) {
- return Observer(builder: (_) {
- if (exchangeViewModel.depositAmount.isEmpty) return SizedBox.shrink();
-
- final provider = exchangeViewModel.forcedProvider ?? exchangeViewModel.providerDisplay;
- final rate = exchangeViewModel.forcedProvider == null
- ? exchangeViewModel.bestRate
- : exchangeViewModel.forcedProviderRate;
-
- return GestureDetector(
- onTap: () {
- if (provider != null) {
- Navigator.of(context).push(CupertinoPageRoute(
- builder: (context) => Material(
- child: ProviderSelectorPage(exchangeViewModel: exchangeViewModel),
- ),
- ));
+ Widget build(BuildContext context) => Observer(
+ builder: (_) {
+ final isFetchingDeposit =
+ exchangeViewModel.isFixedRateMode && exchangeViewModel.receiveAmount.isNotEmpty;
+ if (exchangeViewModel.depositAmount.isEmpty && !isFetchingDeposit) {
+ return const SizedBox.shrink();
}
- },
- child: Container(
- height: 48,
- decoration: BoxDecoration(
- color: Theme.of(context).colorScheme.surfaceContainer,
- borderRadius: BorderRadius.circular(16),
- ),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Row(
- spacing: 12,
- children: [
- if (provider != null)
- CakeImageWidget(imageUrl: provider.description.image, width: 28, height: 28),
- if (provider == null) CupertinoActivityIndicator(),
- Text(
- provider?.title ?? "${S.of(context).finding_provider}...",
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w400,
- color: provider == null
- ? Theme.of(context).colorScheme.onSurfaceVariant
- : Theme.of(context).colorScheme.onSurface),
- )
- ],
- ),
- if (provider != null)
- Row(
- children: [
- Text(
- "1 ${exchangeViewModel.depositCurrency} ≈ ${rate.toStringAsFixed(6)} ${exchangeViewModel.receiveCurrency}",
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w400,
- color: Theme.of(context).colorScheme.onSurfaceVariant),
- ),
- CakeImageWidget(
- imageUrl: "assets/new-ui/chooser.svg",
- colorFilter: ColorFilter.mode(
- Theme.of(context).colorScheme.onSurfaceVariant, BlendMode.srcIn),
- )
- ],
- )
- ],
- ),
- ),
- ),
- );
- });
- }
-}
-
-class SwapAmountBox extends StatefulWidget {
- SwapAmountBox({
- Key? key,
- required this.currency,
- required this.currencies,
- required this.onCurrencySelected,
- this.currencyValueValidator,
- this.addressTextFieldValidator,
- this.title = '',
- this.hasRefundAddress = false,
- this.hasAllAmount = false,
- this.useBaseUnit = false,
- this.allAmount,
- this.onPushPasteButton,
- this.onPushAddressBookButton,
- this.onDispose,
- required this.exchangeViewModel,
- required this.isReceiverCard,
- required this.walletSwitcherViewModel,
- }) : super(key: key);
-
- final List<Currency> currencies;
- final Function(Currency) onCurrencySelected;
- final String title;
- final bool isReceiverCard;
- final Currency currency;
- final bool useBaseUnit;
- final bool hasRefundAddress;
- final FormFieldValidator<String>? currencyValueValidator;
- final FormFieldValidator<String>? addressTextFieldValidator;
- final FormFieldValidator<String> allAmountValidator = AllAmountValidator();
- final bool hasAllAmount;
- final VoidCallback? allAmount;
- final void Function(BuildContext context)? onPushPasteButton;
- final void Function(BuildContext context)? onPushAddressBookButton;
- final Function()? onDispose;
- final ExchangeViewModel exchangeViewModel;
- final WalletSwitcherViewModel walletSwitcherViewModel;
-
- @override
- State<SwapAmountBox> createState() => SwapAmountBoxState();
-}
-
-class SwapAmountBoxState extends State<SwapAmountBox> {
- final addressController = TextEditingController();
- final amountController = TextEditingController();
- final fiatAmountController = TextEditingController();
- final amountFocusNode = FocusNode();
- final memoController = TextEditingController();
- ReactionDisposer? _memoReactionDisposer;
- VoidCallback? _memoListener;
-
- @override
- void initState() {
- if (widget.isReceiverCard) {
- memoController.text = widget.exchangeViewModel.receiveAddressExtraId;
- _memoListener = () {
- if (widget.exchangeViewModel.receiveAddressExtraId != memoController.text) {
- widget.exchangeViewModel.receiveAddressExtraId = memoController.text;
- }
- };
- memoController.addListener(_memoListener!);
-
- _memoReactionDisposer =
- reaction((_) => widget.exchangeViewModel.receiveAddressExtraId, (String value) {
- if (memoController.text != value) {
- memoController.text = value;
- }
- });
- }
-
- super.initState();
- }
-
- @override
- void dispose() {
- if (_memoListener != null) {
- memoController.removeListener(_memoListener!);
- }
- _memoReactionDisposer?.call();
- memoController.dispose();
- super.dispose();
- }
-
- bool _fiatInputMode = false;
+ final provider = exchangeViewModel.forcedProvider ?? exchangeViewModel.providerDisplay;
+ final rate = exchangeViewModel.forcedProvider == null
+ ? exchangeViewModel.bestRate
+ : exchangeViewModel.forcedProviderRate;
- @override
- Widget build(BuildContext context) {
- final currencyToShow = (widget.currency is CryptoCurrency)
- ? widget.exchangeViewModel.amountParsingProxy
- .getCryptoSymbol(widget.currency as CryptoCurrency)
- : widget.currency.name.toUpperCase();
-
- final chainIconPath = (widget.currency is CryptoCurrency)
- ? _getCurrencyChainIconPath(widget.currency as CryptoCurrency)
- : null;
-
- return Column(
- spacing: 12,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- widget.title,
- style: TextStyle(
- fontSize: 12,
- fontWeight: FontWeight.w500,
- color: Theme.of(context).colorScheme.onSurfaceVariant),
- ),
- Container(
- decoration: ShapeDecoration(
- color: Theme.of(context).colorScheme.surfaceContainer,
- shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(24))),
- child: Padding(
- padding: const EdgeInsets.all(16.0),
- child: Column(
- spacing: 12,
- children: [
- GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: amountFocusNode.requestFocus,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- spacing: 4,
- children: [
- Expanded(
- child: Row(
- spacing: 4,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Flexible(
- child: IntrinsicWidth(
- child: TextFormField(
- keyboardType: TextInputType.numberWithOptions(
- signed: false,
- decimal: !widget.useBaseUnit,
- ),
- validator: _fiatInputMode ? null : widget.currencyValueValidator,
- controller:
- _fiatInputMode ? fiatAmountController : amountController,
- focusNode: amountFocusNode,
- style: TextStyle(
- fontSize: 28,
- color: Theme.of(context).colorScheme.onSurface,
- fontWeight: FontWeight.w400,
- ),
- decoration: InputDecoration(
- contentPadding: EdgeInsets.zero,
- isDense: true,
- hintText: "0",
- fillColor: Colors.transparent,
- hoverColor: Colors.transparent,
- focusedBorder: InputBorder.none,
- enabledBorder: InputBorder.none,
- ),
- inputFormatters: <TextInputFormatter>[
- DecimalInputFormatter(
- maxDecimals:
- widget.useBaseUnit ? 0 : widget.currency.decimals,
- ),
- ],
- ),
- ),
- ),
- if (_fiatInputMode)
- Center(
- child: Text(
- widget.exchangeViewModel.fiat.title,
- style: TextStyle(
- fontSize: 16,
- color: Theme.of(context).colorScheme.onSurfaceVariant,
- ),
- ),
- ),
- ],
- ),
- ),
- GestureDetector(
- onTap: _presentCurrencyPicker,
- child: Container(
- decoration: BoxDecoration(
- color: Theme.of(context).colorScheme.surface,
- borderRadius: BorderRadius.circular(999999),
- ),
- child: Padding(
- padding: const EdgeInsets.only(top: 4.0, bottom: 4, left: 4, right: 4),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- CakeImageWidget(
- imageUrl: widget.currency.iconPath ?? "",
- width: 28,
- height: 28,
- ),
- const SizedBox(width: 10),
- Text(
- currencyToShow,
- textAlign: TextAlign.center,
- ),
- if (chainIconPath != null && chainIconPath.isNotEmpty) ...[
- SizedBox(width: 4),
- CakeImageWidget(
- imageUrl: chainIconPath,
- width: 12,
- height: 12,
- colorFilter: ColorFilter.mode(
- Theme.of(context).colorScheme.onSurfaceVariant,
- BlendMode.srcIn,
- ),
- ),
- const SizedBox(width: 6)
- ] else
- const SizedBox(width: 10),
- Container(
- width: 16,
- height: 16,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(9999999999),
- color: Theme.of(context).colorScheme.surfaceContainerHigh),
- child: Padding(
- padding: const EdgeInsets.all(4.0),
- child: RotatedBox(
- quarterTurns: 2,
- child: CakeImageWidget(
- imageUrl: "assets/new-ui/dropdown_arrow.svg",
- width: 4,
- height: 4,
- colorFilter: ColorFilter.mode(
- Theme.of(context).colorScheme.primary,
- BlendMode.srcIn,
- ),
- ),
- ),
- ),
- ),
- const SizedBox(width: 4),
- ],
- ),
- ),
- ),
- )
- ],
+ return GestureDetector(
+ onTap: () {
+ if (provider != null) {
+ Navigator.of(context).push(
+ CupertinoPageRoute(
+ builder: (context) => Material(
+ child: ProviderSelectorPage(exchangeViewModel: exchangeViewModel),
+ ),
),
- ),
- Observer(
- builder: (_) {
- final hasAllAmount = !(widget.isReceiverCard ||
- widget.exchangeViewModel.isSendFromExternal ||
- !widget.exchangeViewModel.hasAllAmount);
-
- return FiatAmountBar(
- foregroundElementColor: Theme.of(context).colorScheme.surfaceContainerHigh,
- textColor: Theme.of(context).colorScheme.onSurfaceVariant,
- allAmountColor: hasAllAmount ? null : Colors.transparent,
- allAmountTextColor:
- hasAllAmount ? null : Theme.of(context).colorScheme.onSurfaceVariant,
- fiatInputMode: _fiatInputMode,
- allAmount: !hasAllAmount
- ? widget.isReceiverCard
- ? null
- : widget.exchangeViewModel.balanceDisplay
- : widget.exchangeViewModel.depositAvailableAmount,
- onSwitchButtonPressed: () {
- setState(() => _fiatInputMode = !_fiatInputMode);
- if (_fiatInputMode) {
- updateFiatAmount();
- } else {
- amountController.text = widget.exchangeViewModel.depositAmount;
- }
- },
- onAllButtonPressed: () {
- setState(() {
- _fiatInputMode = false;
- });
- widget.allAmount?.call();
- },
- cryptoAmount: widget.isReceiverCard
- ? widget.exchangeViewModel.roundedReceiveAmount(6)
- : widget.exchangeViewModel.roundedDepositAmount(6),
- fiatAmount: widget.isReceiverCard
- ? widget.exchangeViewModel.roundedReceiveAmountFiat(6)
- : widget.exchangeViewModel.roundedDepositAmountFiat(6),
- cryptoCurrencySymbol: currencyToShow,
- fiatCurrencySymbol: widget.exchangeViewModel.fiat.symbol,
- );
- },
- ),
- Observer(
- builder: (_) {
- final addressEmpty = (widget.isReceiverCard &&
- widget.exchangeViewModel.receiveAddress.isEmpty) ||
- (!widget.isReceiverCard && widget.exchangeViewModel.depositAddress.isEmpty);
- final addressPickerText = widget.isReceiverCard
- ? (addressEmpty ? S.of(context).select_receiver : S.of(context).to)
- : S.of(context).from;
- final addressDescription = widget.isReceiverCard
- ? widget.exchangeViewModel.receiveAddressDisplayName ??
- _middleTruncate(widget.exchangeViewModel.receiveAddress, 8, 8)
- : widget.exchangeViewModel.isSendFromExternal
- ? S.of(context).external
- : widget.exchangeViewModel.wallet.name;
- return Row(
- spacing: 8,
+ );
+ }
+ },
+ child: Container(
+ height: 48,
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.surfaceContainer,
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ spacing: 12,
children: [
- Flexible(
- child: GestureDetector(
- onTap: _presentWalletPicker,
- child: Container(
- height: 36,
- decoration: BoxDecoration(
- color: (addressEmpty && widget.isReceiverCard)
- ? Theme.of(context).colorScheme.primary
- : Theme.of(context).colorScheme.surfaceContainerHigh,
- borderRadius: BorderRadius.circular(9999)),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12.0),
- child: Observer(
- builder: (_) => Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Row(
- spacing: 8,
- mainAxisSize: MainAxisSize.max,
- children: [
- Text(
- addressPickerText,
- style: TextStyle(
- fontSize: 12,
- fontWeight: FontWeight.w500,
- color: (addressEmpty && widget.isReceiverCard)
- ? Theme.of(context).colorScheme.onPrimary
- : Theme.of(context).colorScheme.onSurface),
- ),
- Text(
- addressDescription,
- style: TextStyle(
- fontSize: 12,
- fontWeight: FontWeight.w500,
- color: Theme.of(context).colorScheme.primary),
- )
- ],
- ),
- RotatedBox(
- quarterTurns: 2,
- child: CakeImageWidget(
- imageUrl: "assets/new-ui/dropdown_arrow.svg",
- colorFilter: ColorFilter.mode(
- (addressEmpty && widget.isReceiverCard)
- ? Theme.of(context).colorScheme.onPrimary
- : Theme.of(context).colorScheme.onSurface,
- BlendMode.srcIn,
- ),
- ),
- )
- ],
- ),
- ),
- ),
- ),
+ if (provider != null)
+ CakeImageWidget(
+ imageUrl: provider.description.image,
+ width: 28,
+ height: 28,
),
- ),
- if (!widget.isReceiverCard &&
- widget.exchangeViewModel.isSendFromExternal &&
- widget.exchangeViewModel.depositAddress.isEmpty)
- ModernButton.svg(
- svgPath: "assets/new-ui/refund_address.svg",
- onPressed: askForRefundAddress,
- size: 36,
- iconSize: 18,
- backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
- semanticLabel: S.of(context).refund_address,
+ if (provider == null) const CupertinoActivityIndicator(),
+ Text(
+ provider?.title ?? "${S.of(context).finding_provider}...",
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w400,
+ color: provider == null
+ ? Theme.of(context).colorScheme.onSurfaceVariant
+ : Theme.of(context).colorScheme.onSurface,
),
- if (widget.isReceiverCard &&
- widget.exchangeViewModel.receiveAddress.isEmpty) ...[
- ModernButton.svg(
- svgPath: "assets/new-ui/paste.svg",
- onPressed: () => widget.onPushPasteButton?.call(context),
- size: 36,
- iconSize: 20,
- backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
- semanticLabel: S.of(context).paste,
+ ),
+ ],
+ ),
+ if (provider != null)
+ Row(
+ children: [
+ Text(
+ "1 ${exchangeViewModel.depositCurrency} ≈ ${rate.toStringAsFixed(6)} ${exchangeViewModel.receiveCurrency}",
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w400,
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
),
- ModernButton.svg(
- svgPath: "assets/new-ui/scan.svg",
- onPressed: () => _presentQRScanner(context),
- size: 36,
- iconSize: 20,
- backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
- semanticLabel: S.of(context).scan,
+ CakeImageWidget(
+ imageUrl: "assets/new-ui/chooser.svg",
+ colorFilter: ColorFilter.mode(
+ Theme.of(context).colorScheme.onSurfaceVariant,
+ BlendMode.srcIn,
+ ),
),
- ]
- ],
- );
- },
+ ],
+ ),
+ ],
),
- if (widget.isReceiverCard)
- Observer(builder: (_) {
- final selected = widget.exchangeViewModel.receiveCurrency;
- final labelType = memoLabelTypeFor(selected);
- if (labelType == null) return const SizedBox.shrink();
-
- final isDestinationTag = labelType == MemoLabelType.destinationTag;
- final hint = isDestinationTag
- ? S.of(context).destination_tag_optional
- : S.of(context).memo_optional;
- final disclaimer = isDestinationTag
- ? S.of(context).destination_tag_swap_disclaimer
- : S.of(context).memo_swap_disclaimer;
-
- return NewSendMemoInput(
- memoController: memoController,
- maxMemoLength: isDestinationTag ? 20 : 256,
- memoLength: memoController.text.length,
- hintText: hint,
- disclaimerText: disclaimer,
- );
- }),
- ],
- ),
- ),
- ),
- ],
- );
- }
-
- void changeAddress({required String address}) {
- setState(() => addressController.text = _normalizeAddressFormat(address));
- }
-
- void changeAmount({required String amount}) {
- setState(() => amountController.text = amount);
- }
-
- String _normalizeAddressFormat(String address) {
- if (address.startsWith('bitcoincash:')) address = address.substring(12);
- return address;
- }
-
- void _presentCurrencyPicker() {
- final rawCurrencies = widget.isReceiverCard
- ? widget.exchangeViewModel.receiveCurrencies
- : widget.exchangeViewModel.depositCurrencies;
- final currencies = rawCurrencies.whereType<CryptoCurrency>().toList();
- appendEvmDefaultTokens(currencies);
- if (widget.exchangeViewModel.wallet.type == WalletType.bitcoin) {
- currencies.sort((a, b) {
- if (a == CryptoCurrency.btcln) return -1;
- if (b == CryptoCurrency.btcln) return 1;
- return 0;
- });
- }
-
- final selected = widget.isReceiverCard
- ? widget.exchangeViewModel.receiveCurrency
- : widget.exchangeViewModel.depositCurrency;
-
- CurrencyPickerSheet.show(
- context: context,
- args: CurrencyPickerArgs(
- items: currencies,
- selected: selected,
- recentsSource: RecentsSource.trades,
- onSelected: widget.onCurrencySelected,
- symbolResolver: widget.exchangeViewModel.amountParsingProxy.getCryptoSymbol,
- ),
- );
- }
-
- Future<void> _presentQRScanner(BuildContext context) async {
- bool isCameraPermissionGranted =
- await PermissionHandler.checkPermission(Permission.camera, context);
- if (!isCameraPermissionGranted) return;
- final code = await presentQRScanner(context);
- if (code == null) return;
- if (code.isEmpty) return;
-
- try {
- final uri = Uri.parse(code);
- widget.exchangeViewModel.receiveAddress = uri.path;
- } catch (_) {}
- }
-
- void _presentWalletPicker() async {
- final res = await showMaterialModalBottomSheet(
- context: context,
- backgroundColor: Colors.transparent,
- builder: (context) {
- return ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.of(context).size.height * 0.6,
- ),
- child: SwapAddressSelectionModal(
- isSelectingReceiver: widget.isReceiverCard,
- exchangeViewModel: widget.exchangeViewModel,
+ ),
),
);
- });
- if (res != null && res is SwapAddressSelectionResult) {
- if (widget.isReceiverCard) {
- widget.exchangeViewModel.selectedAddressBookWallet = res.walletInfo;
- widget.exchangeViewModel.receiveAddress = res.address!;
- if (res.walletInfo?.name != null) {
- if (res.accountName != null) {
- widget.exchangeViewModel.receiveAddressDisplayName =
- "${res.walletInfo!.name} → ${res.accountName}";
- } else {
- widget.exchangeViewModel.receiveAddressDisplayName = res.walletInfo!.name;
- }
- }
- } else if (res.address == null || res.address!.isEmpty) {
- widget.exchangeViewModel.isSendFromExternal = true;
- askForRefundAddress();
- } else {
- widget.exchangeViewModel.isSendFromExternal = false;
- switchToDepositWallet(res.walletInfo!.name);
- }
- }
- }
-
- void switchToDepositWallet(String walletName) async {
- final walletType = cryptoCurrencyOrTokenToWalletType(widget.exchangeViewModel.depositCurrency);
- if (walletType == null) return;
- final wallet = await WalletInfo.get(walletName, walletType);
- if (wallet == null) return;
- widget.exchangeViewModel.depositAddress = wallet.address;
- addressController.text = _normalizeAddressFormat(wallet.address);
- widget.walletSwitcherViewModel.selectWallet(wallet);
- await widget.walletSwitcherViewModel.switchToSelectedWallet();
- }
-
- void askForRefundAddress() async {
- final refundAddress = await showModalBottomSheet(
- context: context,
- isScrollControlled: true,
- backgroundColor: Colors.transparent,
- builder: (context) => RefundAddressModal(
- selectedCurrency: widget.exchangeViewModel.depositCurrency,
- isFromWalletSelection: true,
- ));
- if (refundAddress != null && refundAddress is String) {
- widget.exchangeViewModel.depositAddress = refundAddress;
- } else {
- widget.exchangeViewModel.depositAddress = "";
- }
- }
-
- void updateFiatAmount() {
- final newText = widget.isReceiverCard
- ? widget.exchangeViewModel.receiveAmountFiat
- : widget.exchangeViewModel.depositAmountFiat;
-
- if (double.tryParse(fiatAmountController.text) != double.tryParse(newText)) {
- if (newText == "0.00") {
- fiatAmountController.text = "";
- } else {
- fiatAmountController.text =
- newText.replaceAll(RegExp(r'(?<=\.\d*)0+$'), '').replaceAll(RegExp(r'\.$'), '');
- }
- }
- }
-
- String _middleTruncate(String s, int head, int tail) {
- if (s.length <= head + tail + 3) return s;
- return s.substring(0, head) + '...' + s.substring(s.length - tail);
- }
-
- String? _getCurrencyChainIconPath(CryptoCurrency curr) {
- try {
- if (curr.chainIconPath != null) return curr.chainIconPath!;
-
- if (curr.tag != null) {
- final currencyFromTag = CryptoCurrency.fromString(curr.tag!);
-
- if (currencyFromTag.chainIconPath != null) return currencyFromTag.chainIconPath!;
- }
- } catch (_) {}
- return null;
- }
+ },
+ );
}
diff --git a/lib/new-ui/widgets/anypay/evm_address_detected_sheet.dart b/lib/new-ui/widgets/anypay/evm_address_detected_sheet.dart
new file mode 100644
index 00000000..809230ff
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/evm_address_detected_sheet.dart
@@ -0,0 +1,131 @@
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/anypay/select_recipient_network_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:flutter/material.dart";
+
+class EvmAddressDetectedSheet extends StatelessWidget {
+ const EvmAddressDetectedSheet({super.key, required this.networks});
+
+ final List<RecipientNetworkItem> networks;
+
+ static Future<int?> show({
+ required BuildContext context,
+ required List<RecipientNetworkItem> networks,
+ }) {
+ return showModalBottomSheet<int>(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => EvmAddressDetectedSheet(networks: networks),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Container(
+ decoration: BoxDecoration(
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ color: colors.surface,
+ ),
+ child: SafeArea(
+ top: false,
+ child: Column(
+ children: [
+ ModalTopBar(
+ title: "",
+ trailingIcon: const Icon(Icons.close),
+ onTrailingPressed: () => Navigator.of(context).maybePop(),
+ ),
+ const SizedBox(height: 32),
+ StackedNetworkIcons(iconPaths: networks.map((n) => n.iconPath).toList()),
+ const SizedBox(height: 24),
+ Text(
+ S.of(context).evm_address_detected,
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .titleLarge
+ ?.copyWith(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: -0.1),
+ ),
+ const SizedBox(height: 24),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32),
+ child: Text(
+ S.of(context).select_recipient_network_for_tx,
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ ),
+ const SizedBox(height: 64),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: NetworkListCard(
+ rows: [
+ for (final network in networks)
+ RecipientNetworkListRow(
+ item: network,
+ imageOverride: network.chainBadgeIconPath,
+ onTap: () => Navigator.of(context).pop(network.chainId),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class StackedNetworkIcons extends StatelessWidget {
+ const StackedNetworkIcons({
+ required this.iconPaths,
+ this.size = 50,
+ this.step = 34,
+ });
+
+ final List<String> iconPaths;
+ final double size;
+ final double step;
+
+ @override
+ Widget build(BuildContext context) {
+ if (iconPaths.isEmpty) return const SizedBox.shrink();
+
+ final colors = Theme.of(context).colorScheme;
+ final width = size + (iconPaths.length - 1) * step;
+
+ return SizedBox(
+ height: size,
+ width: width,
+ child: Stack(
+ children: [
+ for (int i = 0; i < iconPaths.length; i++)
+ Positioned(
+ left: i * step,
+ child: Container(
+ width: size,
+ height: size,
+ padding: const EdgeInsets.all(2),
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colors.surfaceContainer,
+ border: Border.all(color: colors.surface, width: 2),
+ ),
+ child: CakeImageWidget(imageUrl: iconPaths[i], fit: BoxFit.contain),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/anypay/recipient_network_row.dart b/lib/new-ui/widgets/anypay/recipient_network_row.dart
new file mode 100644
index 00000000..3d978fa1
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/recipient_network_row.dart
@@ -0,0 +1,100 @@
+import "package:cake_wallet/evm/evm.dart";
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:cw_core/wallet_base.dart";
+import "package:flutter/material.dart";
+
+class RecipientNetworkSelector extends StatelessWidget {
+ const RecipientNetworkSelector({
+ super.key,
+ required this.wallet,
+ required this.onTap,
+ });
+
+ final WalletBase wallet;
+ final void Function(ChainInfo currentChain) onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ if (evm == null) return const SizedBox.shrink();
+
+ final currentChainId =
+ evm!.getSelectedChainId(wallet) ?? evm!.getChainIdByWalletType(wallet.type);
+ final currentChain = evm!.getChainInfoByChainId(currentChainId);
+ if (currentChain == null) {
+ printV("RecipientNetworkSelector: no chain info for chainId $currentChainId");
+ return const SizedBox.shrink();
+ }
+
+ return _RecipientNetworkRow(
+ networkName: currentChain.name,
+ networkIconPath: symbolIconPathForWalletType(wallet.type) ?? "",
+ onTap: () => onTap(currentChain),
+ );
+ }
+}
+
+class _RecipientNetworkRow extends StatelessWidget {
+ const _RecipientNetworkRow({
+ required this.networkName,
+ required this.networkIconPath,
+ required this.onTap,
+ });
+
+ final String networkName;
+ final String networkIconPath;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return GestureDetector(
+ onTap: onTap,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ S.of(context).network_prefix_on,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ const SizedBox(width: 12),
+ CakeImageWidget(
+ imageUrl: networkIconPath,
+ width: 16,
+ height: 16,
+ fit: BoxFit.cover,
+ color: isMonochromeSymbolIcon(networkIconPath) ? colors.primary : null,
+ ),
+ const SizedBox(width: 8),
+ Text(
+ networkName,
+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w400,
+ letterSpacing: -0.07,
+ color: colors.primary,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Container(
+ width: 28,
+ height: 28,
+ decoration: BoxDecoration(
+ color: colors.surfaceContainer,
+ shape: BoxShape.circle,
+ ),
+ child: Icon(
+ Icons.keyboard_arrow_down,
+ size: 18,
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/anypay/select_recipient_network_sheet.dart b/lib/new-ui/widgets/anypay/select_recipient_network_sheet.dart
new file mode 100644
index 00000000..5e823569
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/select_recipient_network_sheet.dart
@@ -0,0 +1,243 @@
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:flutter/material.dart";
+
+class RecipientNetworkItem {
+ const RecipientNetworkItem({
+ required this.chainId,
+ required this.name,
+ required this.iconPath,
+ this.chainBadgeIconPath,
+ });
+
+ final int chainId;
+ final String name;
+ final String iconPath;
+ final String? chainBadgeIconPath;
+}
+
+class SelectRecipientNetworkSheet extends StatelessWidget {
+ const SelectRecipientNetworkSheet({
+ super.key,
+ required this.networks,
+ required this.currentChainId,
+ });
+
+ final List<RecipientNetworkItem> networks;
+ final int currentChainId;
+
+ static Future<int?> show({
+ required BuildContext context,
+ required List<RecipientNetworkItem> networks,
+ required int currentChainId,
+ }) {
+ return showModalBottomSheet<int>(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ enableDrag: false,
+ isDismissible: false,
+ backgroundColor: Colors.transparent,
+ builder: (_) => SelectRecipientNetworkSheet(
+ networks: networks,
+ currentChainId: currentChainId,
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+
+ RecipientNetworkItem? current;
+ final compatible = <RecipientNetworkItem>[];
+ for (final network in networks) {
+ if (network.chainId == currentChainId && current == null) {
+ current = network;
+ } else {
+ compatible.add(network);
+ }
+ }
+
+ return Container(
+ decoration: BoxDecoration(
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ color: colors.surface,
+ ),
+ child: SafeArea(
+ top: false,
+ child: Column(
+ children: [
+ ModalTopBar(
+ title: "",
+ trailingIcon: const Icon(Icons.close),
+ onTrailingPressed: () => Navigator.of(context).maybePop(),
+ ),
+ const SizedBox(height: 32),
+ CakeImageWidget(
+ imageUrl: "assets/new-ui/network_cube.svg",
+ width: 75,
+ height: 75,
+ colorFilter: ColorFilter.mode(colors.onSurfaceVariant, BlendMode.srcIn),
+ ),
+ const SizedBox(height: 24),
+ Text(
+ S.of(context).select_recipient_network,
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .titleLarge
+ ?.copyWith(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: -0.1),
+ ),
+ const SizedBox(height: 24),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32),
+ child: Text(
+ S.of(context).select_recipient_network_description,
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ ),
+ const SizedBox(height: 32),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (current != null) ...[
+ NetworkListCard(
+ rows: [
+ RecipientNetworkListRow(
+ item: current,
+ subtitle: S.of(context).current_network,
+ onTap: () => Navigator.of(context).pop(current!.chainId),
+ ),
+ ],
+ ),
+ const SizedBox(height: 24),
+ ],
+ if (compatible.isNotEmpty) ...[
+ Text(
+ S.of(context).compatible_networks,
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.06),
+ ),
+ const SizedBox(height: 12),
+ NetworkListCard(
+ rows: [
+ for (final network in compatible)
+ RecipientNetworkListRow(
+ item: network,
+ onTap: () => Navigator.of(context).pop(network.chainId),
+ ),
+ ],
+ ),
+ ],
+ const SizedBox(height: 16),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class NetworkListCard extends StatelessWidget {
+ const NetworkListCard({required this.rows});
+
+ final List<Widget> rows;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Container(
+ decoration: BoxDecoration(
+ color: colors.surfaceContainer,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var i = 0; i < rows.length; i++) ...[
+ rows[i],
+ if (i != rows.length - 1)
+ Divider(
+ height: 1,
+ thickness: 1,
+ color: colors.surfaceContainerHigh,
+ indent: 48,
+ endIndent: 12,
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+class RecipientNetworkListRow extends StatelessWidget {
+ const RecipientNetworkListRow(
+ {super.key, required this.item, required this.onTap, this.subtitle, this.imageOverride});
+
+ final String? subtitle;
+ final String? imageOverride;
+ final VoidCallback onTap;
+ final RecipientNetworkItem item;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return InkWell(
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
+ child: Row(
+ children: [
+ CakeImageWidget(
+ imageUrl: imageOverride ?? item.iconPath,
+ width: 24,
+ height: 24,
+ fit: BoxFit.cover,
+ color: isMonochromeSymbolIcon(imageOverride ?? item.iconPath) ? colors.primary : null,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 4,
+ children: [
+ Text(
+ item.name,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(fontWeight: FontWeight.w400, letterSpacing: -0.07),
+ ),
+ if (subtitle != null)
+ Text(
+ subtitle!,
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: colors.onSurfaceVariant, letterSpacing: -0.06, fontSize: 12),
+ ),
+ ],
+ ),
+ ),
+ Icon(Icons.chevron_right, size: 16, color: colors.onSurfaceVariant),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/anypay/send_to_network_page.dart b/lib/new-ui/widgets/anypay/send_to_network_page.dart
new file mode 100644
index 00000000..f25cd6d1
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/send_to_network_page.dart
@@ -0,0 +1,122 @@
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/new_primary_button.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:flutter/material.dart";
+
+class SendToNetworkPage extends StatelessWidget {
+ const SendToNetworkPage({
+ required this.title,
+ required this.destinationNetworkName,
+ required this.destinationIconPath,
+ required this.currentNetworkName,
+ required this.onSwitchWallet,
+ required this.onSwap,
+ super.key,
+ });
+
+ final String title;
+ final String destinationNetworkName;
+ final String destinationIconPath;
+ final String currentNetworkName;
+ final VoidCallback onSwitchWallet;
+ final VoidCallback onSwap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Material(
+ color: colors.surface,
+ child: SafeArea(
+ child: Column(
+ children: [
+ ModalTopBar(
+ title: "",
+ leadingIcon: const Icon(Icons.arrow_back_ios_new),
+ leadingSemanticLabel: S.of(context).seed_alert_back,
+ onLeadingPressed: () => Navigator.of(context).maybePop(),
+ trailingIcon: const Icon(Icons.close),
+ trailingSemanticLabel: S.of(context).close,
+ onTrailingPressed: () => Navigator.of(context).maybePop(),
+ ),
+ Expanded(
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ CakeImageWidget(
+ imageUrl: destinationIconPath,
+ width: 75,
+ height: 75,
+ fit: BoxFit.contain,
+ color: isMonochromeSymbolIcon(destinationIconPath) ? colors.primary : null,
+ ),
+ const SizedBox(height: 24),
+ Text(
+ title,
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.titleLarge?.copyWith(
+ fontSize: 20,
+ fontWeight: FontWeight.w500,
+ letterSpacing: -0.1,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ S.of(context).send_to_network_description(
+ destinationNetworkName,
+ currentNetworkName,
+ ),
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ NewPrimaryButton(
+ onPressed: onSwitchWallet,
+ image: CakeImageWidget(
+ imageUrl: "assets/new-ui/wallet_filled.svg",
+ width: 24,
+ height: 24,
+ colorFilter: ColorFilter.mode(colors.onPrimary, BlendMode.srcIn),
+ ),
+ text: S.of(context).switch_to_x_wallet(destinationNetworkName),
+ color: colors.primary,
+ textColor: colors.onPrimary,
+ ),
+ const SizedBox(height: 12),
+ NewPrimaryButton(
+ onPressed: onSwap,
+ image: CakeImageWidget(
+ imageUrl: "assets/new-ui/swap_arrows.svg",
+ width: 24,
+ height: 24,
+ colorFilter: ColorFilter.mode(colors.primary, BlendMode.srcIn),
+ ),
+ text: S.of(context).swap_from_network(currentNetworkName),
+ color: colors.surfaceContainer,
+ textColor: colors.primary,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/anypay/swap_from_network_page.dart b/lib/new-ui/widgets/anypay/swap_from_network_page.dart
new file mode 100644
index 00000000..24e41731
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/swap_from_network_page.dart
@@ -0,0 +1,140 @@
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/new_primary_button.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:flutter/material.dart";
+
+class SwapFromNetworkPage extends StatelessWidget {
+ const SwapFromNetworkPage({
+ required this.title,
+ required this.primaryButtonText,
+ required this.destinationNetworkName,
+ required this.destinationNetworkIconPath,
+ required this.currentNetworkName,
+ required this.currentNetworkIconPath,
+ required this.onProceed,
+ super.key,
+ this.primaryHasSwapIcon = false,
+ });
+
+ final String title;
+ final String primaryButtonText;
+ final bool primaryHasSwapIcon;
+ final String destinationNetworkName;
+ final String destinationNetworkIconPath;
+ final String currentNetworkName;
+ final String currentNetworkIconPath;
+ final VoidCallback onProceed;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Material(
+ color: colors.surface,
+ child: SafeArea(
+ child: Column(
+ children: [
+ ModalTopBar(
+ title: "",
+ leadingIcon: const Icon(Icons.arrow_back_ios_new),
+ leadingSemanticLabel: S.of(context).seed_alert_back,
+ onLeadingPressed: () => Navigator.of(context).maybePop(),
+ trailingIcon: const Icon(Icons.close),
+ trailingSemanticLabel: S.of(context).close,
+ onTrailingPressed: () => Navigator.of(context).maybePop(),
+ ),
+ Expanded(
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ spacing: 12,
+ children: [
+ CakeImageWidget(
+ imageUrl: currentNetworkIconPath,
+ width: 50,
+ height: 50,
+ fit: BoxFit.contain,
+ color: isMonochromeSymbolIcon(currentNetworkIconPath)
+ ? colors.primary
+ : null,
+ ),
+ Icon(Icons.arrow_forward, color: colors.primary, size: 28),
+ CakeImageWidget(
+ imageUrl: destinationNetworkIconPath,
+ width: 50,
+ height: 50,
+ fit: BoxFit.contain,
+ color: isMonochromeSymbolIcon(destinationNetworkIconPath)
+ ? colors.primary
+ : null,
+ ),
+ ],
+ ),
+ const SizedBox(height: 24),
+ Text(
+ title,
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.titleLarge?.copyWith(
+ fontSize: 20,
+ fontWeight: FontWeight.w500,
+ letterSpacing: -0.1,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ S.of(context).swap_from_network_description(
+ destinationNetworkName,
+ currentNetworkName,
+ ),
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ NewPrimaryButton(
+ onPressed: onProceed,
+ image: primaryHasSwapIcon
+ ? CakeImageWidget(
+ imageUrl: "assets/new-ui/swap_arrows.svg",
+ width: 24,
+ height: 24,
+ colorFilter: ColorFilter.mode(colors.onPrimary, BlendMode.srcIn),
+ )
+ : null,
+ text: primaryButtonText,
+ color: colors.primary,
+ textColor: colors.onPrimary,
+ ),
+ const SizedBox(height: 12),
+ NewPrimaryButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ text: S.of(context).cancel,
+ color: colors.surfaceContainer,
+ textColor: colors.primary,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/anypay/switch_network_wallet_page.dart b/lib/new-ui/widgets/anypay/switch_network_wallet_page.dart
new file mode 100644
index 00000000..49ec0482
--- /dev/null
+++ b/lib/new-ui/widgets/anypay/switch_network_wallet_page.dart
@@ -0,0 +1,108 @@
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/receive_page/receive_top_bar.dart";
+import "package:cake_wallet/new-ui/widgets/send_page/l2_action_wallet_selector.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:flutter/cupertino.dart";
+import "package:flutter/material.dart";
+
+class SwitchNetworkWalletPage extends StatelessWidget {
+ const SwitchNetworkWalletPage({
+ required this.wallets,
+ required this.networkName,
+ required this.destinationIconPath,
+ super.key,
+ });
+
+ final String networkName;
+ final String destinationIconPath;
+ final List<WalletInfo> wallets;
+
+ static Future<WalletInfo?> push({
+ required BuildContext context,
+ required String networkName,
+ required String targetIconPath,
+ required List<WalletInfo> wallets,
+ }) =>
+ Navigator.of(context).push<WalletInfo>(
+ CupertinoPageRoute(
+ builder: (_) => SwitchNetworkWalletPage(
+ networkName: networkName,
+ destinationIconPath: targetIconPath,
+ wallets: wallets,
+ ),
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Material(
+ color: colors.surface,
+ child: SafeArea(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ ModalTopBar(
+ title: "",
+ leadingIcon: const Icon(Icons.arrow_back_ios_new),
+ leadingSemanticLabel: S.of(context).seed_alert_back,
+ onLeadingPressed: () => Navigator.of(context).maybePop(),
+ ),
+ const SizedBox(height: 124),
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.arrow_forward, color: colors.primary, size: 32),
+ const SizedBox(width: 8),
+ CakeImageWidget(
+ imageUrl: destinationIconPath,
+ width: 50,
+ height: 50,
+ fit: BoxFit.contain,
+ color: isMonochromeSymbolIcon(destinationIconPath) ? colors.primary : null,
+ ),
+ ],
+ ),
+ const SizedBox(height: 24),
+ Text(
+ S.of(context).switch_to_x_wallet(networkName),
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .titleLarge
+ ?.copyWith(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: -0.1),
+ ),
+ const SizedBox(height: 24),
+ Text(
+ S.of(context).select_compatible_wallet,
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, letterSpacing: -0.07),
+ ),
+ const SizedBox(height: 24),
+ Expanded(
+ child: ListView.separated(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ itemCount: wallets.length,
+ separatorBuilder: (_, __) => const SizedBox(height: 12),
+ itemBuilder: (_, index) {
+ final wallet = wallets[index];
+ return WalletRow(
+ currencyIconPath: getCryptoCurrencyIconForWalletListItem(wallet.type),
+ walletName: wallet.name,
+ onTap: () => Navigator.of(context).pop(wallet),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/coins_page/assets_history/history_trade_tile.dart b/lib/new-ui/widgets/coins_page/assets_history/history_trade_tile.dart
index 805b16b3..cd4fc843 100644
--- a/lib/new-ui/widgets/coins_page/assets_history/history_trade_tile.dart
+++ b/lib/new-ui/widgets/coins_page/assets_history/history_trade_tile.dart
@@ -117,7 +117,12 @@ class HistoryTradeTile extends StatelessWidget {
to!.title,
),
if (toChainIcon?.isNotEmpty ?? false)
- CakeImageWidget(imageUrl: toChainIcon, width: 12, height: 12)
+ CakeImageWidget(
+ imageUrl: toChainIcon,
+ width: 12,
+ height: 12,
+ color: Theme.of(context).colorScheme.onSurface,
+ )
],
),
leadingIcon: _getLeadingStack(context),
diff --git a/lib/new-ui/widgets/currency_picker/currency_picker_args.dart b/lib/new-ui/widgets/currency_picker/currency_picker_args.dart
index db3914c4..13a06523 100644
--- a/lib/new-ui/widgets/currency_picker/currency_picker_args.dart
+++ b/lib/new-ui/widgets/currency_picker/currency_picker_args.dart
@@ -1,13 +1,18 @@
-import 'package:cake_wallet/evm/evm.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/currency_for_wallet_type.dart';
-import 'package:cw_core/currency_groups.dart';
-import 'package:cw_core/wallet_type.dart';
+import "package:cake_wallet/evm/evm.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:cw_core/currency_groups.dart";
+import "package:cw_core/erc20_token.dart";
+import "package:cw_core/spl_token.dart";
+import "package:cw_core/tron_token.dart";
+import "package:cw_core/wallet_type.dart";
String chainNameForCurrency(CryptoCurrency c) {
- if (c == CryptoCurrency.btcln) return 'Lightning';
+ if (c == CryptoCurrency.btcln) {
+ return "Lightning";
+ }
final wt = cryptoCurrencyOrTokenToWalletType(c);
- return wt != null ? walletTypeToString(wt) : (c.tag ?? '');
+ return wt != null ? walletTypeToString(wt) : (c.tag ?? "");
}
final Set<String> _stablecoinSymbols = {
@@ -27,19 +32,25 @@ const _kEvmDefaultTokenNatives = <CryptoCurrency>[
];
void appendEvmDefaultTokens(List<CryptoCurrency> into) {
- if (evm == null) return;
+ if (evm == null) {
+ return;
+ }
String keyFor(CryptoCurrency c) {
final wt = cryptoCurrencyOrTokenToWalletType(c);
- final chain = wt?.toString() ?? (c.tag ?? '').toUpperCase();
- return '${c.title.toUpperCase()}|$chain';
+ final chain = wt?.toString() ?? (c.tag ?? "").toUpperCase();
+ return "${c.title.toUpperCase()}|$chain";
}
final seen = <String>{for (final c in into) keyFor(c)};
for (final native in _kEvmDefaultTokenNatives) {
final chainId = getChainIdByCryptoCurrency(native);
- if (chainId == null) continue;
+ if (chainId == null) {
+ continue;
+ }
for (final t in evm!.getDefaultTokensByChainId(chainId)) {
- if (seen.add(keyFor(t))) into.add(t);
+ if (seen.add(keyFor(t))) {
+ into.add(t);
+ }
}
}
}
@@ -52,6 +63,55 @@ class CurrencyPickerBalance {
final double? fiatValue;
}
+String? _assetAddressKey(CryptoCurrency c) {
+ if (c is Erc20Token) {
+ return c.contractAddress.toLowerCase();
+ }
+ if (c is TronToken) {
+ return c.contractAddress.toLowerCase();
+ }
+ if (c is SPLToken) {
+ return c.mintAddress.toLowerCase();
+ }
+ return null;
+}
+
+CurrencyPickerBalance? balanceForAsset(
+ Map<CryptoCurrency, CurrencyPickerBalance>? balances,
+ CryptoCurrency asset,
+) {
+ if (balances == null || balances.isEmpty) {
+ return null;
+ }
+
+ final direct = balances[asset];
+ if (direct != null) {
+ return direct;
+ }
+
+ final addressKey = _assetAddressKey(asset);
+ if (addressKey != null) {
+ for (final entry in balances.entries) {
+ if (_assetAddressKey(entry.key) == addressKey) {
+ return entry.value;
+ }
+ }
+ return null;
+ }
+
+ final title = asset.title.toUpperCase();
+ CurrencyPickerBalance? byTitle;
+ for (final entry in balances.entries) {
+ if (entry.key.title.toUpperCase() == title) {
+ if (byTitle != null) {
+ return null;
+ }
+ byTitle = entry.value;
+ }
+ }
+ return byTitle;
+}
+
enum RecentsSource { none, trades, orders }
class CurrencyPickerArgs {
@@ -63,6 +123,7 @@ class CurrencyPickerArgs {
required this.onSelected,
required this.symbolResolver,
this.recentsSource = RecentsSource.none,
+ this.useSingleNetworkLayout = false,
});
final CryptoCurrency? selected;
@@ -72,6 +133,5 @@ class CurrencyPickerArgs {
final String Function(CryptoCurrency) symbolResolver;
final Map<CryptoCurrency, CurrencyPickerBalance>? balanceByAsset;
final RecentsSource recentsSource;
-
- bool get isPreFiltered => filterByNetwork != null;
+ final bool useSingleNetworkLayout;
}
diff --git a/lib/new-ui/widgets/currency_picker/currency_picker_sheet.dart b/lib/new-ui/widgets/currency_picker/currency_picker_sheet.dart
index a59b8d71..43577eef 100644
--- a/lib/new-ui/widgets/currency_picker/currency_picker_sheet.dart
+++ b/lib/new-ui/widgets/currency_picker/currency_picker_sheet.dart
@@ -47,7 +47,7 @@ class CurrencyPickerSheet extends StatelessWidget {
onLeadingPressed: () => Navigator.of(context).maybePop(),
),
Expanded(
- child: args.isPreFiltered
+ child: args.useSingleNetworkLayout
? SingleNetworkCurrencyPicker(args: args)
: MultiNetworkCurrencyPicker(args: args),
),
diff --git a/lib/new-ui/widgets/currency_picker/single_network_currency_picker.dart b/lib/new-ui/widgets/currency_picker/single_network_currency_picker.dart
index 9eb80722..a6fd378d 100644
--- a/lib/new-ui/widgets/currency_picker/single_network_currency_picker.dart
+++ b/lib/new-ui/widgets/currency_picker/single_network_currency_picker.dart
@@ -1,17 +1,20 @@
-import 'package:cake_wallet/generated/i18n.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_list_container.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_row.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_search_field.dart';
-import 'package:cake_wallet/new-ui/widgets/currency_picker/picker_section_header.dart';
-import 'package:cake_wallet/reactions/wallet_utils.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/currency_for_wallet_type.dart';
-import 'package:cw_core/wallet_type.dart';
-import 'package:flutter/material.dart';
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_list_container.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_row.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_search_field.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/picker_section_header.dart";
+import "package:cake_wallet/reactions/wallet_utils.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter/material.dart";
class SingleNetworkCurrencyPicker extends StatefulWidget {
- const SingleNetworkCurrencyPicker({super.key, required this.args});
+ const SingleNetworkCurrencyPicker({
+ required this.args,
+ super.key,
+ });
final CurrencyPickerArgs args;
@@ -41,24 +44,36 @@ class _SingleNetworkCurrencyPickerState extends State<SingleNetworkCurrencyPicke
Navigator.of(context).maybePop();
}
- double _fiatValueFor(CryptoCurrency c) => _args.balanceByAsset?[c]?.fiatValue ?? 0;
+ CurrencyPickerBalance? _balanceFor(CryptoCurrency c) => balanceForAsset(_args.balanceByAsset, c);
+
+ double _fiatValueFor(CryptoCurrency c) => _balanceFor(c)?.fiatValue ?? 0;
@override
Widget build(BuildContext context) {
final native = walletTypeToCryptoCurrency(_network);
final query = _searchController.text.trim();
- final tokens =
- _args.items.where((c) => c != native).where((c) => currencyMatchesQuery(c, query)).toList();
+ final tokens = _args.items
+ .where(
+ (c) =>
+ c != native &&
+ cryptoCurrencyOrTokenToWalletType(c) == _network &&
+ currencyMatchesQuery(c, query),
+ )
+ .toList();
final insertOrder = {for (var i = 0; i < tokens.length; i++) tokens[i]: i};
tokens.sort((a, b) {
final av = _fiatValueFor(a);
final bv = _fiatValueFor(b);
- if (bv != av) return bv.compareTo(av);
+ if (bv != av) {
+ return bv.compareTo(av);
+ }
return (insertOrder[a] ?? 0).compareTo(insertOrder[b] ?? 0);
});
final nativeMatches = currencyMatchesQuery(native, query);
+ final showSectionHeaders = _network != WalletType.bitcoin;
+
return Column(
mainAxisSize: MainAxisSize.max,
children: [
@@ -66,40 +81,61 @@ class _SingleNetworkCurrencyPickerState extends State<SingleNetworkCurrencyPicke
child: (nativeMatches || tokens.isNotEmpty)
? ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
- children: [
- if (nativeMatches) ...[
- PickerSectionHeader(title: S.of(context).picker_section_gas_token),
- CurrencyPickerListContainer(
- rows: [
- CurrencyPickerRow(
- currency: native,
- isSelected: _args.selected == native,
- trailing: _BalanceTrailing(balance: _args.balanceByAsset?[native]),
- onTap: () => _selectCurrency(native),
- ),
- ],
- ),
- const SizedBox(height: 16),
- ],
- if (tokens.isNotEmpty) ...[
- PickerSectionHeader(
- title: S
- .of(context)
- .picker_section_tokens_standard(tokenStandardFor(_network)),
- ),
- CurrencyPickerListContainer(
- rows: [
- for (final t in tokens)
- CurrencyPickerRow(
- currency: t,
- isSelected: _args.selected == t,
- trailing: _BalanceTrailing(balance: _args.balanceByAsset?[t]),
- onTap: () => _selectCurrency(t),
+ children: showSectionHeaders
+ ? [
+ if (nativeMatches) ...[
+ PickerSectionHeader(title: S.of(context).picker_section_gas_token),
+ CurrencyPickerListContainer(
+ rows: [
+ CurrencyPickerRow(
+ currency: native,
+ isSelected: _args.selected == native,
+ trailing: _BalanceTrailing(balance: _balanceFor(native)),
+ onTap: () => _selectCurrency(native),
+ ),
+ ],
),
+ const SizedBox(height: 16),
+ ],
+ if (tokens.isNotEmpty) ...[
+ PickerSectionHeader(
+ title: S
+ .of(context)
+ .picker_section_tokens_standard(tokenStandardFor(_network)),
+ ),
+ CurrencyPickerListContainer(
+ rows: [
+ for (final t in tokens)
+ CurrencyPickerRow(
+ currency: t,
+ isSelected: _args.selected == t,
+ trailing: _BalanceTrailing(balance: _balanceFor(t)),
+ onTap: () => _selectCurrency(t),
+ ),
+ ],
+ ),
+ ],
+ ]
+ : [
+ CurrencyPickerListContainer(
+ rows: [
+ if (nativeMatches)
+ CurrencyPickerRow(
+ currency: native,
+ isSelected: _args.selected == native,
+ trailing: _BalanceTrailing(balance: _balanceFor(native)),
+ onTap: () => _selectCurrency(native),
+ ),
+ for (final t in tokens)
+ CurrencyPickerRow(
+ currency: t,
+ isSelected: _args.selected == t,
+ trailing: _BalanceTrailing(balance: _balanceFor(t)),
+ onTap: () => _selectCurrency(t),
+ ),
+ ],
+ ),
],
- ),
- ],
- ],
)
: Center(
child: Padding(
@@ -131,7 +167,7 @@ class _BalanceTrailing extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
- final amount = balance?.amount ?? '—';
+ final amount = balance?.amount ?? "—";
final fiat = balance?.fiat;
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
diff --git a/lib/new-ui/widgets/new_primary_button.dart b/lib/new-ui/widgets/new_primary_button.dart
index 3447a460..1995cd15 100644
--- a/lib/new-ui/widgets/new_primary_button.dart
+++ b/lib/new-ui/widgets/new_primary_button.dart
@@ -1,14 +1,13 @@
-import 'package:flutter/cupertino.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter_svg/flutter_svg.dart';
+import "package:flutter/cupertino.dart";
+import "package:flutter/material.dart";
class NewPrimaryButton extends StatelessWidget {
const NewPrimaryButton({
required this.onPressed,
- this.image,
required this.text,
required this.color,
required this.textColor,
+ this.image,
this.isLoading = false,
this.borderColor = Colors.transparent,
this.disabled = false,
@@ -18,48 +17,46 @@ class NewPrimaryButton extends StatelessWidget {
final VoidCallback onPressed;
final bool isLoading;
final bool disabled;
- final SvgPicture? image;
+ final Widget? image;
final Color color;
final Color textColor;
final Color borderColor;
final String text;
@override
- Widget build(BuildContext context) {
- return SizedBox(
- height: 52.0,
- child: TextButton(
- onPressed: disabled ? null : onPressed,
- style: ButtonStyle(
- backgroundColor: WidgetStateProperty.all(
- disabled ? color.withAlpha(128) : color,
- ),
- shape: WidgetStateProperty.all<RoundedSuperellipseBorder>(
- RoundedSuperellipseBorder(
- borderRadius: BorderRadius.circular(18.0),
+ Widget build(BuildContext context) => SizedBox(
+ height: 52,
+ child: TextButton(
+ onPressed: disabled ? null : onPressed,
+ style: ButtonStyle(
+ backgroundColor: WidgetStateProperty.all(
+ disabled ? color.withAlpha(128) : color,
+ ),
+ shape: WidgetStateProperty.all<RoundedSuperellipseBorder>(
+ RoundedSuperellipseBorder(
+ borderRadius: BorderRadius.circular(18),
+ ),
),
),
+ child: Center(
+ child: isLoading
+ ? const CupertinoActivityIndicator()
+ : Row(
+ spacing: 10,
+ mainAxisSize: MainAxisSize.min,
+ children: <Widget>[
+ if (image != null) image!,
+ Text(
+ text,
+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(
+ fontSize: 14,
+ fontWeight: FontWeight.w600,
+ color: textColor,
+ ),
+ ),
+ ],
+ ),
+ ),
),
- child: Center(
- child: isLoading
- ? CupertinoActivityIndicator()
- : Row(
- spacing: 10,
- mainAxisSize: MainAxisSize.min,
- children: <Widget>[
- if (image != null) image!,
- Text(
- text,
- style: Theme.of(context).textTheme.bodyMedium?.copyWith(
- fontSize: 14,
- fontWeight: FontWeight.w600,
- color: textColor,
- ),
- )
- ],
- ),
- ),
- ),
- );
- }
+ );
}
diff --git a/lib/new-ui/widgets/swap_page/anypay_swap_footer.dart b/lib/new-ui/widgets/swap_page/anypay_swap_footer.dart
new file mode 100644
index 00000000..f0d03e65
--- /dev/null
+++ b/lib/new-ui/widgets/swap_page/anypay_swap_footer.dart
@@ -0,0 +1,106 @@
+import "package:auto_size_text/auto_size_text.dart";
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/provider_selector_page.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cake_wallet/view_model/exchange/exchange_view_model.dart";
+import "package:flutter/cupertino.dart";
+import "package:flutter/material.dart";
+import "package:flutter_mobx/flutter_mobx.dart";
+
+class AnyPaySwapFooter extends StatelessWidget {
+ const AnyPaySwapFooter({required this.exchangeViewModel, super.key});
+
+ final ExchangeViewModel exchangeViewModel;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final textTheme = Theme.of(context).textTheme;
+ return Observer(
+ builder: (_) {
+ if (exchangeViewModel.depositAmount.isEmpty) {
+ return const SizedBox.shrink();
+ }
+
+ final provider = exchangeViewModel.forcedProvider ?? exchangeViewModel.providerDisplay;
+ final depositAmount = exchangeViewModel.depositAmount;
+ final depositSymbol =
+ exchangeViewModel.amountParsingProxy.getCryptoSymbol(exchangeViewModel.depositCurrency);
+ final depositFiat = exchangeViewModel.roundedDepositAmountFiat(2);
+ final showFiat = !exchangeViewModel.isFiatDisabled && depositFiat.isNotEmpty;
+ return Row(
+ children: [
+ Expanded(
+ child: Container(
+ alignment: Alignment.center,
+ height: 48,
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(18),
+ border: Border.all(color: colors.primary),
+ ),
+ child: AutoSizeText.rich(
+ TextSpan(
+ children: [
+ TextSpan(text: "$depositAmount $depositSymbol"),
+ if (showFiat)
+ TextSpan(
+ text: " ≈ ${exchangeViewModel.fiat.symbol}$depositFiat",
+ style: TextStyle(color: colors.onSurfaceVariant),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ minFontSize: 10,
+ style: textTheme.bodySmall
+ ?.copyWith(fontWeight: FontWeight.w500, letterSpacing: -0.06),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: provider == null
+ ? null
+ : () => Navigator.of(context).push(
+ CupertinoPageRoute<void>(
+ builder: (context) => Material(
+ child: ProviderSelectorPage(exchangeViewModel: exchangeViewModel),
+ ),
+ ),
+ ),
+ child: Container(
+ height: 48,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ decoration: BoxDecoration(
+ color: colors.surfaceContainer,
+ borderRadius: BorderRadius.circular(24),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (provider != null)
+ CakeImageWidget(imageUrl: provider.description.image, width: 24, height: 24)
+ else
+ const CupertinoActivityIndicator(),
+ const SizedBox(width: 8),
+ Text(
+ provider?.title ?? "${S.of(context).finding_provider}...",
+ style: textTheme.bodyMedium?.copyWith(letterSpacing: -0.07),
+ ),
+ const SizedBox(width: 8),
+ CakeImageWidget(
+ imageUrl: "assets/new-ui/chooser.svg",
+ width: 12,
+ height: 12,
+ colorFilter: ColorFilter.mode(colors.onSurfaceVariant, BlendMode.srcIn),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
diff --git a/lib/new-ui/widgets/swap_page/swap_amount_box.dart b/lib/new-ui/widgets/swap_page/swap_amount_box.dart
new file mode 100644
index 00000000..9f7debf0
--- /dev/null
+++ b/lib/new-ui/widgets/swap_page/swap_amount_box.dart
@@ -0,0 +1,789 @@
+import "package:cake_wallet/core/amount_validator.dart";
+import "package:cake_wallet/entities/qr_scanner.dart";
+import "package:cake_wallet/generated/i18n.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart";
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_sheet.dart";
+import "package:cake_wallet/new-ui/widgets/modern_button.dart";
+import "package:cake_wallet/new-ui/widgets/send_page/fiat_amount_bar.dart";
+import "package:cake_wallet/new-ui/widgets/send_page/send_memo_input.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/refund_address_modal.dart";
+import "package:cake_wallet/new-ui/widgets/swap_page/swap_address_selection_modal.dart";
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cake_wallet/utils/decimal_input_formatter.dart";
+import "package:cake_wallet/utils/permission_handler.dart";
+import "package:cake_wallet/view_model/exchange/exchange_view_model.dart";
+import "package:cake_wallet/view_model/wallet_switcher_view_model.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currencies_with_memo.dart";
+import "package:cw_core/currency.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter/material.dart";
+import "package:flutter/services.dart";
+import "package:flutter_mobx/flutter_mobx.dart";
+import "package:mobx/mobx.dart" as mobx;
+import "package:modal_bottom_sheet/modal_bottom_sheet.dart";
+import "package:permission_handler/permission_handler.dart";
+
+class SwapAmountBox extends StatefulWidget {
+ SwapAmountBox({
+ required this.exchangeViewModel,
+ required this.isReceiverCard,
+ required this.walletSwitcherViewModel,
+ required this.currency,
+ required this.currencies,
+ required this.onCurrencySelected,
+ this.currencyValueValidator,
+ this.addressTextFieldValidator,
+ this.title = "",
+ this.hasRefundAddress = false,
+ this.hasAllAmount = false,
+ this.useBaseUnit = false,
+ this.allAmount,
+ this.onPushPasteButton,
+ this.onPushAddressBookButton,
+ this.filteredNetwork,
+ this.sourceSelectorMode = false,
+ this.walletName,
+ this.balanceByAsset,
+ this.useSingleNetworkLayout = false,
+ super.key,
+ });
+
+ final List<Currency> currencies;
+ final Function(Currency) onCurrencySelected;
+ final String title;
+ final bool isReceiverCard;
+ final Currency currency;
+ final bool useBaseUnit;
+ final bool hasRefundAddress;
+ final FormFieldValidator<String>? currencyValueValidator;
+ final FormFieldValidator<String>? addressTextFieldValidator;
+ final FormFieldValidator<String> allAmountValidator = AllAmountValidator();
+ final bool hasAllAmount;
+ final VoidCallback? allAmount;
+ final void Function(BuildContext context)? onPushPasteButton;
+ final void Function(BuildContext context)? onPushAddressBookButton;
+ final ExchangeViewModel exchangeViewModel;
+ final WalletSwitcherViewModel walletSwitcherViewModel;
+ final WalletType? filteredNetwork;
+ final bool sourceSelectorMode;
+ final String? walletName;
+ final Map<CryptoCurrency, CurrencyPickerBalance>? balanceByAsset;
+ final bool useSingleNetworkLayout;
+
+ @override
+ State<SwapAmountBox> createState() => SwapAmountBoxState();
+}
+
+class SwapAmountBoxState extends State<SwapAmountBox> {
+ final addressController = TextEditingController();
+ final amountController = TextEditingController();
+ final fiatAmountController = TextEditingController();
+ final amountFocusNode = FocusNode();
+ final memoController = TextEditingController();
+ mobx.ReactionDisposer? _memoReactionDisposer;
+
+ @override
+ void initState() {
+ if (widget.isReceiverCard) {
+ memoController.text = widget.exchangeViewModel.receiveAddressExtraId;
+
+ memoController.addListener(() {
+ if (widget.exchangeViewModel.receiveAddressExtraId != memoController.text) {
+ widget.exchangeViewModel.receiveAddressExtraId = memoController.text;
+ }
+ });
+
+ _memoReactionDisposer =
+ mobx.reaction((_) => widget.exchangeViewModel.receiveAddressExtraId, (String value) {
+ if (memoController.text != value) {
+ memoController.text = value;
+ }
+ });
+ }
+
+ super.initState();
+ }
+
+ @override
+ void dispose() {
+ _memoReactionDisposer?.call();
+ memoController.dispose();
+ addressController.dispose();
+ amountController.dispose();
+ fiatAmountController.dispose();
+ amountFocusNode.dispose();
+ super.dispose();
+ }
+
+ bool _fiatInputMode = false;
+
+ /// Whether the amount field is currently taking fiat input, the page's
+ /// best-rate reaction needs this to know which controller holds the amount.
+ bool get fiatInputMode => _fiatInputMode;
+
+ CurrencyPickerBalance? _sourceBalance() {
+ final selected = widget.currency;
+ if (selected is! CryptoCurrency) {
+ return null;
+ }
+ return balanceForAsset(widget.balanceByAsset, selected);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final currencyToShow = (widget.currency is CryptoCurrency)
+ ? widget.exchangeViewModel.amountParsingProxy
+ .getCryptoSymbol(widget.currency as CryptoCurrency)
+ : widget.currency.name.toUpperCase();
+
+ final chainIconPath = (widget.currency is CryptoCurrency)
+ ? _getCurrencyChainIconPath(widget.currency as CryptoCurrency)
+ : null;
+
+ final colors = Theme.of(context).colorScheme;
+
+ if (widget.sourceSelectorMode) {
+ final available = _sourceBalance()?.amount.split(" ").first ?? "—";
+ return Column(
+ spacing: 12,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ GestureDetector(
+ onTap: _presentCurrencyPicker,
+ child: Container(
+ height: 52,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ decoration: BoxDecoration(
+ color: colors.surfaceContainer,
+ borderRadius: BorderRadius.circular(18),
+ ),
+ child: Row(
+ children: [
+ CakeImageWidget(
+ imageUrl: widget.currency.iconPath ?? "",
+ width: 24,
+ height: 24,
+ ),
+ const SizedBox(width: 8),
+ Text(
+ currencyToShow,
+ style: Theme.of(context).textTheme.bodyLarge?.copyWith(letterSpacing: -0.08),
+ ),
+ if (chainIconPath != null && chainIconPath.isNotEmpty) ...[
+ const SizedBox(width: 4),
+ CakeImageWidget(
+ imageUrl: chainIconPath,
+ width: 12,
+ height: 12,
+ colorFilter: ColorFilter.mode(colors.onSurfaceVariant, BlendMode.srcIn),
+ ),
+ ],
+ const Spacer(),
+ CakeImageWidget(
+ imageUrl: "assets/new-ui/chooser.svg",
+ width: 12,
+ height: 12,
+ colorFilter: ColorFilter.mode(colors.onSurfaceVariant, BlendMode.srcIn),
+ ),
+ ],
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ CakeImageWidget(
+ imageUrl: "assets/new-ui/wallet_filled.svg",
+ width: 16,
+ height: 16,
+ colorFilter: ColorFilter.mode(colors.onSurfaceVariant, BlendMode.srcIn),
+ ),
+ const SizedBox(width: 4),
+ Flexible(
+ child: Text(
+ widget.walletName ?? "",
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ letterSpacing: -0.06,
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text(
+ "${S.of(context).avl}: $available",
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ letterSpacing: -0.06,
+ color: colors.primary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+
+ return Column(
+ spacing: 12,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (widget.title.isNotEmpty)
+ Text(
+ widget.title,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w500,
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ Container(
+ decoration: ShapeDecoration(
+ color: Theme.of(context).colorScheme.surfaceContainer,
+ shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(24)),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ spacing: 12,
+ children: [
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: amountFocusNode.requestFocus,
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ spacing: 4,
+ children: [
+ Expanded(
+ child: Row(
+ spacing: 4,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Flexible(
+ child: IntrinsicWidth(
+ child: Observer(
+ builder: (_) {
+ final showFetching = !widget.isReceiverCard &&
+ widget.exchangeViewModel.isFixedRateMode &&
+ widget.exchangeViewModel.receiveAmount.isNotEmpty &&
+ widget.exchangeViewModel.depositAmount.isEmpty;
+ return TextFormField(
+ keyboardType: TextInputType.numberWithOptions(
+ signed: false,
+ decimal: !widget.useBaseUnit,
+ ),
+ validator:
+ _fiatInputMode ? null : widget.currencyValueValidator,
+ controller:
+ _fiatInputMode ? fiatAmountController : amountController,
+ focusNode: amountFocusNode,
+ style: TextStyle(
+ fontSize: 28,
+ color: Theme.of(context).colorScheme.onSurface,
+ fontWeight: FontWeight.w400,
+ ),
+ decoration: InputDecoration(
+ contentPadding: EdgeInsets.zero,
+ isDense: true,
+ hintText: showFetching ? S.of(context).fetching : "0",
+ fillColor: Colors.transparent,
+ hoverColor: Colors.transparent,
+ focusedBorder: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ ),
+ inputFormatters: <TextInputFormatter>[
+ DecimalInputFormatter(
+ maxDecimals:
+ widget.useBaseUnit ? 0 : widget.currency.decimals,
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ if (_fiatInputMode)
+ Center(
+ child: Text(
+ widget.exchangeViewModel.fiat.title,
+ style: TextStyle(
+ fontSize: 16,
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ GestureDetector(
+ onTap: _presentCurrencyPicker,
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.surface,
+ borderRadius: BorderRadius.circular(999999),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.only(top: 4, bottom: 4, left: 4, right: 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ CakeImageWidget(
+ imageUrl: widget.currency.iconPath ?? "",
+ width: 28,
+ height: 28,
+ ),
+ const SizedBox(width: 10),
+ Text(
+ currencyToShow,
+ textAlign: TextAlign.center,
+ ),
+ if (chainIconPath != null && chainIconPath.isNotEmpty) ...[
+ const SizedBox(width: 4),
+ CakeImageWidget(
+ imageUrl: chainIconPath,
+ width: 12,
+ height: 12,
+ colorFilter: ColorFilter.mode(
+ Theme.of(context).colorScheme.onSurfaceVariant,
+ BlendMode.srcIn,
+ ),
+ ),
+ const SizedBox(width: 6),
+ ] else
+ const SizedBox(width: 10),
+ Container(
+ width: 16,
+ height: 16,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(9999999999),
+ color: Theme.of(context).colorScheme.surfaceContainerHigh,
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(4),
+ child: RotatedBox(
+ quarterTurns: 2,
+ child: CakeImageWidget(
+ imageUrl: "assets/new-ui/dropdown_arrow.svg",
+ width: 4,
+ height: 4,
+ colorFilter: ColorFilter.mode(
+ Theme.of(context).colorScheme.primary,
+ BlendMode.srcIn,
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 4),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Observer(
+ builder: (_) {
+ final hasAllAmount = !(widget.isReceiverCard ||
+ widget.exchangeViewModel.isSendFromExternal ||
+ !widget.exchangeViewModel.hasAllAmount);
+
+ return FiatAmountBar(
+ foregroundElementColor: Theme.of(context).colorScheme.surfaceContainerHigh,
+ textColor: Theme.of(context).colorScheme.onSurfaceVariant,
+ allAmountColor: hasAllAmount ? null : Colors.transparent,
+ allAmountTextColor:
+ hasAllAmount ? null : Theme.of(context).colorScheme.onSurfaceVariant,
+ fiatInputMode: _fiatInputMode,
+ allAmount: !hasAllAmount
+ ? widget.isReceiverCard
+ ? null
+ : widget.exchangeViewModel.balanceDisplay
+ : widget.exchangeViewModel.depositAvailableAmount,
+ onSwitchButtonPressed: () {
+ setState(() => _fiatInputMode = !_fiatInputMode);
+ if (_fiatInputMode) {
+ updateFiatAmount();
+ } else {
+ amountController.text = widget.isReceiverCard
+ ? widget.exchangeViewModel.receiveAmount
+ : widget.exchangeViewModel.depositAmount;
+ }
+ },
+ onAllButtonPressed: () {
+ setState(() {
+ _fiatInputMode = false;
+ });
+ widget.allAmount?.call();
+ },
+ cryptoAmount: widget.isReceiverCard
+ ? widget.exchangeViewModel.roundedReceiveAmount(6)
+ : widget.exchangeViewModel.roundedDepositAmount(6),
+ fiatAmount: widget.isReceiverCard
+ ? widget.exchangeViewModel.roundedReceiveAmountFiat(6)
+ : widget.exchangeViewModel.roundedDepositAmountFiat(6),
+ cryptoCurrencySymbol: currencyToShow,
+ fiatCurrencySymbol: widget.exchangeViewModel.fiat.symbol,
+ );
+ },
+ ),
+ Observer(
+ builder: (_) {
+ final addressEmpty = (widget.isReceiverCard &&
+ widget.exchangeViewModel.receiveAddress.isEmpty) ||
+ (!widget.isReceiverCard && widget.exchangeViewModel.depositAddress.isEmpty);
+ final addressPickerText = widget.isReceiverCard
+ ? (addressEmpty ? S.of(context).select_receiver : S.of(context).to)
+ : S.of(context).from;
+ final addressDescription = widget.isReceiverCard
+ ? widget.exchangeViewModel.receiveAddressDisplayName ??
+ _middleTruncate(widget.exchangeViewModel.receiveAddress, 8, 8)
+ : widget.exchangeViewModel.isSendFromExternal
+ ? S.of(context).external
+ : widget.exchangeViewModel.wallet.name;
+ return Row(
+ spacing: 8,
+ children: [
+ Flexible(
+ child: GestureDetector(
+ onTap: _presentWalletPicker,
+ child: Container(
+ height: 36,
+ decoration: BoxDecoration(
+ color: (addressEmpty && widget.isReceiverCard)
+ ? Theme.of(context).colorScheme.primary
+ : Theme.of(context).colorScheme.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(9999),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Observer(
+ builder: (_) => Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ spacing: 8,
+ mainAxisSize: MainAxisSize.max,
+ children: [
+ Text(
+ addressPickerText,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w500,
+ color: (addressEmpty && widget.isReceiverCard)
+ ? Theme.of(context).colorScheme.onPrimary
+ : Theme.of(context).colorScheme.onSurface,
+ ),
+ ),
+ Text(
+ addressDescription,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w500,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ ),
+ ],
+ ),
+ RotatedBox(
+ quarterTurns: 2,
+ child: CakeImageWidget(
+ imageUrl: "assets/new-ui/dropdown_arrow.svg",
+ colorFilter: ColorFilter.mode(
+ (addressEmpty && widget.isReceiverCard)
+ ? Theme.of(context).colorScheme.onPrimary
+ : Theme.of(context).colorScheme.onSurface,
+ BlendMode.srcIn,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (!widget.isReceiverCard &&
+ widget.exchangeViewModel.isSendFromExternal &&
+ widget.exchangeViewModel.depositAddress.isEmpty)
+ ModernButton.svg(
+ svgPath: "assets/new-ui/refund_address.svg",
+ onPressed: askForRefundAddress,
+ size: 36,
+ iconSize: 18,
+ backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
+ semanticLabel: S.of(context).refund_address,
+ ),
+ if (widget.isReceiverCard &&
+ widget.exchangeViewModel.receiveAddress.isEmpty) ...[
+ ModernButton.svg(
+ svgPath: "assets/new-ui/paste.svg",
+ onPressed: () => widget.onPushPasteButton?.call(context),
+ size: 36,
+ iconSize: 20,
+ backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
+ semanticLabel: S.of(context).paste,
+ ),
+ ModernButton.svg(
+ svgPath: "assets/new-ui/scan.svg",
+ onPressed: () => _presentQRScanner(context),
+ size: 36,
+ iconSize: 20,
+ backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
+ semanticLabel: S.of(context).scan,
+ ),
+ ],
+ ],
+ );
+ },
+ ),
+ if (widget.isReceiverCard)
+ Observer(
+ builder: (_) {
+ final selected = widget.exchangeViewModel.receiveCurrency;
+ final labelType = memoLabelTypeFor(selected);
+ if (labelType == null) {
+ return const SizedBox.shrink();
+ }
+
+ final isDestinationTag = labelType == MemoLabelType.destinationTag;
+ final hint = isDestinationTag
+ ? S.of(context).destination_tag_optional
+ : S.of(context).memo_optional;
+ final disclaimer = isDestinationTag
+ ? S.of(context).destination_tag_swap_disclaimer
+ : S.of(context).memo_swap_disclaimer;
+
+ return NewSendMemoInput(
+ memoController: memoController,
+ maxMemoLength: isDestinationTag ? 20 : 256,
+ memoLength: memoController.text.length,
+ hintText: hint,
+ disclaimerText: disclaimer,
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ void changeAddress({required String address}) {
+ setState(() => addressController.text = _normalizeAddressFormat(address));
+ }
+
+ void changeAmount({required String amount}) {
+ setState(() => amountController.text = amount);
+ }
+
+ String _normalizeAddressFormat(String address) {
+ if (address.startsWith("bitcoincash:")) {
+ address = address.substring(12);
+ }
+ return address;
+ }
+
+ void _presentCurrencyPicker() {
+ final rawCurrencies = widget.isReceiverCard
+ ? widget.exchangeViewModel.receiveCurrencies
+ : widget.exchangeViewModel.depositCurrencies;
+ final currencies = rawCurrencies.whereType<CryptoCurrency>().toList();
+ final restrictToCurrentBalances = !widget.isReceiverCard &&
+ widget.balanceByAsset != null &&
+ widget.balanceByAsset!.isNotEmpty;
+ if (!restrictToCurrentBalances) {
+ appendEvmDefaultTokens(currencies);
+ }
+ if (widget.exchangeViewModel.wallet.type == WalletType.bitcoin) {
+ currencies.sort((a, b) {
+ if (a == CryptoCurrency.btcln) {
+ return -1;
+ }
+ if (b == CryptoCurrency.btcln) {
+ return 1;
+ }
+ return 0;
+ });
+ }
+
+ List<CryptoCurrency> items = currencies;
+ if (restrictToCurrentBalances) {
+ final allowed = {
+ for (final asset in widget.balanceByAsset!.keys) asset.title.toUpperCase(),
+ };
+ items = currencies.where((c) => allowed.contains(c.title.toUpperCase())).toList();
+ }
+
+ if (widget.isReceiverCard && widget.filteredNetwork != null) {
+ final network = widget.filteredNetwork!;
+ items = items.where((c) => cryptoCurrencyOrTokenToWalletType(c) == network).toList();
+ }
+
+ if (items.length <= 1) {
+ return;
+ }
+
+ final selected = widget.isReceiverCard
+ ? widget.exchangeViewModel.receiveCurrency
+ : widget.exchangeViewModel.depositCurrency;
+
+ CurrencyPickerSheet.show(
+ context: context,
+ args: CurrencyPickerArgs(
+ items: items,
+ selected: selected,
+ filterByNetwork: widget.filteredNetwork,
+ balanceByAsset: widget.balanceByAsset,
+ useSingleNetworkLayout: widget.useSingleNetworkLayout,
+ recentsSource: RecentsSource.trades,
+ onSelected: widget.onCurrencySelected,
+ symbolResolver: widget.exchangeViewModel.amountParsingProxy.getCryptoSymbol,
+ ),
+ );
+ }
+
+ Future<void> _presentQRScanner(BuildContext context) async {
+ final isCameraPermissionGranted =
+ await PermissionHandler.checkPermission(Permission.camera, context);
+ if (!isCameraPermissionGranted) {
+ return;
+ }
+ final code = await presentQRScanner(context);
+ if (code == null) {
+ return;
+ }
+ if (code.isEmpty) {
+ return;
+ }
+
+ try {
+ final uri = Uri.parse(code);
+ widget.exchangeViewModel.receiveAddress = uri.path;
+ } catch (_) {}
+ }
+
+ void _presentWalletPicker() async {
+ final res = await showMaterialModalBottomSheet(
+ context: context,
+ backgroundColor: Colors.transparent,
+ builder: (context) => ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.of(context).size.height * 0.6,
+ ),
+ child: SwapAddressSelectionModal(
+ isSelectingReceiver: widget.isReceiverCard,
+ exchangeViewModel: widget.exchangeViewModel,
+ ),
+ ),
+ );
+ if (res != null && res is SwapAddressSelectionResult) {
+ if (widget.isReceiverCard) {
+ widget.exchangeViewModel.selectedAddressBookWallet = res.walletInfo;
+ widget.exchangeViewModel.receiveAddress = res.address!;
+ if (res.walletInfo?.name != null) {
+ if (res.accountName != null) {
+ widget.exchangeViewModel.receiveAddressDisplayName =
+ "${res.walletInfo!.name} → ${res.accountName}";
+ } else {
+ widget.exchangeViewModel.receiveAddressDisplayName = res.walletInfo!.name;
+ }
+ }
+ } else if (res.address == null || res.address!.isEmpty) {
+ widget.exchangeViewModel.isSendFromExternal = true;
+ askForRefundAddress();
+ } else {
+ widget.exchangeViewModel.isSendFromExternal = false;
+ switchToDepositWallet(res.walletInfo!.name);
+ }
+ }
+ }
+
+ void switchToDepositWallet(String walletName) async {
+ final walletType = cryptoCurrencyOrTokenToWalletType(widget.exchangeViewModel.depositCurrency);
+ if (walletType == null) {
+ return;
+ }
+ final wallet = await WalletInfo.get(walletName, walletType);
+ if (wallet == null) {
+ return;
+ }
+ widget.exchangeViewModel.depositAddress = wallet.address;
+ addressController.text = _normalizeAddressFormat(wallet.address);
+ widget.walletSwitcherViewModel.selectWallet(wallet);
+ await widget.walletSwitcherViewModel.switchToSelectedWallet();
+ }
+
+ void askForRefundAddress() async {
+ final refundAddress = await showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (context) => RefundAddressModal(
+ selectedCurrency: widget.exchangeViewModel.depositCurrency,
+ isFromWalletSelection: true,
+ ),
+ );
+ if (refundAddress != null && refundAddress is String) {
+ widget.exchangeViewModel.depositAddress = refundAddress;
+ } else {
+ widget.exchangeViewModel.depositAddress = "";
+ }
+ }
+
+ void updateFiatAmount() {
+ final newText = widget.isReceiverCard
+ ? widget.exchangeViewModel.receiveAmountFiat
+ : widget.exchangeViewModel.depositAmountFiat;
+
+ if (double.tryParse(fiatAmountController.text) != double.tryParse(newText)) {
+ if (newText == "0.00") {
+ fiatAmountController.text = "";
+ } else {
+ fiatAmountController.text =
+ newText.replaceAll(RegExp(r"(?<=\.\d*)0+$"), "").replaceAll(RegExp(r"\.$"), "");
+ }
+ }
+ }
+
+ String _middleTruncate(String s, int head, int tail) {
+ if (s.length <= head + tail + 3) {
+ return s;
+ }
+ return s.substring(0, head) + "..." + s.substring(s.length - tail);
+ }
+
+ String? _getCurrencyChainIconPath(CryptoCurrency curr) {
+ try {
+ if (curr.chainIconPath != null) {
+ return curr.chainIconPath!;
+ }
+
+ if (curr.tag != null) {
+ final currencyFromTag = CryptoCurrency.fromString(curr.tag!);
+
+ if (currencyFromTag.chainIconPath != null) {
+ return currencyFromTag.chainIconPath!;
+ }
+ }
+ } catch (_) {}
+ return null;
+ }
+}
diff --git a/lib/new-ui/widgets/swap_page/swap_from_send_args.dart b/lib/new-ui/widgets/swap_page/swap_from_send_args.dart
new file mode 100644
index 00000000..fc939ace
--- /dev/null
+++ b/lib/new-ui/widgets/swap_page/swap_from_send_args.dart
@@ -0,0 +1,20 @@
+import "package:cake_wallet/new-ui/widgets/currency_picker/currency_picker_args.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/wallet_type.dart";
+
+class SwapFromSendArgs {
+ const SwapFromSendArgs({
+ required this.recipientAddress,
+ required this.receiveCurrency,
+ required this.targetWalletType,
+ this.depositBalanceByAsset,
+ this.receiveAmount,
+ });
+
+ final String recipientAddress;
+ final CryptoCurrency receiveCurrency;
+ final WalletType targetWalletType;
+ final Map<CryptoCurrency, CurrencyPickerBalance>? depositBalanceByAsset;
+ final Money? receiveAmount;
+}
diff --git a/lib/new-ui/widgets/swap_page/swap_section_header.dart b/lib/new-ui/widgets/swap_page/swap_section_header.dart
new file mode 100644
index 00000000..507ff2d4
--- /dev/null
+++ b/lib/new-ui/widgets/swap_page/swap_section_header.dart
@@ -0,0 +1,49 @@
+import "package:cake_wallet/src/widgets/cake_image_widget.dart";
+import "package:cw_core/currency_for_wallet_type.dart";
+import "package:flutter/material.dart";
+
+class SwapSectionHeader extends StatelessWidget {
+ const SwapSectionHeader({
+ required this.label,
+ required this.networkName,
+ required this.networkIconPath,
+ });
+
+ final String label;
+ final String networkName;
+ final String networkIconPath;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final textTheme = Theme.of(context).textTheme;
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ children: [
+ Text(
+ label,
+ style:
+ textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500, letterSpacing: -0.07),
+ ),
+ const SizedBox(width: 8),
+ CakeImageWidget(
+ imageUrl: networkIconPath,
+ width: 16,
+ height: 16,
+ color: isMonochromeSymbolIcon(networkIconPath) ? colors.primary : null,
+ ),
+ const SizedBox(width: 4),
+ Text(
+ networkName,
+ style: textTheme.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w500,
+ letterSpacing: -0.07,
+ color: colors.primary,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/reactions/wallet_connect.dart b/lib/reactions/wallet_connect.dart
index fcfb06fe..61a6c11d 100644
--- a/lib/reactions/wallet_connect.dart
+++ b/lib/reactions/wallet_connect.dart
@@ -21,6 +21,17 @@ String walletConnectCompatibleChainsLabel() {
return '$head, and ${names.last}';
}
+String networkDisplayName(WalletType type, int? chainId) {
+ if (evm != null && isEVMCompatibleChain(type)) {
+ final id = chainId ?? evm!.getChainIdByWalletType(type);
+ final info = evm!.getChainInfoByChainId(id);
+ if (info != null) {
+ return info.name;
+ }
+ }
+ return walletTypeToString(type);
+}
+
bool isEVMCompatibleChain(WalletType walletType) {
switch (walletType) {
case WalletType.polygon:
diff --git a/lib/src/widgets/bottom_sheet/token_selection_bottom_sheet.dart b/lib/src/widgets/bottom_sheet/token_selection_bottom_sheet.dart
index c2604533..55aafd51 100644
--- a/lib/src/widgets/bottom_sheet/token_selection_bottom_sheet.dart
+++ b/lib/src/widgets/bottom_sheet/token_selection_bottom_sheet.dart
@@ -381,7 +381,7 @@ class _TokenSelectionContentState extends State<_TokenSelectionContent> {
detectedWalletType: WalletType.solana,
detectedCurrency: selectedToken!,
isValid: true,
- amount: widget.paymentRequest.amount,
+ amount: widget.paymentRequest.resolveTokenAmount(selectedToken!),
note: widget.paymentRequest.note,
scheme: widget.paymentRequest.scheme,
pjUri: widget.paymentRequest.pjUri,
@@ -398,7 +398,7 @@ class _TokenSelectionContentState extends State<_TokenSelectionContent> {
detectedWalletType: WalletType.tron,
detectedCurrency: selectedToken!,
isValid: true,
- amount: widget.paymentRequest.amount,
+ amount: widget.paymentRequest.resolveTokenAmount(selectedToken!),
note: widget.paymentRequest.note,
scheme: widget.paymentRequest.scheme,
pjUri: widget.paymentRequest.pjUri,
@@ -415,7 +415,7 @@ class _TokenSelectionContentState extends State<_TokenSelectionContent> {
detectedWalletType: selectedNetwork!,
detectedCurrency: selectedToken!,
isValid: true,
- amount: widget.paymentRequest.amount,
+ amount: widget.paymentRequest.resolveTokenAmount(selectedToken!),
note: widget.paymentRequest.note,
scheme: widget.paymentRequest.scheme,
pjUri: widget.paymentRequest.pjUri,
diff --git a/lib/src/widgets/new_list_row/list_item_regular_row_widget.dart b/lib/src/widgets/new_list_row/list_item_regular_row_widget.dart
index 21c24206..3e3fb826 100644
--- a/lib/src/widgets/new_list_row/list_item_regular_row_widget.dart
+++ b/lib/src/widgets/new_list_row/list_item_regular_row_widget.dart
@@ -89,16 +89,28 @@ class ListItemRegularRowWidget extends StatelessWidget {
children: [
leadingIcon!,
Positioned(
- right: -3,
- bottom: -3,
- child: CakeImageWidget(
- imageUrl: badgeIconPath!,
- width: badgeIconSize ?? 10,
- height: badgeIconSize ?? 10,
- errorWidget: leadingIconErrorWidget,
- colorFilter: iconColor == null
- ? null
- : ColorFilter.mode(iconColor!, BlendMode.srcIn),
+ right: -2,
+ bottom: -2,
+ child: Container(
+ width: 16,
+ height: 16,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(
+ color: theme.colorScheme.surfaceContainerHigh,
+ width: 2,
+ ),
+ color: theme.colorScheme.onSurface,
+ ),
+ padding: const EdgeInsets.all(2),
+ child: CakeImageWidget(
+ imageUrl: badgeIconPath!,
+ width: badgeIconSize ?? 12,
+ height: badgeIconSize ?? 12,
+ fit: BoxFit.cover,
+ color: theme.colorScheme.surface,
+ errorWidget: leadingIconErrorWidget,
+ ),
),
),
],
diff --git a/lib/utils/debounce.dart b/lib/utils/debounce.dart
index 86a92e5b..32abadc5 100644
--- a/lib/utils/debounce.dart
+++ b/lib/utils/debounce.dart
@@ -11,4 +11,9 @@ class Debounce {
_timer?.cancel();
_timer = Timer(duration, action);
}
+
+ void cancel() {
+ _timer?.cancel();
+ _timer = null;
+ }
}
diff --git a/lib/utils/payment_request.dart b/lib/utils/payment_request.dart
index 06eda7b0..d238f91a 100644
--- a/lib/utils/payment_request.dart
+++ b/lib/utils/payment_request.dart
@@ -1,25 +1,41 @@
-import 'package:cw_core/amount/amount_sanitizer.dart';
-import 'package:cw_core/amount/money.dart';
-import 'package:cw_core/crypto_currency.dart';
-import 'package:cw_core/lnurl.dart';
-import 'package:cw_core/payment_uris.dart';
-import 'package:cake_wallet/nano/nano.dart';
+import "package:cake_wallet/nano/nano.dart";
+import "package:cw_core/amount/amount_sanitizer.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/format_fixed.dart";
+import "package:cw_core/lnurl.dart";
+import "package:cw_core/payment_uris.dart";
+import "package:cw_core/utils/print_verbose.dart";
class PaymentRequest {
- PaymentRequest(this.address, this.amount, this.note, this.scheme, this.pjUri,
- {this.callbackUrl, this.callbackMessage, this.contractAddress});
+ PaymentRequest(
+ this.address,
+ this.amount,
+ this.note,
+ this.scheme,
+ this.pjUri, {
+ this.callbackUrl,
+ this.callbackMessage,
+ this.contractAddress,
+ this.chainId,
+ this.rawTokenAmount,
+ });
factory PaymentRequest.fromString(String input) {
try {
return PaymentRequest.fromBolt11(input);
} catch (_) {
- return PaymentRequest.fromUri(Uri.parse(input));
+ try {
+ return PaymentRequest.fromUri(Uri.parse(input));
+ } catch (_) {
+ return PaymentRequest(input, "", "", "", null);
+ }
}
}
factory PaymentRequest.fromBolt11(String invoice) {
final amount = getBolt11Amount(invoice) ?? Money.zero(CryptoCurrency.btcln);
- return PaymentRequest(invoice, amount.toString(), '', 'lightning', null);
+ return PaymentRequest(invoice, amount.toString(), "", "lightning", null);
}
factory PaymentRequest.fromUri(Uri? uri) {
@@ -32,13 +48,15 @@ class PaymentRequest {
String? callbackMessage;
String? pjUri;
String? contractAddress;
+ int? chainId;
+ String? rawTokenAmount;
if (uri != null) {
- if (uri.queryParameters['pj'] != null) {
+ if (uri.queryParameters["pj"] != null) {
pjUri = uri.toString();
}
- address = uri.queryParameters['address'] ?? uri.path;
+ address = uri.queryParameters["address"] ?? uri.path;
try {
final lnAmount = getBolt11Amount(uri.path) ?? Money.zero(CryptoCurrency.btcln);
@@ -47,27 +65,30 @@ class PaymentRequest {
}
} catch (_) {}
if (amount.isEmpty) {
- amount = uri.queryParameters['tx_amount'] ?? uri.queryParameters['amount'] ?? "";
+ amount = uri.queryParameters["tx_amount"] ?? uri.queryParameters["amount"] ?? "";
}
- note = uri.queryParameters['tx_description'] ?? uri.queryParameters['message'] ?? "";
+ note = uri.queryParameters["tx_description"] ?? uri.queryParameters["message"] ?? "";
scheme = uri.scheme;
- callbackUrl = uri.queryParameters['callback'];
- callbackMessage = uri.queryParameters['callbackMessage'];
- walletType = uri.queryParameters['type'];
+ callbackUrl = uri.queryParameters["callback"];
+ callbackMessage = uri.queryParameters["callbackMessage"];
+ walletType = uri.queryParameters["type"];
if (scheme == "ethereum") {
final paymentUri = ERC681URI.fromUri(uri);
+ final hasExplicitChainId = uri.path.contains("@");
address = paymentUri.address;
amount = paymentUri.amount;
contractAddress = paymentUri.contractAddress;
+ chainId = hasExplicitChainId ? paymentUri.chainId : null;
+ rawTokenAmount = paymentUri.rawTokenAmount;
} else if (scheme == "tron") {
- final token = uri.queryParameters['token'];
+ final token = uri.queryParameters["token"];
if (token != null && token.isNotEmpty) {
contractAddress = token;
}
} else if (scheme == "solana") {
- final splToken = uri.queryParameters['spl-token'];
+ final splToken = uri.queryParameters["spl-token"];
if (splToken != null && splToken.isNotEmpty) {
contractAddress = splToken;
}
@@ -99,6 +120,8 @@ class PaymentRequest {
callbackUrl: callbackUrl,
callbackMessage: callbackMessage,
contractAddress: contractAddress,
+ chainId: chainId,
+ rawTokenAmount: rawTokenAmount,
);
}
@@ -110,23 +133,53 @@ class PaymentRequest {
final String? callbackUrl;
final String? callbackMessage;
final String? contractAddress;
+ final int? chainId;
+ final String? rawTokenAmount;
+
+ String? resolveTokenAmount(CryptoCurrency token) {
+ if (amount.isNotEmpty) {
+ return amount;
+ }
+
+ if (rawTokenAmount == null || rawTokenAmount!.isEmpty) {
+ return null;
+ }
+
+ final raw = BigInt.tryParse(rawTokenAmount!);
+ if (raw == null) {
+ return null;
+ }
+
+ // 1e9 whole tokens is beyond any real payment, so a larger result means the QR
+ // came from an old app version that encoded with 18 decimals regardless of token.
+ if (token.decimals != 18 && raw > BigInt.from(10).pow(token.decimals + 9)) {
+ printV("resolveTokenAmount: reading $rawTokenAmount with legacy 18 decimals");
+ return formatFixed(raw, 18);
+ }
+
+ return formatFixed(raw, token.decimals);
+ }
/// Checks if the amount string is already in a usable format (e.g., "123.45") and doesn't need to be converted from raw format.
///
/// This was causing an error for us when we scan Nano QRs with amounts in them, the amounts are already in usable format so when the parsing was done, it returns 0 wrongly.
static bool _isAlreadyUsableAmount(String amount) {
- if (amount.isEmpty) return false;
+ if (amount.isEmpty) {
+ return false;
+ }
final parsed = double.tryParse(amount.sanitized());
- if (parsed == null) return false;
-
- // Check if the amount contains a decimal point and is a reasonable number,
- // it's likely already in usable format rather than raw format
- // Raw amounts are typically very large integers without decimal points
- if (amount.contains('.') && parsed > 0 && parsed < 1000000000) return true;
+ if (parsed == null) {
+ return false;
+ }
+ if (amount.contains(".") && parsed > 0 && parsed < 1000000000) {
+ return true;
+ }
// If it's a small integer (less than 1 billion), it's likely already usable
- if (parsed == parsed.toInt() && parsed < 1000000000) return true;
+ if (parsed == parsed.toInt() && parsed < 1000000000) {
+ return true;
+ }
return false;
}
diff --git a/lib/utils/token_utilities.dart b/lib/utils/token_utilities.dart
index 34dc393a..7fedd27a 100644
--- a/lib/utils/token_utilities.dart
+++ b/lib/utils/token_utilities.dart
@@ -222,6 +222,24 @@ class TokenUtilities {
return null;
}
+ static String? findSolanaTokenMint(CryptoCurrency currency) {
+ if (currency is SPLToken) return currency.mintAddress;
+
+ for (final token in loadDefaultSolTokensForSwap()) {
+ if (_matchesCurrency(token, currency)) return token.mintAddress;
+ }
+ return null;
+ }
+
+ static String? findTronTokenContract(CryptoCurrency currency) {
+ if (currency is TronToken) return currency.contractAddress;
+
+ for (final token in loadDefaultTronTokensForSwap()) {
+ if (_matchesCurrency(token, currency)) return token.contractAddress;
+ }
+ return null;
+ }
+
static bool isNativeToken(CryptoCurrency currency) {
final title = currency.title.toLowerCase();
final tag = currency.tag?.toLowerCase();
@@ -289,9 +307,7 @@ class TokenUtilities {
final allTokens = <CryptoCurrency>[baseCurrency];
final addedAddresses = <String>{};
- // Handle EVM networks
if (isEVMCompatibleChain(network)) {
- // First, collect all user tokens
final userTokens = await _getUserTokensForNetwork(baseCurrency);
for (final token in userTokens) {
if (token is Erc20Token) {
@@ -302,7 +318,17 @@ class TokenUtilities {
}
}
- // Then add tokens from CryptoCurrency.all that don't duplicate user tokens
+ if (evm != null) {
+ final chainId = evm!.getChainIdByWalletType(network);
+ for (final token in evm!.getDefaultTokensByChainId(chainId)) {
+ final address = token.contractAddress.toLowerCase();
+ if (addedAddresses.add(address)) {
+ allTokens.add(token);
+ }
+ }
+ }
+
+ // Add tokens from CryptoCurrency.all that don't duplicate user tokens
for (final currency in CryptoCurrency.all) {
// Match by tag for POL/BASE, match by title==tag for ETH
final matches = (baseCurrency.tag == null && baseCurrency.title == currency.tag) ||
@@ -320,10 +346,7 @@ class TokenUtilities {
}
}
}
- }
-
- // Handle Solana network
- else if (network == WalletType.solana) {
+ } else if (network == WalletType.solana) {
final userSolTokens = await loadAllUniqueSolTokens();
for (final token in userSolTokens) {
final mintAddress = token.mintAddress.toLowerCase();
@@ -332,6 +355,13 @@ class TokenUtilities {
}
}
+ for (final token in loadDefaultSolTokensForSwap()) {
+ final mintAddress = token.mintAddress.toLowerCase();
+ if (addedAddresses.add(mintAddress)) {
+ allTokens.add(token);
+ }
+ }
+
for (final currency in CryptoCurrency.all) {
if (currency.tag?.toLowerCase() == 'sol') {
if (currency is SPLToken) {
@@ -356,6 +386,13 @@ class TokenUtilities {
}
}
+ for (final token in loadDefaultTronTokensForSwap()) {
+ final contractAddress = token.contractAddress.toLowerCase();
+ if (addedAddresses.add(contractAddress)) {
+ allTokens.add(token);
+ }
+ }
+
for (final currency in CryptoCurrency.all) {
if (currency.tag?.toLowerCase() == 'trx') {
if (currency is TronToken) {
diff --git a/lib/view_model/exchange/exchange_trade_view_model.dart b/lib/view_model/exchange/exchange_trade_view_model.dart
index 5ca718eb..dfc0d566 100644
--- a/lib/view_model/exchange/exchange_trade_view_model.dart
+++ b/lib/view_model/exchange/exchange_trade_view_model.dart
@@ -448,9 +448,17 @@ abstraWhy this scored 34/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.