fix: Minor swap fixes (#3046)

* Integrate new design mockup with ViewModel (#2653) * feat: add Lightning Network support for Bitcoin wallets * refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase * feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model * feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling * feat: add method to retrieve unused Spark deposit address for Bitcoin wallets * feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows * chore: update Breez SDK dependency to version 0.3.4 in pubspec files * Add bitcoin secrets config [skip ci] * feat: extend Lightning wallet functionality with transaction history fetching * feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration * refactor: simplify `ReceivePageOption` logic * refactor: centralize `PaymentURI` generation logic across wallet types * feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality * refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types * refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart` * refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support * feat: reload balance and tx history after sending a lightning transaction * feat: improve address formatting for human-readable addresses and update the default LNURL domain * fix: merge conflicts * feat: add error handling for LightningWallet initialization and adjust transaction direction logic * integrate homepage from new ui mockup * fix import * feat: add Lightning Network support for Bitcoin wallets * refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase * feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model * feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling * feat: add method to retrieve unused Spark deposit address for Bitcoin wallets * feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows * chore: update Breez SDK dependency to version 0.3.4 in pubspec files * Add bitcoin secrets config [skip ci] * feat: extend Lightning wallet functionality with transaction history fetching * feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration * refactor: simplify `ReceivePageOption` logic * refactor: centralize `PaymentURI` generation logic across wallet types * feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality * refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types * refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart` * refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support * feat: reload balance and tx history after sending a lightning transaction * feat: improve address formatting for human-readable addresses and update the default LNURL domain * fix: merge conflicts * feat: add error handling for LightningWallet initialization and adjust transaction direction logic * integrate homepage from new ui mockup * fix import * add new-ui dir to pubspec_base * minor layout fixes * cleanup navbar logic * Modify navbar behaviour * smooth color change when selecting navbar options * open old ui pages with new ui action buttons * feat: working navbar in new ui * fix: minor sizing tweaks * CW-1266-integrate-bitcoin-lightning-through-spark-sdk (#2623) * feat: add Lightning Network support for Bitcoin wallets * refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase * feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model * feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling * feat: add method to retrieve unused Spark deposit address for Bitcoin wallets * feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows * chore: update Breez SDK dependency to version 0.3.4 in pubspec files * Add bitcoin secrets config [skip ci] * feat: extend Lightning wallet functionality with transaction history fetching * feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration * refactor: simplify `ReceivePageOption` logic * refactor: centralize `PaymentURI` generation logic across wallet types * feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality * refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types * refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart` * refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support * feat: reload balance and tx history after sending a lightning transaction * feat: improve address formatting for human-readable addresses and update the default LNURL domain * fix: merge conflicts * feat: add error handling for LightningWallet initialization and adjust transaction direction logic * feat: enable private transactions by default in LightningWallet and update Breez SDK version to 0.4.2 * minor fixes [skip ci] * chore: fix some minor issues in comments (#2654) Signed-off-by: black5box <black5box@outlook.com> * fix: handle send-all functionality for LightningWallet transactions and adjust amount calculation logic * fix-german (#2659) * chore: update German localization strings for consistency and accuracy * chore: update German localization strings for consistency and accuracy [skip-ci] * feat: add LNURL support for address validation and LightningWallet compatibility, enhance error handling for OpenCryptoPay * fix: adjust LightningWallet amount parsing from 9 to 8 decimal places * feat: add LNURL support in LightningPaymentRequest and LightningWallet * Fix navigation gradient (#2657) * Fix navigation gradient * Fix CONFIG_ARGS formatting in app_config.sh (#2660) * fix: block wrongly parsed addresses (#2656) * fix: block wrongly parsed addresses * fix: move parsed address check into handlePaymentFlow method * fix: Handle QR URLs separately for pay anything flow * feat: add electrum seed support for Lightning * refactor: improve `parseFixed` logic and add comprehensive unit tests for edge cases (#2661) * Update cw_bitcoin/lib/bitcoin_wallet.dart [skip ci] * resolve conflict issue --------- Signed-off-by: black5box <black5box@outlook.com> Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> Co-authored-by: black5box <black5box@outlook.com> Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: cyan <cyjan@mrcyjanek.net> Co-authored-by: David Adegoke <64401859+Blazebrain@users.noreply.github.com> * remove old code [skip ci] * fix: page widgets rebuilt every time * chore: formatting * remove unused navbar * fix: lightning balance on balance card in lightning mode * fix: return if uri == null * feat: trade history in new ui * feat: enhance balance model with secondary asset handling * feat: unique card colors and icons for coins * wip: card customization * fix: merge conflict * feat: customizable balance card * Fix some spacings and test sizing * Fix formatting * feat: add Lightning Network support for send flow and fee handling adjustments * refactor: remove unnecessary debug print statement in send flow for Lightning Network balance * feat: integrate OpenCryptoPay QR handling in send flow and improve scan action handling logic * feat: add maxDepositClaimFee parameter for Lightning wallet configuration * Switch balance card to RoundedSuperellipse and set color list to Wrap * Fix * Switch to scroll view * refactor: update navigation route from `receive` to `addressPage` in coin action row * feat: bloc-based viewmodel for card customizer * feat: mobx-independent balance card customizer vm * minor fixes * copyWith constructor for cleaner state changes * refactor: wrap `HistorySection` with `Observer` for reactive state updates, update navigation for "Buy" action, and fix incorrect balance property * feat: enhance Bitcoin receive flow with Lightning and SegWit options, update address page registration, and localize coin action labels * feat: add helper methods for Lightning and SegWit receive page options in Bitcoin configuration * feat: add Lightning transaction type handling and enable navigation to transaction details from history * Add more special card types * feat: new ui settings page * feat: add Lightning actions to balance cards, refactor card rendering logic * refactor: update settings page localization, hide unused settings items * feat: add secrets generation for cw_bitcoin, including breezApiKey * Lightning switcher animation (#2725) * Properly animate bitcoin/lightning switcher * Cleanup and fix sizing * Final cleanup * Fix action button colors (#2732) * feat: add hardware wallet type handling and improve parsed address reset flow * Refactor settings page to use generic row items (#2745) * fix android back button in settings on android, force iphone-style transitions on all platforms * move settings page to generic row impl * fix imports * Balance card fixes (#2729) * Update balance card sizing * Fix spacing * Initial font changes (#2731) * Initial font changes * More font changes * feat: integrate Lightning transaction support and improve transaction history UX - Enhanced dashboard to compute confirmations using the first and last transactions. - Updated `BitcoinWallet` to subscribe for and manage Lightning transactions. - Improved `HistoryTile` layout and introduced new leading icons for Lightning transactions. * feat: add unclaimed deposit actions and enhance Lightning event handling * release changes [skip ci] * Enhanced card customizer (#2744) * enhanced card customizer * Fix conflicts * Add missing icons + adjust spacing --------- Co-authored-by: tuxsudo <tuxsudo@tux.pizza> * feat: enhance Lightning invoice handling and address validation - Added support for identifying non-zero amount Lightning invoices. - Refined invoice matching with updated regex patterns. - Improved UI to conditionally display addresses in sending confirmations. - Adjusted logic to handle zero-value Lightning invoices. * feat: add `isPayjoinAvailable` computed property and update Payjoin visibility logic * feat: improve Lightning wallet handling and block explorer logic * update patch version [skip ci] --------- Signed-off-by: black5box <black5box@outlook.com> Co-authored-by: Konstantin Ullrich <konstantinullrich12@gmail.com> Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: black5box <black5box@outlook.com> Co-authored-by: cyan <cyjan@mrcyjanek.net> Co-authored-by: David Adegoke <64401859+Blazebrain@users.noreply.github.com> * minor new ui fixes * padding for new row separators * remove debug prints * New design improve nav bar (#2763) * tweak navigation bar touch targets and sizing * feat: add tests for identifying zero and non-zero amount Lightning invoices (#2772) * feat: add tests for identifying zero and non-zero amount Lightning invoices - Added unit tests to validate recognition of Bolt11 zero-amount and non-zero-amount invoices. - Enhanced `isBolt11ZeroInvoice` function to handle `lightning:` prefixed invoices. * fix: correct currency selection logic for Lightning wallets in Send ViewModel * feat: improve Lightning wallet initialization and address generation - Updated `init` method in `LightningWallet` to return a boolean for initialization success, adding error handling for failed setups. - Integrated dynamic name generation using `generateName` for Lightning wallet addresses. * refactor: relocate `generate_name` to `cw_core` and update imports * chore: update breez sdk (#2789) * Wire tokens and NFTs to new Home page (#2804) * wiring for assets on home page * fix imports * wire nft page in new ui * fix nft display in new ui * fix totalWidth calc * add tokens button + bugfixes * add tokens button + bugfixes * fix late initialization * fix history section exception * fixes * Add haptic feedback (#2813) * Add haptic feedback * Add haptic feedback to correct ActionButton * Return bottom gradient (#2808) * Add IgnorePointer to bottom nav gradient (#2822) * New design send page (#2791) * new ui send page (wip) * coin control page improvements * fee settings, new send confirmation modal * minor aesthetic fixes * load network name without cw_bitcoin import * recipient dot cleanup * minor logic fixes * ui polish * - add aliaspay support - fix wording for max button - fix back button action in modals * Sizing changes * dismiss transaction on modal close * sizing fix * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix button sizing - add description for fees page * Update lib/view_model/unspent_coins/unspent_coins_list_view_model.dart [skip ci] * Update lib/view_model/send/send_view_model.dart [skip ci] --------- Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * Fix conflicts with dev * Fix conflicts with dev * Add zcash receive options to new design flow * wire in missing settings in new ui * up migration version * formatting * translations * lint.sh * New design receive page (#2834) * feat: viewmodel on new receive page (wip) * feat: address type selector for new ui receive page * fix: minor fixes to touch targets and tap anims * minor ui fix * wip receive page changes * receive page + address selection page * receive page + address selection page * add font * add svg * minor ui fixes * receive page fixes/improvements * change receive page modal design * further ui polish * icons for infobox * fix restricted import * fix closing label modal * - fix balance card appearance on address page - fix search bar position - fix mweb position in address type selector * receive page fixes * fix anonpay * remove restricted import * fixes * fix receive on zec * simplify chain id * lint fix * fix migration numbering Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fix migration version Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fix settings * readability * fix formatting * move dismiss infobox to vm * disable addr rotation on zcash * remove _setEffects * translations --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * New UI Sync bar (#2831) * syncbar * small styling fixes * modify duration * lint.sh * syncHeavy wallet types Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * update translations, add pull-down refresh, separate top bar components to files --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * alphabetize * New design balance card icons (#2824) * Add the other crypto card icons * Update Zano, add Zcash and Arbitrum * Update default card style and available gradients * Fix broken preview * Fix animation * Color combinations fix * Minor updates * Add decred icon * if(!mounted) return; * New design minor fixes (#2842) * More minor fixes * Update modal sheet behaviour * Update missing currency image links * List row and navigation bar tweaks * Minor navbar fix * New UI Swap page (#2829) * new ui send page (wip) * coin control page improvements * fee settings, new send confirmation modal * minor aesthetic fixes * load network name without cw_bitcoin import * recipient dot cleanup * minor logic fixes * ui polish * - add aliaspay support - fix wording for max button - fix back button action in modals * Sizing changes * dismiss transaction on modal close * sizing fix * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix button sizing - add description for fees page * swap page * fixes * further fixes * merge * png -> svg * minor condition changes * lint.sh * fix swapsxyz isCentralized Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * translations, readability improvements, remove debug rows * cleanup * alphabetize strings * small bugfixes --------- Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fix new ui coin control page layout (#2843) * New design lightning flows (#2821) * new ui send page (wip) * coin control page improvements * fee settings, new send confirmation modal * minor aesthetic fixes * load network name without cw_bitcoin import * recipient dot cleanup * minor logic fixes * ui polish * - add aliaspay support - fix wording for max button - fix back button action in modals * Sizing changes * dismiss transaction on modal close * sizing fix * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix remove recipient icon - properly round amounts - fix coin control page spacing * - fix button sizing - add description for fees page * lightning flow wip * lightning flow wip #2 * lightning withdraw flow * lightning deposit flow (wip, currently works but really janky) * send from external + bugfixes * merge fixes * merge fixes * fixes * Update lib/new-ui/widgets/send_page/l2_action_wallet_selector.dart --------- Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fix covered create wallet button * fix: close modal after transaction commitment in Send ViewModel (#2858) * New design tweaks (#2847) * Add more haptic feedback * Fix background gradients and modify SafeArea in home_page.dart * Fix history padding, fix divider color, disable Charts, update base_page.dart appbar style, fix nav bar border + height on iOS * Lightning Username setup flow for new UI (#2845) * lightning username edit/create flow * fix button color * fix layout * fixes * remove character limitation for internal builds * remove dependency on cw_bitcoin * fix username requirements * fixes * condition fix * Update lib/new-ui/pages/lightning_username_page.dart --------- Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> * keyboard hide overlay for iphone * New design UI tweaks (#2870) * Fix nav height on Android * Fix blue gradient * Update transactions view and minor UI tweaks * CW1011-Allow-users-to-view-bitcoin-amounts-in-sats (#2678) * feat: introduce `formatFixed` integration and sats display preference * feat: enable display of Bitcoin amounts in satoshis and refactor amount formatting logic * refactor: consolidate fee formatting logic and add support for MWEB availability check * feat: add support for satoshi-based amount display and enhance fiat conversion logic * feat: add support for satoshi-based amount parsing, formatting, and display preferences across buy/sell flow and UI adjustments * feat: implement `AmountParsingProxy` with unit tests for parsing and formatting crypto amounts in various display modes * feat: replace `preferBalanceInSats` with `displayAmountsInSatoshi` and introduce `AmountParsingProxy` for unified crypto amount handling across the app * refactor: streamline amount formatting logic and enhance unspent coins handling with `AmountParsingProxy` integration for unified crypto processing * refactor: replace direct bitcoin amount formatting with `AmountParsingProxy` and remove debug print in `exchange_view_model` * refactor: replace `getIt<AmountParsingProxy>` with `_appStore.amountParsingProxy`, remove redundant dependencies across view models and adjust related imports * refactor: remove redundant `AmountParsingProxy` registration in DI setup to simplify dependency management [skip ci] * feat: add getCryptoSymbol to simplify the Symbol selection between Sats and Bitcoin * fix: merge conflict * Revert "fix: merge conflict" This reverts commit 6debdaa0466747d6fcc85d6bd0be115e6fb4d856. * fix import [skip ci] * feat: remove number formatter from exchangeVM * refactor: replace `SettingsStore` with `AppStore` across view models, integrate `AmountParsingProxy` for amount formatting, and clean up redundant imports * refactor: remove debug print statements from `getCryptoOutputAmount` in `AmountParsingProxy` * feat: enhance fee and deposit amount formatting with crypto symbols and improved parsing * feat: integrate `AmountParsingProxy` for improved Bitcoin amount parsing in `PaymentURI` and fiat-to-crypto conversion * feat: append crypto symbols to Bitcoin transaction amounts in dashboard view * feat: improve crypto amount parsing in SendCard widget and Output view model using `AmountParsingProxy` * feat: conditionally show Bitcoin amount display setting for Bitcoin wallets and refactor `DisplaySettingsViewModel` to use `AppStore` * refactor: clean up redundant imports in `bitcoin_wallet.dart` and `electrum_wallet.dart` * feat: append crypto symbols to fee values in send and cake pay card widgets for improved clarity * refactor: replace `currencyTitle` with `currency` across widgets and integrate `AmountParsingProxy` for improved crypto amount formatting and parsing * refactor: improve validation logic and amount parsing in SendCard and Output widgets * refactor: standardize amount parsing and formatting logic with `AmountParsingProxy` across ViewModels and widgets * refactor: `AppStore` remove debug prints * refactor: rename amount parsing/formatting methods for better clarity in tests [skip ci] * fix: AmountParsingProxy and optimize `cryptoAmount` handling in BuySellViewModel * fix: adjust balance calculation for Monero and Wownero to exclude unlocked amount from full balance * fix: correct `_appStore` usage and format adjustments in `SendViewModel` * feat: enhance satoshi on new-ui * feat: add computed property for `amountParsingProxy` in AppStore * feat: localize Bitcoin amount display option and update asset history UI * feat: improve exchange amount processing and refactor fiat conversion values --------- Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> * New design unconfirmed balance widget (#2861) * unconfirmed balance display widget for new ui * unconfirmed balance display widget for new ui * merge * alphabetize translations * New UI fixes (#2860) * fix asset top bar * improve wordmark in large qr mode on receive * receive option fixes * exchange -> swap * send page fixes * update pubspec base * go to home on wallet change * nicer card customizer * don't show account name for single-account wallets * special card design for lightning * fiat amount bar improvement * update translations * add sending indicator * fix non-number input to receive amount * de-jank fiat input * nicer balance card animation when switching btc-ln * nicer balance card animation when switching btc-ln * fix backup password input * display time+date in history * fix error on buy * fix incorrect wallet showing in wallets tab * fix wallet list layout * only show coin control option on hasCoinControl * better error on send page * fiat value in coin control * add zano to isSyncHeeavy * fix keys in settings * fix assets condition * fix import * remove BasePage dependency in RescanPage * add missing settings * show send/receive in swap confirm sheet * fix receive background on ios * fix assets spacing * fix trade tile sizing * fix padding * fix icon in wallet select modal * change text on swap initial modal * spacing * l2 send external modal styling * fix null on swap confirm sheet * change infobox text * add chain icon to asset widgets * add chain icon to asset widgets * disable swap page reset * fix wallet list page layout * revert merge conflict issue [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * Account Customizer for new UI Monero (#2859) * new ui monero account management (wip) * account reordering wip * account reordering wip * account reordering (works) * cards view compact mode * format * translation * name generation * fix for non-xmr wallets * } * allow reset order, fallback on improperly saved order * translation * fix for pre-reorder wallet loading * fix loading * - save cards on modal slide-down - always load active account as first * fix card customizer close anim * fixes * fix condition * merge * fix migration versions * use updated flutter rust bridge in lightning and payjoin * mvp fixes * new ui mweb mask/unmask * fallback for balance card amount format * New UI tweaks (#2872) * Update lightning transaction history view * Add BNB card design * Color, padding, and radius fixes * Fix wallet list bottom section & gradient * Update Apps page * reformat * nicer sat picker * fix keyboard * chain badges * enhance styling for card customizer * mweb settings icon * mweb chain badge * update wording in settings * bnb chain icon * always round send amount * always round all amount * token placeholder * Fix ModernButton colors (#2888) * Fix ModernButton colors * Minor * guard for unconfirmed balance widget * fix error on wallet switch * New design mvp fixes (#2890) * mvp fixes * fallback for balance card amount format * reformat * nicer sat picker * fix keyboard * chain badges * enhance styling for card customizer * bnb chain icon * always round send amount * always round all amount * guard for unconfirmed balance widget * fix error on wallet switch * Update lib/new-ui/pages/account_customizer.dart Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fixes --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * Install Protoc in reusable build workflow Added step to install Protoc before building. * Fix protobuf-compiler installation step Update package list before installing protobuf-compiler. * Modify Protoc installation command to handle update errors Change the install command for Protoc to avoid failure on update. * Streamline Lightning wallet balance management and crypto handling (#2893) * refactor: streamline crypto amount handling and improve Lightning balance management - Removed redundancy in balance calculations for Lightning wallets. - Centralized crypto symbol creation with `selectedCryptoCurrencySymbol`. - Enhanced crypto amount handling and formatting with `AmountParsingProxy`. - Simplified logic for displaying Lightning balances across UI components. * refactor: remove sats display logic and unused formatting from BalanceCard widget * chore: update breez-sdk-spark-flutter to latest commit * feat: enhance crypto amount formatting with localized separators and max decimals * fixes * fix: handle null balance records in Lightning wallet cards * New design add validators (#2894) * add validation, fix node form * Add validator to send amount input field Added a validator to the amount input field. --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * Disable 'addresses' button on receive screen for BTC LN (#2896) * feat: Disable addresses button on receive screen for BTC LN * chore: remove debug print in uri computation * feat: introduce swap action toggle and UI updates * feat: conditionally display Zcash card setting for Zcash wallets in Display Settings * Fix leading button color (#2898) * fix amount format * fix loadCards * pre-beta fixes * cyjan: fix: order being null for certain index * pre-beta fixes v2 (#2905) * minor context check [skip ci] * persist fee priority for zcash (#2907) * Add support for Zcash address detection and amount logic refactor (#2906) * refactor: consolidate crypto amount handling with `displayAmount` and `cryptoCurrencySymbol`, improve fiat conversion logic, and optimize token currency management * refactor: simplify `displayAmount` logic and remove unused `_rawAmount` property * feat: add support for Zcash transparent address detection and simplify amount conversion logic * Improve Lightning invoice handling and crypto formatting (#2908) * fix: update Lightning address regex to support additional formats and prefixes * fix: conditionally render advanced settings dropdown based on fees or coin control availability * feat: enhance address detection, Lightning invoice handling, and crypto formatting * feat: improve Lightning invoice parsing and crypto amount formatting on send page * chore: remove unnecessary exception printing in `getBolt11Amount` function * Fix lightning swap * import fix (hide Mac;) * parse -> tryParse * Transaction Commited -> Transaction Sent! * feat: enable clipboard paste for deposit and receive addresses in swap page (#2909) * fix: resolving LNURLS (#2911) * new UI pre-beta fixes (#2910) * fixes * parse -> tryParse * change sat display settings style * minor fix until hive is removed [skip ci] * Remove redundant logic and improve send page features (#2913) * fix: update crypto amount parsing logic in send confirmation sheet * feat: Added checkbox to toggle Litecoin MWEB coins on the send page. fix: LNUrlPayRecord * fix: remove redundant `.withLocalSeperator()` from fiat balance formatting logic * fix: update Bitcoin amount display titles to align with consistent formatting standards * force boolean to update (#2916) * force boolean to update * fix bnb balance * fixes #4 (#2917) * only display sats for btc wallets in card customizer * fix: resolve async handling of Lightning transaction history in `fetchTransactions` method (#2919) * New design pre beta fixes 5 (#2918) * improve l2 deposit/withdraw flow layouts * add copied indicator * SafeArea * fix addr rotation * fix styling of lightning switcher * no raster graphics in new ui please * optimization for assets/history section * remove unused bloc provider * optimize dashboard + fix duplicated name * disable lightning mode on wallet change * remove broken animation * safearea around nodes page * fix rescan page layout * fix exception on really fast switching * remove broken blur * card customizer autosave * remove debug print * add better fallbacks for currency titles * revert due to broken animation * fix send page crash * fix chain title for arb * fix cupertino date picker * Update lib/new-ui/widgets/receive_page/receive_bottom_buttons.dart [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * feat: add focus management and external address validation to send page forms - Introduced `focusNode` to `NewSendAddressInput` for better input handling. - Enhanced address validation by synchronizing with parsed external addresses. - Updated logic for non-MWEB unspent coin type in send actions. - Suppressed unnecessary exception logs in Bitcoin wallet transactions. * New design swap page fixes (#2923) * swap page fixes * add scroll controller * comment * tweak refresh pulldown (#2924) * add copy button to l2 send external modal (#2925) * account customizer padding * feat: lightning transaction fetching and Lightning wallet integration (#2927) - Allow nullable `height` in `ElectrumTransactionInfo`. - Add `fromDate` support for filtered Lightning transaction history retrieval. - Simplify Lightning address handling logic in wallet addresses. - Optimize Lightning wallet transaction syncing based on the last Lightning transaction date. - Clean up imports in `electrum_transaction_history.dart`. * New balance handeling (#2931) * feat: lightning transaction fetching and Lightning wallet integration - Allow nullable `height` in `ElectrumTransactionInfo`. - Add `fromDate` support for filtered Lightning transaction history retrieval. - Simplify Lightning address handling logic in wallet addresses. - Optimize Lightning wallet transaction syncing based on the last Lightning transaction date. - Clean up imports in `electrum_transaction_history.dart`. * feat: add support for Lightning balance in wallet snapshot and initialization * Disable Lightning switcher for hardware wallets (#2932) * fix: disable Lightning switcher for hardware wallets * fix: update wallet type check to use `isSoftwareWallet` for Lightning support * New design pre beta fixes 6 (#2929) * fix swaps from ln * prevent crash if ln balance isn't loaded yet * fix currency icons disappearing on swap confirm sheet * fix swap fiat validation * display ln at top on swap currency selector in btc wallets * update icon for card options * display default fiat and crypto at top of currency picker * fix fiat amount bar formatting * add modal scroll controller to provider logs * revert premature optimization (sizing issue) * New design pre beta fixes 7 (#2935) * fix swaps from ln * prevent crash if ln balance isn't loaded yet * fix currency icons disappearing on swap confirm sheet * fix swap fiat validation * display ln at top on swap currency selector in btc wallets * update icon for card options * display default fiat and crypto at top of currency picker * fix fiat amount bar formatting * add modal scroll controller to provider logs * revert premature optimization (sizing issue) * copyable trade id * disable swaptrade on ln * set isFixedRate properly * update color * display trocador provider on swap confirmation sheet * add "exchange rate is fixed" text --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * updated l2 modal (#2934) * display names for send addr input (#2936) * fix: MWEB toggle logic on send page (#2938) * feat: add retry logic to `getAddress` in Lightning wallet (#2939) * Enhance crypto address handling and add Lightning invoice support (#2937) * feat: enhance crypto address handling and add Lightning invoice support - Added `_overrideFromCryptoCurrency` and `_overrideToCryptoCurrency` for Zcash unified and shielded addresses. - Improved Lightning invoice generation with `getLightningInvoice` for Bitcoin wallets. - Updated error handling in exchange provider to accommodate API changes. - Introduced Lightning invoice fallback for deposit and receive addresses in ExchangeViewModel. * feat: Added `_overrideFromCryptoCurrency` and `_overrideToCryptoCurrency` for Zcash unified and shielded addresses. * fix pay anything on paste button (#2940) * Prevent multiple paste triggering any pay flow * fixup fiat input (#2941) * New design small fixes (#2920) * Fix optical symmetry for swipe to send text * Update nav bar icons * Top bar and card tweaks * Update paddings --------- Co-authored-by: malik1004x <malikowskirobert@gmail.com> * fix erc20 balance display (#2944) * fix erc20 balance display * route through cw_evm * New design beta fixes (#2943) * fix asset tile layout * fix card customizer keyboard jumping * fix cardsview exception * fix swap modal height * remove syncbar percentage * add copy icon to trade id * fix trade confirmation appearing twice * remove useless mweb setting * add tag to contact currency selector text * prettify picker for ln * fix receive crash * always route to NewSendPage * handle ln amount on paste * handle ln amount on payment request creation * prettify ln errors * readd "blocks" word * register deeplinks * Enhance bitcoin error message [skip ci] * fix support chat page (#2946) * new-design-fix-confirm-sheet-parsing-error (#2950) * feat: use bigint instead of doubles * feat: use bigint instead of doubles * feat: use bigint instead of doubles * fix: also show sats in confirm sheet * fix: also show sats in confirm sheet * feat: localize amounts and cap amount in tx history (#2951) * fix: linux CI * feat: localize token balances (#2954) * fix: send amount hww (#2955) * chore: use latest breez sdk (#2953) * fix addAddressWord * fixes (#2957) * receive fixes (#2959) * fix: stabilize android build by increasing jvm heap size (#2958) * fix: lighting by having the new SDK Save into a new location (#2961) * New design rc fixes (#2960) * additional safeguards for isSyncHeavy check * fix account name getting reset * update base icon * fix units in swap * readd memos to zec * New design minor UI (#2956) * Wrap text for list item widgets * Update lightning address and QR icons * Update near intents icon * Fix share issue * Fix (#2963) * fix tx amount formatting * rename currency * change wording for zec memo * fix base icon * fix app icon script [skip ci] * New design rc fixes 2 (#2965) * fix account name changes * fix spacing on addresses page * add payjoin copy modal * improve memo ui * potential fix for ci * Set default address for zcash and bitcoin for buy flow (#2979) * new monero.com icons (#2980) * parse and validate deposit amount from api (#2967) * generic fixes * minor context fix [skip ci] * Generic fixes (#2982) - solana send all bug - pasting SOL address triggering payanything flow - add more address types for payanything detection * rescan fix * about page (#2974) Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * update settings icons/wording (#2973) * Changelog modal (New UI) (#2971) * add new changelog modal * typo * print -> printV * Update lib/new-ui/widgets/changelog_modal.dart [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * fix node form (#2970) * new-design-add-breez-logging (#2984) * feat: add Lightning log export functionality for Bitcoin wallets * feat: add multilingual support for Lightning log export strings * feat: add Lightning support toggle in settings and translations for multiple languages * refactor: simplify `setUseLightning` by removing redundant store update * Update cw_bitcoin/lib/electrum_wallet.dart [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * minor fixes [skip ci] * minor context fixe [skip ci] * fix: make walletinfoid unique to prevent duplicates (#2969) * fix: walletconnect not working in new design builds (#2993) * new-design-fix-mweb-coin-enabling (#2995) * feat: add unspent coin type handling to asset details modal send button * fix: improve German translations for wallet, seed, and Lightning-related strings * fix: update Dutch translations to correct terminology and formatting #2992 (#2997) * fix: drop gn (#3000) * vulnerable seeds popup on new ui (#3004) * update mac os monero.com icons (#3003) * Add Payjoin log export and improve logging behavior (#2999) * fix: suppress exception logging in `getAddress` method of Lightning wallet - Added a try-catch block to avoid unnecessary exception logs during Lightning address retries. * fix: update fallback message for missing Lightning address detection * feat: add Payjoin log export and logging enhancements * fix: localize "Export Payjoin Logs" string in settings page * fix: litecoin mweb balance being included in the second asset (#2998) * Minor fixes (#2994) * Minor fixes * Update lib/new-ui/new_dashboard.dart [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * New design post release fixes (#3002) * fix: only throw on deserialize if kDebugMode is true (#2976) This closes #2972, in debug mode we will still catch these issues but if somehow that happens on production it will fallback to safe default * fix: update docs and dockerfile (#2975) * fix: missing steps for linux build [skip ci] (#2985) * move balance to bigint * move balance to bigint * fix electrum issue * fix unconfirmed balance * fixes * Fix minor issue in Spanish translation (#2991) * Fix minor issue in French translation (#2987) * Fix minor issues in German translation (#2986) * update constructor calls in configure.dart * fixes * remove expnded * V6.0.1 Early Release Candidate --------- Co-authored-by: cyan <cyjan@mrcyjanek.net> Co-authored-by: Edwin den Boer <woordenboer@planet.nl> Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> * Swaps xyz swap enhancements (#2615) * refactor token cache and limit handling * Improve SwapsXYZ external send logic * Improve SwapsXYZ fixed-rate handling * disable fixedRate for SwapsXyz * SwapsXYZ contract call * Add track url for swaps xyz * add arbitrum support * add check for unsupported source tokens * enable SwapsXyzExchangeProvider in provider list * refactor SwapsXYZ provider and trade flow handling * Update exchange_trade_view_model.dart * validate evm call-data * Revert "validate evm call-data" * fix msg value for ERC-20 transfers * fix flag for swapsXYZ send check * Update send_view_model.dart * handle Swaps.xyz method selectors & approvals * fix evm approvals * Improve EVM token approval & receipt handling * merge split token transfers in evm tx * fix token allowance check for approvals * add sourceToken validation to EVM tx creation * prioritizing incoming transactions over fetched outgoing ones * compute net flow when merging transactions * add truncateTrailingText to list items and widgets --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> Co-authored-by: Serhii-Borodenko <17529954+Serhii-Borodenko@users.noreply.github.com> * fix wownero balance (#3007) * fix keyboard (#3006) * fix android build * check if stream is closed [skip ci] * [skip ci] lint * fix: populate amount field (#3009) * fix address rotation exception (#3011) * copy uri with amount from recieve page (#3010) * add "transaction sent!" to swap confirmation sheet (#3012) * fix wallet change on token swaps (#3013) * Fix fee estimation and recipient logic in Lightning Network (#3014) * fix: update `hasMultiRecipient` logic to include non-Lightning coin type check * fix: Lightning Network fee estimation and parsing logic * fix: adjust `sumByBigInt` logic to handle `sendAll` flag in send page * fix: move sqlite migrations to sqlite.dart (#3008) * fix: move sqlite migrations to sqlite.dart fix: backup restore not initializing SQL properly * Update cw_core/lib/db/sqlite.dart --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * feat: update currency symbol handling and extend Electrum transaction details (#3016) * Use isCentralized for truncation trade id [skip ci] * fix: Incorrect token amount for tokens and filter out new spam transactions after swaps (#3015) * New design release swap fixes (#3018) * fix deserialize ln * fix get wallet type for bnb tokens * show extraId for swaps * chore: translate using gpt-5.2 (#3021) * add NEAR send-all validation * tiny ui fixes (#3023) * use double parsing for amount comparison[skip ci] * adjust lightning address error message * feat: add BTC LN support to available methods and payment data handling * feat: add cached Lightning address handling for improved performance (#3025) - Introduced `cachedAddress` field to store and reuse the last fetched Lightning address. - Updated `getLightningAddress` method to fallback on `cachedAddress` if no new address is fetched. - Extended wallet constructors and snapshots to include `cachedLightningAddress` for persistence. * Revert transaction history color * Minor * Apply suggestion from @malik1004x * new-design-post-release-fixes-3 (#3028) * fix unnecessary account switching * fix exception on bad payment amount * fallback for currencies on external swap modal * increase balance card touch target * don't use lightning addresses for exchange * increase max length for ln encoding * don't show infobox on ln receive * fix showing old tx details (null tx on createTransaction) * remove unused import * refactor: relocate `_logStream` declaration in `LightningWallet` for better code organization (#3029) * monero build fix update build numbers fix best rate null [skip ci] * hide swap on mweb asset * minor context fix [skip ci] * Fix Silent payment case * new-ui: fix changelog typo (#3036) Fix typo in changelog for account management. * Modify date format to Month DD YYYY * feat: docker based ci * Fix 2FA continue button location (#3043) * fix: Desktop wallet bugs (#2968) * fix: Desktop wallet bugs - repeated wallets post migration - newly created wallets not showing up - extra large components on desktop, needed maxwidth * chore: Remove duplicate logic * chore: remove formatting * refactor: streamline updateList method and handle multiple calls with a future based mutex * refactor: enhance swipe to confirm with dynamic width handling and improved drag threshold logic * fix: Minor fixes * fix: Male exchange provider logger nullable [skip ci] * Improve error handling and duplicate invoice handling in Lightning wallet (#3047) * fix: handle duplicate Lightning invoice payments gracefully * fix: improved error handling in Lightning wallet * General improvements (#3030) * General Improvements - Make borderRadius for CTAs uniform 18px - Identify hardware wallets in title of Seeds/Keys page - Make entire wallet tile clickable in wallet list * chore: Simplify check * Update lib/view_model/wallet_keys_view_model.dart [skip ci] --------- Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com> * homescreen improvements (#3034) * Homescreen improvements - Increase touch area for card editing icon - Tapping any card in the background should move it ino the foreground without closing the account tab - make top left chain icon primary color with full opacity when syncing and 20% when done - add tor indicator to top bar when enabled * fix: remove unneeded color filter * refactor: Adjust structure for tor and sync indicators * minor fixes (#3045) * add safe fallback for strings and remove status code checks * Refactor fetchLimits method to return nullable Limits for better error handling. --------- Signed-off-by: black5box <black5box@outlook.com> Co-authored-by: malik1004x <malikowskirobert@gmail.com> Co-authored-by: Konstantin Ullrich <konstantinullrich12@gmail.com> Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> Co-authored-by: tuxsudo <tuxsudo@tux.pizza> Co-authored-by: black5box <black5box@outlook.com> Co-authored-by: cyan <cyjan@mrcyjanek.net> Co-authored-by: Konstantin Ullrich <konstantin@cakewallet.com> Co-authored-by: Serhii <borodenko.sv@gmail.com> Co-authored-by: Edwin den Boer <woordenboer@planet.nl> Co-authored-by: Serhii <17529954+serhii-bor@users.noreply.github.com> Co-authored-by: Serhii-Borodenko <17529954+Serhii-Borodenko@users.noreply.github.com> Co-authored-by: rottenwheel <92872541+rottenwheel@users.noreply.github.com>

David Adegoke committed Mar 18, 2026 at 21:21 UTC 410c496bfc64c0dfe3d2738f9f720e39cd83baeb
21 files changed +230 -114
lib/core/trade_monitor.dart
-1
@@ -127,7 +127,6 @@ class TradeMonitor {
127
128 bool _shouldSkipTrade(Trade trade, String walletId, ExchangeProvider? provider) {
129 if (trade.walletId != walletId) {
130 - printV('Skipping trade ${trade.id} because it\'s not for this wallet');
130 return true;
131 }
132
lib/entities/calculate_fiat_amount.dart
+2 -1
@@ -5,7 +5,8 @@ String calculateFiatAmount({double? price, String? cryptoAmount, bool raw = fals
5
6 cryptoAmount = cryptoAmount.replaceAll(',', '.');
7
8 - final _amount = double.parse(cryptoAmount);
8 + final _amount = double.tryParse(cryptoAmount);
9 + if (_amount == null || _amount.isNaN) return '0.00';
10 final _result = price * _amount;
11 final result = _result < 0 ? _result * -1 : _result;
12
lib/exchange/provider/chainflip_exchange_provider.dart
+1 -1
@@ -63,7 +63,7 @@ class ChainflipExchangeProvider extends ExchangeProvider {
63 Future<bool> checkIsAvailable() async => true;
64
65 @override
66 - Future<Limits> fetchLimits(
66 + Future<Limits?> fetchLimits(
67 {required CryptoCurrency from,
68 required CryptoCurrency to,
69 required bool isFixedRateMode}) async {
lib/exchange/provider/changenow_exchange_provider.dart
+22 -18
@@ -23,7 +23,6 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
23 : _settingsStore = settingsStore,
24 _lastUsedRateId = '';
25
26 -
26 static final apiKey =
27 isMoneroOnly ? secrets.changeNowMoneroApiKey : secrets.changeNowCakeWalletApiKey;
28 static const apiAuthority = 'api.changenow.io';
@@ -55,7 +54,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
54 Future<bool> checkIsAvailable() async => true;
55
56 @override
58 - Future<Limits> fetchLimits(
57 + Future<Limits?> fetchLimits(
58 {required CryptoCurrency from,
59 required CryptoCurrency to,
60 required bool isFixedRateMode}) async {
@@ -81,18 +80,19 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
80 throw Exception('Unexpected http status: ${response.statusCode}');
81
82 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
84 - return Limits(
85 - min: responseJSON['minAmount'] as double?, max: responseJSON['maxAmount'] as double?);
83 + final min = double.tryParse(responseJSON['minAmount']?.toString() ?? '');
84 + final max = double.tryParse(responseJSON['maxAmount']?.toString() ?? '');
85 + if (max == 0) return null;
86 + return Limits(min: min, max: max);
87 }
88
89 @override
89 - Future<double> fetchRate({
90 - required CryptoCurrency from,
91 - required CryptoCurrency to,
92 - required double amount,
93 - required bool isFixedRateMode,
94 - required bool isReceiveAmount
95 - }) async {
90 + Future<double> fetchRate(
91 + {required CryptoCurrency from,
92 + required CryptoCurrency to,
93 + required double amount,
94 + required bool isFixedRateMode,
95 + required bool isReceiveAmount}) async {
96 try {
97 if (amount == 0) return 0.0;
98
@@ -117,8 +117,9 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
117 final response = await ProxyWrapper().get(clearnetUri: uri, headers: headers);
118
119 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
120 - final fromAmount = double.parse(responseJSON['fromAmount'].toString());
121 - final toAmount = double.parse(responseJSON['toAmount'].toString());
120 + final fromAmount = double.tryParse(responseJSON['fromAmount']?.toString() ?? '') ?? 0.0;
121 + final toAmount = double.tryParse(responseJSON['toAmount']?.toString() ?? '') ?? 0.0;
122 + if (fromAmount <= 0 || toAmount <= 0) return 0.0;
123 final rateId = responseJSON['rateId'] as String? ?? '';
124
125 if (rateId.isNotEmpty) _lastUsedRateId = rateId;
@@ -278,14 +279,18 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
279 final fromCurrency = responseJSON['fromCurrency'] as String;
280 final fromNetwork = responseJSON['fromNetwork'] as String?;
281 final _normalizedFromNetwork = _normalizeNetworkType(fromNetwork ?? '');
281 - final fromTag = fromCurrency.toUpperCase() == _normalizedFromNetwork.toUpperCase() ? null : _normalizedFromNetwork;
282 + final fromTag = fromCurrency.toUpperCase() == _normalizedFromNetwork.toUpperCase()
283 + ? null
284 + : _normalizedFromNetwork;
285 final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
286
287 // Parsing 'to' currency
288 final toCurrency = responseJSON['toCurrency'] as String;
289 final toNetwork = responseJSON['toNetwork'] as String?;
290 final _normalizedToNetwork = _normalizeNetworkType(toNetwork ?? '');
288 - final toTag = toCurrency.toUpperCase() == _normalizedToNetwork.toUpperCase() ? null : _normalizedToNetwork;
291 + final toTag = toCurrency.toUpperCase() == _normalizedToNetwork.toUpperCase()
292 + ? null
293 + : _normalizedToNetwork;
294 final to = CryptoCurrency.safeParseCurrencyFromString(toCurrency, tag: toTag);
295
296 final inputAddress = responseJSON['payinAddress'] as String;
@@ -310,7 +315,8 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
315 expiredAt: expiredAt,
316 outputTransaction: outputTransaction,
317 payoutAddress: payoutAddress,
313 - userCurrencyFromRaw: '${fromCurrency.toUpperCase()}' + '_' + '${fromTag?.toUpperCase() ?? ''}',
318 + userCurrencyFromRaw:
319 + '${fromCurrency.toUpperCase()}' + '_' + '${fromTag?.toUpperCase() ?? ''}',
320 userCurrencyToRaw: '${toCurrency.toUpperCase()}' + '_' + '${toTag?.toUpperCase() ?? ''}',
321 );
322 }
@@ -363,6 +369,4 @@ class ChangeNowExchangeProvider extends ExchangeProvider {
369 _ => network,
370 };
371 }
366 -
367 -
372 }
lib/exchange/provider/exchange_provider.dart
+1 -1
@@ -23,7 +23,7 @@ abstract class ExchangeProvider {
23 @override
24 String toString() => title;
25
26 - Future<Limits> fetchLimits(
26 + Future<Limits?> fetchLimits(
27 {required CryptoCurrency from, required CryptoCurrency to, required bool isFixedRateMode});
28
29 Future<Trade> createTrade(
lib/exchange/provider/exolix_exchange_provider.dart
+2 -2
@@ -42,7 +42,7 @@ class ExolixExchangeProvider extends ExchangeProvider {
42 Future<bool> checkIsAvailable() async => true;
43
44 @override
45 - Future<Limits> fetchLimits({
45 + Future<Limits?> fetchLimits({
46 required CryptoCurrency from,
47 required CryptoCurrency to,
48 required bool isFixedRateMode,
@@ -143,7 +143,7 @@ class ExolixExchangeProvider extends ExchangeProvider {
143 throw Exception(message);
144 }
145
146 - final rate = responseJSON['rate'] as double;
146 + final rate = double.tryParse(responseJSON['rate']?.toString() ?? '') ?? 0.0;
147
148 ExchangeProviderLogger.logSuccess(
149 provider: description,
lib/exchange/provider/jupiter_exchange_provider.dart
+1 -1
@@ -72,7 +72,7 @@ class JupiterExchangeProvider extends ExchangeProvider {
72 }
73
74 @override
75 - Future<Limits> fetchLimits({
75 + Future<Limits?> fetchLimits({
76 required CryptoCurrency from,
77 required CryptoCurrency to,
78 required bool isFixedRateMode,
lib/exchange/provider/letsexchange_exchange_provider.dart
+1 -1
@@ -47,7 +47,7 @@ class LetsExchangeExchangeProvider extends ExchangeProvider {
47 Future<bool> checkIsAvailable() async => true;
48
49 @override
50 - Future<Limits> fetchLimits(
50 + Future<Limits?> fetchLimits(
51 {required CryptoCurrency from,
52 required CryptoCurrency to,
53 required bool isFixedRateMode}) async {
lib/exchange/provider/near_Intents_exchange_provider.dart
+1 -1
@@ -97,7 +97,7 @@ class NearIntentsExchangeProvider extends ExchangeProvider {
97 Future<bool> checkIsAvailable() async => true;
98
99 @override
100 - Future<Limits> fetchLimits(
100 + Future<Limits?> fetchLimits(
101 {required CryptoCurrency from,
102 required CryptoCurrency to,
103 required bool isFixedRateMode}) async {
lib/exchange/provider/sideshift_exchange_provider.dart
+1 -1
@@ -60,7 +60,7 @@ class SideShiftExchangeProvider extends ExchangeProvider {
60 }
61
62 @override
63 - Future<Limits> fetchLimits(
63 + Future<Limits?> fetchLimits(
64 {required CryptoCurrency from,
65 required CryptoCurrency to,
66 required bool isFixedRateMode}) async {
lib/exchange/provider/simpleswap_exchange_provider.dart
+1 -1
@@ -51,7 +51,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider {
51 }
52
53 @override
54 - Future<Limits> fetchLimits(
54 + Future<Limits?> fetchLimits(
55 {required CryptoCurrency from,
56 required CryptoCurrency to,
57 required bool isFixedRateMode}) async {
lib/exchange/provider/stealth_ex_exchange_provider.dart
+1 -1
@@ -43,7 +43,7 @@ class StealthExExchangeProvider extends ExchangeProvider {
43 Future<bool> checkIsAvailable() async => true;
44
45 @override
46 - Future<Limits> fetchLimits(
46 + Future<Limits?> fetchLimits(
47 {required CryptoCurrency from,
48 required CryptoCurrency to,
49 required bool isFixedRateMode}) async {
lib/exchange/provider/swapsxyz_exchange_provider.dart
+1 -1
@@ -62,7 +62,7 @@ class SwapsXyzExchangeProvider extends ExchangeProvider {
62 Future<bool> checkIsAvailable() async => true;
63
64 @override
65 - Future<Limits> fetchLimits({
65 + Future<Limits?> fetchLimits({
66 required CryptoCurrency from,
67 required CryptoCurrency to,
68 required bool isFixedRateMode,
lib/exchange/provider/swaptrade_exchange_provider.dart
+26 -15
@@ -9,7 +9,6 @@ import 'package:cake_wallet/exchange/trade_not_created_exception.dart';
9 import 'package:cake_wallet/exchange/trade_not_found_exception.dart';
10 import 'package:cake_wallet/exchange/trade_request.dart';
11 import 'package:cake_wallet/exchange/trade_state.dart';
12 -import 'package:cake_wallet/exchange/utils/currency_pairs_utils.dart';
12 import 'package:cw_core/utils/proxy_wrapper.dart';
13 import 'package:cw_core/crypto_currency.dart';
14 import 'package:cw_core/utils/print_verbose.dart';
@@ -47,7 +46,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
46 Future<bool> checkIsAvailable() async => true;
47
48 @override
50 - Future<Limits> fetchLimits({
49 + Future<Limits?> fetchLimits({
50 required CryptoCurrency from,
51 required CryptoCurrency to,
52 required bool isFixedRateMode,
@@ -55,29 +54,33 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
54 try {
55 final uri = Uri.https(apiAuthority, getCoins);
56 final response = await ProxyWrapper().get(clearnetUri: uri);
58 -
57
58 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
59
60 if (response.statusCode != 200)
61 throw Exception('Unexpected http status: ${response.statusCode}');
62
65 - final coinsInfo = responseJSON['data'] as List<dynamic>;
63 + final coinsInfoRaw = responseJSON['data'];
64 + final coinsInfo = coinsInfoRaw is List<dynamic> ? coinsInfoRaw : <dynamic>[];
65
67 - final coin = coinsInfo.firstWhere(
68 - (coin) => coin['id'].toString().toUpperCase() == _normalizeCurrency(from),
69 - orElse: () => null,
66 + final normalized = _normalizeCurrency(from);
67 + final coin = coinsInfo.cast<Map<String, dynamic>>().firstWhere(
68 + (c) => (c['id']?.toString().toUpperCase() ?? '') == normalized,
69 + orElse: () => <String, dynamic>{},
70 );
71
72 - if (coin == null) throw Exception('Coin not found: ${_normalizeCurrency(from)}');
72 + if (coin.isEmpty) {
73 + // Currency not supported by SwapTrade (e.g. USDC, DOGE).
74 + return null;
75 + }
76
74 - return Limits(
75 - min: double.parse(coin['min'].toString()),
76 - max: double.parse(coin['max'].toString()),
77 - );
77 + final min = double.tryParse(coin['min']?.toString() ?? '') ?? 0.0;
78 + final max = double.tryParse(coin['max']?.toString() ?? '') ?? 0.0;
79 + if (max == 0) return null;
80 + return Limits(min: min, max: max);
81 } catch (e) {
82 printV(e.toString());
80 - throw Exception('Error fetching limits: ${e.toString()}');
83 + return null;
84 }
85 }
86
@@ -189,7 +192,7 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
192 'amount_send': request.fromAmount,
193 'recipient': request.toAddress,
194 'ref': 'cake',
192 - 'markup': markup,
195 + 'markup': int.tryParse(markup.toString()) ?? 0,
196 'refund_address': request.refundAddress,
197 };
198
@@ -394,7 +397,15 @@ class SwapTradeExchangeProvider extends ExchangeProvider {
397 CryptoCurrency.bnb => 'BNB_BSC',
398 CryptoCurrency.usdterc20 => 'USDT_ERC20',
399 CryptoCurrency.usdttrc20 => 'TRX_USDT_S2UZ',
397 - _ => '',
400 + CryptoCurrency.usdtbsc => 'USDT_BSC',
401 + CryptoCurrency.sol => 'SOL',
402 + CryptoCurrency.btc => 'BTC',
403 + CryptoCurrency.xmr => 'XMR',
404 + CryptoCurrency.ltc => 'LTC',
405 + CryptoCurrency.ada => 'ADA',
406 + CryptoCurrency.bch => 'BCH',
407 + CryptoCurrency.zec => 'ZEC',
408 + _ => currency.title.toUpperCase(),
409 };
410 return network;
411 }
lib/exchange/provider/thorchain_exchange.provider.dart
+1 -1
@@ -109,7 +109,7 @@ class ThorChainExchangeProvider extends ExchangeProvider {
109 }
110
111 @override
112 - Future<Limits> fetchLimits(
112 + Future<Limits?> fetchLimits(
113 {required CryptoCurrency from,
114 required CryptoCurrency to,
115 required bool isFixedRateMode}) async {
lib/exchange/provider/trocador_exchange_provider.dart
+64 -43
@@ -82,7 +82,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
82 Future<bool> checkIsAvailable() async => true;
83
84 @override
85 - Future<Limits> fetchLimits(
85 + Future<Limits?> fetchLimits(
86 {required CryptoCurrency from,
87 required CryptoCurrency to,
88 required bool isFixedRateMode}) async {
@@ -103,10 +103,10 @@ class TrocadorExchangeProvider extends ExchangeProvider {
103
104 final coinJson = responseJSON.first as Map<String, dynamic>;
105
106 - return Limits(
107 - min: coinJson['minimum'] as double?,
108 - max: coinJson['maximum'] as double?,
109 - );
106 + final min = double.tryParse(coinJson['minimum']?.toString() ?? '');
107 + final max = double.tryParse(coinJson['maximum']?.toString() ?? '');
108 + if (max == 0) return null;
109 + return Limits(min: min, max: max);
110 }
111
112 @override
@@ -135,11 +135,18 @@ class TrocadorExchangeProvider extends ExchangeProvider {
135 final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
136
137 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
138 - final fromAmount = double.parse(responseJSON['amount_from'].toString());
139 - final toAmount = double.parse(responseJSON['amount_to'].toString());
140 - final rateId = responseJSON['trade_id'] as String? ?? '';
138 + final fromAmount = double.tryParse(responseJSON['amount_from']?.toString() ?? '') ?? 0.0;
139 + final toAmount = double.tryParse(responseJSON['amount_to']?.toString() ?? '') ?? 0.0;
140 +
141 + if (fromAmount <= 0 || toAmount <= 0) return 0.0;
142
142 - var quotes = responseJSON['quotes']['quotes'] as List;
143 + final quotesData = responseJSON['quotes'];
144 + final rateId = _safeString(responseJSON, 'trade_id');
145 +
146 + if (quotesData == null || quotesData is! Map<String, dynamic>) {
147 + return 0.0;
148 + }
149 + final quotes = (quotesData['quotes'] as List?) ?? [];
150 _provider = quotes
151 .where((quote) => providerStates[quote['provider']] != false)
152 .map((quote) => quote['provider'])
@@ -243,7 +250,7 @@ class TrocadorExchangeProvider extends ExchangeProvider {
250 params['id'] = _lastUsedRateId;
251 }
252
246 - if (_provider.isEmpty) {
253 + if (_provider.isEmpty || _provider.first == null || _provider.first.toString().isEmpty) {
254 ExchangeProviderLogger.logError(
255 provider: description,
256 function: 'createTrade',
@@ -264,15 +271,15 @@ class TrocadorExchangeProvider extends ExchangeProvider {
271 throw Exception('No available provider is enabled');
272 }
273
267 - params['provider'] = _provider.first as String;
274 + params['provider'] = _provider.first.toString();
275
276 final uri = await _getUri(createTradePath, params);
277 final response = await ProxyWrapper().get(clearnetUri: uri, headers: {'API-Key': apiKey});
278
279 if (response.statusCode == 400) {
280 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
274 - final error = responseJSON['error'] as String;
275 - final message = responseJSON['message'] as String;
281 + final error = _safeString(responseJSON, 'error', 'Unknown error');
282 + final message = _safeString(responseJSON, 'message');
283
284 ExchangeProviderLogger.logError(
285 provider: description,
@@ -319,18 +326,18 @@ class TrocadorExchangeProvider extends ExchangeProvider {
326 }
327
328 final responseJSON = json.decode(response.body) as Map<String, dynamic>;
322 - final id = responseJSON['trade_id'] as String;
323 - final inputAddress = responseJSON['address_provider'] as String;
324 - final refundAddress = responseJSON['refund_address'] as String;
325 - final status = responseJSON['status'] as String;
326 - final payoutAddress = responseJSON['address_user'] as String;
327 - final date = responseJSON['date'] as String;
328 - final password = responseJSON['password'] as String;
329 - final providerId = responseJSON['id_provider'] as String;
330 - final providerName = responseJSON['provider'] as String;
331 - final amount = responseJSON['amount_from']?.toString();
332 - final receiveAmount = responseJSON['amount_to']?.toString();
333 - final addressProviderMemo = responseJSON['address_provider_memo'] as String?;
329 + final id = _safeString(responseJSON, 'trade_id');
330 + final inputAddress = _safeString(responseJSON, 'address_provider');
331 + final refundAddress = _safeString(responseJSON, 'refund_address');
332 + final status = _safeString(responseJSON, 'status');
333 + final payoutAddress = _safeString(responseJSON, 'address_user');
334 + final date = _safeString(responseJSON, 'date');
335 + final password = _safeString(responseJSON, 'password');
336 + final providerId = _safeString(responseJSON, 'id_provider');
337 + final providerName = _safeString(responseJSON, 'provider');
338 + final amount = _safeString(responseJSON, 'amount_from');
339 + final receiveAmount = _safeString(responseJSON, 'amount_to');
340 + final addressProviderMemo = _safeString(responseJSON, 'address_provider_memo');
341
342 ExchangeProviderLogger.logSuccess(
343 provider: description,
@@ -365,6 +372,9 @@ class TrocadorExchangeProvider extends ExchangeProvider {
372 },
373 );
374
375 + final amountToTrade = amount.isEmpty ? request.fromAmount : amount;
376 + final receiveAmountToTrade = receiveAmount.isEmpty ? request.toAmount : receiveAmount;
377 +
378 return Trade(
379 id: id,
380 from: request.fromCurrency,
@@ -377,8 +387,8 @@ class TrocadorExchangeProvider extends ExchangeProvider {
387 providerId: providerId,
388 providerName: providerName,
389 createdAt: DateTime.tryParse(date)?.toLocal(),
380 - amount: amount ?? request.fromAmount,
381 - receiveAmount: receiveAmount ?? request.toAmount,
390 + amount: amountToTrade,
391 + receiveAmount: receiveAmountToTrade,
392 payoutAddress: payoutAddress,
393 isSendAll: isSendAll,
394 extraId: addressProviderMemo,
@@ -396,19 +406,21 @@ class TrocadorExchangeProvider extends ExchangeProvider {
406 throw Exception('Unexpected http status: ${response.statusCode}');
407
408 final responseListJson = json.decode(response.body) as List;
399 - final responseJSON = responseListJson.first;
400 - final id = responseJSON['trade_id'] as String;
401 - final payoutAddress = responseJSON['address_user'] as String;
402 - final refundAddress = responseJSON['refund_address'] as String;
403 - final inputAddress = responseJSON['address_provider'] as String;
409 + final responseJSON = responseListJson.first as Map<String, dynamic>;
410 + final id = _safeString(responseJSON, 'trade_id');
411 + final payoutAddress = _safeString(responseJSON, 'address_user');
412 + final refundAddress = _safeString(responseJSON, 'refund_address');
413 + final inputAddress = _safeString(responseJSON, 'address_provider');
414 final fromAmount = responseJSON['amount_from']?.toString() ?? '0';
405 - final password = responseJSON['password'] as String;
406 - final providerId = responseJSON['id_provider'] as String;
407 - final providerName = responseJSON['provider'] as String;
408 - final addressProviderMemo = responseJSON['address_provider_memo'] as String?;
409 -
410 - final fromCurrency = responseJSON['ticker_from'] as String;
411 - final fromNetwork = responseJSON['network_from'] as String?;
415 + final password = _safeString(responseJSON, 'password');
416 + final providerId = _safeString(responseJSON, 'id_provider');
417 + final providerName = _safeString(responseJSON, 'provider');
418 + final memoVal = _safeString(responseJSON, 'address_provider_memo');
419 + final addressProviderMemo = memoVal.isEmpty ? null : memoVal;
420 +
421 + final fromCurrency = _safeString(responseJSON, 'ticker_from');
422 + final fromNetworkVal = _safeString(responseJSON, 'network_from');
423 + final fromNetwork = fromNetworkVal.isEmpty ? null : fromNetworkVal;
424 final _normalizedFromNetwork = _normalizeNetworkType(fromNetwork ?? '');
425 final fromTag = _normalizedFromNetwork.isEmpty ||
426 _normalizedFromNetwork == fromCurrency.toUpperCase() ||
@@ -418,8 +430,9 @@ class TrocadorExchangeProvider extends ExchangeProvider {
430
431 final from = CryptoCurrency.safeParseCurrencyFromString(fromCurrency, tag: fromTag);
432
421 - final toCurrency = responseJSON['ticker_to'] as String;
422 - final networkTo = responseJSON['network_to'] as String?;
433 + final toCurrency = _safeString(responseJSON, 'ticker_to');
434 + final networkToVal = _safeString(responseJSON, 'network_to');
435 + final networkTo = networkToVal.isEmpty ? null : networkToVal;
436 final _normalizedToNetwork = _normalizeNetworkType(networkTo ?? '');
437 final toTag = _normalizedToNetwork.isEmpty ||
438 _normalizedToNetwork == toCurrency.toUpperCase() ||
@@ -435,9 +448,9 @@ class TrocadorExchangeProvider extends ExchangeProvider {
448 provider: description,
449 inputAddress: inputAddress,
450 refundAddress: refundAddress,
438 - createdAt: DateTime.parse(responseJSON['date'] as String),
451 + createdAt: DateTime.tryParse(_safeString(responseJSON, 'date')),
452 amount: fromAmount,
440 - state: TradeState.deserialize(raw: responseJSON['status'] as String),
453 + state: TradeState.deserialize(raw: _safeString(responseJSON, 'status')),
454 payoutAddress: payoutAddress,
455 password: password,
456 providerId: providerId,
@@ -541,6 +554,14 @@ class TrocadorExchangeProvider extends ExchangeProvider {
554 return Uri.https(clearNetAuthority, path, queryParams);
555 }
556 }
557 +
558 + /// Safe string extraction from API response. Handles different data types.
559 + static String _safeString(Map<String, dynamic> m, String key, [String nullError = '']) {
560 + final v = m[key];
561 + if (v == null) return nullError;
562 + if (v is String) return v;
563 + return v.toString();
564 + }
565 }
566
567 class TrocadorPartners {
lib/exchange/provider/xoswap_exchange_provider.dart
+1 -1
@@ -150,7 +150,7 @@ class XOSwapExchangeProvider extends ExchangeProvider {
150 }
151 }
152
153 - Future<Limits> fetchLimits({
153 + Future<Limits?> fetchLimits({
154 required CryptoCurrency from,
155 required CryptoCurrency to,
156 required bool isFixedRateMode,
lib/src/screens/dev/exchange_provider_logs_page.dart
+2 -2
@@ -130,7 +130,7 @@ class _StatsCardState extends State<_StatsCard> {
130 child: Row(
131 mainAxisAlignment: MainAxisAlignment.spaceBetween,
132 children: [
133 - Text(entry.key.title),
133 + Text(entry.key?.title ?? 'Unknown'),
134 Text(entry.value.toString()),
135 ],
136 ),
@@ -310,7 +310,7 @@ class _LogEntryCard extends StatelessWidget {
310 SizedBox(width: 8),
311 Expanded(
312 child: Text(
313 - "${log.provider.title} - ${log.function}",
313 + "${log.provider?.title ?? 'Unknown/Empty'} - ${log.function}",
314 style: Theme.of(context).textTheme.titleMedium,
315 ),
316 ),
lib/utils/exchange_provider_logger.dart
+10 -9
@@ -1,9 +1,10 @@
1 import 'dart:convert';
2 +import 'package:cake_wallet/core/utilities.dart';
3 import 'package:cake_wallet/exchange/exchange_provider_description.dart';
4
5 class ExchangeProviderLogEntry {
6 final DateTime timestamp;
6 - final ExchangeProviderDescription provider;
7 + final ExchangeProviderDescription? provider;
8 final String function;
9 final String? error;
10 final String? stackTrace;
@@ -14,8 +15,8 @@ class ExchangeProviderLogEntry {
15
16 ExchangeProviderLogEntry({
17 required this.timestamp,
17 - required this.provider,
18 required this.function,
19 + this.provider,
20 this.error,
21 this.stackTrace,
22 this.callStack,
@@ -26,7 +27,7 @@ class ExchangeProviderLogEntry {
27
28 String toLogString() {
29 final buffer = StringBuffer();
29 - buffer.writeln('Provider: ${provider.title}');
30 + buffer.writeln('Provider: ${provider?.title ?? 'Unknown/Empty'}');
31 buffer.writeln('Function: $function');
32 buffer.writeln('Timestamp: ${timestamp.toIso8601String()}');
33 buffer.writeln('Success: $isSuccess');
@@ -58,7 +59,7 @@ class ExchangeProviderLogEntry {
59 Map<String, dynamic> toJson() {
60 return {
61 'timestamp': timestamp.toIso8601String(),
61 - 'provider': provider.title,
62 + 'provider': provider?.title,
63 'function': function,
64 'error': error,
65 'stackTrace': stackTrace,
@@ -85,14 +86,14 @@ class ExchangeProviderLogEntry {
86 ExchangeProviderDescription.stealthEx,
87 ExchangeProviderDescription.chainflip,
88 ExchangeProviderDescription.xoSwap,
89 + ExchangeProviderDescription.swapsXyz,
90 + ExchangeProviderDescription.nearIntents,
91 + ExchangeProviderDescription.jupiter,
92 ];
93
94 return ExchangeProviderLogEntry(
95 timestamp: DateTime.parse(json['timestamp'] as String),
92 - provider: allProviders.firstWhere(
93 - (p) => p.title == json['provider'] as String,
94 - orElse: () => ExchangeProviderDescription.changeNow,
95 - ),
96 + provider: allProviders.firstWhereOrNull((p) => p.title == json['provider'] as String),
97 function: json['function'] as String,
98 error: json['error'] as String?,
99 stackTrace: json['stackTrace'] as String?,
@@ -131,9 +132,9 @@ class ExchangeProviderLogger {
132 }
133
134 static void logError({
134 - required ExchangeProviderDescription provider,
135 required String function,
136 required dynamic error,
137 + ExchangeProviderDescription? provider,
138 StackTrace? stackTrace,
139 Map<String, dynamic>? requestData,
140 String? callStack,
lib/view_model/dev/exchange_provider_logs_view_model.dart
+3 -2
@@ -43,10 +43,11 @@ abstract class ExchangeProviderLogsViewModelBase with Store {
43 int get errorLogs => logs.where((log) => !log.isSuccess).length;
44
45 @computed
46 - Map<ExchangeProviderDescription, int> get logsByProvider {
46 + Map<ExchangeProviderDescription?, int> get logsByProvider {
47 final Map<ExchangeProviderDescription, int> counts = {};
48 for (final log in logs) {
49 - counts[log.provider] = (counts[log.provider] ?? 0) + 1;
49 + if (log.provider == null) continue;
50 + counts[log.provider!] = (counts[log.provider!] ?? 0) + 1;
51 }
52 return counts;
53 }
lib/view_model/exchange/exchange_view_model.dart
+88 -10
@@ -40,6 +40,7 @@ import 'package:cake_wallet/exchange/trade_request.dart';
40 import 'package:cake_wallet/generated/i18n.dart';
41 import 'package:cake_wallet/src/screens/exchange/widgets/currency_picker.dart';
42 import 'package:cake_wallet/store/app_store.dart';
43 +import 'package:cake_wallet/utils/exchange_provider_logger.dart';
44 import 'package:cake_wallet/utils/show_pop_up.dart';
45 import 'package:cw_core/currency.dart';
46 import "package:cw_core/wallet_info.dart";
@@ -321,7 +322,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
322
323 final List<ExchangeProvider> _tradeAvailableProviders = [];
324
324 - Map<ExchangeProvider, Limits> _providerLimits = {};
325 + Map<ExchangeProvider, Limits?> _providerLimits = {};
326
327 @observable
328 ObservableList<ExchangeProvider> selectedProviders;
@@ -681,14 +682,16 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
682 if (receiveAmountFiat.split(".").last.length <= digits) {
683 return receiveAmountFiat;
684 }
684 - return double.parse(receiveAmountFiat).toStringAsPrecision(digits);
685 +
686 + return double.tryParse(receiveAmountFiat)?.toStringAsPrecision(digits) ?? '0.00';
687 }
688
689 String roundedDepositAmountFiat(int digits) {
690 if (depositAmountFiat.split(".").last.length <= digits) {
691 return depositAmountFiat;
692 }
691 - return double.parse(depositAmountFiat).toStringAsPrecision(digits);
693 +
694 + return double.tryParse(depositAmountFiat)?.toStringAsPrecision(digits) ?? '0.00';
695 }
696
697 @action
@@ -875,6 +878,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
878 // will throw "Concurrent modification during iteration" error if modified at the same
879 // time [createTrade] is called, as this is not a normal map, but a sorted map
880 }
881 + } else {
882 + printV('calculateBestRate: ${_providers[i].title} returned rate=0');
883 }
884 }
885
@@ -914,10 +919,10 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
919 to: to,
920 isFixedRateMode: isFixedRateMode,
921 )
917 - .onError((error, stackTrace) => Limits(max: 0.0, min: double.maxFinite))
922 + .onError((error, stackTrace) => null)
923 .timeout(
924 Duration(seconds: 7),
920 - onTimeout: () => Limits(max: 0.0, min: double.maxFinite),
925 + onTimeout: () => null,
926 );
927 return MapEntry(provider, limits);
928 }).toList();
@@ -925,7 +930,9 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
930 final entries = await Future.wait(futures);
931 _providerLimits = Map.fromEntries(entries);
932
928 - _providerLimits.values.forEach((tempLimits) {
933 + _providerLimits.values
934 + .whereType<Limits>()
935 + .forEach((tempLimits) {
936 if (lowestMin != null && (tempLimits.min ?? -1) < lowestMin!) {
937 lowestMin = tempLimits.min;
938 }
@@ -968,18 +975,58 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
975 }
976 }
977
971 - late final Map<double, ExchangeProvider> providers;
978 + if (depositCurrency == CryptoCurrency.btcln &&
979 + depositAddress == wallet.walletAddresses.addressForExchange) {
980 + final invoice = await bitcoin!.getLightningInvoice(wallet, BigInt.zero);
981 + if (invoice != null) {
982 + depositAddress = invoice;
983 + }
984 + }
985 +
986 + if (receiveCurrency == CryptoCurrency.btcln &&
987 + receiveAddress == wallet.walletAddresses.addressForExchange) {
988 + final invoice = await bitcoin!.getLightningInvoice(wallet, BigInt.zero);
989 + if (invoice != null) {
990 + receiveAddress = invoice;
991 + }
992 + }
993 +
994 + Map<double, ExchangeProvider> providers;
995 if (forcedProvider != null) {
996 providers = {forcedProviderRate: forcedProvider!};
997 } else {
975 - providers = _sortedAvailableProviders;
998 + providers = Map.fromEntries(
999 + _sortedAvailableProviders.entries.where(
1000 + (e) => selectedProviders.contains(e.value),
1001 + ),
1002 + );
1003 }
1004
1005 // Ensure we have providers available before attempting to create trade
1006 if (providers.isEmpty) {
1007 await calculateBestRate();
1008 + if (forcedProvider != null) {
1009 + providers = {forcedProviderRate: forcedProvider!};
1010 + } else {
1011 + providers = Map.fromEntries(
1012 + _sortedAvailableProviders.entries.where(
1013 + (e) => selectedProviders.contains(e.value),
1014 + ),
1015 + );
1016 + }
1017
1018 if (providers.isEmpty) {
1019 + ExchangeProviderLogger.logError(
1020 + provider: null,
1021 + function: 'createTrade',
1022 + error: 'No providers available for $depositCurrency->$receiveCurrency',
1023 + requestData: {
1024 + 'from': depositCurrency.title,
1025 + 'to': receiveCurrency.title,
1026 + 'fromAmount': _depositAmount,
1027 + 'toAmount': _receiveAmount,
1028 + },
1029 + );
1030 tradeState = TradeIsCreatedFailure(
1031 title: S.current.trade_not_created,
1032 error: S.current.none_of_selected_providers_can_exchange);
@@ -1022,6 +1069,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
1069 final provider = providersSnapshot[i];
1070 final providerRate = ratesSnapshot[i];
1071
1072 + printV('createTrade: trying provider=${provider.title}');
1073 +
1074 // Skip Swaps.xyz when sending from external
1075 if (isSendFromExternal &&
1076 provider.description == ExchangeProviderDescription.swapsXyz) {
@@ -1055,7 +1104,10 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
1104 amount = amount.replaceAll(',', '.');
1105
1106 if (limitsState is LimitsLoadedSuccessfully) {
1058 - if (double.tryParse(amount) == null) continue;
1107 + if (double.tryParse(amount) == null) {
1108 + printV('createTrade: ${provider.title} amount parse failed: "$amount"');
1109 + continue;
1110 + }
1111
1112 if (limits.min != null && double.parse(amount) < limits.min!) {
1113 continue;
@@ -1075,6 +1127,17 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
1127
1128 final canCreateTrade = await isCanCreateTrade(trade);
1129 if (!canCreateTrade.result) {
1130 + ExchangeProviderLogger.logError(
1131 + provider: provider.description,
1132 + function: 'createTrade',
1133 + error: canCreateTrade.errorMessage ?? 'isCanCreateTrade returned false',
1134 + requestData: {
1135 + 'from': depositCurrency.title,
1136 + 'to': receiveCurrency.title,
1137 + 'fromAmount': _depositAmount,
1138 + 'toAmount': _receiveAmount,
1139 + },
1140 + );
1141 continue;
1142 }
1143
@@ -1084,7 +1147,21 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
1147
1148 /// return after the first successful trade
1149 return;
1087 - } catch (e) {
1150 + } catch (e, s) {
1151 + ExchangeProviderLogger.logError(
1152 + provider: provider.description,
1153 + function: 'createTrade',
1154 + error: e,
1155 + stackTrace: s,
1156 + requestData: {
1157 + 'from': depositCurrency.title,
1158 + 'to': receiveCurrency.title,
1159 + 'fromAmount': _depositAmount,
1160 + 'toAmount': _receiveAmount,
1161 + 'toAddress': receiveAddress,
1162 + 'refundAddress': depositAddress,
1163 + },
1164 + );
1165 continue;
1166 }
1167 }
@@ -1206,6 +1283,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
1283 _receiveAmount = '';
1284 bestRate = 0.0;
1285 bestRateProvider = null;
1286 + _sortedAvailableProviders.clear();
1287 loadLimits();
1288 _setAvailableProviders();
1289 }